Programs & Examples On #Sieve

Sieves are a type of algorithm used e.g. in finding primes with the sieve of Eratosthenes, sieve of Atkin etc. "Sieving" refers to gradual dismissal of directly generated sequences of numbers as possible candidates, until only the desired numbers are left.

Sieve of Eratosthenes - Finding Primes Python

My implementation:

import math
n = 100
marked = {}
for i in range(2, int(math.sqrt(n))):
    if not marked.get(i):
        for x in range(i * i, n, i):
            marked[x] = True

for i in range(2, n):
    if not marked.get(i):
        print i

Do I cast the result of malloc?

TL;DR

int *sieve = (int *) malloc(sizeof(int) * length);

has two problems. The cast and that you're using the type instead of variable as argument for sizeof. Instead, do like this:

int *sieve = malloc(sizeof *sieve * length);

Long version

No; you don't cast the result, since:

  • It is unnecessary, as void * is automatically and safely promoted to any other pointer type in this case.
  • It adds clutter to the code, casts are not very easy to read (especially if the pointer type is long).
  • It makes you repeat yourself, which is generally bad.
  • It can hide an error if you forgot to include <stdlib.h>. This can cause crashes (or, worse, not cause a crash until way later in some totally different part of the code). Consider what happens if pointers and integers are differently sized; then you're hiding a warning by casting and might lose bits of your returned address. Note: as of C99 implicit functions are gone from C, and this point is no longer relevant since there's no automatic assumption that undeclared functions return int.

As a clarification, note that I said "you don't cast", not "you don't need to cast". In my opinion, it's a failure to include the cast, even if you got it right. There are simply no benefits to doing it, but a bunch of potential risks, and including the cast indicates that you don't know about the risks.

Also note, as commentators point out, that the above talks about straight C, not C++. I very firmly believe in C and C++ as separate languages.

To add further, your code needlessly repeats the type information (int) which can cause errors. It's better to de-reference the pointer being used to store the return value, to "lock" the two together:

int *sieve = malloc(length * sizeof *sieve);

This also moves the length to the front for increased visibility, and drops the redundant parentheses with sizeof; they are only needed when the argument is a type name. Many people seem to not know (or ignore) this, which makes their code more verbose. Remember: sizeof is not a function! :)


While moving length to the front may increase visibility in some rare cases, one should also pay attention that in the general case, it should be better to write the expression as:

int *sieve = malloc(sizeof *sieve * length);

Since keeping the sizeof first, in this case, ensures multiplication is done with at least size_t math.

Compare: malloc(sizeof *sieve * length * width) vs. malloc(length * width * sizeof *sieve) the second may overflow the length * width when width and length are smaller types than size_t.

Which is the fastest algorithm to find prime numbers?

I will let you decide if it's the fastest or not.

using System;
namespace PrimeNumbers
{

public static class Program
{
    static int primesCount = 0;


    public static void Main()
    {
        DateTime startingTime = DateTime.Now;

        RangePrime(1,1000000);   

        DateTime endingTime = DateTime.Now;

        TimeSpan span = endingTime - startingTime;

        Console.WriteLine("span = {0}", span.TotalSeconds);

    }


    public static void RangePrime(int start, int end)
    {
        for (int i = start; i != end+1; i++)
        {
            bool isPrime = IsPrime(i);
            if(isPrime)
            {
                primesCount++;
                Console.WriteLine("number = {0}", i);
            }
        }
        Console.WriteLine("primes count = {0}",primesCount);
    }



    public static bool IsPrime(int ToCheck)
    {

        if (ToCheck == 2) return true;
        if (ToCheck < 2) return false;


        if (IsOdd(ToCheck))
        {
            for (int i = 3; i <= (ToCheck / 3); i += 2)
            {
                if (ToCheck % i == 0) return false;
            }
            return true;
        }
        else return false; // even numbers(excluding 2) are composite
    }

    public static bool IsOdd(int ToCheck)
    {
        return ((ToCheck % 2 != 0) ? true : false);
    }
}
}

It takes approximately 82 seconds to find and print prime numbers within a range of 1 to 1,000,000, on my Core 2 Duo laptop with a 2.40 GHz processor. And it found 78,498 prime numbers.

Algorithm to calculate the number of divisors of a given number

The following is a C program to find the number of divisors of a given number.

The complexity of the above algorithm is O(sqrt(n)).

This algorithm will work correctly for the number which are perfect square as well as the numbers which are not perfect square.

Note that the upperlimit of the loop is set to the square-root of number to have the algorithm most efficient.

Note that storing the upperlimit in a separate variable also saves the time, you should not call the sqrt function in the condition section of the for loop, this also saves your computational time.

#include<stdio.h>
#include<math.h>
int main()
{
    int i,n,limit,numberOfDivisors=1;
    printf("Enter the number : ");
    scanf("%d",&n);
    limit=(int)sqrt((double)n);
    for(i=2;i<=limit;i++)
        if(n%i==0)
        {
            if(i!=n/i)
                numberOfDivisors+=2;
            else
                numberOfDivisors++;
        }
    printf("%d\n",numberOfDivisors);
    return 0;
}

Instead of the above for loop you can also use the following loop which is even more efficient as this removes the need to find the square-root of the number.

for(i=2;i*i<=n;i++)
{
    ...
}

How to update each dependency in package.json to the latest version?

I solved this by seeing the instructions from https://github.com/tjunnone/npm-check-updates

$ npm install -g npm-check-updates
$ ncu
$ ncu -u # to update all the dependencies to latest
$ ncu -u "specific module name"  #in case you want to update specific dependencies to latest

Get statistics for each group (such as count, mean, etc) using pandas GroupBy?

Quick Answer:

The simplest way to get row counts per group is by calling .size(), which returns a Series:

df.groupby(['col1','col2']).size()


Usually you want this result as a DataFrame (instead of a Series) so you can do:

df.groupby(['col1', 'col2']).size().reset_index(name='counts')


If you want to find out how to calculate the row counts and other statistics for each group continue reading below.


Detailed example:

Consider the following example dataframe:

In [2]: df
Out[2]: 
  col1 col2  col3  col4  col5  col6
0    A    B  0.20 -0.61 -0.49  1.49
1    A    B -1.53 -1.01 -0.39  1.82
2    A    B -0.44  0.27  0.72  0.11
3    A    B  0.28 -1.32  0.38  0.18
4    C    D  0.12  0.59  0.81  0.66
5    C    D -0.13 -1.65 -1.64  0.50
6    C    D -1.42 -0.11 -0.18 -0.44
7    E    F -0.00  1.42 -0.26  1.17
8    E    F  0.91 -0.47  1.35 -0.34
9    G    H  1.48 -0.63 -1.14  0.17

First let's use .size() to get the row counts:

In [3]: df.groupby(['col1', 'col2']).size()
Out[3]: 
col1  col2
A     B       4
C     D       3
E     F       2
G     H       1
dtype: int64

Then let's use .size().reset_index(name='counts') to get the row counts:

In [4]: df.groupby(['col1', 'col2']).size().reset_index(name='counts')
Out[4]: 
  col1 col2  counts
0    A    B       4
1    C    D       3
2    E    F       2
3    G    H       1


Including results for more statistics

When you want to calculate statistics on grouped data, it usually looks like this:

In [5]: (df
   ...: .groupby(['col1', 'col2'])
   ...: .agg({
   ...:     'col3': ['mean', 'count'], 
   ...:     'col4': ['median', 'min', 'count']
   ...: }))
Out[5]: 
            col4                  col3      
          median   min count      mean count
col1 col2                                   
A    B    -0.810 -1.32     4 -0.372500     4
C    D    -0.110 -1.65     3 -0.476667     3
E    F     0.475 -0.47     2  0.455000     2
G    H    -0.630 -0.63     1  1.480000     1

The result above is a little annoying to deal with because of the nested column labels, and also because row counts are on a per column basis.

To gain more control over the output I usually split the statistics into individual aggregations that I then combine using join. It looks like this:

In [6]: gb = df.groupby(['col1', 'col2'])
   ...: counts = gb.size().to_frame(name='counts')
   ...: (counts
   ...:  .join(gb.agg({'col3': 'mean'}).rename(columns={'col3': 'col3_mean'}))
   ...:  .join(gb.agg({'col4': 'median'}).rename(columns={'col4': 'col4_median'}))
   ...:  .join(gb.agg({'col4': 'min'}).rename(columns={'col4': 'col4_min'}))
   ...:  .reset_index()
   ...: )
   ...: 
Out[6]: 
  col1 col2  counts  col3_mean  col4_median  col4_min
0    A    B       4  -0.372500       -0.810     -1.32
1    C    D       3  -0.476667       -0.110     -1.65
2    E    F       2   0.455000        0.475     -0.47
3    G    H       1   1.480000       -0.630     -0.63



Footnotes

The code used to generate the test data is shown below:

In [1]: import numpy as np
   ...: import pandas as pd 
   ...: 
   ...: keys = np.array([
   ...:         ['A', 'B'],
   ...:         ['A', 'B'],
   ...:         ['A', 'B'],
   ...:         ['A', 'B'],
   ...:         ['C', 'D'],
   ...:         ['C', 'D'],
   ...:         ['C', 'D'],
   ...:         ['E', 'F'],
   ...:         ['E', 'F'],
   ...:         ['G', 'H'] 
   ...:         ])
   ...: 
   ...: df = pd.DataFrame(
   ...:     np.hstack([keys,np.random.randn(10,4).round(2)]), 
   ...:     columns = ['col1', 'col2', 'col3', 'col4', 'col5', 'col6']
   ...: )
   ...: 
   ...: df[['col3', 'col4', 'col5', 'col6']] = \
   ...:     df[['col3', 'col4', 'col5', 'col6']].astype(float)
   ...: 


Disclaimer:

If some of the columns that you are aggregating have null values, then you really want to be looking at the group row counts as an independent aggregation for each column. Otherwise you may be misled as to how many records are actually being used to calculate things like the mean because pandas will drop NaN entries in the mean calculation without telling you about it.

Go build: "Cannot find package" (even though GOPATH is set)

I solved this problem by set my go env GO111MODULE to off

go env -w  GO111MODULE=off

How to redirect output of an already running process

Screen

If process is running in a screen session you can use screen's log command to log the output of that window to a file:

Switch to the script's window, C-a H to log.
Now you can :

$ tail -f screenlog.2 | grep whatever

From screen's man page:

log [on|off]

Start/stop writing output of the current window to a file "screenlog.n" in the window's default directory, where n is the number of the current window. This filename can be changed with the 'logfile' command. If no parameter is given, the state of logging is toggled. The session log is appended to the previous contents of the file if it already exists. The current contents and the contents of the scrollback history are not included in the session log. Default is 'off'.

I'm sure tmux has something similar as well.

Why write <script type="text/javascript"> when the mime type is set by the server?

Boris Zbarsky (Mozilla), who probably knows more about the innards of Gecko than anyone else, provided at http://lists.w3.org/Archives/Public/public-html/2009Apr/0195.html the pseudocode repeated below to describe what Gecko based browsers do:

if (@type not set or empty) {
   if (@language not set or empty) {
     // Treat as default script language; what this is depends on the
     // content-script-type HTTP header or equivalent META tag
   } else {
     if (@language is one of "javascript", "livescript", "mocha",
                             "javascript1.0", "javascript1.1",
                             "javascript1.2", "javascript1.3",
                             "javascript1.4", "javascript1.5",
                             "javascript1.6", "javascript1.7",
                             "javascript1.8") {
       // Treat as javascript
     } else {
       // Treat as unknown script language; do not execute
     }
   }
} else {
   if (@type is one of "text/javascript", "text/ecmascript",
                       "application/javascript",
                       "application/ecmascript",
                       "application/x-javascript") {
     // Treat as javascript
   } else {
     // Treat as specified (e.g. if pyxpcom is installed and
     // python script is allowed in this context and the type
     // is one that the python runtime claims to handle, use that).
     // If we don't have a runtime for this type, do not execute.
   }
}

Get name of property as a string

You can use Reflection to obtain the actual names of the properties.

http://www.csharp-examples.net/reflection-property-names/

If you need a way to assign a "String Name" to a property, why don't you write an attribute that you can reflect over to get the string name?

[StringName("MyStringName")]
private string MyProperty
{
    get { ... }
}

Default value to a parameter while passing by reference in C++

It's possible with const qualifier for State:

virtual const ULONG Write(const ULONG &State = 0, bool sequence = true);

Pandas: sum DataFrame rows for given columns

The shortest and simpliest way here is to use

    df.eval('e = a + b + d')

How can I embed a YouTube video on GitHub wiki pages?

I created https://yt-embed.herokuapp.com/ to simplify this. The usage is direct, from the examples above:

[![Everything Is AWESOME](https://yt-embed.herokuapp.com/embed?v=StTqXEQ2l-Y)](https://www.youtube.com/watch?v=StTqXEQ2l-Y "Everything Is AWESOME")

Will result in: example of usage of yt-embed

Just make a call to: https://yt-embed.herokuapp.com/embed?v=[video_id] as the image instead of https://img.youtube.com/vi/.

TypeError: Cannot read property "0" from undefined

For me, the problem was I was using a package that isn't included in package.json nor installed.

import { ToastrService } from 'ngx-toastr';

So when the compiler tried to compile this, it threw an error.

(I installed it locally, and when running a build on an external server the error was thrown)

adding classpath in linux

For linux users, and to sum up and add to what others have said here, you should know the following:

  1. Global variables are not evil. $CLASSPATH is specifically what Java uses to look through multiple directories to find all the different classes it needs for your script (unless you explicitly tell it otherwise with the -cp override).

  2. The colon (":") character separates the different directories. There is only one $CLASSPATH and it has all the directories in it. So, when you run "export CLASSPATH=...." you want to include the current value "$CLASSPATH" in order to append to it. For example:

    export CLASSPATH=.
    export CLASSPATH=$CLASSPATH:/usr/share/java/mysql-connector-java-5.1.12.jar
    

    In the first line above, you start CLASSPATH out with just a simple 'dot' which is the path to your current working directory. With that, whenever you run java it will look in the current working directory (the one you're in) for classes. In the second line above, $CLASSPATH grabs the value that you previously entered (.) and appends the path to a mysql dirver. Now, java will look for the driver AND for your classes.

  3. echo $CLASSPATH
    

    is super handy, and what it returns should read like a colon-separated list of all the directories you want java looking in for what it needs to run your script.

  4. Tomcat does not use CLASSPATH. Read what to do about that here: https://tomcat.apache.org/tomcat-8.0-doc/class-loader-howto.html

How to prevent page from reloading after form submit - JQuery

The <button> element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:

  1. Use <button type="button"> to override default submission behavior
  2. Use event.preventDefault() in the onSubmit event to prevent form submission

Solution 1:

  • Advantage: simple change to markup
  • Disadvantage: subverts default form behavior, especially when JS is disabled. What if the user wants to hit "enter" to submit?

Insert extra type attribute to your button markup:

<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>

Solution 2:

  • Advantage: form will work even when JS is disabled, and respects standard form UI/UX such that at least one button is used for submission

Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:

$(document).ready(function () {
  // Listen to click event on the submit button
  $('#button').click(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Better variant:

In this improvement, we listen to the submit event emitted from the <form> element:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Even better variant: use .serialize() to serialize your form, but remember to add name attributes to your input:

The name attribute is required for .serialize() to work, as per jQuery's documentation:

For a form element's value to be included in the serialized string, the element must have a name attribute.

<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]">

And then in your JS:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    // Prevent form submission which refreshes page
    e.preventDefault();

    // Serialize data
    var formData = $(this).serialize();

    // Make AJAX request
    $.post("process.php", formData).complete(function() {
      console.log("Success");
    });
  });
});

Remove Object from Array using JavaScript

You can use several methods to remove item(s) from an Array:

//1
someArray.shift(); // first element removed
//2
someArray = someArray.slice(1); // first element removed
//3
someArray.splice(0, 1); // first element removed
//4
someArray.pop(); // last element removed
//5
someArray = someArray.slice(0, a.length - 1); // last element removed
//6
someArray.length = someArray.length - 1; // last element removed

If you want to remove element at position x, use:

someArray.splice(x, 1);

Or

someArray = someArray.slice(0, x).concat(someArray.slice(-x));

Reply to the comment of @chill182: you can remove one or more elements from an array using Array.filter, or Array.splice combined with Array.findIndex (see MDN), e.g.

_x000D_
_x000D_
// non destructive filter > noJohn = John removed, but someArray will not change_x000D_
let someArray = getArray();_x000D_
let noJohn = someArray.filter( el => el.name !== "John" ); _x000D_
log("non destructive filter > noJohn = ", format(noJohn));_x000D_
log(`**someArray.length ${someArray.length}`);_x000D_
_x000D_
// destructive filter/reassign John removed > someArray2 =_x000D_
let someArray2 = getArray();_x000D_
someArray2 = someArray2.filter( el => el.name !== "John" );_x000D_
log("", "destructive filter/reassign John removed > someArray2 =", _x000D_
  format(someArray2));_x000D_
log(`**someArray2.length ${someArray2.length}`);_x000D_
_x000D_
// destructive splice /w findIndex Brian remains > someArray3 =_x000D_
let someArray3 = getArray();_x000D_
someArray3.splice(someArray3.findIndex(v => v.name === "Kristian"), 1);_x000D_
someArray3.splice(someArray3.findIndex(v => v.name === "John"), 1);_x000D_
log("", "destructive splice /w findIndex Brian remains > someArray3 =", _x000D_
  format(someArray3));_x000D_
log(`**someArray3.length ${someArray3.length}`);_x000D_
_x000D_
// Note: if you're not sure about the contents of your array, _x000D_
// you should check the results of findIndex first_x000D_
let someArray4 = getArray();_x000D_
const indx = someArray4.findIndex(v => v.name === "Michael");_x000D_
someArray4.splice(indx, indx >= 0 ? 1 : 0);_x000D_
log("", "check findIndex result first > someArray4 (nothing is removed) > ",_x000D_
  format(someArray4));_x000D_
log(`**someArray4.length (should still be 3) ${someArray4.length}`);_x000D_
_x000D_
function format(obj) {_x000D_
  return JSON.stringify(obj, null, " ");_x000D_
}_x000D_
_x000D_
function log(...txt) {_x000D_
  document.querySelector("pre").textContent += `${txt.join("\n")}\n`_x000D_
}_x000D_
_x000D_
function getArray() {_x000D_
  return [ {name: "Kristian", lines: "2,5,10"},_x000D_
           {name: "John", lines: "1,19,26,96"},_x000D_
           {name: "Brian", lines: "3,9,62,36"} ];_x000D_
}
_x000D_
<pre>_x000D_
**Results**_x000D_
_x000D_
</pre>
_x000D_
_x000D_
_x000D_

Fast and Lean PDF Viewer for iPhone / iPad / iOS - tips and hints?

Since iOS 11, you can use the native framework called PDFKit for displaying and manipulating PDFs.

After importing PDFKit, you should initialize a PDFView with a local or a remote URL and display it in your view.

if let url = Bundle.main.url(forResource: "example", withExtension: "pdf") {
    let pdfView = PDFView(frame: view.frame)
    pdfView.document = PDFDocument(url: url)
    view.addSubview(pdfView)
}

Read more about PDFKit in the Apple Developer documentation.

Is there a NumPy function to return the first index of something in an array?

You can also convert a NumPy array to list in the air and get its index. For example,

l = [1,2,3,4,5] # Python list
a = numpy.array(l) # NumPy array
i = a.tolist().index(2) # i will return index of 2
print i

It will print 1.

adb connection over tcp not working now

Try to do port forwarding,

adb forward tcp:<PC port> tcp:<device port>.

like:

adb forward tcp:5555 tcp:5555.

sounds like 5555 port is captured so use other one. As I know 7612 is empty

[Edit]

C:\Users\m>adb forward tcp:7612 tcp:7612

C:\Users\m>adb tcpip 7612
restarting in TCP mode port: 7612

C:\Users\m>adb connect 192.168.1.12
connected to 192.168.1.12:7612

Be sure that you connect to the right IP address. (You can download Network Info 2 to check your IP)

Does List<T> guarantee insertion order?

If you will change the order of operations, you will avoid the strange behavior: First insert the value to the right place in the list, and then delete it from his first position. Make sure you delete it by his index, because if you will delete it by reference, you might delete them both...

google console error `OR-IEH-01`

It looks like your Google Play registration payment didn’t process. This can happen sometimes if a card has expired, the credit card or credit card verification (CVC) number was entered incorrectly, or if your billing address doesn't match the address in your Google Payments account.

Here’s how you can find the details of your transaction:

  1. Sign in to your Google Payments account at https://payments.google.com.

  2. On the left menu, select the “Subscriptions and services” page.

  3. On the “Other purchase activity” card, click View purchases.

  4. Click the “Google Play” registration transaction to see your payment method.

  5. You can click “Payment methods” on the left menu if you need to edit the addresses on your Google Payments account.

To add a new credit or debit card to your account, you can follow the instructions on the Google Payments Help Center (https://support.google.com/payments/answer/6220309).

String Array object in Java

public static void main(String[] args) {

        public String[] name = {"Art", "Dan", "Jen"};
        public String[] country = {"Canada", "Germant", "USA"};
        // initialize your performance array here too.

        //Your constructor takes arrays as an argument so you need to be sure to pass in the arrays and not just objects.
        Athlete art = new Athlete(name, country, performance);   

}

brew install mysql on macOS

I had the same issue after I tried to restart mysql.

I use the following two aliases in my .profile for convenience

alias mysql-stop='launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist'
alias mysql-start='launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist' 

After stoping mysql and then trying to restart I experienced the issue you were having. I looked into the launchctl load and it was reporting a “nothing found to load” error.

After a quick search I found this..

http://www.daveoncode.com/2013/02/01/solve-mac-osx-launchctl-nothing-found-to-load-error/

So I updated me mysql-start alias as follows

alias mysql-start='launchctl load -w -F ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist'

This solved my issue which may be useful for you.

How can you strip non-ASCII characters from a string? (in C#)

Necromancing.
Also, the method by bzlm can be used to remove characters that are not in an arbitrary charset, not just ASCII:

// https://en.wikipedia.org/wiki/Code_page#EBCDIC-based_code_pages
// https://en.wikipedia.org/wiki/Windows_code_page#East_Asian_multi-byte_code_pages
// https://en.wikipedia.org/wiki/Chinese_character_encoding
System.Text.Encoding encRemoveAllBut = System.Text.Encoding.ASCII;
encRemoveAllBut = System.Text.Encoding.GetEncoding(System.Globalization.CultureInfo.InstalledUICulture.TextInfo.ANSICodePage); // System-encoding
encRemoveAllBut = System.Text.Encoding.GetEncoding(1252); // Western European (iso-8859-1)
encRemoveAllBut = System.Text.Encoding.GetEncoding(1251); // Windows-1251/KOI8-R
encRemoveAllBut = System.Text.Encoding.GetEncoding("ISO-8859-5"); // used by less than 0.1% of websites
encRemoveAllBut = System.Text.Encoding.GetEncoding(37); // IBM EBCDIC US-Canada
encRemoveAllBut = System.Text.Encoding.GetEncoding(500); // IBM EBCDIC Latin 1
encRemoveAllBut = System.Text.Encoding.GetEncoding(936); // Chinese Simplified
encRemoveAllBut = System.Text.Encoding.GetEncoding(950); // Chinese Traditional
encRemoveAllBut = System.Text.Encoding.ASCII; // putting ASCII again, as to answer the question 

// https://stackoverflow.com/questions/123336/how-can-you-strip-non-ascii-characters-from-a-string-in-c
string inputString = "Räksmör??????, ???gås";
string asAscii = encRemoveAllBut.GetString(
    System.Text.Encoding.Convert(
        System.Text.Encoding.UTF8,
        System.Text.Encoding.GetEncoding(
            encRemoveAllBut.CodePage,
            new System.Text.EncoderReplacementFallback(string.Empty),
            new System.Text.DecoderExceptionFallback()
            ),
        System.Text.Encoding.UTF8.GetBytes(inputString)
    )
);

System.Console.WriteLine(asAscii);

AND for those that just want to remote the accents:
(caution, because Normalize != Latinize != Romanize)

// string str = Latinize("(æøå âôû?aè");
public static string Latinize(string stIn)
{
    // Special treatment for German Umlauts
    stIn = stIn.Replace("ä", "ae");
    stIn = stIn.Replace("ö", "oe");
    stIn = stIn.Replace("ü", "ue");

    stIn = stIn.Replace("Ä", "Ae");
    stIn = stIn.Replace("Ö", "Oe");
    stIn = stIn.Replace("Ü", "Ue");
    // End special treatment for German Umlauts

    string stFormD = stIn.Normalize(System.Text.NormalizationForm.FormD);
    System.Text.StringBuilder sb = new System.Text.StringBuilder();

    for (int ich = 0; ich < stFormD.Length; ich++)
    {
        System.Globalization.UnicodeCategory uc = System.Globalization.CharUnicodeInfo.GetUnicodeCategory(stFormD[ich]);

        if (uc != System.Globalization.UnicodeCategory.NonSpacingMark)
        {
            sb.Append(stFormD[ich]);
        } // End if (uc != System.Globalization.UnicodeCategory.NonSpacingMark)

    } // Next ich


    //return (sb.ToString().Normalize(System.Text.NormalizationForm.FormC));
    return (sb.ToString().Normalize(System.Text.NormalizationForm.FormKC));
} // End Function Latinize

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

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

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

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

Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ.

A better solution is explained in the official explanation. I left the answer I have given before under the horizontal line.

According to the solution there:

Use an external tag and write down the following code below in the top-level build.gradle file. You're going to change the version to a variable rather than a static version number.

ext {
    compileSdkVersion = 26
    supportLibVersion = "27.1.1"
}

Change the static version numbers in your app-level build.gradle file, the one has (Module: app) near.

android {
    compileSdkVersion rootProject.ext.compileSdkVersion // It was 26 for example
    // the below lines will stay
}

// here there are some other stuff maybe

dependencies {
    implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
    // the below lines will stay
}

Sync your project and you'll get no errors.


You don't need to add anything to Gradle scripts. Install the necessary SDKs and the problem will be solved.

In your case, install the libraries below from Preferences > Android SDK or Tools > Android > SDK Manager

enter image description here

Is there a way to remove unused imports and declarations from Angular 2+?

Edit (as suggested in comments and other people), Visual Studio Code has evolved and provides this functionality in-built as the command "Organize imports", with the following default keyboard shortcuts:

option+Shift+O for Mac

Alt + Shift + O for Windows


Original answer:

I hope this visual studio code extension will suffice your need: https://marketplace.visualstudio.com/items?itemName=rbbit.typescript-hero

It provides following features:

  • Add imports of your project or libraries to your current file
  • Add an import for the current name under the cursor
  • Add all missing imports of a file with one command
  • Intellisense that suggests symbols and automatically adds the needed imports "Light bulb feature" that fixes code you wrote
  • Sort and organize your imports (sort and remove unused)
  • Code outline view of your open TS / TSX document
  • All the cool stuff for JavaScript as well! (experimental stage though, better description below.)

For Mac: control+option+o

For Win: Ctrl+Alt+o

NumPy array is not JSON serializable

May do simple for loop with checking types:

with open("jsondontdoit.json", 'w') as fp:
    for key in bests.keys():
        if type(bests[key]) == np.ndarray:
            bests[key] = bests[key].tolist()
            continue
        for idx in bests[key]:
            if type(bests[key][idx]) == np.ndarray:
                bests[key][idx] = bests[key][idx].tolist()
    json.dump(bests, fp)
    fp.close()

Check if input is integer type in C

I've been searching for a simpler solution using only loops and if statements, and this is what I came up with. The program also works with negative integers and correctly rejects any mixed inputs that may contain both integers and other characters.


#include <stdio.h>
#include <stdlib.h> // Used for atoi() function
#include <string.h> // Used for strlen() function

#define TRUE 1
#define FALSE 0

int main(void)
{
    char n[10]; // Limits characters to the equivalent of the 32 bits integers limit (10 digits)
    int intTest;
    printf("Give me an int: ");

    do
    {        
        scanf(" %s", n);

        intTest = TRUE; // Sets the default for the integer test variable to TRUE

        int i = 0, l = strlen(n);
        if (n[0] == '-') // Tests for the negative sign to correctly handle negative integer values
            i++;
        while (i < l)
        {            
            if (n[i] < '0' || n[i] > '9') // Tests the string characters for non-integer values
            {              
                intTest = FALSE; // Changes intTest variable from TRUE to FALSE and breaks the loop early
                break;
            }
            i++;
        }
        if (intTest == TRUE)
            printf("%i\n", atoi(n)); // Converts the string to an integer and prints the integer value
        else
            printf("Retry: "); // Prints "Retry:" if tested FALSE
    }
    while (intTest == FALSE); // Continues to ask the user to input a valid integer value
    return 0;
}

How to draw a rounded Rectangle on HTML Canvas?

To make the function more consistent with the normal means of using a canvas context, the canvas context class can be extended to include a 'fillRoundedRect' method -- that can be called in the same way fillRect is called:

var canv = document.createElement("canvas");
var cctx = canv.getContext("2d");

// If thie canvasContext class doesn't have  a fillRoundedRect, extend it now
if (!cctx.constructor.prototype.fillRoundedRect) {
  // Extend the canvaseContext class with a fillRoundedRect method
  cctx.constructor.prototype.fillRoundedRect = 
    function (xx,yy, ww,hh, rad, fill, stroke) {
      if (typeof(rad) == "undefined") rad = 5;
      this.beginPath();
      this.moveTo(xx+rad, yy);
      this.arcTo(xx+ww, yy,    xx+ww, yy+hh, rad);
      this.arcTo(xx+ww, yy+hh, xx,    yy+hh, rad);
      this.arcTo(xx,    yy+hh, xx,    yy,    rad);
      this.arcTo(xx,    yy,    xx+ww, yy,    rad);
      if (stroke) this.stroke();  // Default to no stroke
      if (fill || typeof(fill)=="undefined") this.fill();  // Default to fill
  }; // end of fillRoundedRect method
} 

The code checks to see if the prototype for the constructor for the canvas context object contains a 'fillRoundedRect' property and adds one -- the first time around. It is invoked in the same manner as the fillRect method:

  ctx.fillStyle = "#eef";  ctx.strokeStyle = "#ddf";
  // ctx.fillRect(10,10, 200,100);
  ctx.fillRoundedRect(10,10, 200,100, 5);

The method uses the arcTo method as Grumdring did. In the method, this is a reference to the ctx object. The stroke argument defaults to false if undefined. The fill argument defaults to fill the rectangle if undefined.

(Tested on Firefox, I don't know if all implementations permit extension in this manner.)

How to pass complex object to ASP.NET WebApi GET from jQuery ajax call?

If you append json data to query string, and parse it later in web api side. you can parse complex object. It's useful rather than post json object style. This is my solution.

//javascript file 
var data = { UserID: "10", UserName: "Long", AppInstanceID: "100", ProcessGUID: "BF1CC2EB-D9BD-45FD-BF87-939DD8FF9071" };
var request = JSON.stringify(data);
request = encodeURIComponent(request);

doAjaxGet("/ProductWebApi/api/Workflow/StartProcess?data=", request, function (result) {
    window.console.log(result);
});

//webapi file:
[HttpGet]
public ResponseResult StartProcess()
{
    dynamic queryJson = ParseHttpGetJson(Request.RequestUri.Query);
        int appInstanceID = int.Parse(queryJson.AppInstanceID.Value);
    Guid processGUID = Guid.Parse(queryJson.ProcessGUID.Value);
    int userID = int.Parse(queryJson.UserID.Value);
    string userName = queryJson.UserName.Value;
}

//utility function:
public static dynamic ParseHttpGetJson(string query)
{
    if (!string.IsNullOrEmpty(query))
    {
        try
        {
            var json = query.Substring(7, query.Length - 7); //seperate ?data= characters
            json = System.Web.HttpUtility.UrlDecode(json);
            dynamic queryJson = JsonConvert.DeserializeObject<dynamic>(json);

            return queryJson;
        }
        catch (System.Exception e)
        {
            throw new ApplicationException("can't deserialize object as wrong string content!", e);
        }
    }
    else
    {
        return null;
    }
}

Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Please, don't forget to clean the build folder after you add arm64 to excluded architecture.

Parsing a CSV file using NodeJS

Ok so there are many answers here and I dont think they answer your question which I think is similar to mine.

You need to do an operation like contacting a database or third part api that will take time and is asyncronus. You do not want to load the entire document into memory due to being to large or some other reason so you need to read line by line to process.

I have read into the fs documents and it can pause on reading but using .on('data') call will make it continous which most of these answer use and cause the problem.


UPDATE: I know more info about Streams than I ever wanted

The best way to do this is to create a writable stream. This will pipe the csv data into your writable stream which you can manage asyncronus calls. The pipe will manage the buffer all the way back to the reader so you will not wind up with heavy memory usage

Simple Version

const parser = require('csv-parser');
const stripBom = require('strip-bom-stream');
const stream = require('stream')

const mySimpleWritable = new stream.Writable({
  objectMode: true, // Because input is object from csv-parser
  write(chunk, encoding, done) { // Required
    // chunk is object with data from a line in the csv
    console.log('chunk', chunk)
    done();
  },
  final(done) { // Optional
    // last place to clean up when done
    done();
  }
});
fs.createReadStream(fileNameFull).pipe(stripBom()).pipe(parser()).pipe(mySimpleWritable)

Class Version

const parser = require('csv-parser');
const stripBom = require('strip-bom-stream');
const stream = require('stream')
// Create writable class
class MyWritable extends stream.Writable {
  // Used to set object mode because we get an object piped in from csv-parser
  constructor(another_variable, options) {
    // Calls the stream.Writable() constructor.
    super({ ...options, objectMode: true });
    // additional information if you want
    this.another_variable = another_variable
  }
  // The write method
  // Called over and over, for each line in the csv
  async _write(chunk, encoding, done) {
    // The chunk will be a line of your csv as an object
    console.log('Chunk Data', this.another_variable, chunk)

    // demonstrate await call
    // This will pause the process until it is finished
    await new Promise(resolve => setTimeout(resolve, 2000));

    // Very important to add.  Keeps the pipe buffers correct.  Will load the next line of data
    done();
  };
  // Gets called when all lines have been read
  async _final(done) {
    // Can do more calls here with left over information in the class
    console.log('clean up')
    // lets pipe know its done and the .on('final') will be called
    done()
  }
}

// Instantiate the new writable class
myWritable = new MyWritable(somevariable)
// Pipe the read stream to csv-parser, then to your write class
// stripBom is due to Excel saving csv files with UTF8 - BOM format
fs.createReadStream(fileNameFull).pipe(stripBom()).pipe(parser()).pipe(myWritable)

// optional
.on('finish', () => {
  // will be called after the wriables internal _final
  console.log('Called very last')
})

OLD METHOD:

PROBLEM WITH readable

const csv = require('csv-parser');
const fs = require('fs');

const processFileByLine = async(fileNameFull) => {

  let reading = false

  const rr = fs.createReadStream(fileNameFull)
  .pipe(csv())

  // Magic happens here
  rr.on('readable', async function(){
    // Called once when data starts flowing
    console.log('starting readable')

    // Found this might be called a second time for some reason
    // This will stop that event from happening
    if (reading) {
      console.log('ignoring reading')
      return
    }
    reading = true
    
    while (null !== (data = rr.read())) {
      // data variable will be an object with information from the line it read
      // PROCESS DATA HERE
      console.log('new line of data', data)
    }

    // All lines have been read and file is done.
    // End event will be called about now so that code will run before below code

    console.log('Finished readable')
  })


  rr.on("end", function () {
    // File has finished being read
    console.log('closing file')
  });

  rr.on("error", err => {
    // Some basic error handling for fs error events
    console.log('error', err);
  });
}

You will notice a reading flag. I have noticed that for some reason right near the end of the file the .on('readable') gets called a second time on small and large files. I am unsure why but this blocks that from a second process reading the same line items.

string sanitizer for filename

preg_replace("[^\w\s\d\.\-_~,;:\[\]\(\]]", '', $file)

Add/remove more valid characters depending on what is allowed for your system.

Alternatively you can try to create the file and then return an error if it's bad.

How can I check if two segments intersect?

Implemented in JAVA. However It seems that it does not work for co-linear lines (aka line segments that exist within each other L1(0,0)(10,10) L2(1,1)(2,2)

public class TestCode
{

  public class Point
  {
    public double x = 0;
    public double y = 0;
    public Point(){}
  }

  public class Line
  {
    public Point p1, p2;
    public Line( double x1, double y1, double x2, double y2) 
    {
      p1 = new Point();
      p2 = new Point();
      p1.x = x1;
      p1.y = y1;
      p2.x = x2;
      p2.y = y2;
    }
  }

  //line segments
  private static Line s1;
  private static Line s2;

  public TestCode()
  {
    s1 = new Line(0,0,0,10);
    s2 = new Line(-1,0,0,10);
  }

  public TestCode(double x1, double y1, 
    double x2, double y2,
    double x3, double y3,
    double x4, double y4)
  {
    s1 = new Line(x1,y1, x2,y2);
    s2 = new Line(x3,y3, x4,y4);
  }

  public static void main(String args[])
  {
     TestCode code  = null;
////////////////////////////
     code = new TestCode(0,0,0,10,
                         0,1,0,5);
     if( intersect(code) )
     { System.out.println( "OK COLINEAR: INTERSECTS" ); }
     else
     { System.out.println( "ERROR COLINEAR: DO NOT INTERSECT" ); }
////////////////////////////
     code = new TestCode(0,0,0,10,
                         0,1,0,10);
     if( intersect(code) )
     { System.out.println( "OK COLINEAR: INTERSECTS" ); }
     else
     { System.out.println( "ERROR COLINEAR: DO NOT INTERSECT" ); }
////////////////////////////
     code = new TestCode(0,0,10,0,
                         5,0,15,0);
     if( intersect(code) )
     { System.out.println( "OK COLINEAR: INTERSECTS" ); }
     else
     { System.out.println( "ERROR COLINEAR: DO NOT INTERSECT" ); }
////////////////////////////
     code = new TestCode(0,0,10,0,
                         0,0,15,0);
     if( intersect(code) )
     { System.out.println( "OK COLINEAR: INTERSECTS" ); }
     else
     { System.out.println( "ERROR COLINEAR: DO NOT INTERSECT" ); }

////////////////////////////
     code = new TestCode(0,0,10,10,
                         1,1,5,5);
     if( intersect(code) )
     { System.out.println( "OK COLINEAR: INTERSECTS" ); }
     else
     { System.out.println( "ERROR COLINEAR: DO NOT INTERSECT" ); }
////////////////////////////
     code = new TestCode(0,0,0,10,
                         -1,-1,0,10);
     if( intersect(code) )
     { System.out.println( "OK SLOPE END: INTERSECTS" ); }
     else
     { System.out.println( "ERROR SLOPE END: DO NOT INTERSECT" ); }
////////////////////////////
     code = new TestCode(-10,-10,10,10,
                         -10,10,10,-10);
     if( intersect(code) )
     { System.out.println( "OK SLOPE Intersect(0,0): INTERSECTS" ); }
     else
     { System.out.println( "ERROR SLOPE Intersect(0,0): DO NOT INTERSECT" ); }
////////////////////////////
     code = new TestCode(-10,-10,10,10,
                         -3,-2,50,-2);
     if( intersect(code) )
     { System.out.println( "OK SLOPE Line2 VERTIAL: INTERSECTS" ); }
     else
     { System.out.println( "ERROR SLOPE Line2 VERTICAL: DO NOT INTERSECT" ); }
////////////////////////////
     code = new TestCode(-10,-10,10,10,
                         50,-2,-3,-2);
     if( intersect(code) )
     { System.out.println( "OK SLOPE Line2 (reversed) VERTIAL: INTERSECTS" ); }
     else
     { System.out.println( "ERROR SLOPE Line2 (reversed) VERTICAL: DO NOT INTERSECT" ); }
////////////////////////////
     code = new TestCode(0,0,0,10,
                         1,0,1,10);
     if( intersect(code) )
     { System.out.println( "ERROR PARALLEL VERTICAL: INTERSECTS" ); }
     else
     { System.out.println( "OK PARALLEL VERTICAL: DO NOT INTERSECT" ); }
////////////////////////////
     code = new TestCode(0,2,10,2,
                         0,10,10,10);
     if( intersect(code) )
     { System.out.println( "ERROR PARALLEL HORIZONTAL: INTERSECTS" ); }
     else
     { System.out.println( "OK PARALLEL HORIZONTAL: DO NOT INTERSECT" ); }
////////////////////////////
     code = new TestCode(0,10,5,13.75,
                         0,18.75,10,15);
     if( intersect(code) )
     { System.out.println( "ERROR PARALLEL SLOPE=.75: INTERSECTS" ); }
     else
     { System.out.println( "OK PARALLEL SLOPE=.75: DO NOT INTERSECT" ); }
////////////////////////////
     code = new TestCode(0,0,1,1,
                         2,-1,2,10);
     if( intersect(code) )
     { System.out.println( "ERROR SEPERATE SEGMENTS: INTERSECTS" ); }
     else
     { System.out.println( "OK SEPERATE SEGMENTS: DO NOT INTERSECT" ); }
////////////////////////////
     code = new TestCode(0,0,1,1,
                         -1,-10,-5,10);
     if( intersect(code) )
     { System.out.println( "ERROR SEPERATE SEGMENTS 2: INTERSECTS" ); }
     else
     { System.out.println( "OK SEPERATE SEGMENTS 2: DO NOT INTERSECT" ); }
  }

  public static boolean intersect( TestCode code )
  {
    return intersect( code.s1, code.s2);
  }

  public static boolean intersect( Line line1, Line line2 )
  {
    double i1min = Math.min(line1.p1.x, line1.p2.x);
    double i1max = Math.max(line1.p1.x, line1.p2.x);
    double i2min = Math.min(line2.p1.x, line2.p2.x);
    double i2max = Math.max(line2.p1.x, line2.p2.x);

    double iamax = Math.max(i1min, i2min);
    double iamin = Math.min(i1max, i2max);

    if( Math.max(line1.p1.x, line1.p2.x) < Math.min(line2.p1.x, line2.p2.x) )
      return false;

    double m1 = (line1.p2.y - line1.p1.y) / (line1.p2.x - line1.p1.x );
    double m2 = (line2.p2.y - line2.p1.y) / (line2.p2.x - line2.p1.x );

    if( m1 == m2 )
        return false;

    //b1 = line1[0][1] - m1 * line1[0][0]
    //b2 = line2[0][1] - m2 * line2[0][0]
    double b1 = line1.p1.y - m1 * line1.p1.x;
    double b2 = line2.p1.y - m2 * line2.p1.x;
    double x1 = (b2 - b1) / (m1 - m2);
    if( (x1 < Math.max(i1min, i2min)) || (x1 > Math.min(i1max, i2max)) )
        return false;
    return true;
  }
}

Output thus far is

ERROR COLINEAR: DO NOT INTERSECT
ERROR COLINEAR: DO NOT INTERSECT
ERROR COLINEAR: DO NOT INTERSECT
ERROR COLINEAR: DO NOT INTERSECT
ERROR COLINEAR: DO NOT INTERSECT
OK SLOPE END: INTERSECTS
OK SLOPE Intersect(0,0): INTERSECTS
OK SLOPE Line2 VERTIAL: INTERSECTS
OK SLOPE Line2 (reversed) VERTIAL: INTERSECTS
OK PARALLEL VERTICAL: DO NOT INTERSECT
OK PARALLEL HORIZONTAL: DO NOT INTERSECT
OK PARALLEL SLOPE=.75: DO NOT INTERSECT
OK SEPERATE SEGMENTS: DO NOT INTERSECT
OK SEPERATE SEGMENTS 2: DO NOT INTERSECT

Get a worksheet name using Excel VBA

This works for me.

worksheetName = ActiveSheet.Name  

Open terminal here in Mac OS finder

If like me you turn off the Finder toolbar, this Service adds an item to every folder's contextual menu: http://blog.leenarts.net/2009/09/03/open-service-here/

This also allows you to open any folder you see in Finder tree view.

"column not allowed here" error in INSERT statement

Like Scaffman said - You are missing quotes. Always when you are passing a value to varchar2 use quotes

INSERT INTO LOCATION VALUES('PQ95VM','HAPPY_STREET','FRANCE');

So one (') starts the string and the second (') closes it.

But if you want to add a quote symbol into a string for example:

My father told me: 'you have to be brave, son'.

You have to use a triple quote symbol like:

'My father told me: ''you have to be brave, son''.'

*adding quote method can vary on different db engines

Improve INSERT-per-second performance of SQLite

I coudn't get any gain from transactions until I raised cache_size to a higher value i.e. PRAGMA cache_size=10000;

Moving from position A to position B slowly with animation

You can animate it after the fadeIn completes using the callback as shown below:

$("#Friends").fadeIn('slow',function(){
  $(this).animate({'top': '-=30px'},'slow');
});

How do I programmatically set device orientation in iOS 7?

This worked me perfectly....

NSNumber *value = [NSNumber numberWithInt:UIDeviceOrientationPortrait];
[[UIDevice currentDevice] setValue:value forKey:@"orientation"];

Difference between spring @Controller and @RestController annotation

  • @Controller is used to mark classes as Spring MVC Controller.
  • @RestController is a convenience annotation that does nothing more than adding the @Controller and @ResponseBody annotations (see: Javadoc)

So the following two controller definitions should do the same

@Controller
@ResponseBody
public class MyController { }

@RestController
public class MyRestController { }

handle textview link click in my android app

Coming at this almost a year later, there's a different manner in which I solved my particular problem. Since I wanted the link to be handled by my own app, there is a solution that is a bit simpler.

Besides the default intent filter, I simply let my target activity listen to ACTION_VIEW intents, and specifically, those with the scheme com.package.name

<intent-filter>
    <category android:name="android.intent.category.DEFAULT" />
    <action android:name="android.intent.action.VIEW" />
    <data android:scheme="com.package.name" />  
</intent-filter>

This means that links starting with com.package.name:// will be handled by my activity.

So all I have to do is construct a URL that contains the information I want to convey:

com.package.name://action-to-perform/id-that-might-be-needed/

In my target activity, I can retrieve this address:

Uri data = getIntent().getData();

In my example, I could simply check data for null values, because when ever it isn't null, I'll know it was invoked by means of such a link. From there, I extract the instructions I need from the url to be able to display the appropriate data.

What's the difference between setWebViewClient vs. setWebChromeClient?

From the source code:

// Instance of WebViewClient that is the client callback.
private volatile WebViewClient mWebViewClient;
// Instance of WebChromeClient for handling all chrome functions.
private volatile WebChromeClient mWebChromeClient;

// SOME OTHER SUTFFF.......

/**
 * Set the WebViewClient.
 * @param client An implementation of WebViewClient.
 */
public void setWebViewClient(WebViewClient client) {
    mWebViewClient = client;
}

/**
 * Set the WebChromeClient.
 * @param client An implementation of WebChromeClient.
 */
public void setWebChromeClient(WebChromeClient client) {
    mWebChromeClient = client;
}

Using WebChromeClient allows you to handle Javascript dialogs, favicons, titles, and the progress. Take a look of this example: Adding alert() support to a WebView

At first glance, there are too many differences WebViewClient & WebChromeClient. But, basically: if you are developing a WebView that won't require too many features but rendering HTML, you can just use a WebViewClient. On the other hand, if you want to (for instance) load the favicon of the page you are rendering, you should use a WebChromeClient object and override the onReceivedIcon(WebView view, Bitmap icon).

Most of the times, if you don't want to worry about those things... you can just do this:

webView= (WebView) findViewById(R.id.webview); 
webView.setWebChromeClient(new WebChromeClient()); 
webView.setWebViewClient(new WebViewClient()); 
webView.getSettings().setJavaScriptEnabled(true); 
webView.loadUrl(url); 

And your WebView will (in theory) have all features implemented (as the android native browser).

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

in my case I have used - (Hyphen) in my script name in case of Jenkinsfile Library. Got resolved after replacing Hyphen(-) with Underscore(_)

T-SQL Format integer to 2-digit string

Example for converting one digit number to two digit by adding 0 :

DECLARE @int INT = 9 
        SELECT CASE WHEN @int < 10
                    THEN FORMAT(CAST(@int AS INT),'0#')
               ELSE 
                   FORMAT(CAST(@int AS INT),'0')
               END

Is Constructor Overriding Possible?

method overriding in java is used to improve the recent code performance written previously .

some code like shows that here we are creating reference of base class and creating phyisical instance of the derived class. in constructors overloading is possible.

InputStream fis=new FileInputStream("a.txt");
int size=fis.available();

size will return the total number of bytes possible in a.txt so

Get PHP class property by string

Something like this? Haven't tested it but should work fine.

function magic($obj, $var, $value = NULL)
{
    if($value == NULL)
    {
        return $obj->$var;
    }
    else
    {
        $obj->$var = $value;
    }
}

How to get the current location in Google Maps Android API v2?

try this

LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = service.getBestProvider(criteria, false);
Location location = service.getLastKnownLocation(provider);
LatLng userLocation = new LatLng(location.getLatitude(),location.getLongitude());

ssh server connect to host xxx port 22: Connection timed out on linux-ubuntu

There can be many possible reasons for this failure.

Some are listed above. I faced the same issue, it is very hard to find the root cause of the failure.

I will recommend you to check the session timeout for shh from ssh_config file. Try to increase the session timeout and see if it fails again

Requests -- how to tell if you're getting a 404

Look at the r.status_code attribute:

if r.status_code == 404:
    # A 404 was issued.

Demo:

>>> import requests
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.status_code
404

If you want requests to raise an exception for error codes (4xx or 5xx), call r.raise_for_status():

>>> r = requests.get('http://httpbin.org/status/404')
>>> r.raise_for_status()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "requests/models.py", line 664, in raise_for_status
    raise http_error
requests.exceptions.HTTPError: 404 Client Error: NOT FOUND
>>> r = requests.get('http://httpbin.org/status/200')
>>> r.raise_for_status()
>>> # no exception raised.

You can also test the response object in a boolean context; if the status code is not an error code (4xx or 5xx), it is considered ‘true’:

if r:
    # successful response

If you want to be more explicit, use if r.ok:.

Can I escape html special chars in javascript?

You can encode every character in your string:

function encode(e){return e.replace(/[^]/g,function(e){return"&#"+e.charCodeAt(0)+";"})}

Or just target the main characters to worry about (&, inebreaks, <, >, " and ') like:

_x000D_
_x000D_
function encode(r){_x000D_
return r.replace(/[\x26\x0A\<>'"]/g,function(r){return"&#"+r.charCodeAt(0)+";"})_x000D_
}_x000D_
_x000D_
test.value=encode('How to encode\nonly html tags &<>\'" nice & fast!');_x000D_
_x000D_
/*************_x000D_
* \x26 is &ampersand (it has to be first),_x000D_
* \x0A is newline,_x000D_
*************/
_x000D_
<textarea id=test rows="9" cols="55">&#119;&#119;&#119;&#46;&#87;&#72;&#65;&#75;&#46;&#99;&#111;&#109;</textarea>
_x000D_
_x000D_
_x000D_

How do I line up 3 divs on the same row?

See my code

_x000D_
_x000D_
.float-left {_x000D_
    float:left;_x000D_
    width:300px; // or 33% for equal width independent of parent width_x000D_
}
_x000D_
<div>_x000D_
    <h2 align="center">San Andreas: Multiplayer</h2>_x000D_
    <div align="center" class="float-left">CONTENT OF COLUMN ONE GOES HERE</div>_x000D_
    <div align="center" class="float-left">CONTENT OF COLUMN TWO GOES HERE</div>_x000D_
    <div align="center" class="float-left">CONTENT OF COLUMN THREE GOES HERE</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Validating IPv4 addresses with regexp

This one matches only valid IPs (no prepended 0's, but it will match octets from 0-255 regardless of their 'function' [ie reserved, private, etc]) and allows for inline matching, where there may be spaces before and/or after the IP, or when using CIDR notation.

grep -E '(^| )((([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])($| |/)'

$ grep -E '(^| )((([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])($| |/)' <<< '10.0.1.2'
10.0.1.2

$ grep -E '(^| )((([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])($| |/)' <<< 'ip address 10.0.1.2'
ip address 10.0.1.2

$ grep -E '(^| )((([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])($| |/)' <<< 'ip address 10.0.1.2 255.255.255.255'
ip address 10.0.1.2 255.255.255.255

$ grep -E '(^| )((([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])($| |/)' <<< 'ip address 10.0.1.2/32'
ip address 10.0.1.2/32

$ grep -E '(^| )((([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])($| |/)' <<< 'ip address 10.0.1.2.32'
$

$ grep -E '(^| )((([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])($| |/)' <<< 'ip address10.0.1.2'
$

$ grep -E '(^| )((([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])($| |/)' <<< '10.0.1.256'
$

$ grep -E '(^| )((([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])($| |/)' <<< '0.0.0.0'
0.0.0.0

$ grep -E '(^| )((([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])($| |/)' <<< '255.255.255.255'
255.255.255.255

$ grep -E '(^| )((([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])($| |/)' <<< '255.255.255.256'
$

Of course, in cases where the IP is inline, you can use grep option "-o" and your preference of whitespace trimmer if you just want the whole IP and nothing but the IP.

For those of us using python, the equivalent is roughly:

>>> ipv4_regex = re.compile(r'(^| )((?:[1-9]?\d|1\d{2}|2[0-4]\d|25[0-5])\.){3}(?:[1-9]?\d|1\d{2}|2[0-4]\d|25[0-5])($| |/)')
>>> ipv4_regex.search('ip address 10.1.2.3/32')
<re.Match object; span=(10, 20), match=' 10.1.2.3/'>

If you're picky (lazy) like me, you probably would prefer to use grouping to get the whole IP and nothing but the IP, or the CIDR and nothing but the CIDR or some combination thereof. We can use (?P) syntax to name our groups for easier reference.

>>> ipv4_regex = re.compile(r'(?:^| )(?P<address>((?:[1-9]?\d|1\d{2}|2[0-4]\d|25[0-5])\.){3}(?:[1-9]?\d|1\d{2}|2[0-4]\d|25[0-5]))(?P<slash>/)?(?(slash)(?P<cidr>[0-9]|[12][0-9]|3[0-2]))(?:$| )')
>>> match = ipv4_regex.search('ip address 10.0.1.2/32')
>>> match.group('address')
'10.0.1.2'
>>> match.group('cidr')
'32'
>>> "".join((match.group('address'), match.group('slash'), match.group('cidr')))
'10.0.1.2/32'

There's ways of not using just regex, of course. Here's some conditions that you could check (this one doesn't find inline, just validates the passed address is valid).

First check is that each char in the address is a digit or a '.'

Next checking that there are exactly 3 '.'

The next two checks check that each octet is between 0 and 255.

And the last check is that no octets are prepended with a '0'

def validate_ipv4_address(address):
    return all(re.match('\.|\d', c) for c in address) \
        and address.count('.') == 3 \
        and all(0 <= int(octet) <= 255 for octet in address.split('.')) \
        and all((len(bin(int(octet))) <= 10 for octet in address.split('.'))) \
        and all(len(octet) == 1 or d[0] != '0' for octet in address.split('.'))


>>> validate_ipv4_address('255.255.255.255')
True
>>> validate_ipv4_address('10.0.0.1')
True
>>> validate_ipv4_address('01.01.01.01')
False
>>> validate_ipv4_address('123.456.789.0')
False
>>> validate_ipv4_address('0.0.0.0')
True
>>> validate_ipv4_address('-1.0.0.0')
False
>>> validate_ipv4_address('1.1.1.')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in validate_ipv4_address
  File "<stdin>", line 4, in <genexpr>
ValueError: invalid literal for int() with base 10: ''
>>> validate_ipv4_address('.1.1.1')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in validate_ipv4_address
  File "<stdin>", line 4, in <genexpr>
ValueError: invalid literal for int() with base 10: ''
>>> validate_ipv4_address('1..1.1')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in validate_ipv4_address
  File "<stdin>", line 4, in <genexpr>
ValueError: invalid literal for int() with base 10: ''

(bitwise, each octet should be 8 bits or less, but each is prepended with '0b')

>>> bin(0)
'0b0'
>>> len(bin(0))
3
>>> bin(255)
'0b11111111'
>>> len(bin(256))
11

Create HTML table using Javascript

In the html file there are three input boxes with userid,username,department respectively.

These inputboxes are used to get the input from the user.

The user can add any number of inputs to the page.

When clicking the button the script will enable the debugger mode.

In javascript, to enable the debugger mode, we have to add the following tag in the javascript.

/************************************************************************\

    Tools->Internet Options-->Advanced-->uncheck
    Disable script debugging(Internet Explorer)
    Disable script debugging(Other)

    <html xmlns="http://www.w3.org/1999/xhtml" >

    <head runat="server">

    <title>Dynamic Table</title>

    <script language="javascript" type="text/javascript">

    // <!CDATA[

    function CmdAdd_onclick() {

    var newTable,startTag,endTag;



    //Creating a new table

    startTag="<TABLE id='mainTable'><TBODY><TR><TD style=\"WIDTH: 120px\">User ID</TD>
    <TD style=\"WIDTH: 120px\">User Name</TD><TD style=\"WIDTH: 120px\">Department</TD></TR>"

    endTag="</TBODY></TABLE>"

    newTable=startTag;

    var trContents;

    //Get the row contents

    trContents=document.body.getElementsByTagName('TR');

    if(trContents.length>1)

    {

    for(i=1;i<trContents.length;i++)

    {

    if(trContents(i).innerHTML)

    {

    // Add previous rows

    newTable+="<TR>";

    newTable+=trContents(i).innerHTML;

    newTable+="</TR>";

    } 

    }

    }

    //Add the Latest row

    newTable+="<TR><TD style=\"WIDTH: 120px\" >" +
        document.getElementById('userid').value +"</TD>";

    newTable+="<TD style=\"WIDTH: 120px\" >" +
        document.getElementById('username').value +"</TD>";

    newTable+="<TD style=\"WIDTH: 120px\" >" +
        document.getElementById('department').value +"</TD><TR>";

    newTable+=endTag;

    //Update the Previous Table With New Table.

    document.getElementById('tableDiv').innerHTML=newTable;

    }

    // ]]>

    </script>

    </head>

    <body>

    <form id="form1" runat="server">

    <div>

    <br />

    <label>UserID</label> 

    <input id="userid" type="text" /><br />

    <label>UserName</label> 

    <input id="username" type="text" /><br />

    <label>Department</label> 

    <input id="department" type="text" />

    <center>

    <input id="CmdAdd" type="button" value="Add" onclick="return CmdAdd_onclick()" />
    </center>



    </div>

    <div id="tableDiv" style="text-align:center" >

    <table id="mainTable">

    <tr style="width:120px " >

    <td >User ID</td>

    <td>User Name</td>

    <td>Department</td>

    </tr>

    </table>

    </div>

    </form>

    </body>

    </html>

Is there a performance difference between i++ and ++i in C?

First of all: The difference between i++ and ++i is neglegible in C.


To the details.

1. The well known C++ issue: ++i is faster

In C++, ++i is more efficient iff i is some kind of an object with an overloaded increment operator.

Why?
In ++i, the object is first incremented, and can subsequently passed as a const reference to any other function. This is not possible if the expression is foo(i++) because now the increment needs to be done before foo() is called, but the old value needs to be passed to foo(). Consequently, the compiler is forced to make a copy of i before it executes the increment operator on the original. The additional constructor/destructor calls are the bad part.

As noted above, this does not apply to fundamental types.

2. The little known fact: i++ may be faster

If no constructor/destructor needs to be called, which is always the case in C, ++i and i++ should be equally fast, right? No. They are virtually equally fast, but there may be small differences, which most other answerers got the wrong way around.

How can i++ be faster?
The point is data dependencies. If the value needs to be loaded from memory, two subsequent operations need to be done with it, incrementing it, and using it. With ++i, the incrementation needs to be done before the value can be used. With i++, the use does not depend on the increment, and the CPU may perform the use operation in parallel to the increment operation. The difference is at most one CPU cycle, so it is really neglegible, but it is there. And it is the other way round then many would expect.

How do I upload a file to an SFTP server in C# (.NET)?

Following code shows how to upload a file to a SFTP server using our Rebex SFTP component.

// create client, connect and log in 
Sftp client = new Sftp();
client.Connect(hostname);
client.Login(username, password);

// upload the 'test.zip' file to the current directory at the server 
client.PutFile(@"c:\data\test.zip", "test.zip");

client.Disconnect();

You can write a complete communication log to a file using a LogWriter property as follows. Examples output (from FTP component but the SFTP output is similar) can be found here.

client.LogWriter = new Rebex.FileLogWriter(
   @"c:\temp\log.txt", Rebex.LogLevel.Debug); 

or intercept the communication using events as follows:

Sftp client = new Sftp();
client.CommandSent += new SftpCommandSentEventHandler(client_CommandSent);
client.ResponseRead += new SftpResponseReadEventHandler(client_ResponseRead);
client.Connect("sftp.example.org");

//... 
private void client_CommandSent(object sender, SftpCommandSentEventArgs e)
{
    Console.WriteLine("Command: {0}", e.Command);
}

private void client_ResponseRead(object sender, SftpResponseReadEventArgs e)
{
    Console.WriteLine("Response: {0}", e.Response);
}

For more info see tutorial or download a trial and check samples.

How to write a Unit Test?

Like @CoolBeans mentioned, take a look at jUnit. Here is a short tutorial to get you started as well with jUnit 4.x

Finally, if you really want to learn more about testing and test-driven development (TDD) I recommend you take a look at the following book by Kent Beck: Test-Driven Development By Example.

How to parse date string to Date?

String target = "27-09-1991 20:29:30";
DateFormat df = new SimpleDateFormat("dd MM yyyy HH:mm:ss");
Date result =  df.parse(target);
System.out.println(result); 

This works fine?

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

Just delete the Github repo and create a new one. By far the fastest, easiest and safest approach. After all, what do you have to gain carrying out all those commands in the accepted solution when all you want is the master branch with a single commit?

Returning JSON object from an ASP.NET page

If you get code behind, use some like this

        MyCustomObject myObject = new MyCustomObject();
        myObject.name='try';
        //OBJECT -> JSON
        var javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        string myObjectJson = javaScriptSerializer.Serialize(myObject);
        //return JSON   
        Response.Clear();     
        Response.ContentType = "application/json; charset=utf-8";
        Response.Write(myObjectJson );
        Response.End();

So you return a json object serialized with all attributes of MyCustomObject.

How do I attach events to dynamic HTML elements with jQuery?

After jQuery 1.7 the preferred methods are .on() and .off()

Sean's answer shows an example.

Now Deprecated:

Use the jQuery functions .live() and .die(). Available in jQuery 1.3.x

From the docs:

To display each paragraph's text in an alert box whenever it is clicked:

$("p").live("click", function(){
  alert( $(this).text() );
});

Also, the livequery plugin does this and has support for more events.

Creating a "Hello World" WebSocket example

I couldnt find a simple working example anywhere (as of Jan 19), so here is an updated version. I have chrome version 71.0.3578.98.

C# Websocket server :

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;

namespace WebSocketServer
{
    class Program
    {
    static Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
    static private string guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";

    static void Main(string[] args)
    {
        serverSocket.Bind(new IPEndPoint(IPAddress.Any, 8080));
        serverSocket.Listen(1); //just one socket
        serverSocket.BeginAccept(null, 0, OnAccept, null);
        Console.Read();
    }

    private static void OnAccept(IAsyncResult result)
    {
        byte[] buffer = new byte[1024];
        try
        {
            Socket client = null;
            string headerResponse = "";
            if (serverSocket != null && serverSocket.IsBound)
            {
                client = serverSocket.EndAccept(result);
                var i = client.Receive(buffer);
                headerResponse = (System.Text.Encoding.UTF8.GetString(buffer)).Substring(0, i);
                // write received data to the console
                Console.WriteLine(headerResponse);
                Console.WriteLine("=====================");
            }
            if (client != null)
            {
                /* Handshaking and managing ClientSocket */
                var key = headerResponse.Replace("ey:", "`")
                          .Split('`')[1]                     // dGhlIHNhbXBsZSBub25jZQ== \r\n .......
                          .Replace("\r", "").Split('\n')[0]  // dGhlIHNhbXBsZSBub25jZQ==
                          .Trim();

                // key should now equal dGhlIHNhbXBsZSBub25jZQ==
                var test1 = AcceptKey(ref key);

                var newLine = "\r\n";

                var response = "HTTP/1.1 101 Switching Protocols" + newLine
                     + "Upgrade: websocket" + newLine
                     + "Connection: Upgrade" + newLine
                     + "Sec-WebSocket-Accept: " + test1 + newLine + newLine
                     //+ "Sec-WebSocket-Protocol: chat, superchat" + newLine
                     //+ "Sec-WebSocket-Version: 13" + newLine
                     ;

                client.Send(System.Text.Encoding.UTF8.GetBytes(response));
                var i = client.Receive(buffer); // wait for client to send a message
                string browserSent = GetDecodedData(buffer, i);
                Console.WriteLine("BrowserSent: " + browserSent);

                Console.WriteLine("=====================");
                //now send message to client
                client.Send(GetFrameFromString("This is message from server to client."));
                System.Threading.Thread.Sleep(10000);//wait for message to be sent
            }
        }
        catch (SocketException exception)
        {
            throw exception;
        }
        finally
        {
            if (serverSocket != null && serverSocket.IsBound)
            {
                serverSocket.BeginAccept(null, 0, OnAccept, null);
            }
        }
    }

    public static T[] SubArray<T>(T[] data, int index, int length)
    {
        T[] result = new T[length];
        Array.Copy(data, index, result, 0, length);
        return result;
    }

    private static string AcceptKey(ref string key)
    {
        string longKey = key + guid;
        byte[] hashBytes = ComputeHash(longKey);
        return Convert.ToBase64String(hashBytes);
    }

    static SHA1 sha1 = SHA1CryptoServiceProvider.Create();
    private static byte[] ComputeHash(string str)
    {
        return sha1.ComputeHash(System.Text.Encoding.ASCII.GetBytes(str));
    }

    //Needed to decode frame
    public static string GetDecodedData(byte[] buffer, int length)
    {
        byte b = buffer[1];
        int dataLength = 0;
        int totalLength = 0;
        int keyIndex = 0;

        if (b - 128 <= 125)
        {
            dataLength = b - 128;
            keyIndex = 2;
            totalLength = dataLength + 6;
        }

        if (b - 128 == 126)
        {
            dataLength = BitConverter.ToInt16(new byte[] { buffer[3], buffer[2] }, 0);
            keyIndex = 4;
            totalLength = dataLength + 8;
        }

        if (b - 128 == 127)
        {
            dataLength = (int)BitConverter.ToInt64(new byte[] { buffer[9], buffer[8], buffer[7], buffer[6], buffer[5], buffer[4], buffer[3], buffer[2] }, 0);
            keyIndex = 10;
            totalLength = dataLength + 14;
        }

        if (totalLength > length)
            throw new Exception("The buffer length is small than the data length");

        byte[] key = new byte[] { buffer[keyIndex], buffer[keyIndex + 1], buffer[keyIndex + 2], buffer[keyIndex + 3] };

        int dataIndex = keyIndex + 4;
        int count = 0;
        for (int i = dataIndex; i < totalLength; i++)
        {
            buffer[i] = (byte)(buffer[i] ^ key[count % 4]);
            count++;
        }

        return Encoding.ASCII.GetString(buffer, dataIndex, dataLength);
    }

    //function to create  frames to send to client 
    /// <summary>
    /// Enum for opcode types
    /// </summary>
    public enum EOpcodeType
    {
        /* Denotes a continuation code */
        Fragment = 0,

        /* Denotes a text code */
        Text = 1,

        /* Denotes a binary code */
        Binary = 2,

        /* Denotes a closed connection */
        ClosedConnection = 8,

        /* Denotes a ping*/
        Ping = 9,

        /* Denotes a pong */
        Pong = 10
    }

    /// <summary>Gets an encoded websocket frame to send to a client from a string</summary>
    /// <param name="Message">The message to encode into the frame</param>
    /// <param name="Opcode">The opcode of the frame</param>
    /// <returns>Byte array in form of a websocket frame</returns>
    public static byte[] GetFrameFromString(string Message, EOpcodeType Opcode = EOpcodeType.Text)
    {
        byte[] response;
        byte[] bytesRaw = Encoding.Default.GetBytes(Message);
        byte[] frame = new byte[10];

        int indexStartRawData = -1;
        int length = bytesRaw.Length;

        frame[0] = (byte)(128 + (int)Opcode);
        if (length <= 125)
        {
            frame[1] = (byte)length;
            indexStartRawData = 2;
        }
        else if (length >= 126 && length <= 65535)
        {
            frame[1] = (byte)126;
            frame[2] = (byte)((length >> 8) & 255);
            frame[3] = (byte)(length & 255);
            indexStartRawData = 4;
        }
        else
        {
            frame[1] = (byte)127;
            frame[2] = (byte)((length >> 56) & 255);
            frame[3] = (byte)((length >> 48) & 255);
            frame[4] = (byte)((length >> 40) & 255);
            frame[5] = (byte)((length >> 32) & 255);
            frame[6] = (byte)((length >> 24) & 255);
            frame[7] = (byte)((length >> 16) & 255);
            frame[8] = (byte)((length >> 8) & 255);
            frame[9] = (byte)(length & 255);

            indexStartRawData = 10;
        }

        response = new byte[indexStartRawData + length];

        int i, reponseIdx = 0;

        //Add the frame bytes to the reponse
        for (i = 0; i < indexStartRawData; i++)
        {
            response[reponseIdx] = frame[i];
            reponseIdx++;
        }

        //Add the data bytes to the response
        for (i = 0; i < length; i++)
        {
            response[reponseIdx] = bytesRaw[i];
            reponseIdx++;
        }

        return response;
    }
}
}

Client html and javascript:

_x000D_
_x000D_
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"_x000D_
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
    <script type="text/javascript">_x000D_
        var socket = new WebSocket('ws://localhost:8080/websession');_x000D_
        socket.onopen = function() {_x000D_
           // alert('handshake successfully established. May send data now...');_x000D_
     socket.send("Hi there from browser.");_x000D_
        };_x000D_
  socket.onmessage = function (evt) {_x000D_
                //alert("About to receive data");_x000D_
                var received_msg = evt.data;_x000D_
                alert("Message received = "+received_msg);_x000D_
            };_x000D_
        socket.onclose = function() {_x000D_
            alert('connection closed');_x000D_
        };_x000D_
    </script>_x000D_
</head>_x000D_
<body>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How do you uninstall the package manager "pip", if installed from source?

That way you haven't installed pip, you installed just the easy_install i.e. setuptools.

First you should remove all the packages you installed with easy_install using (see uninstall):

easy_install -m PackageName

This includes pip if you installed it using easy_install pip.

After this you remove the setuptools following the instructions from here:

If setuptools package is found in your global site-packages directory, you may safely remove the following file/directory:

setuptools-*.egg

If setuptools is installed in some other location such as the user site directory (eg: ~/.local, ~/Library/Python or %APPDATA%), then you may safely remove the following files:

pkg_resources.py
easy_install.py
setuptools/
setuptools-*.egg-info/

Setting up a JavaScript variable from Spring model by using Thymeleaf

According to the documentation there are several ways to do the inlining.
The right way you must choose based on the situation.

1) Simply put the variable from server to javascript :

<script th:inline="javascript">
/*<![CDATA[*/

var message = [[${message}]];
alert(message);

/*]]>*/
</script>

2) Combine javascript variables with server side variables, e.g. you need to create link for requesting inside the javascript:

<script th:inline="javascript">
        /*<![CDATA[*/
        function sampleGetByJquery(v) {
            /*[+
            var url = [[@{/my/get/url(var1=${#httpServletRequest.getParameter('var1')})}]] 
                      + "&var2="+v;
             +]*/
            $("#myPanel").load(url, function() {});
        }
        /*]]>*/
        </script>

The one situation I can't resolve - then I need to pass javascript variable inside the Java method calling inside the template (it's impossible I guess).

How can you determine a point is between two other points on a line segment?

Using a more geometric approach, calculate the following distances:

ab = sqrt((a.x-b.x)**2 + (a.y-b.y)**2)
ac = sqrt((a.x-c.x)**2 + (a.y-c.y)**2)
bc = sqrt((b.x-c.x)**2 + (b.y-c.y)**2)

and test whether ac+bc equals ab:

is_on_segment = abs(ac + bc - ab) < EPSILON

That's because there are three possibilities:

  • The 3 points form a triangle => ac+bc > ab
  • They are collinear and c is outside the ab segment => ac+bc > ab
  • They are collinear and c is inside the ab segment => ac+bc = ab

remote: repository not found fatal: not found

Make sure your git username and password is correct. In my case, it gave error when the username and password(especially the GIT TOKEN) was not correct.

How to view Plugin Manager in Notepad++

It can be installed with one command for N++ installer version:

choco install notepadplusplus-nppPluginManager

"ssl module in Python is not available" when installing package with pip3

Agree with the answer by mastaBlasta. Worked for me. I encountered the same problem as the topic description.

Environment: MacOS Sierra. And I use Homebrew.

My solution:

  1. Reinstall openssl by brew uninstall openssl; brew install openssl
  2. According to the hints given by Homebrew, do the following:

    echo 'export PATH="/usr/local/opt/openssl/bin:$PATH"' >> ~/.bash_profile
    export LDFLAGS="-L/usr/local/opt/openssl/lib"
    export CPPFLAGS="-I/usr/local/opt/openssl/include"
    

Xcode error - Thread 1: signal SIGABRT

You are trying to load a XIB named DetailViewController, but no such XIB exists or it's not member of your current target.

Checking whether the pip is installed?

In CMD, type:

pip freeze

And it will show you a list of all the modules installed including the version number.

Output:

aiohttp==1.1.4
async-timeout==1.1.0
cx-Freeze==4.3.4
Django==1.9.2
django-allauth==0.24.1
django-cors-headers==1.2.2
django-crispy-forms==1.6.0
django-robots==2.0
djangorestframework==3.3.2
easygui==0.98.0
future==0.16.0
httpie==0.9.6
matplotlib==1.5.3
multidict==2.1.2
numpy==1.11.2
oauthlib==1.0.3
pandas==0.19.1
pefile==2016.3.28
pygame==1.9.2b1
Pygments==2.1.3
PyInstaller==3.2
pyparsing==2.1.10
pypiwin32==219
PyQt5==5.7
pytz==2016.7
requests==2.9.1
requests-oauthlib==0.6
six==1.10.0
sympy==1.0
virtualenv==15.0.3
xlrd==1.0.0
yarl==0.7.0

Why does writeObject throw java.io.NotSerializableException and how do I fix it?

java.io.NotSerializableException can occur when you serialize an inner class instance because:

serializing such an inner class instance will result in serialization of its associated outer class instance as well

Serialization of inner classes (i.e., nested classes that are not static member classes), including local and anonymous classes, is strongly discouraged

Ref: The Serializable Interface

Dataset - Vehicle make/model/year (free)

How about Freebase? I think they have an API available, too.

http://www.freebase.com/

How to resolve the "ADB server didn't ACK" error?

Similar questions are

First close IDE.

In my case I killed adb via Task Manager(adb kill-server did not work)
then adb start-server

  • daemon not running. starting it now on port 5037 *
  • daemon started successfully *

If you see "started successfully" than it is solved, now start IDE.

How to open a new tab using Selenium WebDriver

This code is working for me (Selenium 3.8.1, chromedriver 2.34.522940, and Chrome 63.0):

public void openNewTabInChrome() {

    driver.get("http://www.google.com");

    WebElement element = driver.findElement(By.linkText("Gmail"));
    Actions actionOpenLinkInNewTab = new Actions(driver);
    actionOpenLinkInNewTab.moveToElement(element)
            .keyDown(Keys.CONTROL) // MacOS: Keys.COMMAND
            .keyDown(Keys.SHIFT).click(element)
            .keyUp(Keys.CONTROL).keyUp(Keys.SHIFT).perform();


    ArrayList<String> tabs = new ArrayList(driver.getWindowHandles());
    driver.switchTo().window(tabs.get(1));
    driver.get("http://www.yahoo.com");
    //driver.close();
}

How to POST URL in data of a curl request

Perhaps you don't have to include the single quotes:

curl --request POST 'http://localhost/Service' --data "path=/xyz/pqr/test/&fileName=1.doc"

Update: Reading curl's manual, you could actually separate both fields with two --data:

curl --request POST 'http://localhost/Service' --data "path=/xyz/pqr/test/" --data "fileName=1.doc"

You could also try --data-binary:

curl --request POST 'http://localhost/Service' --data-binary "path=/xyz/pqr/test/" --data-binary "fileName=1.doc"

And --data-urlencode:

curl --request POST 'http://localhost/Service' --data-urlencode "path=/xyz/pqr/test/" --data-urlencode "fileName=1.doc"

including parameters in OPENQUERY

From the MSDN page:

OPENQUERY does not accept variables for its arguments

Fundamentally, this means you cannot issue a dynamic query. To achieve what your sample is attempting, try this:

SELECT * FROM 
   OPENQUERY([NameOfLinkedSERVER], 'SELECT * FROM TABLENAME') T1 
   INNER JOIN 
   MYSQLSERVER.DATABASE.DBO.TABLENAME T2 ON T1.PK = T2.PK 
where
   T1.field1 = @someParameter

Clearly if your TABLENAME table contains a large amount of data, this will go across the network too and performance might be poor. On the other hand, for a small amount of data, this works well and avoids the dynamic sql construction overheads (sql injection, escaping quotes) that an exec approach might require.

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack

Use this, works for me always.

Response.Redirect(Request.RawUrl, false);

Here, Response.Redirect(Request.RawUrl) simply redirects to the url of the current context, while the second parameter "false" indicates to either endResponse or not.

printing a value of a variable in postgresql

You can raise a notice in Postgres as follows:

raise notice 'Value: %', deletedContactId;

Read here

Eclipse: Error ".. overlaps the location of another project.." when trying to create new project

This too took me sometime to figure out.

Solution:

To create a new Maven Project under the existing workspace, just have the "Use default Workspace location" ticked (Ignore what is in the grayed out location text input).

The name of the project will be determined by you Artifact Id in step 2 of the creation wizard.

Reasoning:

It was so confusing because in my case, because when I selected to create a new Maven Project: the default workspace loaction is ticked and directly proceeding it is the grayed out "Location" text input had the workspace location + the existing project I was looking at before choose to create a new Maven Project. (ie: Location = '[workspace path]/last looked at project')

So I unticked the default workspace location box and entered in '[workspace path]/new project', which didn't work because eclipse expects the [workspace path] to be different compared to the default path. (Otherwise we would of selected the default workspace check box).

How do I pass a datetime value as a URI parameter in asp.net mvc?

Try to use toISOString(). It returns string in ISO8601 format.

from javascript

$.get('/example/doGet?date=' + new Date().toISOString(), function (result) {
    console.log(result);
});

from c#

[HttpGet]
public JsonResult DoGet(DateTime date)
{
    return Json(date.ToString(), JsonRequestBehavior.AllowGet);
}

How to deny access to a file in .htaccess

Well you could use the <Directory> tag for example:

<Directory /inscription>
  <Files log.txt>
    Order allow,deny
    Deny from all
  </Files>
</Directory>

Do not use ./ because if you just use / it looks at the root directory of your site.

For a more detailed example visit http://httpd.apache.org/docs/2.2/sections.html

How to generate all permutations of a list?

My Python Solution:

def permutes(input,offset):
    if( len(input) == offset ):
        return [''.join(input)]

    result=[]        
    for i in range( offset, len(input) ):
         input[offset], input[i] = input[i], input[offset]
         result = result + permutes(input,offset+1)
         input[offset], input[i] = input[i], input[offset]
    return result

# input is a "string"
# return value is a list of strings
def permutations(input):
    return permutes( list(input), 0 )

# Main Program
print( permutations("wxyz") )

Handling urllib2's timeout? - Python

In Python 2.7.3:

import urllib2
import socket

class MyException(Exception):
    pass

try:
    urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError as e:
    print type(e)    #not catch
except socket.timeout as e:
    print type(e)    #catched
    raise MyException("There was an error: %r" % e)

How to check undefined in Typescript

NOT STRICTLY RELATED TO TYPESCRIPT

Just to add to all the above answers, we can also use the shorthand syntax

var result = uemail || '';

This will give you the email if uemail variable has some value and it will simply return an empty string if uemail variable is undefined.

This gives a nice syntax for handling undefined variables and also provide a way to use a default value in case the variable is undefined.

How should I print types like off_t and size_t?

You'll want to use the formatting macros from inttypes.h.

See this question: Cross platform format string for variables of type size_t?

SQL: parse the first, middle and last name from a fullname field

Based on @hajili's contribution (which is a creative use of the parsename function, intended to parse the name of an object that is period-separated), I modified it so it can handle cases where the data doesn't containt a middle name or when the name is "John and Jane Doe". It's not 100% perfect but it's compact and might do the trick depending on the business case.

SELECT NAME,
CASE WHEN parsename(replace(NAME, ' ', '.'), 4) IS NOT NULL THEN 
   parsename(replace(NAME, ' ', '.'), 4) ELSE
    CASE WHEN parsename(replace(NAME, ' ', '.'), 3) IS NOT NULL THEN 
    parsename(replace(NAME, ' ', '.'), 3) ELSE
   parsename(replace(NAME, ' ', '.'), 2) end END as FirstName
   ,
CASE WHEN parsename(replace(NAME, ' ', '.'), 3) IS NOT NULL THEN 
   parsename(replace(NAME, ' ', '.'), 2) ELSE NULL END as MiddleName,
   parsename(replace(NAME, ' ', '.'), 1) as LastName
from  {@YourTableName}

Unable to execute dex: method ID not in [0, 0xffff]: 65536

I was facing the same issue today what worked for is below down

For ANDROID STUDIO... Enable Instant Run

In File->Preferences->Build, Execution, Deployment->Instant Run-> Check Enable Instant run for hot swap...

Hope it helps

Best Regular Expression for Email Validation in C#

This C# function uses a regular expression to evaluate whether the passed email address is syntactically valid or not.

public static bool isValidEmail(string inputEmail)
{
   string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
         @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" + 
         @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
   Regex re = new Regex(strRegex);
   if (re.IsMatch(inputEmail))
    return (true);
   else
    return (false);
}

How to remove the bottom border of a box with CSS

You could just set the width to auto. Then the width of the div will equal 0 if it has no content.

width:auto;

Node.js Generate html

You can use jade + express:

app.get('/', function (req, res) { res.render('index', { title : 'Home' } ) });

above you see 'index' and an object {title : 'Home'}, 'index' is your html and the object is your data that will be rendered in your html.

How to use the curl command in PowerShell?

In Powershell 3.0 and above there is both a Invoke-WebRequest and Invoke-RestMethod. Curl is actually an alias of Invoke-WebRequest in PoSH. I think using native Powershell would be much more appropriate than curl, but it's up to you :).

Invoke-WebRequest MSDN docs are here: https://technet.microsoft.com/en-us/library/hh849901.aspx?f=255&MSPPError=-2147217396

Invoke-RestMethod MSDN docs are here: https://technet.microsoft.com/en-us/library/hh849971.aspx?f=255&MSPPError=-2147217396

Why use a ReentrantLock if one can use synchronized(this)?

I think the wait/notify/notifyAll methods don't belong on the Object class as it pollutes all objects with methods that are rarely used. They make much more sense on a dedicated Lock class. So from this point of view, perhaps it's better to use a tool that is explicitly designed for the job at hand - ie ReentrantLock.

SQL JOIN - WHERE clause vs. ON clause

There is great difference between where clause vs. on clause, when it comes to left join.

Here is example:

mysql> desc t1; 
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int(11)     | NO   |     | NULL    |       |
| fid   | int(11)     | NO   |     | NULL    |       |
| v     | varchar(20) | NO   |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+

There fid is id of table t2.

mysql> desc t2;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int(11)     | NO   |     | NULL    |       |
| v     | varchar(10) | NO   |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

Query on "on clause" :

mysql> SELECT * FROM `t1` left join t2 on fid = t2.id AND t1.v = 'K' 
    -> ;
+----+-----+---+------+------+
| id | fid | v | id   | v    |
+----+-----+---+------+------+
|  1 |   1 | H | NULL | NULL |
|  2 |   1 | B | NULL | NULL |
|  3 |   2 | H | NULL | NULL |
|  4 |   7 | K | NULL | NULL |
|  5 |   5 | L | NULL | NULL |
+----+-----+---+------+------+
5 rows in set (0.00 sec)

Query on "where clause":

mysql> SELECT * FROM `t1` left join t2 on fid = t2.id where t1.v = 'K';
+----+-----+---+------+------+
| id | fid | v | id   | v    |
+----+-----+---+------+------+
|  4 |   7 | K | NULL | NULL |
+----+-----+---+------+------+
1 row in set (0.00 sec)

It is clear that, the first query returns a record from t1 and its dependent row from t2, if any, for row t1.v = 'K'.

The second query returns rows from t1, but only for t1.v = 'K' will have any associated row with it.

How do I set 'semi-bold' font via CSS? Font-weight of 600 doesn't make it look like the semi-bold I see in my Photoshop file

font-family: 'Open Sans'; font-weight: 600; important to change to a different font-family

Online SQL Query Syntax Checker

A lot of people, including me, use sqlfiddle.com to test SQL.

What's the best way to store Phone number in Django models

You might actually look into the internationally standardized format E.164, recommended by Twilio for example (who have a service and an API for sending SMS or phone-calls via REST requests).

This is likely to be the most universal way to store phone numbers, in particular if you have international numbers work with.

1. Phone by PhoneNumberField

You can use phonenumber_field library. It is port of Google's libphonenumber library, which powers Android's phone number handling https://github.com/stefanfoulis/django-phonenumber-field

In model:

from phonenumber_field.modelfields import PhoneNumberField

class Client(models.Model, Importable):
    phone = PhoneNumberField(null=False, blank=False, unique=True)

In form:

from phonenumber_field.formfields import PhoneNumberField
class ClientForm(forms.Form):
    phone = PhoneNumberField()

Get phone as string from object field:

    client.phone.as_e164 

Normolize phone string (for tests and other staff):

    from phonenumber_field.phonenumber import PhoneNumber
    phone = PhoneNumber.from_string(phone_number=raw_phone, region='RU').as_e164

2. Phone by regexp

One note for your model: E.164 numbers have a max character length of 15.

To validate, you can employ some combination of formatting and then attempting to contact the number immediately to verify.

I believe I used something like the following on my django project:

class ReceiverForm(forms.ModelForm):
    phone_number = forms.RegexField(regex=r'^\+?1?\d{9,15}$', 
                                error_message = ("Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed."))

EDIT

It appears that this post has been useful to some folks, and it seems worth it to integrate the comment below into a more full-fledged answer. As per jpotter6, you can do something like the following on your models as well:

models.py:

from django.core.validators import RegexValidator

class PhoneModel(models.Model):
    ...
    phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.")
    phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=True) # validators should be a list

What does it mean when MySQL is in the state "Sending data"?

In this state:

The thread is reading and processing rows for a SELECT statement, and sending data to the client.

Because operations occurring during this this state tend to perform large amounts of disk access (reads).

That's why it takes more time to complete and so is the longest-running state over the lifetime of a given query.

C# - using List<T>.Find() with custom objects

It's easy, just use list.Find(x => x.name == "stringNameOfObjectToFind");

How to implode array with key and value without foreach in PHP

There is also var_export and print_r more commonly known for printing debug output but both functions can take an optional argument to return a string instead.

Using the example from the question as data.

$array = ["item1"=>"object1", "item2"=>"object2","item-n"=>"object-n"];

Using print_r to turn the array into a string

This will output a human readable representation of the variable.

$string = print_r($array, true);
echo $string;

Will output:

Array
(
    [item1] => object1
    [item2] => object2
    [item-n] => object-n
)

Using var_export to turn the array into a string

Which will output a php string representation of the variable.

$string = var_export($array, true);
echo $string;

Will output:

array (
  'item1' => 'object1',
  'item2' => 'object2',
  'item-n' => 'object-n',
)

Because it is valid php we can evaluate it.

eval('$array2 = ' . var_export($array, true) . ';');
var_dump($array2 === $array);

Outputs:

bool(true)

Using OR & AND in COUNTIFS

There is probably a more efficient solution to your question, but following formula should do the trick:

=SUM(COUNTIFS(J1:J196,"agree",A1:A196,"yes"),COUNTIFS(J1:J196,"agree",A1:A196,"no"))

The import com.google.android.gms cannot be resolved

From my experience (Eclipse):

  1. Added google-play-services_lib as a project and referenced it from my app.
  2. Removed all jars added manually
  3. Added google-play-services.jar in the "libs" folder of my project.
  4. I had some big issues because I messed up with the Order and Export tab, so the working solution is (in this order): src, gen, Google APIs, Android Dependencies, Android Private Libraries (only this one checked to be exported).

pointer to array c++

j[0]; dereferences a pointer to int, so its type is int.

(*j)[0] has no type. *j dereferences a pointer to an int, so it returns an int, and (*j)[0] attempts to dereference an int. It's like attempting int x = 8; x[0];.

Getting fb.me URL

Facebook uses Bit.ly's services to shorten links from their site. While pages that have a username turns into "fb.me/<username>", other links associated with Facebook turns into "on.fb.me/*****". To you use the on.fb.me service, just use your Bit.ly account. Note that if you change the default link shortener on your Bit.ly account to j.mp from bit.ly this service won't work.

Is there a difference between PhoneGap and Cordova commands?

This first choice might be a confusing one but it’s really very simple. PhoneGap is a product owned by Adobe which currently includes additional build services, and it may or may not eventually offer additional services and/or charge payments for use in the future. Cordova is owned and maintained by Apache, and will always be maintained as an open source project. Currently they both have a very similar API. I would recommend going with Cordova, unless you require the additional PhoneGap build services.

Java Compare Two Lists

If you are looking for a handy way to test the equality of two collections, you can use org.apache.commons.collections.CollectionUtils.isEqualCollection, which compares two collections regardless of the ordering.

Is it possible to use raw SQL within a Spring Repository

It is also possible to use Spring Data JDBC repository, which is a community project built on top of Spring Data Commons to access to databases with raw SQL, without using JPA.

It is less powerful than Spring Data JPA, but if you want lightweight solution for simple projects without using a an ORM like Hibernate, that a solution worth to try.

What does 'Unsupported major.minor version 52.0' mean, and how do I fix it?

You don't need to change the compliance level here, or rather, you should but that's not the issue.

The code compliance ensures your code is compatible with a given Java version.

For instance, if you have a code compliance targeting Java 6, you can't use Java 7's or 8's new syntax features (e.g. the diamond, the lambdas, etc. etc.).

The actual issue here is that you are trying to compile something in a Java version that seems different from the project dependencies in the classpath.

Instead, you should check the JDK/JRE you're using to build.

In Eclipse, open the project properties and check the selected JRE in the Java build path.

If you're using custom Ant (etc.) scripts, you also want to take a look there, in case the above is not sufficient per se.

Appending values to dictionary in Python

vowels = ("a","e","i","o","u") #create a list of vowels  
my_str = ("this is my dog and a cat") # sample string to get the vowel count
count = {}.fromkeys(vowels,0) #create dict initializing the count to each vowel to 0                                                                    
for char in my_str :  
    if char in count:  
       count[char] += 1  

print(count)  

Convert System.Drawing.Color to RGB and Hex Value

I found an extension method that works quite well

public static string ToHex(this Color color)
{
    return String.Format("#{0}{1}{2}{3}"
        , color.A.ToString("X").Length == 1 ? String.Format("0{0}", color.A.ToString("X")) : color.A.ToString("X")
        , color.R.ToString("X").Length == 1 ? String.Format("0{0}", color.R.ToString("X")) : color.R.ToString("X")
        , color.G.ToString("X").Length == 1 ? String.Format("0{0}", color.G.ToString("X")) : color.G.ToString("X")
        , color.B.ToString("X").Length == 1 ? String.Format("0{0}", color.B.ToString("X")) : color.B.ToString("X"));
}

Ref: https://social.msdn.microsoft.com/Forums/en-US/4c77ba6c-6659-4a46-920a-7261dd4a15d0/how-to-convert-rgba-value-into-its-equivalent-hex-code?forum=winappswithcsharp

Iif equivalent in C#

It's limited in that you can't put statements in there. You can only put values(or things that return/evaluate to values), to return

This works ('a' is a static int within class Blah)

Blah.a=Blah.a<5?1:8;

(round brackets are impicitly between the equals and the question mark).

This doesn't work.

Blah.a = Blah.a < 4 ? Console.WriteLine("asdf") : Console.WriteLine("34er");
or
Blah.a = Blah.a < 4 ? MessageBox.Show("asdf") : MessageBox.Show("34er");

So you can only use the c# ternary operator for returning values. So it's not quite like a shortened form of an if. Javascript and perhaps some other languages let you put statements in there.

Get name of currently executing test in JUnit 4

Based on the previous comment and further considering I created an extension of TestWather which you can use in your JUnit test methods with this:

public class ImportUtilsTest {
    private static final Logger LOGGER = Logger.getLogger(ImportUtilsTest.class);

    @Rule
    public TestWatcher testWatcher = new JUnitHelper(LOGGER);

    @Test
    public test1(){
    ...
    }
}

The test helper class is the next:

public class JUnitHelper extends TestWatcher {
private Logger LOGGER;

public JUnitHelper(Logger LOGGER) {
    this.LOGGER = LOGGER;
}

@Override
protected void starting(final Description description) {
    LOGGER.info("STARTED " + description.getMethodName());
}

@Override
protected void succeeded(Description description) {
    LOGGER.info("SUCCESSFUL " + description.getMethodName());
}

@Override
protected void failed(Throwable e, Description description) {
    LOGGER.error("FAILURE " + description.getMethodName());
}
}

Enjoy!

IntelliJ inspection gives "Cannot resolve symbol" but still compiles code

Inconsistent/duplicate module names in project structure was causing this issue for me.

  1. Go to File -> Project Strucutre -> Modules
  2. In Click on modules which have red underline
  3. Got to "Dependencies" tab
  4. Make sure the dependencies which are red actually exist in dependency list. If not, rename them to match existing dependency names

This can happen when IntelliJ doesn't shut down properly and thus cannot properly save renamed module names.

path.join vs path.resolve with __dirname

Yes there is a difference between the functions but the way you are using them in this case will result in the same outcome.

path.join returns a normalized path by merging two paths together. It can return an absolute path, but it doesn't necessarily always do so.

For instance:

path.join('app/libs/oauth', '/../ssl')

resolves to app/libs/ssl

path.resolve, on the other hand, will resolve to an absolute path.

For instance, when you run:

path.resolve('bar', '/foo');

The path returned will be /foo since that is the first absolute path that can be constructed.

However, if you run:

path.resolve('/bar/bae', '/foo', 'test');

The path returned will be /foo/test again because that is the first absolute path that can be formed from right to left.

If you don't provide a path that specifies the root directory then the paths given to the resolve function are appended to the current working directory. So if your working directory was /home/mark/project/:

path.resolve('test', 'directory', '../back');

resolves to

/home/mark/project/test/back

Using __dirname is the absolute path to the directory containing the source file. When you use path.resolve or path.join they will return the same result if you give the same path following __dirname. In such cases it's really just a matter of preference.

How can I solve equations in Python?

How about SymPy? Their solver looks like what you need. Have a look at their source code if you want to build the library yourself…

C++ Compare char array with string

You're not working with strings. You're working with pointers. var1 is a char pointer (const char*). It is not a string. If it is null-terminated, then certain C functions will treat it as a string, but it is fundamentally just a pointer.

So when you compare it to a char array, the array decays to a pointer as well, and the compiler then tries to find an operator == (const char*, const char*).

Such an operator does exist. It takes two pointers and returns true if they point to the same address. So the compiler invokes that, and your code breaks.

IF you want to do string comparisons, you have to tell the compiler that you want to deal with strings, not pointers.

The C way of doing this is to use the strcmp function:

strcmp(var1, "dev");

This will return zero if the two strings are equal. (It will return a value greater than zero if the left-hand side is lexicographically greater than the right hand side, and a value less than zero otherwise.)

So to compare for equality you need to do one of these:

if (!strcmp(var1, "dev")){...}
if (strcmp(var1, "dev") == 0) {...}

However, C++ has a very useful string class. If we use that your code becomes a fair bit simpler. Of course we could create strings from both arguments, but we only need to do it with one of them:

std::string var1 = getenv("myEnvVar");

if(var1 == "dev")
{
   // do stuff
}

Now the compiler encounters a comparison between string and char pointer. It can handle that, because a char pointer can be implicitly converted to a string, yielding a string/string comparison. And those behave exactly as you'd expect.

How to clear PermGen space Error in tomcat

You have to allocate more space to the PermGenSpace of the tomcat JVM.

This can be done with the JVM argument : -XX:MaxPermSize=128m

By default, the PermGen space is 64M (and it contains all compiled classes, so if you have a lot of jar (classes) in your classpath, you may indeed fill this space).

On a side note, you can monitor the size of the PermGen space with JVisualVM and you can even inspect its content with YourKit Java Profiler

Django DateField default options

This is why you should always import the base datetime module: import datetime, rather than the datetime class within that module: from datetime import datetime.

The other mistake you have made is to actually call the function in the default, with the (). This means that all models will get the date at the time the class is first defined - so if your server stays up for days or weeks without restarting Apache, all elements will get same the initial date.

So the field should be:

import datetime
date = models.DateField(_("Date"), default=datetime.date.today)

How to set up default schema name in JPA configuration?

For others who use spring-boot, java based configuration,

I set the schema value in application.properties

spring.jpa.properties.hibernate.dialect=...
spring.jpa.properties.hibernate.default_schema=...

Chrome not rendering SVG referenced via <img> tag

I make sure that I add the Style of the Image. It worked for me

style= "width:320; height:240"

Drawing a dot on HTML5 canvas

This should do the job

//get a reference to the canvas
var ctx = $('#canvas')[0].getContext("2d");

//draw a dot
ctx.beginPath();
ctx.arc(20, 20, 10, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();

Make file echo displaying "$PATH" string

The make uses the $ for its own variable expansions. E.g. single character variable $A or variable with a long name - ${VAR} and $(VAR).

To put the $ into a command, use the $$, for example:

all:
  @echo "Please execute next commands:"
  @echo 'setenv PATH /usr/local/greenhills/mips5/linux86:$$PATH'

Also note that to make the "" and '' (double and single quoting) do not play any role and they are passed verbatim to the shell. (Remove the @ sign to see what make sends to shell.) To prevent the shell from expanding $PATH, second line uses the ''.

Array formula on Excel for Mac

  1. Select the desired range of cells
  2. Press Fn + F2 or CONTROL + U
  3. Paste in your array value
  4. Press COMMAND (?) + SHIFT + RETURN

How to create a dump with Oracle PL/SQL Developer?

EXP (export) and IMP (import) are the two tools you need. It's is better to try to run these on the command line and on the same machine.

It can be run from remote, you just need to setup you TNSNAMES.ORA correctly and install all the developer tools with the same version as the database. Without knowing the error message you are experiencing then I can't help you to get exp/imp to work.

The command to export a single user:

exp userid=dba/dbapassword OWNER=username DIRECT=Y FILE=filename.dmp

This will create the export dump file.

To import the dump file into a different user schema, first create the newuser in SQLPLUS:

SQL> create user newuser identified by 'password' quota unlimited users;

Then import the data:

imp userid=dba/dbapassword FILE=filename.dmp FROMUSER=username TOUSER=newusername

If there is a lot of data then investigate increasing the BUFFERS or look into expdp/impdp

Most common errors for exp and imp are setup. Check your PATH includes $ORACLE_HOME/bin, check $ORACLE_HOME is set correctly and check $ORACLE_SID is set

Spring Boot Adding Http Request Interceptors

I had the same issue of WebMvcConfigurerAdapter being deprecated. When I searched for examples, I hardly found any implemented code. Here is a piece of working code.

create a class that extends HandlerInterceptorAdapter

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import me.rajnarayanan.datatest.DataTestApplication;
@Component
public class EmployeeInterceptor extends HandlerInterceptorAdapter {
    private static final Logger logger = LoggerFactory.getLogger(DataTestApplication.class);
    @Override
    public boolean preHandle(HttpServletRequest request, 
            HttpServletResponse response, Object handler) throws Exception {

            String x = request.getMethod();
            logger.info(x + "intercepted");
        return true;
    }

}

then Implement WebMvcConfigurer interface

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import me.rajnarayanan.datatest.interceptor.EmployeeInterceptor;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Autowired
    EmployeeInterceptor employeeInterceptor ;

    @Override
    public void addInterceptors(InterceptorRegistry registry){
        registry.addInterceptor(employeeInterceptor).addPathPatterns("/employee");
    }
}

disable a hyperlink using jQuery

function EnableHyperLink(id) {
        $('#' + id).attr('onclick', 'Pagination("' + id + '")');//onclick event which u 
        $('#' + id).addClass('enable-link');
        $('#' + id).removeClass('disable-link');
    }

    function DisableHyperLink(id) {
        $('#' + id).addClass('disable-link');
        $('#' + id).removeClass('enable-link');
        $('#' + id).removeAttr('onclick');
    }

.disable-link
{
    text-decoration: none !important;
    color: black !important;
    cursor: default;
}
.enable-link
{
    text-decoration: underline !important;
    color: #075798 !important;
    cursor: pointer !important;
}

Android Studio - Failed to notify project evaluation listener error

Just Change the Distribution url at gradle-wrapper.properties

Place it : https://services.gradle.org/distributions/gradle-4.10.1-all.zip

How to add a footer to the UITableView?

Initially I was just trying the method:

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section

but after using this along with:

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section

problem was solved. Sample Program-

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 30.0f;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *sampleView = [[UIView alloc] init];
    sampleView.frame = CGRectMake(SCREEN_WIDTH/2, 5, 60, 4);
    sampleView.backgroundColor = [UIColor blackColor];
    return sampleView;
}

and include UITableViewDelegate protocol.

@interface TestViewController : UIViewController <UITableViewDelegate>

Error in plot.new() : figure margins too large in R

I had this error when I was trying to plot high dimensional data. If that's what is going on with you, try multidimensional scaling: http://www.statmethods.net/advstats/mds.html

Hibernate, @SequenceGenerator and allocationSize

allocationSize=1 It is a micro optimization before getting query Hibernate tries to assign value in the range of allocationSize and so try to avoid querying database for sequence. But this query will be executed every time if you set it to 1. This hardly makes any difference since if your data base is accessed by some other application then it will create issues if same id is used by another application meantime .

Next generation of Sequence Id is based on allocationSize.

By defualt it is kept as 50 which is too much. It will also only help if your going to have near about 50 records in one session which are not persisted and which will be persisted using this particular session and transation.

So you should always use allocationSize=1 while using SequenceGenerator. As for most of underlying databases sequence is always incremented by 1.

Recursion or Iteration?

Recursion is very useful is some situations. For example consider the code for finding the factorial

int factorial ( int input )
{
  int x, fact = 1;
  for ( x = input; x > 1; x--)
     fact *= x;
  return fact;
}

Now consider it by using the recursive function

int factorial ( int input )
{
  if (input == 0)
  {
     return 1;
  }
  return input * factorial(input - 1);
}

By observing these two, we can see that recursion is easy to understand. But if it is not used with care it can be so much error prone too. Suppose if we miss if (input == 0), then the code will be executed for some time and ends with usually a stack overflow.

Android Recyclerview vs ListView with Viewholder

I used a ListView with Glide image loader, having memory growth. Then I replaced the ListView with a RecyclerView. It is not only more difficult in coding, but also leads to a more memory usage than a ListView. At least, in my project.

In another activity I used a complex list with EditText's. In some of them an input method may vary, also a TextWatcher can be applied. If I used a ViewHolder, how could I replace a TextWatcher during scrolling? So, I used a ListView without a ViewHolder, and it works.

Popup window in winform c#

Just create another form (let's call it formPopup) using Visual Studio. In a button handler write the following code:

var formPopup = new Form();
formPopup.Show(this); // if you need non-modal window

If you need a non-modal window use: formPopup.Show();. If you need a dialog (so your code will hang on this invocation until you close the opened form) use: formPopup.ShowDialog()

How to configure log4j to only keep log files for the last seven days?

My script based on @dogbane's answer

/etc/cron.daily/hbase

#!/bin/sh
find /var/log/hbase -type f -name "phoenix-hbase-server.log.[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]" -exec bzip2 {} ";"
find /var/log/hbase -type f -regex ".*.out.[0-9][0-9]?" -exec bzip2 {} ";"
find /var/log/hbase -type f -mtime +7 -name "*.bz2" -exec rm -f {} ";"

/etc/cron.daily/tomcat

#!/bin/sh
find /opt/tomcat/log/ -type f -mtime +1 -name "*.[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9].*log" -exec bzip2 {} ";"
find /opt/tomcat/log/ -type f -mtime +1 -name "*.[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9].txt" -exec bzip2 {} ";"
find /opt/tomcat/log/ -type f -mtime +7 -name "*.bz2" -exec rm -f {} ";"

because Tomcat rotate needs one day delay.

How to recognize swipe in all 4 directions

I just felt like contributing this, looks more elegant in the end:

func addSwipe() {
    let directions: [UISwipeGestureRecognizerDirection] = [.Right, .Left, .Up, .Down]
    for direction in directions {
        let gesture = UISwipeGestureRecognizer(target: self, action: Selector("handleSwipe:"))
        gesture.direction = direction
        self.addGestureRecognizer(gesture)
    }
}

func handleSwipe(sender: UISwipeGestureRecognizer) {
    print(sender.direction)
}

How to get full path of a file?

Works on Mac, Linux, *nix:

This will give you a quoted csv of all files in the current dir:

ls | xargs -I {} echo "$(pwd -P)/{}" | xargs | sed 's/ /","/g'

The output of this can be easily copied into a python list or any similar data structure.

.NET console application as Windows service

I've had great success with TopShelf.

TopShelf is a Nuget package designed to make it easy to create .NET Windows apps that can run as console apps or as Windows Services. You can quickly hook up events such as your service Start and Stop events, configure using code e.g. to set the account it runs as, configure dependencies on other services, and configure how it recovers from errors.

From the Package Manager Console (Nuget):

Install-Package Topshelf

Refer to the code samples to get started.

Example:

HostFactory.Run(x =>                                 
{
    x.Service<TownCrier>(s =>                        
    {
       s.ConstructUsing(name=> new TownCrier());     
       s.WhenStarted(tc => tc.Start());              
       s.WhenStopped(tc => tc.Stop());               
    });
    x.RunAsLocalSystem();                            

    x.SetDescription("Sample Topshelf Host");        
    x.SetDisplayName("Stuff");                       
    x.SetServiceName("stuff");                       
}); 

TopShelf also takes care of service installation, which can save a lot of time and removes boilerplate code from your solution. To install your .exe as a service you just execute the following from the command prompt:

myservice.exe install -servicename "MyService" -displayname "My Service" -description "This is my service."

You don't need to hook up a ServiceInstaller and all that - TopShelf does it all for you.

<code> vs <pre> vs <samp> for inline and block code snippets

This works for me to display code in frontend:

<style>
.content{
    height:50vh;
    width: 100%;
    background: transparent;
    border: none;
    border-radius: 0;
    resize: none;
    outline: none;
}
.content:focus{
    border: none;
    -webkit-box-shadow: none;
    -moz-box-shadow: none;
    box-shadow: none;
}
</style>

<textarea class="content">
<div>my div</div><p>my paragraph</p>
</textarea>

View Live Demo: https://jsfiddle.net/bytxj50e/

How to identify numpy types in python?

Old question but I came up with a definitive answer with an example. Can't hurt to keep questions fresh as I had this same problem and didn't find a clear answer. The key is to make sure you have numpy imported, and then run the isinstance bool. While this may seem simple, if you are doing some computations across different data types, this small check can serve as a quick test before your start some numpy vectorized operation.

##################
# important part!
##################

import numpy as np

####################
# toy array for demo
####################

arr = np.asarray(range(1,100,2))

########################
# The instance check
######################## 

isinstance(arr,np.ndarray)

500 Error on AppHarbor but downloaded build works on my machine

Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.

So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.

Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.

Convert a list of characters into a string

besides str.join which is the most natural way, a possibility is to use io.StringIO and abusing writelines to write all elements in one go:

import io

a = ['a','b','c','d']

out = io.StringIO()
out.writelines(a)
print(out.getvalue())

prints:

abcd

When using this approach with a generator function or an iterable which isn't a tuple or a list, it saves the temporary list creation that join does to allocate the right size in one go (and a list of 1-character strings is very expensive memory-wise).

If you're low in memory and you have a lazily-evaluated object as input, this approach is the best solution.

How can I escape white space in a bash loop list?

I use

SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
for f in $( find "$1" -type d ! -path "$1" )
do
  echo $f
done
IFS=$SAVEIFS

Wouldn't that be enough?
Idea taken from http://www.cyberciti.biz/tips/handling-filenames-with-spaces-in-bash.html

CSS performance relative to translateZ(0)

If you want implications, in some scenarios Google Chrome performance is horrible with hardware acceleration enabled. Oddly enough, changing the "trick" to -webkit-transform: rotateZ(360deg); worked just fine.

I don't believe we ever figured out why.

How to represent e^(-t^2) in MATLAB?

All the 3 first ways are identical. You have make sure that if t is a matrix you add . before using multiplication or the power.

for matrix:

t= [1 2 3;2 3 4;3 4 5];
tp=t.*t;
x=exp(-(t.^2));
y=exp(-(t.*t));
z=exp(-(tp));

gives the results:

x =

0.3679    0.0183    0.0001
0.0183    0.0001    0.0000
0.0001    0.0000    0.0000

y =

0.3679    0.0183    0.0001
0.0183    0.0001    0.0000
0.0001    0.0000    0.0000

z=

0.3679    0.0183    0.0001
0.0183    0.0001    0.0000
0.0001    0.0000    0.0000

And using a scalar:

p=3;
pp=p^2;
x=exp(-(p^2));
y=exp(-(p*p));
z=exp(-pp);

gives the results:

x =

1.2341e-004

y =

1.2341e-004

z =

1.2341e-004

How to escape indicator characters (i.e. : or - ) in YAML

Quotes, but I prefer them on the just the value:

url: "http://www.example.com/"

Putting them across the whole line looks like it might cause problems.

Modify property value of the objects in list using Java 8 streams

You can use just forEach. No stream at all:

fruits.forEach(fruit -> fruit.setName(fruit.getName() + "s"));

Environment variable to control java.io.tmpdir?

You could set your _JAVA_OPTIONS environmental variable. For example in bash this would do the trick:

export _JAVA_OPTIONS=-Djava.io.tmpdir=/new/tmp/dir

I put that into my bash login script and it seems to do the trick.

How to build a 'release' APK in Android Studio?

AndroidStudio is alpha version for now. So you have to edit gradle build script files by yourself. Add next lines to your build.gradle

android {

    signingConfigs {

        release {

            storeFile file('android.keystore')
            storePassword "pwd"
            keyAlias "alias"
            keyPassword "pwd"
        }
    }

    buildTypes {

       release {

           signingConfig signingConfigs.release
       }
    }
}

To actually run your application at emulator or device run gradle installDebug or gradle installRelease.

You can create helloworld project from AndroidStudio wizard to see what structure of gradle files is needed. Or export gradle files from working eclipse project. Also this series of articles are helpfull http://blog.stylingandroid.com/archives/1872#more-1872

How to use z-index in svg elements?

There is no z-index for svgs. But svg determines which of your elements are the uppermost by theire position in the DOM. Thus you can remove the Object and place it to the end of the svg making it the "last rendered" element. That one is then rendered "topmost" visually.


Using jQuery:

function moveUp(thisObject){
    thisObject.appendTo(thisObject.parents('svg>g'));
}

usage:

moveUp($('#myTopElement'));

Using D3.js:

d3.selection.prototype.moveUp = function() {
    return this.each(function() {
        this.parentNode.appendChild(this);
    });
};

usage:

myTopElement.moveUp();

System.IO.IOException: file used by another process

The code works as best I can tell. I would fire up Sysinternals process explorer and find out what is holding the file open. It might very well be Visual Studio.

What does "connection reset by peer" mean?

This means that a TCP RST was received and the connection is now closed. This occurs when a packet is sent from your end of the connection but the other end does not recognize the connection; it will send back a packet with the RST bit set in order to forcibly close the connection.

This can happen if the other side crashes and then comes back up or if it calls close() on the socket while there is data from you in transit, and is an indication to you that some of the data that you previously sent may not have been received.

It is up to you whether that is an error; if the information you were sending was only for the benefit of the remote client then it may not matter that any final data may have been lost. However you should close the socket and free up any other resources associated with the connection.

'names' attribute must be the same length as the vector

I have seen such error and i solved it. You may have missing values in your data set. Number of observations in every column must also be the same.

Is calling destructor manually always a sign of bad design?

I have never come across a situation where one needs to call a destructor manually. I seem to remember even Stroustrup claims it is bad practice.

WPF - add static items to a combo box

<ComboBox Text="Something">
            <ComboBoxItem Content="Item1"></ComboBoxItem >
            <ComboBoxItem Content="Item2"></ComboBoxItem >
            <ComboBoxItem Content="Item3"></ComboBoxItem >
</ComboBox>

How do I join two SQLite tables in my Android application?

"Ambiguous column" usually means that the same column name appears in at least two tables; the database engine can't tell which one you want. Use full table names or table aliases to remove the ambiguity.

Here's an example I happened to have in my editor. It's from someone else's problem, but should make sense anyway.

select P.* 
from product_has_image P
inner join highest_priority_images H 
        on (H.id_product = P.id_product and H.priority = p.priority)

How do you run a Python script as a service in Windows?

pysc: Service Control Manager on Python

Example script to run as a service taken from pythonhosted.org:

from xmlrpc.server import SimpleXMLRPCServer

from pysc import event_stop


class TestServer:

    def echo(self, msg):
        return msg


if __name__ == '__main__':
    server = SimpleXMLRPCServer(('127.0.0.1', 9001))

    @event_stop
    def stop():
        server.server_close()

    server.register_instance(TestServer())
    server.serve_forever()

Create and start service

import os
import sys
from xmlrpc.client import ServerProxy

import pysc


if __name__ == '__main__':
    service_name = 'test_xmlrpc_server'
    script_path = os.path.join(
        os.path.dirname(__file__), 'xmlrpc_server.py'
    )
    pysc.create(
        service_name=service_name,
        cmd=[sys.executable, script_path]
    )
    pysc.start(service_name)

    client = ServerProxy('http://127.0.0.1:9001')
    print(client.echo('test scm'))

Stop and delete service

import pysc

service_name = 'test_xmlrpc_server'

pysc.stop(service_name)
pysc.delete(service_name)
pip install pysc

How to serialize Joda DateTime with Jackson JSON processor?

This has become very easy with Jackson 2.0 and the Joda module.

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JodaModule());

Maven dependency:

<dependency>
  <groupId>com.fasterxml.jackson.datatype</groupId>
  <artifactId>jackson-datatype-joda</artifactId>
  <version>2.1.1</version>
</dependency>  

Code and documentation: https://github.com/FasterXML/jackson-datatype-joda

Binaries: http://repo1.maven.org/maven2/com/fasterxml/jackson/datatype/jackson-datatype-joda/

<script> tag vs <script type = 'text/javascript'> tag

In HTML 4, the type attribute is required. In my experience, all browsers will default to text/javascript if it is absent, but that behaviour is not defined anywhere. While you can in theory leave it out and assume it will be interpreted as JavaScript, it's invalid HTML, so why not add it.

In HTML 5, the type attribute is optional and defaults to text/javascript

Use <script type="text/javascript"> or simply <script> (if omitted, the type is the same). Do not use <script language="JavaScript">; the language attribute is deprecated

Ref :
http://social.msdn.microsoft.com/Forums/vstudio/en-US/65aaf5f3-09db-4f7e-a32d-d53e9720ad4c/script-languagejavascript-or-script-typetextjavascript-?forum=netfxjscript
and
Difference between <script> tag with type and <script> without type?

Do you need type attribute at all?

I am using HTML5- No

I am not using HTML5 - Yes

PHP: Call to undefined function: simplexml_load_string()

I also faced this issue. My Operating system is Ubuntu 18.04 and my PHP version is PHP 7.2.

Here's how I solved it:

Install Simplexml on your Ubuntu Server:

sudo apt-get install php7.2-simplexml

Restart Apache Server

sudo systemctl restart apache2

That's all.

I hope this helps

How to Ping External IP from Java Android

This is a simple ping I use in one of the projects:

public static class Ping {
    public String net = "NO_CONNECTION";
    public String host = "";
    public String ip = "";
    public int dns = Integer.MAX_VALUE;
    public int cnt = Integer.MAX_VALUE;
}

public static Ping ping(URL url, Context ctx) {
    Ping r = new Ping();
    if (isNetworkConnected(ctx)) {
        r.net = getNetworkType(ctx);
        try {
            String hostAddress;
            long start = System.currentTimeMillis();
            hostAddress = InetAddress.getByName(url.getHost()).getHostAddress();
            long dnsResolved = System.currentTimeMillis();
            Socket socket = new Socket(hostAddress, url.getPort());
            socket.close();
            long probeFinish = System.currentTimeMillis();
            r.dns = (int) (dnsResolved - start);
            r.cnt = (int) (probeFinish - dnsResolved);
            r.host = url.getHost();
            r.ip = hostAddress;
        }
        catch (Exception ex) {
            Timber.e("Unable to ping");
        }
    }
    return r;
}

public static boolean isNetworkConnected(Context context) {
    ConnectivityManager cm =
            (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}

@Nullable
public static String getNetworkType(Context context) {
    ConnectivityManager cm =
            (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (activeNetwork != null) {
        return activeNetwork.getTypeName();
    }
    return null;
}

Usage: ping(new URL("https://www.google.com:443/"), this);

Result: {"cnt":100,"dns":109,"host":"www.google.com","ip":"212.188.10.114","net":"WIFI"}

How to add parameters to a HTTP GET request in Android?

To build uri with get parameters, Uri.Builder provides a more effective way.

Uri uri = new Uri.Builder()
    .scheme("http")
    .authority("foo.com")
    .path("someservlet")
    .appendQueryParameter("param1", foo)
    .appendQueryParameter("param2", bar)
    .build();

background:none vs background:transparent what is the difference?

To complement the other answers: if you want to reset all background properties to their initial value (which includes background-color: transparent and background-image: none) without explicitly specifying any value such as transparent or none, you can do so by writing:

background: initial;

How to get all registered routes in Express?

Within your app at /routes display your express route names

app.get('/routes', (req, res) => {
    res.send(app._router.stack
        .filter(r => r.route) 
        .map(r => r.route.path))
})

http://localhost:3000/routes

How to communicate between iframe and the parent site?

With different domains, it is not possible to call methods or access the iframe's content document directly.

You have to use cross-document messaging.

For example in the top window:

 myIframe.contentWindow.postMessage('hello', '*');

and in the iframe:

window.onmessage = function(e){
    if (e.data == 'hello') {
        alert('It works!');
    }
};

If you are posting message from iframe to parent window

window.top.postMessage('hello', '*')

How to delete all files and folders in a directory?

private void ClearFolder(string FolderName)
{
    DirectoryInfo dir = new DirectoryInfo(FolderName);

    foreach (FileInfo fi in dir.GetFiles())
    {
        fi.IsReadOnly = false;
        fi.Delete();
    }

    foreach (DirectoryInfo di in dir.GetDirectories())
    {
        ClearFolder(di.FullName);
        di.Delete();
    }
}

Does Django scale?

  1. "What are the largest sites built on Django today?"

    There isn't any single place that collects information about traffic on Django built sites, so I'll have to take a stab at it using data from various locations. First, we have a list of Django sites on the front page of the main Django project page and then a list of Django built sites at djangosites.org. Going through the lists and picking some that I know have decent traffic we see:

  2. "Can Django deal with 100,000 users daily, each visiting the site for a couple of hours?"

    Yes, see above.

  3. "Could a site like Stack Overflow run on Django?"

    My gut feeling is yes but, as others answered and Mike Malone mentions in his presentation, database design is critical. Strong proof might also be found at www.cnprog.com if we can find any reliable traffic stats. Anyway, it's not just something that will happen by throwing together a bunch of Django models :)

There are, of course, many more sites and bloggers of interest, but I have got to stop somewhere!


Blog post about Using Django to build high-traffic site michaelmoore.com described as a top 10,000 website. Quantcast stats and compete.com stats.


(*) The author of the edit, including such reference, used to work as outsourced developer in that project.

Difference of two date time in sql server

Just a caveat to add about DateDiff, it counts the number of times you pass the boundary you specify as your units, so is subject to problems if you are looking for a precise timespan. e.g.

select datediff (m, '20100131', '20100201')

gives an answer of 1, because it crossed the boundary from January to February, so even though the span is 2 days, datediff would return a value of 1 - it crossed 1 date boundary.

select datediff(mi, '2010-01-22 15:29:55.090' , '2010-01-22 15:30:09.153')

Gives a value of 1, again, it passed the minute boundary once, so even though it is approx 14 seconds, it would be returned as a single minute when using Minutes as the units.

How can I check whether a numpy array is empty or not?

One caveat, though. Note that np.array(None).size returns 1! This is because a.size is equivalent to np.prod(a.shape), np.array(None).shape is (), and an empty product is 1.

>>> import numpy as np
>>> np.array(None).size
1
>>> np.array(None).shape
()
>>> np.prod(())
1.0

Therefore, I use the following to test if a numpy array has elements:

>>> def elements(array):
    ...     return array.ndim and array.size

>>> elements(np.array(None))
0
>>> elements(np.array([]))
0
>>> elements(np.zeros((2,3,4)))
24

How to iterate over arguments in a Bash script

Rewrite of a now-deleted answer by VonC.

Robert Gamble's succinct answer deals directly with the question. This one amplifies on some issues with filenames containing spaces.

See also: ${1:+"$@"} in /bin/sh

Basic thesis: "$@" is correct, and $* (unquoted) is almost always wrong. This is because "$@" works fine when arguments contain spaces, and works the same as $* when they don't. In some circumstances, "$*" is OK too, but "$@" usually (but not always) works in the same places. Unquoted, $@ and $* are equivalent (and almost always wrong).

So, what is the difference between $*, $@, "$*", and "$@"? They are all related to 'all the arguments to the shell', but they do different things. When unquoted, $* and $@ do the same thing. They treat each 'word' (sequence of non-whitespace) as a separate argument. The quoted forms are quite different, though: "$*" treats the argument list as a single space-separated string, whereas "$@" treats the arguments almost exactly as they were when specified on the command line. "$@" expands to nothing at all when there are no positional arguments; "$*" expands to an empty string — and yes, there's a difference, though it can be hard to perceive it. See more information below, after the introduction of the (non-standard) command al.

Secondary thesis: if you need to process arguments with spaces and then pass them on to other commands, then you sometimes need non-standard tools to assist. (Or you should use arrays, carefully: "${array[@]}" behaves analogously to "$@".)

Example:

    $ mkdir "my dir" anotherdir
    $ ls
    anotherdir      my dir
    $ cp /dev/null "my dir/my file"
    $ cp /dev/null "anotherdir/myfile"
    $ ls -Fltr
    total 0
    drwxr-xr-x   3 jleffler  staff  102 Nov  1 14:55 my dir/
    drwxr-xr-x   3 jleffler  staff  102 Nov  1 14:55 anotherdir/
    $ ls -Fltr *
    my dir:
    total 0
    -rw-r--r--   1 jleffler  staff  0 Nov  1 14:55 my file

    anotherdir:
    total 0
    -rw-r--r--   1 jleffler  staff  0 Nov  1 14:55 myfile
    $ ls -Fltr "./my dir" "./anotherdir"
    ./my dir:
    total 0
    -rw-r--r--   1 jleffler  staff  0 Nov  1 14:55 my file

    ./anotherdir:
    total 0
    -rw-r--r--   1 jleffler  staff  0 Nov  1 14:55 myfile
    $ var='"./my dir" "./anotherdir"' && echo $var
    "./my dir" "./anotherdir"
    $ ls -Fltr $var
    ls: "./anotherdir": No such file or directory
    ls: "./my: No such file or directory
    ls: dir": No such file or directory
    $

Why doesn't that work? It doesn't work because the shell processes quotes before it expands variables. So, to get the shell to pay attention to the quotes embedded in $var, you have to use eval:

    $ eval ls -Fltr $var
    ./my dir:
    total 0
    -rw-r--r--   1 jleffler  staff  0 Nov  1 14:55 my file

    ./anotherdir:
    total 0
    -rw-r--r--   1 jleffler  staff  0 Nov  1 14:55 myfile
    $ 

This gets really tricky when you have file names such as "He said, "Don't do this!"" (with quotes and double quotes and spaces).

    $ cp /dev/null "He said, \"Don't do this!\""
    $ ls
    He said, "Don't do this!"       anotherdir                      my dir
    $ ls -l
    total 0
    -rw-r--r--   1 jleffler  staff    0 Nov  1 15:54 He said, "Don't do this!"
    drwxr-xr-x   3 jleffler  staff  102 Nov  1 14:55 anotherdir
    drwxr-xr-x   3 jleffler  staff  102 Nov  1 14:55 my dir
    $ 

The shells (all of them) do not make it particularly easy to handle such stuff, so (funnily enough) many Unix programs do not do a good job of handling them. On Unix, a filename (single component) can contain any characters except slash and NUL '\0'. However, the shells strongly encourage no spaces or newlines or tabs anywhere in a path names. It is also why standard Unix file names do not contain spaces, etc.

When dealing with file names that may contain spaces and other troublesome characters, you have to be extremely careful, and I found long ago that I needed a program that is not standard on Unix. I call it escape (version 1.1 was dated 1989-08-23T16:01:45Z).

Here is an example of escape in use - with the SCCS control system. It is a cover script that does both a delta (think check-in) and a get (think check-out). Various arguments, especially -y (the reason why you made the change) would contain blanks and newlines. Note that the script dates from 1992, so it uses back-ticks instead of $(cmd ...) notation and does not use #!/bin/sh on the first line.

:   "@(#)$Id: delget.sh,v 1.8 1992/12/29 10:46:21 jl Exp $"
#
#   Delta and get files
#   Uses escape to allow for all weird combinations of quotes in arguments

case `basename $0 .sh` in
deledit)    eflag="-e";;
esac

sflag="-s"
for arg in "$@"
do
    case "$arg" in
    -r*)    gargs="$gargs `escape \"$arg\"`"
            dargs="$dargs `escape \"$arg\"`"
            ;;
    -e)     gargs="$gargs `escape \"$arg\"`"
            sflag=""
            eflag=""
            ;;
    -*)     dargs="$dargs `escape \"$arg\"`"
            ;;
    *)      gargs="$gargs `escape \"$arg\"`"
            dargs="$dargs `escape \"$arg\"`"
            ;;
    esac
done

eval delta "$dargs" && eval get $eflag $sflag "$gargs"

(I would probably not use escape quite so thoroughly these days - it is not needed with the -e argument, for example - but overall, this is one of my simpler scripts using escape.)

The escape program simply outputs its arguments, rather like echo does, but it ensures that the arguments are protected for use with eval (one level of eval; I do have a program which did remote shell execution, and that needed to escape the output of escape).

    $ escape $var
    '"./my' 'dir"' '"./anotherdir"'
    $ escape "$var"
    '"./my dir" "./anotherdir"'
    $ escape x y z
    x y z
    $ 

I have another program called al that lists its arguments one per line (and it is even more ancient: version 1.1 dated 1987-01-27T14:35:49). It is most useful when debugging scripts, as it can be plugged into a command line to see what arguments are actually passed to the command.

    $ echo "$var"
    "./my dir" "./anotherdir"
    $ al $var
    "./my
    dir"
    "./anotherdir"
    $ al "$var"
    "./my dir" "./anotherdir"
    $

[Added: And now to show the difference between the various "$@" notations, here is one more example:

$ cat xx.sh
set -x
al $@
al $*
al "$*"
al "$@"
$ sh xx.sh     *      */*
+ al He said, '"Don'\''t' do 'this!"' anotherdir my dir xx.sh anotherdir/myfile my dir/my file
He
said,
"Don't
do
this!"
anotherdir
my
dir
xx.sh
anotherdir/myfile
my
dir/my
file
+ al He said, '"Don'\''t' do 'this!"' anotherdir my dir xx.sh anotherdir/myfile my dir/my file
He
said,
"Don't
do
this!"
anotherdir
my
dir
xx.sh
anotherdir/myfile
my
dir/my
file
+ al 'He said, "Don'\''t do this!" anotherdir my dir xx.sh anotherdir/myfile my dir/my file'
He said, "Don't do this!" anotherdir my dir xx.sh anotherdir/myfile my dir/my file
+ al 'He said, "Don'\''t do this!"' anotherdir 'my dir' xx.sh anotherdir/myfile 'my dir/my file'
He said, "Don't do this!"
anotherdir
my dir
xx.sh
anotherdir/myfile
my dir/my file
$

Notice that nothing preserves the original blanks between the * and */* on the command line. Also, note that you can change the 'command line arguments' in the shell by using:

set -- -new -opt and "arg with space"

This sets 4 options, '-new', '-opt', 'and', and 'arg with space'.
]

Hmm, that's quite a long answer - perhaps exegesis is the better term. Source code for escape available on request (email to firstname dot lastname at gmail dot com). The source code for al is incredibly simple:

#include <stdio.h>
int main(int argc, char **argv)
{
    while (*++argv != 0)
        puts(*argv);
    return(0);
}

That's all. It is equivalent to the test.sh script that Robert Gamble showed, and could be written as a shell function (but shell functions didn't exist in the local version of Bourne shell when I first wrote al).

Also note that you can write al as a simple shell script:

[ $# != 0 ] && printf "%s\n" "$@"

The conditional is needed so that it produces no output when passed no arguments. The printf command will produce a blank line with only the format string argument, but the C program produces nothing.

How to get the file name from a full path using JavaScript?

This solution is much simpler and generic, for both 'file name' and 'path'.

const str = 'C:\\Documents and Settings\\img\\recycled log.jpg';

// regex to split path to two groups '(.*[\\\/])' for path and '(.*)' for file name
const regexPath = /^(.*[\\\/])(.*)$/;

// execute the match on the string str
const match = regexPath.exec(str);
if (match !== null) {
    // we ignore the match[0] because it's the match for the hole path string
    const filePath = match[1];
    const fileName = match[2];
}

How to escape a JSON string to have it in a URL?

I was looking to do the same thing. problem for me was my url was getting way too long. I found a solution today using Bruno Jouhier's jsUrl.js library.

I haven't tested it very thoroughly yet. However, here is an example showing character lengths of the string output after encoding the same large object using 3 different methods:

  • 2651 characters using jQuery.param
  • 1691 characters using JSON.stringify + encodeURIComponent
  • 821 characters using JSURL.stringify

clearly JSURL has the most optimized format for urlEncoding a js object.

the thread at https://groups.google.com/forum/?fromgroups=#!topic/nodejs/ivdZuGCF86Q shows benchmarks for encoding and parsing.

Note: After testing, it looks like jsurl.js library uses ECMAScript 5 functions such as Object.keys, Array.map, and Array.filter. Therefore, it will only work on modern browsers (no ie 8 and under). However, are polyfills for these functions that would make it compatible with more browsers.

Do you have to put Task.Run in a method to make it async?

First, let's clear up some terminology: "asynchronous" (async) means that it may yield control back to the calling thread before it starts. In an async method, those "yield" points are await expressions.

This is very different than the term "asynchronous", as (mis)used by the MSDN documentation for years to mean "executes on a background thread".

To futher confuse the issue, async is very different than "awaitable"; there are some async methods whose return types are not awaitable, and many methods returning awaitable types that are not async.

Enough about what they aren't; here's what they are:

  • The async keyword allows an asynchronous method (that is, it allows await expressions). async methods may return Task, Task<T>, or (if you must) void.
  • Any type that follows a certain pattern can be awaitable. The most common awaitable types are Task and Task<T>.

So, if we reformulate your question to "how can I run an operation on a background thread in a way that it's awaitable", the answer is to use Task.Run:

private Task<int> DoWorkAsync() // No async because the method does not need await
{
  return Task.Run(() =>
  {
    return 1 + 2;
  });
}

(But this pattern is a poor approach; see below).

But if your question is "how do I create an async method that can yield back to its caller instead of blocking", the answer is to declare the method async and use await for its "yielding" points:

private async Task<int> GetWebPageHtmlSizeAsync()
{
  var client = new HttpClient();
  var html = await client.GetAsync("http://www.example.com/");
  return html.Length;
}

So, the basic pattern of things is to have async code depend on "awaitables" in its await expressions. These "awaitables" can be other async methods or just regular methods returning awaitables. Regular methods returning Task/Task<T> can use Task.Run to execute code on a background thread, or (more commonly) they can use TaskCompletionSource<T> or one of its shortcuts (TaskFactory.FromAsync, Task.FromResult, etc). I don't recommend wrapping an entire method in Task.Run; synchronous methods should have synchronous signatures, and it should be left up to the consumer whether it should be wrapped in a Task.Run:

private int DoWork()
{
  return 1 + 2;
}

private void MoreSynchronousProcessing()
{
  // Execute it directly (synchronously), since we are also a synchronous method.
  var result = DoWork();
  ...
}

private async Task DoVariousThingsFromTheUIThreadAsync()
{
  // I have a bunch of async work to do, and I am executed on the UI thread.
  var result = await Task.Run(() => DoWork());
  ...
}

I have an async/await intro on my blog; at the end are some good followup resources. The MSDN docs for async are unusually good, too.

How to print a single backslash?

You need to escape your backslash by preceding it with, yes, another backslash:

print("\\")

And for versions prior to Python 3:

print "\\"

The \ character is called an escape character, which interprets the character following it differently. For example, n by itself is simply a letter, but when you precede it with a backslash, it becomes \n, which is the newline character.

As you can probably guess, \ also needs to be escaped so it doesn't function like an escape character. You have to... escape the escape, essentially.

See the Python 3 documentation for string literals.

JQuery - Set Attribute value

Some things before the actual code..

the hash (#) you use as the selector is for IDs and not for names of elements. also the disabled attribute is not a true false scenario .. if it has disabled attribute it means that it is true .. you need to remove the attribute and not set it to false. Also there are the form selectors that identify specific types of items in a form ..

so the code would be

$("input:checkbox[name='chk0']").removeAttr('disabled');

Bringing the answer up-to-date

You should use the .prop() method (added since v1.6)

$("input:checkbox[name='chk0']").prop('disabled', false); // to enable the checkbox

and

$("input:checkbox[name='chk0']").prop('disabled', true); // to disable the checkbox

Compile throws a "User-defined type not defined" error but does not go to the offending line of code

Possible solution, you are trying to work with Powerpoint via Excel VBA and you didn't activate Powerpoint Object Library first.

To do this, in the VBA editor top menu select Tools, References, then scroll down to click the library called Microsoft Powerpoint xx.x Object Library. Office 2007 is library 12, each Office version has a different library. FYI, I've experienced some odd errors and file corruption when I activate the 2007 library but someone tries to open and run this macro using Excel 2003. The old version of Excel doesn't recognize the newer library, which seems to cause problems.

How to mock static methods in c# using MOQ framework?

As mentioned in the other answers MOQ cannot mock static methods and, as a general rule, one should avoid statics where possible.

Sometimes it is not possible. One is working with legacy or 3rd party code or with even with the BCL methods that are static.

A possible solution is to wrap the static in a proxy with an interface which can be mocked

    public interface IFileProxy {
        void Delete(string path);
    }

    public class FileProxy : IFileProxy {
        public void Delete(string path) {
            System.IO.File.Delete(path);
        }
    }

    public class MyClass {

        private IFileProxy _fileProxy;

        public MyClass(IFileProxy fileProxy) {
            _fileProxy = fileProxy;
        }

        public void DoSomethingAndDeleteFile(string path) {
            // Do Something with file
            // ...
            // Delete
            System.IO.File.Delete(path);
        }

        public void DoSomethingAndDeleteFileUsingProxy(string path) {
            // Do Something with file
            // ...
            // Delete
            _fileProxy.Delete(path);

        }
    }

The downside is that the ctor can become very cluttered if there are a lot of proxies (though it could be argued that if there are a lot of proxies then the class may be trying to do too much and could be refactored)

Another possibility is to have a 'static proxy' with different implementations of the interface behind it

   public static class FileServices {

        static FileServices() {
            Reset();
        }

        internal static IFileProxy FileProxy { private get; set; }

        public static void Reset(){
           FileProxy = new FileProxy();
        }

        public static void Delete(string path) {
            FileProxy.Delete(path);
        }

    }

Our method now becomes

    public void DoSomethingAndDeleteFileUsingStaticProxy(string path) {
            // Do Something with file
            // ...
            // Delete
            FileServices.Delete(path);

    }

For testing, we can set the FileProxy property to our mock. Using this style reduces the number of interfaces to be injected but makes dependencies a bit less obvious (though no more so than the original static calls I suppose).

Android SDK Manager gives "Failed to fetch URL https://dl-ssl.google.com/android/repository/repository.xml" error when selecting repository

I had the same problem, made all the workarounds you advised: still the same error. I updated Eclipse via "Help / Check for updates" and now everything is ok. This update brought a completely new version of the Android SDK Manager.

ssl_error_rx_record_too_long and Apache SSL

In my case the problem was that https was unable to start correctly because Listen 443 was in "IfDefine SSL" derective, but my apache didnt start with -DSSL option. The fix was to change my apachectl script in:

$HTTPD -k $ARGV

to:

$HTTPD -k $ARGV -DSSL

Hope that helps somebody.

Pass multiple values with onClick in HTML link

Please try this

for static values--onclick="return ReAssign('valuationId','user')"
for dynamic values--onclick="return ReAssign(valuationId,user)"

Remove folder and its contents from git/GitHub's history

The best and most accurate method I found was to download the bfg.jar file: https://rtyley.github.io/bfg-repo-cleaner/

Then run the commands:

git clone --bare https://project/repository project-repository
cd project-repository
java -jar bfg.jar --delete-folders DIRECTORY_NAME
git reflog expire --expire=now --all && git gc --prune=now --aggressive
git push --mirror https://project/new-repository

If you want to delete files then use the delete-files option instead:

java -jar bfg.jar --delete-files *.pyc

CSS set li indent

Also try:

ul {
  list-style-position: inside;
}

LINQ: "contains" and a Lambda query

Here is how you can use Contains to achieve what you want:

buildingStatus.Select(item => item.GetCharValue()).Contains(v.Status) this will return a Boolean value.

Display current time in 12 hour format with AM/PM

Just replace below statement and it will work.

SimpleDateFormat formatDate = new SimpleDateFormat("hh:mm a");

How to update one file in a zip archive

7zip (7za) can be used for adding/updating files/directories nicely:

Example: Replacing (regardless of file date) the MANIFEST.MF file in a JAR file. The /source/META-INF directory contains the MANIFEST.MF file that you want to put into the jar (zip):

7za a /tmp/file.jar /source/META-INF/

Only update (does not replace the target if the source is older)

7za u /tmp/file.jar /source/META-INF/

Mocking Extension Methods with Moq

I like to use the wrapper (adapter pattern) when I am wrapping the object itself. I'm not sure I'd use that for wrapping an extension method, which is not part of the object.

I use an internal Lazy Injectable Property of either type Action, Func, Predicate, or delegate and allow for injecting (swapping out) the method during a unit test.

    internal Func<IMyObject, string, object> DoWorkMethod
    {
        [ExcludeFromCodeCoverage]
        get { return _DoWorkMethod ?? (_DoWorkMethod = (obj, val) => { return obj.DoWork(val); }); }
        set { _DoWorkMethod = value; }
    } private Func<IMyObject, string, object> _DoWorkMethod;

Then you call the Func instead of the actual method.

    public object SomeFunction()
    {
        var val = "doesn't matter for this example";
        return DoWorkMethod.Invoke(MyObjectProperty, val);
    }

For a more complete example, check out http://www.rhyous.com/2016/08/11/unit-testing-calls-to-complex-extension-methods/

iptables block access to port 8000 except from IP address

This question should be on Server Fault. Nevertheless, the following should do the trick, assuming you're talking about TCP and the IP you want to allow is 1.2.3.4:

iptables -A INPUT -p tcp --dport 8000 -s 1.2.3.4 -j ACCEPT
iptables -A INPUT -p tcp --dport 8000 -j DROP

Angular 5 Reactive Forms - Radio Button Group

I tried your code, you didn't assign/bind a value to your formControlName.

In HTML file:

<form [formGroup]="form">
   <label>
     <input type="radio" value="Male" formControlName="gender">
       <span>male</span>
   </label>
   <label>
     <input type="radio" value="Female" formControlName="gender">
       <span>female</span>
   </label>
</form>

In the TS file:

  form: FormGroup;
  constructor(fb: FormBuilder) {
    this.name = 'Angular2'
    this.form = fb.group({
      gender: ['', Validators.required]
    });
  }

Make sure you use Reactive form properly: [formGroup]="form" and you don't need the name attribute.

In my sample. words male and female in span tags are the values display along the radio button and Male and Female values are bind to formControlName

See the screenshot: enter image description here

To make it shorter:

<form [formGroup]="form">
  <input type="radio" value='Male' formControlName="gender" >Male
  <input type="radio" value='Female' formControlName="gender">Female
</form>

enter image description here

Hope it helps:)

Reading integers from binary file in Python

An alternative method which does not make use of 'struct.unpack()' would be to use NumPy:

import numpy as np

f = open("file.bin", "r")
a = np.fromfile(f, dtype=np.uint32)

'dtype' represents the datatype and can be int#, uint#, float#, complex# or a user defined type. See numpy.fromfile.

Personally prefer using NumPy to work with array/matrix data as it is a lot faster than using Python lists.

Using the RUN instruction in a Dockerfile with 'source' does not work

Simplest way is to use the dot operator in place of source, which is the sh equivalent of the bash source command:

Instead of:

RUN source /usr/local/bin/virtualenvwrapper.sh

Use:

RUN . /usr/local/bin/virtualenvwrapper.sh

Unable to verify leaf signature

Following commands worked for me :

> npm config set strict-ssl false
> npm cache clean --force

The problem is that you are attempting to install a module from a repository with a bad or untrusted SSL[Secure Sockets Layer] certificate. Once you clean the cache, this problem will be resolved.You might need to turn it to true later on.

How To: Execute command line in C#, get STD OUT results

The accepted answer on this page has a weakness that is troublesome in rare situations. There are two file handles which programs write to by convention, stdout, and stderr. If you just read a single file handle such as the answer from Ray, and the program you are starting writes enough output to stderr, it will fill up the output stderr buffer and block. Then your two processes are deadlocked. The buffer size may be 4K. This is extremely rare on short-lived programs, but if you have a long running program which repeatedly outputs to stderr, it will happen eventually. This is tricky to debug and track down.

There are a couple good ways to deal with this.

  1. One way is to execute cmd.exe instead of your program and use the /c argument to cmd.exe to invoke your program along with the "2>&1" argument to cmd.exe to tell it to merge stdout and stderr.

            var p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.Arguments = "/c mycmd.exe 2>&1";
    
  2. Another way is to use a programming model which reads both handles at the same time.

            var p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.Arguments = @"/c dir \windows";
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardInput = false;
            p.OutputDataReceived += (a, b) => Console.WriteLine(b.Data);
            p.ErrorDataReceived += (a, b) => Console.WriteLine(b.Data);
            p.Start();
            p.BeginErrorReadLine();
            p.BeginOutputReadLine();
            p.WaitForExit();
    

StringUtils.isBlank() vs String.isEmpty()

StringUtils.isBlank(foo) will perform a null check for you. If you perform foo.isEmpty() and foo is null, you will raise a NullPointerException.

Pip freeze vs. pip list

For those looking for a solution. If you accidentally made pip requirements with pip list instead of pip freeze, and want to convert into pip freeze format. I wrote this R script to do so.

library(tidyverse)

pip_list = read_lines("requirements.txt")

pip_freeze = pip_list %>%
  str_replace_all(" \\(", "==") %>%
  str_replace_all("\\)$", "")

pip_freeze %>% write_lines("requirements.txt")

Javascript: Uncaught TypeError: Cannot call method 'addEventListener' of null

Move script tag at the end of BODY instead of HEAD because in current code when the script is computed html element doesn't exist in document.

Since you don't want to you jquery. Use window.onload or document.onload to execute the entire piece of code that you have in current script tag. window.onload vs document.onload

How do I convert Int/Decimal to float in C#?

You don't even need to cast, it is implicit.

int i = 3;

float f = i;

A full list/table of implicit numeric conversions can be seen here http://msdn.microsoft.com/en-us/library/y5b434w4.aspx

How to retrieve Request Payload

If I understand the situation correctly, you are just passing json data through the http body, instead of application/x-www-form-urlencoded data.

You can fetch this data with this snippet:

$request_body = file_get_contents('php://input');

If you are passing json, then you can do:

$data = json_decode($request_body);

$data then contains the json data is php array.

php://input is a so called wrapper.

php://input is a read-only stream that allows you to read raw data from the request body. In the case of POST requests, it is preferable to use php://input instead of $HTTP_RAW_POST_DATA as it does not depend on special php.ini directives. Moreover, for those cases where $HTTP_RAW_POST_DATA is not populated by default, it is a potentially less memory intensive alternative to activating always_populate_raw_post_data. php://input is not available with enctype="multipart/form-data".

XmlSerializer: remove unnecessary xsi and xsd namespaces

Since Dave asked for me to repeat my answer to Omitting all xsi and xsd namespaces when serializing an object in .NET, I have updated this post and repeated my answer here from the afore-mentioned link. The example used in this answer is the same example used for the other question. What follows is copied, verbatim.


After reading Microsoft's documentation and several solutions online, I have discovered the solution to this problem. It works with both the built-in XmlSerializer and custom XML serialization via IXmlSerialiazble.

To whit, I'll use the same MyTypeWithNamespaces XML sample that's been used in the answers to this question so far.

[XmlRoot("MyTypeWithNamespaces", Namespace="urn:Abracadabra", IsNullable=false)]
public class MyTypeWithNamespaces
{
    // As noted below, per Microsoft's documentation, if the class exposes a public
    // member of type XmlSerializerNamespaces decorated with the 
    // XmlNamespacesDeclarationAttribute, then the XmlSerializer will utilize those
    // namespaces during serialization.
    public MyTypeWithNamespaces( )
    {
        this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
            // Don't do this!! Microsoft's documentation explicitly says it's not supported.
            // It doesn't throw any exceptions, but in my testing, it didn't always work.

            // new XmlQualifiedName(string.Empty, string.Empty),  // And don't do this:
            // new XmlQualifiedName("", "")

            // DO THIS:
            new XmlQualifiedName(string.Empty, "urn:Abracadabra") // Default Namespace
            // Add any other namespaces, with prefixes, here.
        });
    }

    // If you have other constructors, make sure to call the default constructor.
    public MyTypeWithNamespaces(string label, int epoch) : this( )
    {
        this._label = label;
        this._epoch = epoch;
    }

    // An element with a declared namespace different than the namespace
    // of the enclosing type.
    [XmlElement(Namespace="urn:Whoohoo")]
    public string Label
    {
        get { return this._label; }
        set { this._label = value; }
    }
    private string _label;

    // An element whose tag will be the same name as the property name.
    // Also, this element will inherit the namespace of the enclosing type.
    public int Epoch
    {
        get { return this._epoch; }
        set { this._epoch = value; }
    }
    private int _epoch;

    // Per Microsoft's documentation, you can add some public member that
    // returns a XmlSerializerNamespaces object. They use a public field,
    // but that's sloppy. So I'll use a private backed-field with a public
    // getter property. Also, per the documentation, for this to work with
    // the XmlSerializer, decorate it with the XmlNamespaceDeclarations
    // attribute.
    [XmlNamespaceDeclarations]
    public XmlSerializerNamespaces Namespaces
    {
        get { return this._namespaces; }
    }
    private XmlSerializerNamespaces _namespaces;
}

That's all to this class. Now, some objected to having an XmlSerializerNamespaces object somewhere within their classes; but as you can see, I neatly tucked it away in the default constructor and exposed a public property to return the namespaces.

Now, when it comes time to serialize the class, you would use the following code:

MyTypeWithNamespaces myType = new MyTypeWithNamespaces("myLabel", 42);

/******
   OK, I just figured I could do this to make the code shorter, so I commented out the
   below and replaced it with what follows:

// You have to use this constructor in order for the root element to have the right namespaces.
// If you need to do custom serialization of inner objects, you can use a shortened constructor.
XmlSerializer xs = new XmlSerializer(typeof(MyTypeWithNamespaces), new XmlAttributeOverrides(),
    new Type[]{}, new XmlRootAttribute("MyTypeWithNamespaces"), "urn:Abracadabra");

******/
XmlSerializer xs = new XmlSerializer(typeof(MyTypeWithNamespaces),
    new XmlRootAttribute("MyTypeWithNamespaces") { Namespace="urn:Abracadabra" });

// I'll use a MemoryStream as my backing store.
MemoryStream ms = new MemoryStream();

// This is extra! If you want to change the settings for the XmlSerializer, you have to create
// a separate XmlWriterSettings object and use the XmlTextWriter.Create(...) factory method.
// So, in this case, I want to omit the XML declaration.
XmlWriterSettings xws = new XmlWriterSettings();
xws.OmitXmlDeclaration = true;
xws.Encoding = Encoding.UTF8; // This is probably the default
// You could use the XmlWriterSetting to set indenting and new line options, but the
// XmlTextWriter class has a much easier method to accomplish that.

// The factory method returns a XmlWriter, not a XmlTextWriter, so cast it.
XmlTextWriter xtw = (XmlTextWriter)XmlTextWriter.Create(ms, xws);
// Then we can set our indenting options (this is, of course, optional).
xtw.Formatting = Formatting.Indented;

// Now serialize our object.
xs.Serialize(xtw, myType, myType.Namespaces);

Once you have done this, you should get the following output:

<MyTypeWithNamespaces>
    <Label xmlns="urn:Whoohoo">myLabel</Label>
    <Epoch>42</Epoch>
</MyTypeWithNamespaces>

I have successfully used this method in a recent project with a deep hierachy of classes that are serialized to XML for web service calls. Microsoft's documentation is not very clear about what to do with the publicly accesible XmlSerializerNamespaces member once you've created it, and so many think it's useless. But by following their documentation and using it in the manner shown above, you can customize how the XmlSerializer generates XML for your classes without resorting to unsupported behavior or "rolling your own" serialization by implementing IXmlSerializable.

It is my hope that this answer will put to rest, once and for all, how to get rid of the standard xsi and xsd namespaces generated by the XmlSerializer.

UPDATE: I just want to make sure I answered the OP's question about removing all namespaces. My code above will work for this; let me show you how. Now, in the example above, you really can't get rid of all namespaces (because there are two namespaces in use). Somewhere in your XML document, you're going to need to have something like xmlns="urn:Abracadabra" xmlns:w="urn:Whoohoo. If the class in the example is part of a larger document, then somewhere above a namespace must be declared for either one of (or both) Abracadbra and Whoohoo. If not, then the element in one or both of the namespaces must be decorated with a prefix of some sort (you can't have two default namespaces, right?). So, for this example, Abracadabra is the default namespace. I could inside my MyTypeWithNamespaces class add a namespace prefix for the Whoohoo namespace like so:

public MyTypeWithNamespaces
{
    this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
        new XmlQualifiedName(string.Empty, "urn:Abracadabra"), // Default Namespace
        new XmlQualifiedName("w", "urn:Whoohoo")
    });
}

Now, in my class definition, I indicated that the <Label/> element is in the namespace "urn:Whoohoo", so I don't need to do anything further. When I now serialize the class using my above serialization code unchanged, this is the output:

<MyTypeWithNamespaces xmlns:w="urn:Whoohoo">
    <w:Label>myLabel</w:Label>
    <Epoch>42</Epoch>
</MyTypeWithNamespaces>

Because <Label> is in a different namespace from the rest of the document, it must, in someway, be "decorated" with a namespace. Notice that there are still no xsi and xsd namespaces.


This ends my answer to the other question. But I wanted to make sure I answered the OP's question about using no namespaces, as I feel I didn't really address it yet. Assume that <Label> is part of the same namespace as the rest of the document, in this case urn:Abracadabra:

<MyTypeWithNamespaces>
    <Label>myLabel<Label>
    <Epoch>42</Epoch>
</MyTypeWithNamespaces>

Your constructor would look as it would in my very first code example, along with the public property to retrieve the default namespace:

// As noted below, per Microsoft's documentation, if the class exposes a public
// member of type XmlSerializerNamespaces decorated with the 
// XmlNamespacesDeclarationAttribute, then the XmlSerializer will utilize those
// namespaces during serialization.
public MyTypeWithNamespaces( )
{
    this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
        new XmlQualifiedName(string.Empty, "urn:Abracadabra") // Default Namespace
    });
}

[XmlNamespaceDeclarations]
public XmlSerializerNamespaces Namespaces
{
    get { return this._namespaces; }
}
private XmlSerializerNamespaces _namespaces;

Then, later, in your code that uses the MyTypeWithNamespaces object to serialize it, you would call it as I did above:

MyTypeWithNamespaces myType = new MyTypeWithNamespaces("myLabel", 42);

XmlSerializer xs = new XmlSerializer(typeof(MyTypeWithNamespaces),
    new XmlRootAttribute("MyTypeWithNamespaces") { Namespace="urn:Abracadabra" });

...

// Above, you'd setup your XmlTextWriter.

// Now serialize our object.
xs.Serialize(xtw, myType, myType.Namespaces);

And the XmlSerializer would spit back out the same XML as shown immediately above with no additional namespaces in the output:

<MyTypeWithNamespaces>
    <Label>myLabel<Label>
    <Epoch>42</Epoch>
</MyTypeWithNamespaces>

How to find the path of Flutter SDK

Visit https://flutter.dev/docs/get-started/install/windows#update-your-path official page of Flutter

for windows you can look an Evroitmen variabel with value name Path

Adding blank spaces to layout

try this

in layout.xml :

<TextView
        android:id="@+id/xxx"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="@string/empty_spaces" />

in strings.xml :

<string name="empty_spaces">\t\t</string>

it worked for me

Why doesn't "System.out.println" work in Android?

it is not displayed in your application... it is under your emulator's logcat

Visual Studio Code: format is not using indent settings

Visual Studio Code detects the current indentation per default and uses this - ignoring the .editorconfig

Set also "editor.detectIndentation" to false

(Files -> Preferences -> Settings)

screenshot