Programs & Examples On #Compilationunit

How to solve java.lang.NullPointerException error?

A NullPointerException means that one of the variables you are passing is null, but the code tries to use it like it is not.

For example, If I do this:

Integer myInteger = null;
int n = myInteger.intValue();

The code tries to grab the intValue of myInteger, but since it is null, it does not have one: a null pointer exception happens.

What this means is that your getTask method is expecting something that is not a null, but you are passing a null. Figure out what getTask needs and pass what it wants!

Python "expected an indented block"

Python is very picky about white space and indentation, more so than many languages. The reason is, rather than using curly braces and semi colons (like javascript or php) python looks for a return character (press enter/return on your keyboard) instead of the semicolon, and a colon with a tab after it for a opening curly brace. When the next piece of code is unindented, it expects that this is the same as a closing curly brace in Javascript or PHP.

From ==>https://teamtreehouse.com/community/what-is-a-indentationerror-expected-an-indented-block

T-SQL Substring - Last 3 Characters

SELECT RIGHT(column, 3)

That's all you need.

You can also do LEFT() in the same way.

Bear in mind if you are using this in a WHERE clause that the RIGHT() can't use any indexes.

Execute CMD command from code

In addition to the answers above, you could use a small extension method:

public static class Extensions
{
   public static void Run(this string fileName, 
                          string workingDir=null, params string[] arguments)
    {
        using (var p = new Process())
        {
            var args = p.StartInfo;
            args.FileName = fileName;
            if (workingDir!=null) args.WorkingDirectory = workingDir;
            if (arguments != null && arguments.Any())
                args.Arguments = string.Join(" ", arguments).Trim();
            else if (fileName.ToLowerInvariant() == "explorer")
                args.Arguments = args.WorkingDirectory;
            p.Start();
        }
    }
}

and use it like so:

// open explorer window with given path
"Explorer".Run(path);   

// open a shell (remanins open)
"cmd".Run(path, "/K");

How can I pass a reference to a function, with parameters?

You can also overload the Function prototype:

// partially applies the specified arguments to a function, returning a new function
Function.prototype.curry = function( ) {
    var func = this;
    var slice = Array.prototype.slice;
    var appliedArgs = slice.call( arguments, 0 );

    return function( ) {
        var leftoverArgs = slice.call( arguments, 0 );
        return func.apply( this, appliedArgs.concat( leftoverArgs ) );
    };
};

// can do other fancy things:

// flips the first two arguments of a function
Function.prototype.flip = function( ) {
    var func = this;
    return function( ) {
        var first = arguments[0];
        var second = arguments[1];
        var rest = Array.prototype.slice.call( arguments, 2 );
        var newArgs = [second, first].concat( rest );

        return func.apply( this, newArgs );
    };
};

/*
e.g.

var foo = function( a, b, c, d ) { console.log( a, b, c, d ); }
var iAmA = foo.curry( "I", "am", "a" );
iAmA( "Donkey" );
-> I am a Donkey

var bah = foo.flip( );
bah( 1, 2, 3, 4 );
-> 2 1 3 4
*/

get all the elements of a particular form

SIMPLE Form code

    <form id="myForm" name="myForm">
        <input type="text" name="User" value="Arsalan"/>
        <input type="password" name="pass" value="123"/>
        <input type="number" name="age" value="24"/>
        <input type="text" name="email" value="[email protected]"/>
        <textarea name="message">Enter Your Message Her</textarea>

    </form>

Javascript Code

//Assign Form by Id to a Variabe
    var myForm = document.getElementById("myForm");
    //Extract Each Element Value
    for (var i = 0; i < myForm.elements.length; i++) {
    console.log(myForm.elements[i].value);
    }

JSFIDDLE : http://jsfiddle.net/rng0hpss/

Can you split/explode a field in a MySQL query?

Building on Alwin Kesler's solution, here's a bit of a more practical real world example.

Assuming that the comma separated list is in my_table.list, and it's a listing of ID's for my_other_table.id, you can do something like:

SELECT 
    * 
FROM 
    my_other_table 
WHERE 
    (SELECT list FROM my_table WHERE id = '1234') REGEXP CONCAT(',?', my_other_table.id, ',?');

Calculate difference between two dates (number of days)?

Assuming StartDate and EndDate are of type DateTime:

(EndDate - StartDate).TotalDays

Android: Create a toggle button with image and no text

ToggleButton inherits from TextView so you can set drawables to be displayed at the 4 borders of the text. You can use that to display the icon you want on top of the text and hide the actual text

<ToggleButton
    android:id="@+id/toggleButton1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:drawableTop="@android:drawable/ic_menu_info_details"
    android:gravity="center"
    android:textOff=""
    android:textOn=""
    android:textSize="0dp" />

The result compared to regular ToggleButton looks like

enter image description here

The seconds option is to use an ImageSpan to actually replace the text with an image. Looks slightly better since the icon is at the correct position but can't be done with layout xml directly.

You create a plain ToggleButton

<ToggleButton
    android:id="@+id/toggleButton3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checked="false" />

Then set the "text" programmatially

ToggleButton button = (ToggleButton) findViewById(R.id.toggleButton3);
ImageSpan imageSpan = new ImageSpan(this, android.R.drawable.ic_menu_info_details);
SpannableString content = new SpannableString("X");
content.setSpan(imageSpan, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
button.setText(content);
button.setTextOn(content);
button.setTextOff(content);

The result here in the middle - icon is placed slightly lower since it takes the place of the text.

enter image description here

Rebuild all indexes in a Database

Try the following script:

Exec sp_msforeachtable 'SET QUOTED_IDENTIFIER ON; ALTER INDEX ALL ON ? REBUILD'
GO

Also

I prefer(After a long search) to use the following script, it contains @fillfactor determines how much percentage of the space on each leaf-level page is filled with data.

DECLARE @TableName VARCHAR(255)
DECLARE @sql NVARCHAR(500)
DECLARE @fillfactor INT
SET @fillfactor = 80 
DECLARE TableCursor CURSOR FOR
SELECT QUOTENAME(OBJECT_SCHEMA_NAME([object_id]))+'.' + QUOTENAME(name) AS TableName
FROM sys.tables
OPEN TableCursor
FETCH NEXT FROM TableCursor INTO @TableName
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sql = 'ALTER INDEX ALL ON ' + @TableName + ' REBUILD WITH (FILLFACTOR = ' + CONVERT(VARCHAR(3),@fillfactor) + ')'
EXEC (@sql)
FETCH NEXT FROM TableCursor INTO @TableName
END
CLOSE TableCursor
DEALLOCATE TableCursor
GO

for more info, check the following link:

https://blog.sqlauthority.com/2009/01/30/sql-server-2008-2005-rebuild-every-index-of-all-tables-of-database-rebuild-index-with-fillfactor/

and if you want to Check Index Fragmentation on Indexes in a Database, try the following script:

SELECT dbschemas.[name] as 'Schema',
dbtables.[name] as 'Table',
dbindexes.[name] as 'Index',
indexstats.avg_fragmentation_in_percent,
indexstats.page_count
FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, NULL) AS indexstats
INNER JOIN sys.tables dbtables on dbtables.[object_id] = indexstats.[object_id]
INNER JOIN sys.schemas dbschemas on dbtables.[schema_id] = dbschemas.[schema_id]
INNER JOIN sys.indexes AS dbindexes ON dbindexes.[object_id] = indexstats.[object_id]
AND indexstats.index_id = dbindexes.index_id
WHERE indexstats.database_id = DB_ID() AND dbtables.[name] like '%%'
ORDER BY indexstats.avg_fragmentation_in_percent desc

For more information, Check the following link:

http://www.schneider-electric.com/en/faqs/FA234246/

How to fix Subversion lock error

Go to the metadata directory as below

your workspace>projectname>.metadata

inside this metada directory, there will be a lock file. Delete this lock file.

Restart eclipse and rebuild project. It worked for me !

3 column layout HTML/CSS

This is less for @easwee and more for others that might have the same question:

If you do not require support for IE < 10, you can use Flexbox. It's an exciting CSS3 property that unfortunately was implemented in several different versions,; add in vendor prefixes, and getting good cross-browser support suddenly requires quite a few more properties than it should.

With the current, final standard, you would be done with

.container {
    display: flex;
}

.container div {
    flex: 1;
}

.column_center {
    order: 2;
}

That's it. If you want to support older implementations like iOS 6, Safari < 6, Firefox 19 or IE10, this blossoms into

.container {
    display: -webkit-box;      /* OLD - iOS 6-, Safari 3.1-6 */
    display: -moz-box;         /* OLD - Firefox 19- (buggy but mostly works) */
    display: -ms-flexbox;      /* TWEENER - IE 10 */
    display: -webkit-flex;     /* NEW - Chrome */
    display: flex;             /* NEW, Spec - Opera 12.1, Firefox 20+ */
}

.container div {
    -webkit-box-flex: 1;      /* OLD - iOS 6-, Safari 3.1-6 */
    -moz-box-flex: 1;         /* OLD - Firefox 19- */
    -webkit-flex: 1;          /* Chrome */
    -ms-flex: 1;              /* IE 10 */
    flex: 1;                  /* NEW, Spec - Opera 12.1, Firefox 20+ */
}

.column_center {
    -webkit-box-ordinal-group: 2;   /* OLD - iOS 6-, Safari 3.1-6 */
    -moz-box-ordinal-group: 2;      /* OLD - Firefox 19- */
    -ms-flex-order: 2;              /* TWEENER - IE 10 */
    -webkit-order: 2;               /* NEW - Chrome */
    order: 2;                       /* NEW, Spec - Opera 12.1, Firefox 20+ */
}

jsFiddle demo

Here is an excellent article about Flexbox cross-browser support: Using Flexbox: Mixing Old And New

Deserialize JSON with C#

A great way to automatically generate these classes for you is to copy your JSON output and throw it in here:

http://json2csharp.com/

It will provide you with a starting point to touch up your classes for deserialization.

iText - add content to existing PDF file

This is the most complicated scenario I can imagine: I have a PDF file created with Ilustrator and modified with Acrobat to have AcroFields (AcroForm) that I'm going to fill with data with this Java code, the result of that PDF file with the data in the fields is modified adding a Document.

Actually in this case I'm dynamically generating a background that is added to a PDF that is also dynamically generated with a Document with an unknown amount of data or pages.

I'm using JBoss and this code is inside a JSP file (should work in any JSP webserver).

Note: if you are using IExplorer you must submit a HTTP form with POST method to be able to download the file. If not you are going to see the PDF code in the screen. This does not happen in Chrome or Firefox.

<%@ page import="java.io.*, com.lowagie.text.*, com.lowagie.text.pdf.*" %><%

response.setContentType("application/download");
response.setHeader("Content-disposition","attachment;filename=listaPrecios.pdf" );  

// -------- FIRST THE PDF WITH THE INFO ----------
String str = "";
// lots of words
for(int i = 0; i < 800; i++) str += "Hello" + i + " ";
// the document
Document doc = new Document( PageSize.A4, 25, 25, 200, 70 );
ByteArrayOutputStream streamDoc = new ByteArrayOutputStream();
PdfWriter.getInstance( doc, streamDoc );
// lets start filling with info
doc.open();
doc.add(new Paragraph(str));
doc.close();
// the beauty of this is the PDF will have all the pages it needs
PdfReader frente = new PdfReader(streamDoc.toByteArray());
PdfStamper stamperDoc = new PdfStamper( frente, response.getOutputStream());

// -------- THE BACKGROUND PDF FILE -------
// in JBoss the file has to be in webinf/classes to be readed this way
PdfReader fondo = new PdfReader("listaPrecios.pdf");
ByteArrayOutputStream streamFondo = new ByteArrayOutputStream();
PdfStamper stamperFondo = new PdfStamper( fondo, streamFondo);
// the acroform
AcroFields form = stamperFondo.getAcroFields();
// the fields 
form.setField("nombre","Avicultura");
form.setField("descripcion","Esto describe para que sirve la lista ");
stamperFondo.setFormFlattening(true);
stamperFondo.close();
// our background is ready
PdfReader fondoEstampado = new PdfReader( streamFondo.toByteArray() );

// ---- ADDING THE BACKGROUND TO EACH DATA PAGE ---------
PdfImportedPage pagina = stamperDoc.getImportedPage(fondoEstampado,1);
int n = frente.getNumberOfPages();
PdfContentByte background;
for (int i = 1; i <= n; i++) {
    background = stamperDoc.getUnderContent(i);
    background.addTemplate(pagina, 0, 0);
}
// after this everithing will be written in response.getOutputStream()
stamperDoc.close(); 
%>

There is another solution much simpler, and solves your problem. It depends the amount of text you want to add.

// read the file
PdfReader fondo = new PdfReader("listaPrecios.pdf");
PdfStamper stamper = new PdfStamper( fondo, response.getOutputStream());
PdfContentByte content = stamper.getOverContent(1);
// add text
ColumnText ct = new ColumnText( content );
// this are the coordinates where you want to add text
// if the text does not fit inside it will be cropped
ct.setSimpleColumn(50,500,500,50);
ct.setText(new Phrase(str, titulo1));
ct.go();

Negative matching using grep (match lines that do not contain foo)

grep -v is your friend:

grep --help | grep invert  

-v, --invert-match select non-matching lines

Also check out the related -L (the complement of -l).

-L, --files-without-match only print FILE names containing no match

Select subset of columns in data.table R

Option using dplyr

require(dplyr)
dt<-as.data.frame(matrix(runif(10*10),10,10))
dt <- select(dt, -V1, -V2, -V3, -V4)
cor(dt)

how to set JAVA_OPTS for Tomcat in Windows?

This is because, the amount of memory you wish to assign for JVM is not available or may be you are assigning more than available memory. Try small size then u can see the difference.
Try:

set JAVA_OPTS=-Xms128m -Xmx512m -XX:PermSize=128m

offsetTop vs. jQuery.offset().top

Try this: parseInt(jQuery.offset().top, 10)

gcc/g++: "No such file or directory"

this works for me, sudo apt-get install libx11-dev

How to get ° character in a string in python?

Above answers assume that UTF8 encoding can safely be used - this one is specifically targetted for Windows.

The Windows console normaly uses CP850 encoding and not utf-8, so if you try to use a source file utf8-encoded, you get those 2 (incorrect) characters instead of a degree °.

Demonstration (using python 2.7 in a windows console):

deg = u'\xb0`  # utf code for degree
print deg.encode('utf8')

effectively outputs .

Fix: just force the correct encoding (or better use unicode):

local_encoding = 'cp850'    # adapt for other encodings
deg = u'\xb0'.encode(local_encoding)
print deg

or if you use a source file that explicitely defines an encoding:

# -*- coding: utf-8 -*-
local_encoding = 'cp850'  # adapt for other encodings
print " The current temperature in the country/city you've entered is " + temp_in_county_or_city + "°C.".decode('utf8').encode(local_encoding)

How to set DOM element as the first child?

2018 version - prepend

parent.prepend(newChild)  // [newChild, child1, child2]

This is modern JS! It is more readable than previous options. It is currently available in Chrome, FF, and Opera.

The equivalent for adding to the end is append, replacing the old appendChild

parent.append(newChild)  // [child1, child2, newChild]

Advanced usage

  1. You can pass multiple values (or use spread operator ...).
  2. Any string value will be added as a text element.

Examples:

parent.prepend(newChild, "foo")   // [newChild, "foo", child1, child2]

const list = ["bar", newChild]
parent.append(...list, "fizz")    // [child1, child2, "bar", newChild, "fizz"]

Related DOM methods

  1. Read More - child.before and child.after
  2. Read More - child.replaceWith

Mozilla Documentation

Can I Use

How to resize datagridview control when form resizes

In your form constructor you could create an event handler like this:

this.SizeChanged(frm_sizeChanged);

Then create an event handler that resizes the grid appropriately, example:

private void frm_sizeChanged(object sender, EventArgs e)
{
     dataGrid.Size = new Size(100, 200);
}

Replacing those numbers with whatever you'd like.

Adding a public key to ~/.ssh/authorized_keys does not log me in automatically

Listing a public key in .ssh/authorized_keys is necessary, but not sufficient for sshd (server) to accept it. If your private key is passphrase-protected, you'll need to give ssh (client) the passphrase every time. Or you can use ssh-agent, or a GNOME equivalent.

Your updated trace is consistent with a passphrase-protected private key. See ssh-agent, or use ssh-keygen -p.

Jinja2 template not rendering if-elif-else statement properly

You are testing if the values of the variables error and Already are present in RepoOutput[RepoName.index(repo)]. If these variables don't exist then an undefined object is used.

Both of your if and elif tests therefore are false; there is no undefined object in the value of RepoOutput[RepoName.index(repo)].

I think you wanted to test if certain strings are in the value instead:

{% if "error" in RepoOutput[RepoName.index(repo)] %}
    <td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% elif "Already" in RepoOutput[RepoName.index(repo) %}
    <td id="good"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% else %}
    <td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% endif %}
</tr>

Other corrections I made:

  • Used {% elif ... %} instead of {$ elif ... %}.
  • moved the </tr> tag out of the if conditional structure, it needs to be there always.
  • put quotes around the id attribute

Note that most likely you want to use a class attribute instead here, not an id, the latter must have a value that must be unique across your HTML document.

Personally, I'd set the class value here and reduce the duplication a little:

{% if "Already" in RepoOutput[RepoName.index(repo)] %}
    {% set row_class = "good" %}
{% else %}
    {% set row_class = "error" %}
{% endif %}
<td class="{{ row_class }}"> {{ RepoOutput[RepoName.index(repo)] }} </td>

Google maps API V3 - multiple markers on exact same spot

Check out Marker Clusterer for V3 - this library clusters nearby points into a group marker. The map zooms in when the clusters are clicked. I'd imagine when zoomed right in you'd still have the same problem with markers on the same spot though.

"The given path's format is not supported."

Image img = Image.FromFile(System.IO.Path.GetFullPath("C:\\ File Address"));

you need getfullpath by pointed class. I had same error and fixed...

Secure random token in Node.js

Look at real_ates ES2016 way, it's more correct.

ECMAScript 2016 (ES7) way

import crypto from 'crypto';

function spawnTokenBuf() {
    return function(callback) {
        crypto.randomBytes(48, callback);
    };
}

async function() {
    console.log((await spawnTokenBuf()).toString('base64'));
};

Generator/Yield Way

var crypto = require('crypto');
var co = require('co');

function spawnTokenBuf() {
    return function(callback) {
        crypto.randomBytes(48, callback);
    };
}

co(function* () {
    console.log((yield spawnTokenBuf()).toString('base64'));
});

Using Position Relative/Absolute within a TD?

With regards to your second attempt, did you try using vertical align ? Either

<td valign="bottom">

or with css

vertical-align:bottom

How do I replace whitespaces with underscore?

Python has a built in method on strings called replace which is used as so:

string.replace(old, new)

So you would use:

string.replace(" ", "_")

I had this problem a while ago and I wrote code to replace characters in a string. I have to start remembering to check the python documentation because they've got built in functions for everything.

Generate a unique id

Why not just use ToString?

public string generateID()
{
    return Guid.NewGuid().ToString("N");
}

If you would like it to be based on a URL, you could simply do the following:

public string generateID(string sourceUrl)
{
    return string.Format("{0}_{1:N}", sourceUrl, Guid.NewGuid());
}

If you want to hide the URL, you could use some form of SHA1 on the sourceURL, but I'm not sure what that might achieve.

Does a foreign key automatically create an index?

No, there is no implicit index on foreign key fields, otherwise why would Microsoft say "Creating an index on a foreign key is often useful". Your colleague may be confusing the foreign key field in the referring table with the primary key in the referred-to table - primary keys do create an implicit index.

How to get a certain element in a list, given the position?

If you frequently need to access the Nth element of a sequence, std::list, which is implemented as a doubly linked list, is probably not the right choice. std::vector or std::deque would likely be better.

That said, you can get an iterator to the Nth element using std::advance:

std::list<Object> l;
// add elements to list 'l'...

unsigned N = /* index of the element you want to retrieve */;
if (l.size() > N)
{
    std::list<Object>::iterator it = l.begin();
    std::advance(it, N);
    // 'it' points to the element at index 'N'
}

For a container that doesn't provide random access, like std::list, std::advance calls operator++ on the iterator N times. Alternatively, if your Standard Library implementation provides it, you may call std::next:

if (l.size() > N)
{
    std::list<Object>::iterator it = std::next(l.begin(), N);
}

std::next is effectively wraps a call to std::advance, making it easier to advance an iterator N times with fewer lines of code and fewer mutable variables. std::next was added in C++11.

How to set Internet options for Android emulator?

delete the existing one and recreate the emulator. The machine(windows/mac) should have internet access,and android emulator gets internet access by default.

Inputting a default image in case the src attribute of an html <img> is not valid?

A modulable version with JQuery, add this at the end of your file:

<script>
    $(function() {
        $('img[data-src-error]').error(function() {
            var o = $(this);
            var errorSrc = o.attr('data-src-error');

            if (o.attr('src') != errorSrc) {
                o.attr('src', errorSrc);
            }
        });
    });
</script>

and on your img tag:

<img src="..." data-src-error="..." />

Two's Complement in Python

Since erikb85 brought up performance, here's travc's answer against Scott Griffiths':

In [534]: a = [0b111111111111, 0b100000000000, 0b1, 0] * 1000
In [535]: %timeit [twos_comp(x, 12) for x in a]
100 loops, best of 3: 8.8 ms per loop
In [536]: %timeit [bitstring.Bits(uint=x, length=12).int for x in a]
10 loops, best of 3: 55.9 ms per loop

So, bitstring is, as found in the other question, almost an order of magnitude slower than int. But on the other hand, it's hard to beat the simplicity—I'm converting a uint to a bit-string then to an int; you'd have to work hard not to understand this, or to find anywhere to introduce a bug. And as Scott Griffiths' answer implies, there's a lot more flexibility to the class which might be useful to the same app. But on the third hand, travc's answer makes it clear what's actually happening—even a novice should be able to understand what conversion from an unsigned int to a 2s complement signed int means just from reading 2 lines of code.

Anyway, unlike the other question, which was about directly manipulating bits, this one is all about doing arithmetic on fixed-length ints, just oddly-sized ones. So I'm guessing if you need performance, it's probably because you have a whole bunch of these things, so you probably want it to be vectorized. Adapting travc's answer to numpy:

def twos_comp_np(vals, bits):
    """compute the 2's compliment of array of int values vals"""
    vals[vals & (1<<(bits-1)) != 0] -= (1<<bits)
    return vals

Now:

In [543]: a = np.array(a)
In [544]: %timeit twos_comp_np(a.copy(), 12)
10000 loops, best of 3: 63.5 µs per loop

You could probably beat that with custom C code, but you probably don't have to.

Angular2 *ngIf check object array length in template

You could use *ngIf="teamMembers != 0" to check whether data is present

Order of execution of tests in TestNG

Use this:

public class TestNG
{
        @BeforeTest
        public void setUp() 
        {
                   /*--Initialize broowsers--*/

        }

        @Test(priority=0)
        public void Login() 
        {

        }

        @Test(priority=2)
        public void Logout() 
        {

        }

        @AfterTest
        public void tearDown() 
        {
                //--Close driver--//

        }

}

Usually TestNG provides number of annotations, We can use @BeforeSuite, @BeforeTest, @BeforeClass for initializing browsers/setup.

We can assign priority if you have written number of test cases in your script and want to execute as per assigned priority then use: @Test(priority=0) starting from 0,1,2,3....

Meanwhile we can group number of test cases and execute it by grouping. for that we will use @Test(Groups='Regression')

At the end like closing the browsers we can use @AfterTest, @AfterSuite, @AfterClass annotations.

Calling async method on button click

You're the victim of the classic deadlock. task.Wait() or task.Result is a blocking call in UI thread which causes the deadlock.

Don't block in the UI thread. Never do it. Just await it.

private async void Button_Click(object sender, RoutedEventArgs 
{
      var task = GetResponseAsync<MyObject>("my url");
      var items = await task;
}

Btw, why are you catching the WebException and throwing it back? It would be better if you simply don't catch it. Both are same.

Also I can see you're mixing the asynchronous code with synchronous code inside the GetResponse method. StreamReader.ReadToEnd is a blocking call --you should be using StreamReader.ReadToEndAsync.

Also use "Async" suffix to methods which returns a Task or asynchronous to follow the TAP("Task based Asynchronous Pattern") convention as Jon says.

Your method should look something like the following when you've addressed all the above concerns.

public static async Task<List<T>> GetResponseAsync<T>(string url)
{
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
    var response = (HttpWebResponse)await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);

    Stream stream = response.GetResponseStream();
    StreamReader strReader = new StreamReader(stream);
    string text = await strReader.ReadToEndAsync();

    return JsonConvert.DeserializeObject<List<T>>(text);
}

".addEventListener is not a function" why does this error occur?

The problem with your code is that the your script is executed prior to the html element being available. Because of the that var comment is an empty array.

So you should move your script after the html element is available.

Also, getElementsByClassName returns html collection, so if you need to add event Listener to an element, you will need to do something like following

comment[0].addEventListener('click' , showComment , false ) ; 

If you want to add event listener to all the elements, then you will need to loop through them

for (var i = 0 ; i < comment.length; i++) {
   comment[i].addEventListener('click' , showComment , false ) ; 
}

Unicode characters in URLs

What Tgr said. Background:

http://www.example.com/düsseldorf?neighbourhood=Lörick

That's not a URI. But it is an IRI.

You can't include an IRI in an HTML4 document; the type of attributes like href is defined as URI and not IRI. Some browsers will handle an IRI here anyway, but it's not really a good idea.

To encode an IRI into a URI, take the path and query parts, UTF-8-encode them then percent-encode the non-ASCII bytes:

http://www.example.com/d%C3%BCsseldorf?neighbourhood=L%C3%B6rick

If there are non-ASCII characters in the hostname part of the IRI, eg. http://??.???/, they have be encoded using Punycode instead.

Now you have a URI. It's an ugly URI. But most browsers will hide that for you: copy and paste it into the address bar or follow it in a link and you'll see it displayed with the original Unicode characters. Wikipedia have been using this for years, eg.:

http://en.wikipedia.org/wiki/?

The one browser whose behaviour is unpredictable and doesn't always display the pretty IRI version is...

...well, you know.

Convert Datetime column from UTC to local time in select statement

For anyone still trying to solve this issue, here's a proof of concept that works in SQL Server 2017

 declare
    @StartDate date = '2020-01-01'

;with cte_utc as
(
    select 
         1 as i
        ,CONVERT(datetime, @StartDate) AS UTC
        ,datepart(weekday, CONVERT(datetime, @StartDate)) as Weekday
        ,datepart(month, CONVERT(datetime, @StartDate)) as [Month]
        ,datepart(YEAR, CONVERT(datetime, @StartDate)) as [Year]
        
    union all

    Select
         i + 1
        ,dateadd(d, 1, utc)
        ,datepart(weekday, CONVERT(datetime, dateadd(d, 1, utc))) as Weekday
        ,datepart(month, CONVERT(datetime, dateadd(d, 1, utc))) as [Month]
        ,datepart(YEAR, CONVERT(datetime, dateadd(d, 1, utc))) as [Year]
    from    
        cte_utc
    where
        (i + 1) < 32767

), cte_utc_dates as 
(
    select 
        *,
        DENSE_RANK()OVER(PARTITION BY [Year], [Month], [Weekday] ORDER BY Utc) WeekDayIndex
    from
        cte_utc

), cte_hours as (
    select 0 as [Hour]
    union all
    select [Hour] + 1 from cte_hours where [Hour] < 23
)

select
    d.*
    , DATEADD(hour, h.Hour, d.UTC) AS UtcTime
    ,CONVERT(datetime, DATEADD(hour, h.Hour, d.UTC) AT TIME ZONE 'UTC' AT TIME ZONE 'Central Standard Time') CST
    ,CONVERT(datetime, DATEADD(hour, h.Hour, d.UTC) AT TIME ZONE 'UTC' AT TIME ZONE 'Eastern Standard Time') EST
from
    cte_utc_dates d, cte_hours h
where
    ([Month] = 3 and [Weekday] = 1 and WeekDayIndex = 2 )-- dst start
    or 
    ([Month] = 11 and [Weekday] = 1 and WeekDayIndex = 1 )-- dst end
order by
    utc
OPTION (MAXRECURSION 32767)

GO

How to delete duplicate lines in a file without sorting it in Unix?

From http://sed.sourceforge.net/sed1line.txt: (Please don't ask me how this works ;-) )

 # delete duplicate, consecutive lines from a file (emulates "uniq").
 # First line in a set of duplicate lines is kept, rest are deleted.
 sed '$!N; /^\(.*\)\n\1$/!P; D'

 # delete duplicate, nonconsecutive lines from a file. Beware not to
 # overflow the buffer size of the hold space, or else use GNU sed.
 sed -n 'G; s/\n/&&/; /^\([ -~]*\n\).*\n\1/d; s/\n//; h; P'

How to terminate a thread when main program ends?

Try with enabling the sub-thread as daemon-thread.

For Instance:

Recommended:

from threading import Thread

t = Thread(target=<your-method>)
t.daemon = True  # This thread dies when main thread (only non-daemon thread) exits.
t.start()

Inline:

t = Thread(target=<your-method>, daemon=True).start()

Old API:

t.setDaemon(True)
t.start()

When your main thread terminates ("i.e. when I press Ctrl+C"), other threads will also be killed by the instructions above.

Is there a limit on number of tcp/ip connections between machines on linux?

You might wanna check out /etc/security/limits.conf

LDAP root query syntax to search more than one specific OU

I don't think this is possible with AD. The distinguishedName attribute is the only thing I know of that contains the OU piece on which you're trying to search, so you'd need a wildcard to get results for objects under those OUs. Unfortunately, the wildcard character isn't supported on DNs.

If at all possible, I'd really look at doing this in 2 queries using OU=Staff... and OU=Vendors... as the base DNs.

Replace image src location using CSS

you can use: content:url("image.jpg")

<style>
.your-class-name{
    content: url("http://imgur.com/SZ8Cm.jpg");
}
</style>

<img class="your-class-name" src="..."/>

Max or Default?

Sounds like a case for DefaultIfEmpty (untested code follows):

Dim x = (From y In context.MyTable _
         Where y.MyField = value _
         Select y.MyCounter).DefaultIfEmpty.Max

How to pass optional arguments to a method in C++?

An important rule with respect to default parameter usage:
Default parameters should be specified at right most end, once you specify a default value parameter you cannot specify non default parameter again. ex:

int DoSomething(int x, int y = 10, int z) -----------> Not Allowed

int DoSomething(int x, int z, int y = 10) -----------> Allowed 

How do I choose the URL for my Spring Boot webapp?

The issue of changing the context path of a Spring application is handled very well in the post titled Spring Boot Change Context Path

Basically the post discusses multiple ways of realizing this viz.

  1. Java Config
  2. Command Line Arguments
  3. Java System Properties
  4. OS Environment Variables
  5. application.properties in Current Directory
  6. application.properties in the classpath (src/main/resources or the packaged jar file)

Getting current device language in iOS?

The solutions provided will actually return the current region of the device - not the currently selected language. These are often one and the same. However, if I am in North America and I set my language to Japanese, my region will still be English (United States). In order to retrieve the currently selected language, you can do:

NSString * language = [[NSLocale preferredLanguages] firstObject];

This will return a two letter code for the currently selected language. "en" for English, "es" for Spanish, "de" for German, etc. For more examples, please see this Wikipedia entry (in particular, the 639-1 column):

List of ISO 639-1 codes

Then it's a simple matter of converting the two letter codes to the string you would like to display. So if it's "en", display "English".

Hope this helps someone that's looking to differentiate between region and currently selected language.

EDIT

Worth to quote the header information from NSLocale.h:

+ (NSArray *)preferredLanguages NS_AVAILABLE(10_5, 2_0); // note that this list does not indicate what language the app is actually running in; the [NSBundle mainBundle] object determines that at launch and knows that information

People interested in app language take a look at @mindvision's answer

Random alpha-numeric string in JavaScript?

function randomString(len) {
    var p = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    return [...Array(len)].reduce(a=>a+p[~~(Math.random()*p.length)],'');
}

Summary:

  1. Create an array of the size we want (because there's no range(len) equivalent in javascript.
  2. For each element in the array: pick a random character from p and add it to a string
  3. Return the generated string.

Some explanation:

[...Array(len)]

Array(len) or new Array(len) creates an array with undefined pointer(s). One-liners are going to be harder to pull off. The Spread syntax conveniently defines the pointers (now they point to undefined objects!).

.reduce(

Reduce the array to, in this case, a single string. The reduce functionality is common in most languages and worth learning.

a=>a+...

We're using an arrow function.

a is the accumulator. In this case it's the end-result string we're going to return when we're done (you know it's a string because the second argument to the reduce function, the initialValue is an empty string: ''). So basically: convert each element in the array with p[~~(Math.random()*p.length)], append the result to the a string and give me a when you're done.

p[...]

p is the string of characters we're selecting from. You can access chars in a string like an index (E.g., "abcdefg"[3] gives us "d")

~~(Math.random()*p.length)

Math.random() returns a floating point between [0, 1) Math.floor(Math.random()*max) is the de facto standard for getting a random integer in javascript. ~ is the bitwise NOT operator in javascript. ~~ is a shorter, arguably sometimes faster, and definitely funner way to say Math.floor( Here's some info

How do I obtain the frequencies of each value in an FFT?

I have used the following:

public static double Index2Freq(int i, double samples, int nFFT) {
  return (double) i * (samples / nFFT / 2.);
}

public static int Freq2Index(double freq, double samples, int nFFT) {
  return (int) (freq / (samples / nFFT / 2.0));
}

The inputs are:

  • i: Bin to access
  • samples: Sampling rate in Hertz (i.e. 8000 Hz, 44100Hz, etc.)
  • nFFT: Size of the FFT vector

MySQL root access from all hosts

mysql_update is what you need.

I don't know why anyone would follow the more complex ways of correcting this issue, when MySql graciously built a tool that already does this...

How to do an INNER JOIN on multiple columns

if mysql is okay for you:

SELECT flights.*, 
       fromairports.city as fromCity, 
       toairports.city as toCity
FROM flights
LEFT JOIN (airports as fromairports, airports as toairports)
ON (fromairports.code=flights.fairport AND toairports.code=flights.tairport )
WHERE flights.fairport = '?' OR fromairports.city = '?'

edit: added example to filter the output for code or city

symfony2 twig path with parameter url creation

In Twig:

{% for l in locations %}

<tr>
    <td>
        <input type="checkbox" class="filled-in" id="filled-in-box-{{ l.idLocation }}" />
        <label for="filled-in-box-{{ l.idLocation }}"></label>
    </td>
    <td>{{ l.loc }}</td>
    <td>{{ l.mun }}</td>
    <td>{{ l.pro }}</td>
    <td>{{ l.cou }}</td>
    {#<td>
        {% if l.active == 1  %}
            <span class="fa fa-check"></span>
        {% else %}
            <span class="fa fa-close"></span>
        {% endif %}
    </td>#}
    <td><a href="{{ url('admin_edit_location',{'id': l.idLocation}) }}" class="db-list-edit"><span class="fa fa-pencil-square-o"></span></a>
    </td>
</tr>{% endfor %}

The route admin_edit_location:

admin_edit_location:
  path: /edit_location/{id}
  defaults: { _controller: "AppBundle:Admin:editLocation" }
  methods: GET

And the controller

public function editLocationAction($id){
    // use $id 

    $em = $this->getDoctrine()->getManager();
    $location = $em->getRepository('BackendBundle:locations')->findOneBy(array(
    'id'    => $id
    ));
}

Java error: Implicit super constructor is undefined for default constructor

You can solve this error by adding an argumentless constructor to the base class (as shown below).

Cheers.

 abstract public class BaseClass {
        // ADD AN ARGUMENTLESS CONSTRUCTOR TO THE BASE CLASS
        public BaseClass(){
        }

        String someString;
        public BaseClass(String someString) {
            this.someString = someString;
        }
        abstract public String getName();
    }

public class ACSubClass extends BaseClass {
    public ASubClass(String someString) {
        super(someString);
    }
    public String getName() {
        return "name value for ASubClass";
    }
}

Can I set an unlimited length for maxJsonLength in web.config?

If you are encountering this sort of issue in View, you can use below method to resolve that. Here Iused Newtonsoft package .

@using Newtonsoft.Json
<script type="text/javascript">
    var partData = @Html.Raw(JsonConvert.SerializeObject(ViewBag.Part));
</script>

git recover deleted file where no commit was made after the delete

git checkout HEAD -- client/src/pp_web/index.cljs

How can I replace the deprecated set_magic_quotes_runtime in php?

Update this function :

if (version_compare(PHP_VERSION, '5.3.0', '<')) {
  set_magic_quotes_runtime(0);
}
else {
  ini_set('magic_quotes_runtime', 0);
}
$magic_quotes = get_magic_quotes_runtime();
$file_buffer = fread($fd, filesize($path));
$file_buffer = $this->EncodeString($file_buffer, $encoding);
fclose($fd);
if ($magic_quotes) {
  if (version_compare(PHP_VERSION, '5.3.0', '<')) {
    set_magic_quotes_runtime($magic_quotes);
  }
  else {
    ini_set('magic_quotes_runtime', $magic_quotes);
  }
}

return $file_buffer;

How to check if my string is equal to null?

Try,

myString!=null && myString.length()>0

Regex to replace everything except numbers and a decimal point

Use this:

document.getElementById(target).value = newVal.replace(/[^0-9.]/g, '');

SQL update from one Table to another based on a ID match

I had the same problem with foo.new being set to null for rows of foo that had no matching key in bar. I did something like this in Oracle:

update foo
set    foo.new = (select bar.new
                  from bar 
                  where foo.key = bar.key)
where exists (select 1
              from bar
              where foo.key = bar.key)

BAT file to open CMD in current directory

you can try:

shift + right click

then, click on Open command prompt here

Postgres: clear entire database before re-creating / re-populating from bash script

If you want to clean your database named "example_db":

1) Login to another db(for example 'postgres'):

psql postgres

2) Remove your database:

DROP DATABASE example_db;

3) Recreate your database:

CREATE DATABASE example_db;

NSUserDefaults - How to tell if a key exists

I just went through this, and all of your answers helped me toward a good solution, for me. I resisted going the route suggested by, just because I found it hard to read and comprehend.

Here's what I did. I had a BOOL being carried around in a variable called "_talkative".

When I set my default (NSUserDefaults) object, I set it as an object, as I could then test to see if it was nil:

//converting BOOL to an object so we can check on nil
[defaults setObject:@(_talkative) forKey:@"talkative"];

Then when I went to see if it existed, I used:

if ([defaults objectForKey:@"talkative"]!=nil )
  {

Then I used the object as a BOOL:

if ([defaults boolForKey:@"talkative"]) {
 ...

This seems to work in my case. It just made more visual sense to me.

Is there a CSS selector by class prefix?

This is not possible with CSS selectors. But you could use two classes instead of one, e.g. status and important instead of status-important.

jQuery: Change button text on click

In HTML:

<button type="button" id="AddButton" onclick="AddButtonClick()" class="btn btn-success btn-block ">Add</button> 

In Jquery write this function:

    function AddButtonClick(){ 
      //change text from add to Update
      $("#AddButton").text('Update');
    }

Local file access with JavaScript

If you're deploying on Windows, the Windows Script Host offers a very useful JScript API to the file system and other local resources. Incorporating WSH scripts into a local web application may not be as elegant as you might wish, however.

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

One more thing to check: if you've set up HTTPS access before setting up PHP -- I used certbot -- you'll need to make the changes in /etc/nginx/sites-available/default twice because there will be two server blocks (one listening on port 80 and one listening on port 443).

(I was setting up this server primarily for email and didn't have any use for PHP when I first installed nginx just as a way to run certbot more easily.)

Edit a commit message in SourceTree Windows (already pushed to remote)

If the comment message includes non-English characters, using method provided by user456814, those characters will be replaced by question marks. (tested under sourcetree Ver2.5.5.0)

So I have to use the following method.

CAUTION: if the commit has been pulled by other members, changes below might cause chaos for them.

Step1: In the sourcetree main window, locate your repo tab, and click the "terminal" button to open the git command console.

Step2:

[Situation A]: target commit is the latest one.

1) In the git command console, input

git commit --amend -m "new comment message"

2) If the target commit has been pushed to remote, you have to push again by force. In the git command console, input

git push --force

[Situation B]: target commit is not the latest one.

1) In the git command console, input

git rebase -i HEAD~n

It is to squash the latest n commits. e.g. if you want to edit the message before the last one, n is 2. This command will open a vi window, the first word of each line is "pick", and you change the "pick" to "reword" for the line you want to edit. Then, input :wq to save&quit that vi window. Now, a new vi window will be open, in this window you input your new message. Also use :wq to save&quit.

2) If the target commit has been pushed to remote, you have to push again by force. In the git command console, input

git push --force


Finally: In the sourcetree main window, Press F5 to refresh.

Parse RSS with jQuery

jFeed is easy and has an example for you to test. But if you're parsing a feed from another server, you'll need to allow Cross Origin Resource Sharing (CORS) on the feed's server. You'll also need to check browser support.

I uploaded the sample but still did not get support from IE in any version when I changed the url in the example to something like example.com/feed.rss via the http protocol. CORS should be supported for IE 8 and above but the jFeed example did not render the feed.

Your best bet is to use Google's API:
https://developers.google.com/feed/v1/devguide

See:
https://github.com/jfhovinne/jFeed
http://en.wikipedia.org/wiki/Cross-origin_resource_sharing
http://en.wikipedia.org/wiki/Same_origin_policy
http://caniuse.com/cors

TCPDF Save file to folder?

$pdf->Output() takes a second parameter $dest, which accepts a single character. The default, $dest='I' opens the PDF in the browser.

Use F to save to file

$pdf->Output('/path/to/file.pdf', 'F')

Finding the length of a Character Array in C

If you have an array, then you can find the number of elements in the array by dividing the size of the array in bytes by the size of each element in bytes:

char x[10];
int elements_in_x = sizeof(x) / sizeof(x[0]);

For the specific case of char, since sizeof(char) == 1, sizeof(x) will yield the same result.

If you only have a pointer to an array, then there's no way to find the number of elements in the pointed-to array. You have to keep track of that yourself. For example, given:

char x[10];
char* pointer_to_x = x;

there is no way to tell from just pointer_to_x that it points to an array of 10 elements. You have to keep track of that information yourself.

There are numerous ways to do that: you can either store the number of elements in a variable or you can encode the contents of the array such that you can get its size somehow by analyzing its contents (this is effectively what null-terminated strings do: they place a '\0' character at the end of the string so that you know when the string ends).

for loop in Python

Use this instead of a for loop:

k = 1
while k <= c:
   #code
   k += 1

How to check how many letters are in a string in java?

1) To answer your question:

  String s="Java";
  System.out.println(s.length()); 

How do a send an HTTPS request through a proxy in Java?

Try the Apache Commons HttpClient library instead of trying to roll your own: http://hc.apache.org/httpclient-3.x/index.html

From their sample code:

  HttpClient httpclient = new HttpClient();
  httpclient.getHostConfiguration().setProxy("myproxyhost", 8080);

  /* Optional if authentication is required.
  httpclient.getState().setProxyCredentials("my-proxy-realm", " myproxyhost",
   new UsernamePasswordCredentials("my-proxy-username", "my-proxy-password"));
  */

  PostMethod post = new PostMethod("https://someurl");
  NameValuePair[] data = {
     new NameValuePair("user", "joe"),
     new NameValuePair("password", "bloggs")
  };
  post.setRequestBody(data);
  // execute method and handle any error responses.
  // ...
  InputStream in = post.getResponseBodyAsStream();
  // handle response.


  /* Example for a GET reqeust
  GetMethod httpget = new GetMethod("https://someurl");
  try { 
    httpclient.executeMethod(httpget);
    System.out.println(httpget.getStatusLine());
  } finally {
    httpget.releaseConnection();
  }
  */

Remove the last chars of the Java String variable

Another way:

if (s.size > 5) s.reverse.substring(5).reverse

BTW, this is Scala code. May need brackets to work in Java.

How to fill DataTable with SQL Table

You can make method which return the datatable of given sql query:

public DataTable GetDataTable()
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["BarManConnectionString"].ConnectionString);
conn.Open();
string query = "SELECT * FROM [EventOne] ";

SqlCommand cmd = new SqlCommand(query, conn);

DataTable t1 = new DataTable();
using (SqlDataAdapter a = new SqlDataAdapter(cmd))
{
    a.Fill(t1);
}
return t1;
}

and now can be used like this:

table = GetDataTable();

How to get row number in dataframe in Pandas?

df.index[df.LastName == 'Smith']

Or

df.query('LastName == "Smith"').index

Will return all row indices where LastName is Smith

Int64Index([1], dtype='int64')

If...Then...Else with multiple statements after Then

This works with multiple statements:

if condition1 Then stmt1:stmt2 Else if condition2 Then stmt3:stmt4 Else stmt5:stmt6

Or you can split it over multiple lines:

if condition1 Then stmt1:stmt2
Else if condition2 Then stmt3:stmt4
Else stmt5:stmt6

How do SO_REUSEADDR and SO_REUSEPORT differ?

Welcome to the wonderful world of portability... or rather the lack of it. Before we start analyzing these two options in detail and take a deeper look how different operating systems handle them, it should be noted that the BSD socket implementation is the mother of all socket implementations. Basically all other systems copied the BSD socket implementation at some point in time (or at least its interfaces) and then started evolving it on their own. Of course the BSD socket implementation was evolved as well at the same time and thus systems that copied it later got features that were lacking in systems that copied it earlier. Understanding the BSD socket implementation is the key to understanding all other socket implementations, so you should read about it even if you don't care to ever write code for a BSD system.

There are a couple of basics you should know before we look at these two options. A TCP/UDP connection is identified by a tuple of five values:

{<protocol>, <src addr>, <src port>, <dest addr>, <dest port>}

Any unique combination of these values identifies a connection. As a result, no two connections can have the same five values, otherwise the system would not be able to distinguish these connections any longer.

The protocol of a socket is set when a socket is created with the socket() function. The source address and port are set with the bind() function. The destination address and port are set with the connect() function. Since UDP is a connectionless protocol, UDP sockets can be used without connecting them. Yet it is allowed to connect them and in some cases very advantageous for your code and general application design. In connectionless mode, UDP sockets that were not explicitly bound when data is sent over them for the first time are usually automatically bound by the system, as an unbound UDP socket cannot receive any (reply) data. Same is true for an unbound TCP socket, it is automatically bound before it will be connected.

If you explicitly bind a socket, it is possible to bind it to port 0, which means "any port". Since a socket cannot really be bound to all existing ports, the system will have to choose a specific port itself in that case (usually from a predefined, OS specific range of source ports). A similar wildcard exists for the source address, which can be "any address" (0.0.0.0 in case of IPv4 and :: in case of IPv6). Unlike in case of ports, a socket can really be bound to "any address" which means "all source IP addresses of all local interfaces". If the socket is connected later on, the system has to choose a specific source IP address, since a socket cannot be connected and at the same time be bound to any local IP address. Depending on the destination address and the content of the routing table, the system will pick an appropriate source address and replace the "any" binding with a binding to the chosen source IP address.

By default, no two sockets can be bound to the same combination of source address and source port. As long as the source port is different, the source address is actually irrelevant. Binding socketA to ipA:portA and socketB to ipB:portB is always possible if ipA != ipB holds true, even when portA == portB. E.g. socketA belongs to a FTP server program and is bound to 192.168.0.1:21 and socketB belongs to another FTP server program and is bound to 10.0.0.1:21, both bindings will succeed. Keep in mind, though, that a socket may be locally bound to "any address". If a socket is bound to 0.0.0.0:21, it is bound to all existing local addresses at the same time and in that case no other socket can be bound to port 21, regardless which specific IP address it tries to bind to, as 0.0.0.0 conflicts with all existing local IP addresses.

Anything said so far is pretty much equal for all major operating system. Things start to get OS specific when address reuse comes into play. We start with BSD, since as I said above, it is the mother of all socket implementations.

BSD

SO_REUSEADDR

If SO_REUSEADDR is enabled on a socket prior to binding it, the socket can be successfully bound unless there is a conflict with another socket bound to exactly the same combination of source address and port. Now you may wonder how is that any different than before? The keyword is "exactly". SO_REUSEADDR mainly changes the way how wildcard addresses ("any IP address") are treated when searching for conflicts.

Without SO_REUSEADDR, binding socketA to 0.0.0.0:21 and then binding socketB to 192.168.0.1:21 will fail (with error EADDRINUSE), since 0.0.0.0 means "any local IP address", thus all local IP addresses are considered in use by this socket and this includes 192.168.0.1, too. With SO_REUSEADDR it will succeed, since 0.0.0.0 and 192.168.0.1 are not exactly the same address, one is a wildcard for all local addresses and the other one is a very specific local address. Note that the statement above is true regardless in which order socketA and socketB are bound; without SO_REUSEADDR it will always fail, with SO_REUSEADDR it will always succeed.

To give you a better overview, let's make a table here and list all possible combinations:

SO_REUSEADDR       socketA        socketB       Result
---------------------------------------------------------------------
  ON/OFF       192.168.0.1:21   192.168.0.1:21    Error (EADDRINUSE)
  ON/OFF       192.168.0.1:21      10.0.0.1:21    OK
  ON/OFF          10.0.0.1:21   192.168.0.1:21    OK
   OFF             0.0.0.0:21   192.168.1.0:21    Error (EADDRINUSE)
   OFF         192.168.1.0:21       0.0.0.0:21    Error (EADDRINUSE)
   ON              0.0.0.0:21   192.168.1.0:21    OK
   ON          192.168.1.0:21       0.0.0.0:21    OK
  ON/OFF           0.0.0.0:21       0.0.0.0:21    Error (EADDRINUSE)

The table above assumes that socketA has already been successfully bound to the address given for socketA, then socketB is created, either gets SO_REUSEADDR set or not, and finally is bound to the address given for socketB. Result is the result of the bind operation for socketB. If the first column says ON/OFF, the value of SO_REUSEADDR is irrelevant to the result.

Okay, SO_REUSEADDR has an effect on wildcard addresses, good to know. Yet that isn't it's only effect it has. There is another well known effect which is also the reason why most people use SO_REUSEADDR in server programs in the first place. For the other important use of this option we have to take a deeper look on how the TCP protocol works.

A socket has a send buffer and if a call to the send() function succeeds, it does not mean that the requested data has actually really been sent out, it only means the data has been added to the send buffer. For UDP sockets, the data is usually sent pretty soon, if not immediately, but for TCP sockets, there can be a relatively long delay between adding data to the send buffer and having the TCP implementation really send that data. As a result, when you close a TCP socket, there may still be pending data in the send buffer, which has not been sent yet but your code considers it as sent, since the send() call succeeded. If the TCP implementation was closing the socket immediately on your request, all of this data would be lost and your code wouldn't even know about that. TCP is said to be a reliable protocol and losing data just like that is not very reliable. That's why a socket that still has data to send will go into a state called TIME_WAIT when you close it. In that state it will wait until all pending data has been successfully sent or until a timeout is hit, in which case the socket is closed forcefully.

At most, the amount of time the kernel will wait before it closes the socket, regardless if it still has data in flight or not, is called the Linger Time. The Linger Time is globally configurable on most systems and by default rather long (two minutes is a common value you will find on many systems). It is also configurable per socket using the socket option SO_LINGER which can be used to make the timeout shorter or longer, and even to disable it completely. Disabling it completely is a very bad idea, though, since closing a TCP socket gracefully is a slightly complex process and involves sending forth and back a couple of packets (as well as resending those packets in case they got lost) and this whole close process is also limited by the Linger Time. If you disable lingering, your socket may not only lose data in flight, it is also always closed forcefully instead of gracefully, which is usually not recommended. The details about how a TCP connection is closed gracefully are beyond the scope of this answer, if you want to learn more about, I recommend you have a look at this page. And even if you disabled lingering with SO_LINGER, if your process dies without explicitly closing the socket, BSD (and possibly other systems) will linger nonetheless, ignoring what you have configured. This will happen for example if your code just calls exit() (pretty common for tiny, simple server programs) or the process is killed by a signal (which includes the possibility that it simply crashes because of an illegal memory access). So there is nothing you can do to make sure a socket will never linger under all circumstances.

The question is, how does the system treat a socket in state TIME_WAIT? If SO_REUSEADDR is not set, a socket in state TIME_WAIT is considered to still be bound to the source address and port and any attempt to bind a new socket to the same address and port will fail until the socket has really been closed, which may take as long as the configured Linger Time. So don't expect that you can rebind the source address of a socket immediately after closing it. In most cases this will fail. However, if SO_REUSEADDR is set for the socket you are trying to bind, another socket bound to the same address and port in state TIME_WAIT is simply ignored, after all its already "half dead", and your socket can bind to exactly the same address without any problem. In that case it plays no role that the other socket may have exactly the same address and port. Note that binding a socket to exactly the same address and port as a dying socket in TIME_WAIT state can have unexpected, and usually undesired, side effects in case the other socket is still "at work", but that is beyond the scope of this answer and fortunately those side effects are rather rare in practice.

There is one final thing you should know about SO_REUSEADDR. Everything written above will work as long as the socket you want to bind to has address reuse enabled. It is not necessary that the other socket, the one which is already bound or is in a TIME_WAIT state, also had this flag set when it was bound. The code that decides if the bind will succeed or fail only inspects the SO_REUSEADDR flag of the socket fed into the bind() call, for all other sockets inspected, this flag is not even looked at.

SO_REUSEPORT

SO_REUSEPORT is what most people would expect SO_REUSEADDR to be. Basically, SO_REUSEPORT allows you to bind an arbitrary number of sockets to exactly the same source address and port as long as all prior bound sockets also had SO_REUSEPORT set before they were bound. If the first socket that is bound to an address and port does not have SO_REUSEPORT set, no other socket can be bound to exactly the same address and port, regardless if this other socket has SO_REUSEPORT set or not, until the first socket releases its binding again. Unlike in case of SO_REUESADDR the code handling SO_REUSEPORT will not only verify that the currently bound socket has SO_REUSEPORT set but it will also verify that the socket with a conflicting address and port had SO_REUSEPORT set when it was bound.

SO_REUSEPORT does not imply SO_REUSEADDR. This means if a socket did not have SO_REUSEPORT set when it was bound and another socket has SO_REUSEPORT set when it is bound to exactly the same address and port, the bind fails, which is expected, but it also fails if the other socket is already dying and is in TIME_WAIT state. To be able to bind a socket to the same addresses and port as another socket in TIME_WAIT state requires either SO_REUSEADDR to be set on that socket or SO_REUSEPORT must have been set on both sockets prior to binding them. Of course it is allowed to set both, SO_REUSEPORT and SO_REUSEADDR, on a socket.

There is not much more to say about SO_REUSEPORT other than that it was added later than SO_REUSEADDR, that's why you will not find it in many socket implementations of other systems, which "forked" the BSD code before this option was added, and that there was no way to bind two sockets to exactly the same socket address in BSD prior to this option.

Connect() Returning EADDRINUSE?

Most people know that bind() may fail with the error EADDRINUSE, however, when you start playing around with address reuse, you may run into the strange situation that connect() fails with that error as well. How can this be? How can a remote address, after all that's what connect adds to a socket, be already in use? Connecting multiple sockets to exactly the same remote address has never been a problem before, so what's going wrong here?

As I said on the very top of my reply, a connection is defined by a tuple of five values, remember? And I also said, that these five values must be unique otherwise the system cannot distinguish two connections any longer, right? Well, with address reuse, you can bind two sockets of the same protocol to the same source address and port. That means three of those five values are already the same for these two sockets. If you now try to connect both of these sockets also to the same destination address and port, you would create two connected sockets, whose tuples are absolutely identical. This cannot work, at least not for TCP connections (UDP connections are no real connections anyway). If data arrived for either one of the two connections, the system could not tell which connection the data belongs to. At least the destination address or destination port must be different for either connection, so that the system has no problem to identify to which connection incoming data belongs to.

So if you bind two sockets of the same protocol to the same source address and port and try to connect them both to the same destination address and port, connect() will actually fail with the error EADDRINUSE for the second socket you try to connect, which means that a socket with an identical tuple of five values is already connected.

Multicast Addresses

Most people ignore the fact that multicast addresses exist, but they do exist. While unicast addresses are used for one-to-one communication, multicast addresses are used for one-to-many communication. Most people got aware of multicast addresses when they learned about IPv6 but multicast addresses also existed in IPv4, even though this feature was never widely used on the public Internet.

The meaning of SO_REUSEADDR changes for multicast addresses as it allows multiple sockets to be bound to exactly the same combination of source multicast address and port. In other words, for multicast addresses SO_REUSEADDR behaves exactly as SO_REUSEPORT for unicast addresses. Actually, the code treats SO_REUSEADDR and SO_REUSEPORT identically for multicast addresses, that means you could say that SO_REUSEADDR implies SO_REUSEPORT for all multicast addresses and the other way round.


FreeBSD/OpenBSD/NetBSD

All these are rather late forks of the original BSD code, that's why they all three offer the same options as BSD and they also behave the same way as in BSD.


macOS (MacOS X)

At its core, macOS is simply a BSD-style UNIX named "Darwin", based on a rather late fork of the BSD code (BSD 4.3), which was then later on even re-synchronized with the (at that time current) FreeBSD 5 code base for the Mac OS 10.3 release, so that Apple could gain full POSIX compliance (macOS is POSIX certified). Despite having a microkernel at its core ("Mach"), the rest of the kernel ("XNU") is basically just a BSD kernel, and that's why macOS offers the same options as BSD and they also behave the same way as in BSD.

iOS / watchOS / tvOS

iOS is just a macOS fork with a slightly modified and trimmed kernel, somewhat stripped down user space toolset and a slightly different default framework set. watchOS and tvOS are iOS forks, that are stripped down even further (especially watchOS). To my best knowledge they all behave exactly as macOS does.


Linux

Linux < 3.9

Prior to Linux 3.9, only the option SO_REUSEADDR existed. This option behaves generally the same as in BSD with two important exceptions:

  1. As long as a listening (server) TCP socket is bound to a specific port, the SO_REUSEADDR option is entirely ignored for all sockets targeting that port. Binding a second socket to the same port is only possible if it was also possible in BSD without having SO_REUSEADDR set. E.g. you cannot bind to a wildcard address and then to a more specific one or the other way round, both is possible in BSD if you set SO_REUSEADDR. What you can do is you can bind to the same port and two different non-wildcard addresses, as that's always allowed. In this aspect Linux is more restrictive than BSD.

  2. The second exception is that for client sockets, this option behaves exactly like SO_REUSEPORT in BSD, as long as both had this flag set before they were bound. The reason for allowing that was simply that it is important to be able to bind multiple sockets to exactly to the same UDP socket address for various protocols and as there used to be no SO_REUSEPORT prior to 3.9, the behavior of SO_REUSEADDR was altered accordingly to fill that gap. In that aspect Linux is less restrictive than BSD.

Linux >= 3.9

Linux 3.9 added the option SO_REUSEPORT to Linux as well. This option behaves exactly like the option in BSD and allows binding to exactly the same address and port number as long as all sockets have this option set prior to binding them.

Yet, there are still two differences to SO_REUSEPORT on other systems:

  1. To prevent "port hijacking", there is one special limitation: All sockets that want to share the same address and port combination must belong to processes that share the same effective user ID! So one user cannot "steal" ports of another user. This is some special magic to somewhat compensate for the missing SO_EXCLBIND/SO_EXCLUSIVEADDRUSE flags.

  2. Additionally the kernel performs some "special magic" for SO_REUSEPORT sockets that isn't found in other operating systems: For UDP sockets, it tries to distribute datagrams evenly, for TCP listening sockets, it tries to distribute incoming connect requests (those accepted by calling accept()) evenly across all the sockets that share the same address and port combination. Thus an application can easily open the same port in multiple child processes and then use SO_REUSEPORT to get a very inexpensive load balancing.


Android

Even though the whole Android system is somewhat different from most Linux distributions, at its core works a slightly modified Linux kernel, thus everything that applies to Linux should apply to Android as well.


Windows

Windows only knows the SO_REUSEADDR option, there is no SO_REUSEPORT. Setting SO_REUSEADDR on a socket in Windows behaves like setting SO_REUSEPORT and SO_REUSEADDR on a socket in BSD, with one exception:

Prior to Windows 2003, a socket with SO_REUSEADDR could always been bound to exactly the same source address and port as an already bound socket, even if the other socket did not have this option set when it was bound. This behavior allowed an application "to steal" the connected port of another application. Needless to say that this has major security implications!

Microsoft realized that and added another important socket option: SO_EXCLUSIVEADDRUSE. Setting SO_EXCLUSIVEADDRUSE on a socket makes sure that if the binding succeeds, the combination of source address and port is owned exclusively by this socket and no other socket can bind to them, not even if it has SO_REUSEADDR set.

This default behavior was changed first in Windows 2003, Microsoft calls that "Enhanced Socket Security" (funny name for a behavior that is default on all other major operating systems). For more details just visit this page. There are three tables: The first one shows the classic behavior (still in use when using compatibility modes!), the second one shows the behavior of Windows 2003 and up when the bind() calls are made by the same user, and the third one when the bind() calls are made by different users.


Solaris

Solaris is the successor of SunOS. SunOS was originally based on a fork of BSD, SunOS 5 and later was based on a fork of SVR4, however SVR4 is a merge of BSD, System V, and Xenix, so up to some degree Solaris is also a BSD fork, and a rather early one. As a result Solaris only knows SO_REUSEADDR, there is no SO_REUSEPORT. The SO_REUSEADDR behaves pretty much the same as it does in BSD. As far as I know there is no way to get the same behavior as SO_REUSEPORT in Solaris, that means it is not possible to bind two sockets to exactly the same address and port.

Similar to Windows, Solaris has an option to give a socket an exclusive binding. This option is named SO_EXCLBIND. If this option is set on a socket prior to binding it, setting SO_REUSEADDR on another socket has no effect if the two sockets are tested for an address conflict. E.g. if socketA is bound to a wildcard address and socketB has SO_REUSEADDR enabled and is bound to a non-wildcard address and the same port as socketA, this bind will normally succeed, unless socketA had SO_EXCLBIND enabled, in which case it will fail regardless the SO_REUSEADDR flag of socketB.


Other Systems

In case your system is not listed above, I wrote a little test program that you can use to find out how your system handles these two options. Also if you think my results are wrong, please first run that program before posting any comments and possibly making false claims.

All that the code requires to build is a bit POSIX API (for the network parts) and a C99 compiler (actually most non-C99 compiler will work as well as long as they offer inttypes.h and stdbool.h; e.g. gcc supported both long before offering full C99 support).

All that the program needs to run is that at least one interface in your system (other than the local interface) has an IP address assigned and that a default route is set which uses that interface. The program will gather that IP address and use it as the second "specific address".

It tests all possible combinations you can think of:

  • TCP and UDP protocol
  • Normal sockets, listen (server) sockets, multicast sockets
  • SO_REUSEADDR set on socket1, socket2, or both sockets
  • SO_REUSEPORT set on socket1, socket2, or both sockets
  • All address combinations you can make out of 0.0.0.0 (wildcard), 127.0.0.1 (specific address), and the second specific address found at your primary interface (for multicast it's just 224.1.2.3 in all tests)

and prints the results in a nice table. It will also work on systems that don't know SO_REUSEPORT, in which case this option is simply not tested.

What the program cannot easily test is how SO_REUSEADDR acts on sockets in TIME_WAIT state as it's very tricky to force and keep a socket in that state. Fortunately most operating systems seems to simply behave like BSD here and most of the time programmers can simply ignore the existence of that state.

Here's the code (I cannot include it here, answers have a size limit and the code would push this reply over the limit).

CreateProcess error=206, The filename or extension is too long when running main() method

it happens due to DataNucleus sometimes overwrite the Arguments with many paths.

You have to overwrite them with this:

-enhancerName ASM -api JDO -pu MediaToGo

Hope help you!

Git fatal: protocol 'https' is not supported

This issue persisted even after the fix from most upvoted answer.

More specific, I pasted in the link without "Ctrl + v", but it still gave fatal: protocol 'https' is not supported.

But if you copy that message in Windows or in Google search bar you will that the actual message is fatal: protocol '##https' is not supported, where '#' stands for this character. As you can see, those 2 characters have not been removed.

I was working on IntelliJ IDEA Community Edition 2019.2.3 and the following fix refers to this tool, but the answer is that those 2 characters are still there and need to be removed from the link.

IntelliJ fix

Go to top bar, select VCS -> Git -> Remotes... and click.

Now it will open something link this

enter image description here

You can see those 2 unrecognised characters. We have to remove them. Either click edit icon and delete those 2 characters or you can delete the link and add a new one.

Make sure you have ".git" folder in your project folder.

enter image description here

And now it should like this. Click "Ok" and now you can push files to your git repository.

enter image description here

How do I get the resource id of an image if I know its name?

Example for a public system resource:

// this will get id for android.R.drawable.ic_dialog_alert
int id = Resources.getSystem().getIdentifier("ic_dialog_alert", "drawable", "android");

alert

Another way is to refer the documentation for android.R.drawable class.

How do I sort a dictionary by value?

Beside using builtin module etc, i try solve it manually..... first i made a function whose job is to returning minimal value each items of the dict :

def returnminDict(_dct):
    dict_items = _dct.items()
    list_items = list(dict_items)
    init_items = list_items[0]
    for i in range(len(list_items)):
        if list_items[i][1] > init_items[1]:
           continue
        else:
           init_items = list_items[i]
    return init_items

Second, now we have a function which return item that has minimal value, then i make a new dict then loop over the dict :

def SelectDictSort(_dct):
    new_dict = {}
    while _dct:
        mindict = returnminDict(_dct)
        new_dict.update(dict((mindict,)))
        _dct.pop(mindict[0])
    return new_dict

i try this SelectDictSort({2: 5, 5: 1, 4: 3, 1: 1, 0: 1, 9: 2, 8: 2}) will return :

{0: 1, 1: 1, 5: 1, 8: 2, 9: 2, 4: 3, 2: 5}

Hmmm... i dont know which is correct but this what i have tried....

(updated code from retrun new_dct to return new_dict)

Android splash screen image sizes to fit all devices

Disclaimer

This answer is from 2013 and is seriously outdated. As of Android 3.2 there are now 6 groups of screen density. This answer will be updated as soon as I am able, but with no ETA. Refer to the official documentation for all the densities at the moment (although information on specific pixel sizes is as always hard to find).

Here's the tl/dr version

  • Create 4 images, one for each screen density:

    • xlarge (xhdpi): 640x960
    • large (hdpi): 480x800
    • medium (mdpi): 320x480
    • small (ldpi): 240x320
  • Read 9-patch image introduction in Android Developer Guide

  • Design images that have areas that can be safely stretched without compromising the end result

With this, Android will select the appropriate file for the device's image density, then it will stretch the image according to the 9-patch standard.

end of tl;dr. Full post ahead

I am answering in respect to the design-related aspect of the question. I am not a developer, so I won't be able to provide code for implementing many of the solutions provided. Alas, my intent is to help designers who are as lost as I was when I helped develop my first Android App.

Fitting all sizes

With Android, companies can develop their mobile phones and tables of almost any size, with almost any resolution they want. Because of that, there is no "right image size" for a splash screen, as there are no fixed screen resolutions. That poses a problem for people that want to implement a splash screen.

Do your users really want to see a splash screen?

(On a side note, splash screens are somewhat discouraged among the usability guys. It is argued that the user already knows what app he tapped on, and branding your image with a splash screen is not necessary, as it only interrupts the user experience with an "ad". It should be used, however, in applications that require some considerable loading when initialized (5s+), including games and such, so that the user is not stuck wondering if the app crashed or not)

Screen density; 4 classes

So, given so many different screen resolutions in the phones on the market, Google implemented some alternatives and nifty solutions that can help. The first thing you have to know is that Android separates ALL screens into 4 distinct screen densities:

  1. Low Density (ldpi ~ 120dpi)
  2. Medium Density (mdpi ~ 160dpi)
  3. High Density (hdpi ~ 240dpi)
  4. Extra-High Density (xhdpi ~ 320dpi) (These dpi values are approximations, since custom built devices will have varying dpi values)

What you (if you're a designer) need to know from this is that Android basically chooses from 4 images to display, depending on the device. So you basically have to design 4 different images (although more can be developed for different formats such as widescreen, portrait/landscape mode, etc).

With that in mind know this: unless you design a screen for every single resolution that is used in Android, your image will stretch to fit screen size. And unless your image is basically a gradient or blur, you'll get some undesired distortion with the stretching. So you have basically two options: create an image for each screen size/density combination, or create four 9-patch images.

The hardest solution is to design a different splash screen for every single resolution. You can start by following the resolutions in the table at the end of this page (there are more. Example: 960 x 720 is not listed there). And assuming you have some small detail in the image, such as small text, you have to design more than one screen for each resolution. For example, a 480x800 image being displayed in a medium screen might look ok, but on a smaller screen (with higher density/dpi) the logo might become too small, or some text might become unreadable.

9-patch image

The other solution is to create a 9-patch image. It is basically a 1-pixel-transparent-border around your image, and by drawing black pixels in the top and left area of this border you can define which portions of your image will be allowed to stretch. I won't go into the details of how 9-patch images work but, in short, the pixels that align to the markings in the top and left area are the pixels that will be repeated to stretch the image.

A few ground rules

  1. You can make these images in photoshop (or any image editing software that can accurately create transparent pngs).
  2. The 1-pixel border has to be FULL TRANSPARENT.
  3. The 1-pixel transparent border has to be all around your image, not just top and left.
  4. you can only draw black (#000000) pixels in this area.
  5. The top and left borders (which define the image stretching) can only have one dot (1px x 1px), two dots (both 1px x 1px) or ONE continuous line (width x 1px or 1px x height).
  6. If you choose to use 2 dots, the image will be expanded proportionally (so each dot will take turns expanding until the final width/height is achieved)
  7. The 1px border has to be in addition to the intended base file dimensions. So a 100x100 9-patch image has to actually have 102x102 (100x100 +1px on top, bottom, left and right)
  8. 9-patch images have to end with *.9.png

So you can place 1 dot on either side of your logo (in the top border), and 1 dot above and below it (on the left border), and these marked rows and columns will be the only pixels to stretch.

Example

Here's a 9-patch image, 102x102px (100x100 final size, for app purposes):

9-patch image, 102x102px

Here's a 200% zoom of the same image:

the same image, magnified 2x for clarity

Notice the 1px marks on top and left saying which rows/columns will expand.

Here's what this image would look like in 100x100 inside the app:

rendered into 100x100

And here's what it would like if expanded to 460x140:

rendered into 460x140

One last thing to consider. These images might look fine on your monitor screen and on most mobiles, but if the device has a very high image density (dpi), the image would look too small. Probably still legible, but on a tablet with 1920x1200 resolution, the image would appear as a very small square in the middle. So what's the solution? Design 4 different 9-patch launcher images, each for a different density set. To ensure that no shrinking will occur, you should design in the lowest common resolution for each density category. Shrinking is undesirable here because 9-patch only accounts for stretching, so in a shrinking process small text and other elements might lose legibility.

Here's a list of the smallest, most common resolutions for each density category:

  • xlarge (xhdpi): 640x960
  • large (hdpi): 480x800
  • medium (mdpi): 320x480
  • small (ldpi): 240x320

So design four splash screens in the above resolutions, expand the images, putting a 1px transparent border around the canvas, and mark which rows/columns will be stretchable. Keep in mind these images will be used for ANY device in the density category, so your ldpi image (240 x 320) might be stretched to 1024x600 on an extra large tablet with small image density (~120 dpi). So 9-patch is the best solution for the stretching, as long as you don't want a photo or complicated graphics for a splash screen (keep in mind these limitations as you create the design).

Again, the only way for this stretching not to happen is to design one screen each resolution (or one for each resolution-density combination, if you want to avoid images becoming too small/big on high/low density devices), or to tell the image not to stretch and have a background color appear wherever stretching would occur (also remember that a specific color rendered by the Android engine will probably look different from the same specific color rendered by photoshop, because of color profiles).

I hope this made any sense. Good luck!

re.sub erroring with "Expected string or bytes-like object"

The simplest solution is to apply Python str function to the column you are trying to loop through.

If you are using pandas, this can be implemented as:

dataframe['column_name']=dataframe['column_name'].apply(str)

What is a semaphore?

Semaphores are act like thread limiters.

Example: If you have a pool of 100 threads and you want to perform some DB operation. If 100 threads access the DB at a given time, then there may be locking issue in DB so we can use semaphore which allow only limited thread at a time.Below Example allow only one thread at a time. When a thread call the acquire() method, it will then get the access and after calling the release() method, it will release the acccess so that next thread will get the access.

    package practice;
    import java.util.concurrent.Semaphore;

    public class SemaphoreExample {
        public static void main(String[] args) {
            Semaphore s = new Semaphore(1);
            semaphoreTask s1 = new semaphoreTask(s);
            semaphoreTask s2 = new semaphoreTask(s);
            semaphoreTask s3 = new semaphoreTask(s);
            semaphoreTask s4 = new semaphoreTask(s);
            semaphoreTask s5 = new semaphoreTask(s);
            s1.start();
            s2.start();
            s3.start();
            s4.start();
            s5.start();
        }
    }

    class semaphoreTask extends Thread {
        Semaphore s;
        public semaphoreTask(Semaphore s) {
            this.s = s;
        }
        @Override
        public void run() {
            try {
                s.acquire();
                Thread.sleep(1000);
                System.out.println(Thread.currentThread().getName()+" Going to perform some operation");
                s.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } 
    }

Python OpenCV2 (cv2) wrapper to get image size?

I'm afraid there is no "better" way to get this size, however it's not that much pain.

Of course your code should be safe for both binary/mono images as well as multi-channel ones, but the principal dimensions of the image always come first in the numpy array's shape. If you opt for readability, or don't want to bother typing this, you can wrap it up in a function, and give it a name you like, e.g. cv_size:

import numpy as np
import cv2

# ...

def cv_size(img):
    return tuple(img.shape[1::-1])

If you're on a terminal / ipython, you can also express it with a lambda:

>>> cv_size = lambda img: tuple(img.shape[1::-1])
>>> cv_size(img)
(640, 480)

Writing functions with def is not fun while working interactively.

Edit

Originally I thought that using [:2] was OK, but the numpy shape is (height, width[, depth]), and we need (width, height), as e.g. cv2.resize expects, so - we must use [1::-1]. Even less memorable than [:2]. And who remembers reverse slicing anyway?

Detect iPad users using jQuery?

Although the accepted solution is correct for iPhones, it will incorrectly declare both isiPhone and isiPad to be true for users visiting your site on their iPad from the Facebook app.

The conventional wisdom is that iOS devices have a user agent for Safari and a user agent for the UIWebView. This assumption is incorrect as iOS apps can and do customize their user agent. The main offender here is Facebook.

Compare these user agent strings from iOS devices:

# iOS Safari
iPad: Mozilla/5.0 (iPad; CPU OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B176 Safari/7534.48.3
iPhone: Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3

# UIWebView
iPad: Mozilla/5.0 (iPad; CPU OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Mobile/98176
iPhone: Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_1 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Mobile/8B117

# Facebook UIWebView
iPad: Mozilla/5.0 (iPad; U; CPU iPhone OS 5_1_1 like Mac OS X; en_US) AppleWebKit (KHTML, like Gecko) Mobile [FBAN/FBForIPhone;FBAV/4.1.1;FBBV/4110.0;FBDV/iPad2,1;FBMD/iPad;FBSN/iPhone OS;FBSV/5.1.1;FBSS/1; FBCR/;FBID/tablet;FBLC/en_US;FBSF/1.0]
iPhone: Mozilla/5.0 (iPhone; U; CPU iPhone OS 5_1_1 like Mac OS X; ru_RU) AppleWebKit (KHTML, like Gecko) Mobile [FBAN/FBForIPhone;FBAV/4.1;FBBV/4100.0;FBDV/iPhone3,1;FBMD/iPhone;FBSN/iPhone OS;FBSV/5.1.1;FBSS/2; tablet;FBLC/en_US]

Note that on the iPad, the Facebook UIWebView's user agent string includes 'iPhone'.

The old way to identify iPhone / iPad in JavaScript:

IS_IPAD = navigator.userAgent.match(/iPad/i) != null;
IS_IPHONE = navigator.userAgent.match(/iPhone/i) != null) || (navigator.userAgent.match(/iPod/i) != null);

If you were to go with this approach for detecting iPhone and iPad, you would end up with IS_IPHONE and IS_IPAD both being true if a user comes from Facebook on an iPad. That could create some odd behavior!

The correct way to identify iPhone / iPad in JavaScript:

IS_IPAD = navigator.userAgent.match(/iPad/i) != null;
IS_IPHONE = (navigator.userAgent.match(/iPhone/i) != null) || (navigator.userAgent.match(/iPod/i) != null);
if (IS_IPAD) {
  IS_IPHONE = false;
}

We declare IS_IPHONE to be false on iPads to cover for the bizarre Facebook UIWebView iPad user agent. This is one example of how user agent sniffing is unreliable. The more iOS apps that customize their user agent, the more issues user agent sniffing will have. If you can avoid user agent sniffing (hint: CSS Media Queries), DO IT.

MySQL: selecting rows where a column is null

As all are given answers I want to add little more. I had also faced the same issue.

Why did your query fail? You have,

SELECT pid FROM planets WHERE userid = NULL;

This will not give you the expected result, because from mysql doc

In SQL, the NULL value is never true in comparison to any other value, even NULL. An expression that contains NULL always produces a NULL value unless otherwise indicated in the documentation for the operators and functions involved in the expression.

Emphasis mine.

To search for column values that are NULL, you cannot use an expr = NULL test. The following statement returns no rows, because expr = NULL is never true for any expression

Solution

SELECT pid FROM planets WHERE userid IS NULL; 

To test for NULL, use the IS NULL and IS NOT NULL operators.

Set encoding and fileencoding to utf-8 in Vim

set encoding=utf-8  " The encoding displayed.
set fileencoding=utf-8  " The encoding written to file.

You may as well set both in your ~/.vimrc if you always want to work with utf-8.

How to find day of week in php in a specific timezone

Thanks a lot guys for your quick comments.

This is what i will be using now. Posting the function here so that somebody may use it.

public function getDayOfWeek($pTimezone)
{

    $userDateTimeZone = new DateTimeZone($pTimezone);
    $UserDateTime = new DateTime("now", $userDateTimeZone);

    $offsetSeconds = $UserDateTime->getOffset(); 
    //echo $offsetSeconds;

    return gmdate("l", time() + $offsetSeconds);

}

Report if you find any corrections.

UIScrollView scroll to bottom programmatically

What if contentSize is lower than bounds?

For Swift it is:

scrollView.setContentOffset(CGPointMake(0, max(scrollView.contentSize.height - scrollView.bounds.size.height, 0) ), animated: true)

Best way to convert an ArrayList to a string

I see quite a few examples which depend on additional resources, but it seems like this would be the simplest solution: (which is what I used in my own project) which is basically just converting from an ArrayList to an Array and then to a List.

    List<Account> accounts = new ArrayList<>();

   public String accountList() 
   {
      Account[] listingArray = accounts.toArray(new Account[accounts.size()]);
      String listingString = Arrays.toString(listingArray);
      return listingString;
   }

LaTeX: Prevent line break in a span of text

Use \nolinebreak

\nolinebreak[number]

The \nolinebreak command prevents LaTeX from breaking the current line at the point of the command. With the optional argument, number, you can convert the \nolinebreak command from a demand to a request. The number must be a number from 0 to 4. The higher the number, the more insistent the request is.

Source: http://www.personal.ceu.hu/tex/breaking.htm#nolinebreak

Counting Line Numbers in Eclipse

I think if you have MyEclipse, it adds a label to the Project Properties page which contains the total number of source code lines. Might not help you as MyEclipse is not free though.

Unfortunately, that wasn't enough in my case so I wrote a source analyzer to gather statistics not gathered by other solutions (for example the metrics mentioned by AlbertoPL).

How good is Java's UUID.randomUUID?

Does anybody have any experience to share?

There are 2^122 possible values for a type-4 UUID. (The spec says that you lose 2 bits for the type, and a further 4 bits for a version number.)

Assuming that you were to generate 1 million random UUIDs a second, the chances of a duplicate occurring in your lifetime would be vanishingly small. And to detect the duplicate, you'd have to solve the problem of comparing 1 million new UUIDs per second against all of the UUIDs you have previously generated1!

The chances that anyone has experienced (i.e. actually noticed) a duplicate in real life are even smaller than vanishingly small ... because of the practical difficulty of looking for collisions.

Now of course, you will typically be using a pseudo-random number generator, not a source of truly random numbers. But I think we can be confident that if you are using a creditable provider for your cryptographic strength random numbers, then it will be cryptographic strength, and the probability of repeats will be the same as for an ideal (non-biased) random number generator.

However, if you were to use a JVM with a "broken" crypto- random number generator, all bets are off. (And that might include some of the workarounds for "shortage of entropy" problems on some systems. Or the possibility that someone has tinkered with your JRE, either on your system or upstream.)


1 - Assuming that you used "some kind of binary btree" as proposed by an anonymous commenter, each UUID is going to need O(NlogN) bits of RAM memory to represent N distinct UUIDs assuming low density and random distribution of the bits. Now multiply that by 1,000,000 and the number of seconds that you are going to run the experiment for. I don't think that is practical for the length of time needed to test for collisions of a high quality RNG. Not even with (hypothetical) clever representations.

How to create a Custom Dialog box in android?

Add the below theme in values -> style.xml

<style name="Theme_Dialog" parent="android:Theme.Light">
     <item name="android:windowNoTitle">true</item>
     <item name="android:windowBackground">@android:color/transparent</item>
</style>

Use this theme in your onCreateDialog method like this:

Dialog dialog = new Dialog(FlightBookActivity.this,R.style.Theme_Dialog);

Define your dialog layout including title bar in the xml file and set that xml file like this:

dialog.setContentView(R.layout.your_dialog_layout);

Installing specific package versions with pip

This below command worked for me

Python version - 2.7

package - python-jenkins

command - $ pip install 'python-jenkins>=1.1.1'

How to put a delay on AngularJS instant search?

I solved this problem with a directive that basicly what it does is to bind the real ng-model on a special attribute which I watch in the directive, then using a debounce service I update my directive attribute, so the user watch on the variable that he bind to debounce-model instead of ng-model.

.directive('debounceDelay', function ($compile, $debounce) {
return {
  replace: false,
  scope: {
    debounceModel: '='
  },
  link: function (scope, element, attr) {
    var delay= attr.debounceDelay;
    var applyFunc = function () {
      scope.debounceModel = scope.model;
    }
    scope.model = scope.debounceModel;
    scope.$watch('model', function(){
      $debounce(applyFunc, delay);
    });
    attr.$set('ngModel', 'model');
    element.removeAttr('debounce-delay'); // so the next $compile won't run it again!

   $compile(element)(scope);
  }
};
});

Usage:

<input type="text" debounce-delay="1000" debounce-model="search"></input>

And in the controller :

    $scope.search = "";
    $scope.$watch('search', function (newVal, oldVal) {
      if(newVal === oldVal){
        return;
      }else{ //do something meaningful }

Demo in jsfiddle: http://jsfiddle.net/6K7Kd/37/

the $debounce service can be found here: http://jsfiddle.net/Warspawn/6K7Kd/

Inspired by eventuallyBind directive http://jsfiddle.net/fctZH/12/

What is the difference between Bower and npm?

This answer is an addition to the answer of Sindre Sorhus. The major difference between npm and Bower is the way they treat recursive dependencies. Note that they can be used together in a single project.

On the npm FAQ: (archive.org link from 6 Sep 2015)

It is much harder to avoid dependency conflicts without nesting dependencies. This is fundamental to the way that npm works, and has proven to be an extremely successful approach.

On Bower homepage:

Bower is optimized for the front-end. Bower uses a flat dependency tree, requiring only one version for each package, reducing page load to a minimum.

In short, npm aims for stability. Bower aims for minimal resource load. If you draw out the dependency structure, you will see this:

npm:

project root
[node_modules] // default directory for dependencies
 -> dependency A
 -> dependency B
    [node_modules]
    -> dependency A

 -> dependency C
    [node_modules]
    -> dependency B
      [node_modules]
       -> dependency A 
    -> dependency D

As you can see it installs some dependencies recursively. Dependency A has three installed instances!

Bower:

project root
[bower_components] // default directory for dependencies
 -> dependency A
 -> dependency B // needs A
 -> dependency C // needs B and D
 -> dependency D

Here you see that all unique dependencies are on the same level.

So, why bother using npm?

Maybe dependency B requires a different version of dependency A than dependency C. npm installs both versions of this dependency so it will work anyway, but Bower will give you a conflict because it does not like duplication (because loading the same resource on a webpage is very inefficient and costly, also it can give some serious errors). You will have to manually pick which version you want to install. This can have the effect that one of the dependencies will break, but that is something that you will need to fix anyway.

So, the common usage is Bower for the packages that you want to publish on your webpages (e.g. runtime, where you avoid duplication), and use npm for other stuff, like testing, building, optimizing, checking, etc. (e.g. development time, where duplication is of less concern).

Update for npm 3:

npm 3 still does things differently compared to Bower. It will install the dependencies globally, but only for the first version it encounters. The other versions are installed in the tree (the parent module, then node_modules).

  • [node_modules]
    • dep A v1.0
    • dep B v1.0
      • dep A v1.0 (uses root version)
    • dep C v1.0
      • dep A v2.0 (this version is different from the root version, so it will be an nested installation)

For more information, I suggest reading the docs of npm 3

How do I call a Django function on button click?

There are 2 possible solutions that I personally use

1.without using form

 <button type="submit" value={{excel_path}} onclick="location.href='{% url 'downloadexcel' %}'" name='mybtn2'>Download Excel file</button>

2.Using Form

<form action="{% url 'downloadexcel' %}" method="post">
{% csrf_token %}


 <button type="submit" name='mybtn2' value={{excel_path}}>Download results in Excel</button>
 </form>

Where urls.py should have this

path('excel/',views1.downloadexcel,name="downloadexcel"),

Setting HTTP headers

Never mind, I figured it out - I used the Set() method on Header() (doh!)

My handler looks like this now:

func saveHandler(w http.ResponseWriter, r *http.Request) {
    // allow cross domain AJAX requests
    w.Header().Set("Access-Control-Allow-Origin", "*")
}

Maybe this will help someone as caffeine deprived as myself sometime :)

Programmatic equivalent of default(Type)

The chosen answer is a good answer, but be careful with the object returned.

string test = null;
string test2 = "";
if (test is string)
     Console.WriteLine("This will never be hit.");
if (test2 is string)
     Console.WriteLine("Always hit.");

Extrapolating...

string test = GetDefault(typeof(string));
if (test is string)
     Console.WriteLine("This will never be hit.");

OS detecting makefile

Here's a simple solution that checks if you are in a Windows or posix-like (Linux/Unix/Cygwin/Mac) environment:

ifeq ($(shell echo "check_quotes"),"check_quotes")
   WINDOWS := yes
else
   WINDOWS := no
endif

It takes advantage of the fact that echo exists on both posix-like and Windows environments, and that in Windows the shell does not filter the quotes.

MySQL load NULL values from CSV data

Converted the input file to include \N for the blank column data using the below sed command in UNix terminal:

sed -i 's/,,/,\\N,/g' $file_name

and then use LOAD DATA INFILE command to load to mysql

How can I access the MySQL command line with XAMPP for Windows?

On the Mac, or at least on my Mac using a default install, I accessed it at:

/Applications/xampp/xamppfiles/bin/mysql -uroot -p

Does bootstrap 4 have a built in horizontal divider?

in Bootstrap 5 you can do something like this:

<div class="py-2 my-1 text-center position-relative mx-2">
            <div class="position-absolute w-100 top-50 start-50 translate-middle" style="z-index: 2">
                <span class="d-inline-block bg-white px-2 text-muted">or</span>
            </div>
            <div class="position-absolute w-100 top-50 start-0 border-muted border-top"></div>
</div>

how to store Image as blob in Sqlite & how to retrieve it?

Here the code i used for my app

This code will take a image from url and convert is to a byte array

byte[] logoImage = getLogoImage(IMAGEURL);

private byte[] getLogoImage(String url){
     try {
             URL imageUrl = new URL(url);
             URLConnection ucon = imageUrl.openConnection();

             InputStream is = ucon.getInputStream();
             BufferedInputStream bis = new BufferedInputStream(is);

             ByteArrayBuffer baf = new ByteArrayBuffer(500);
             int current = 0;
             while ((current = bis.read()) != -1) {
                  baf.append((byte) current);
             }

             return baf.toByteArray();
     } catch (Exception e) {
          Log.d("ImageManager", "Error: " + e.toString());
     }
     return null;
}

To save the image to db i used this code.

 public void insertUser(){
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        String delSql = "DELETE FROM ACCOUNTS";
        SQLiteStatement delStmt = db.compileStatement(delSql);
        delStmt.execute();

        String sql = "INSERT INTO ACCOUNTS (account_id,account_name,account_image) VALUES(?,?,?)";
        SQLiteStatement insertStmt = db.compileStatement(sql);
        insertStmt.clearBindings();
        insertStmt.bindString(1, Integer.toString(this.accId));
        insertStmt.bindString(2,this.accName);
        insertStmt.bindBlob(3, this.accImage);
        insertStmt.executeInsert();
        db.close();
}

To retrieve the image back this is code i used.

public Account getCurrentAccount() {
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    String sql = "SELECT * FROM ACCOUNTS";
    Cursor cursor = db.rawQuery(sql, new String[] {});

    if(cursor.moveToFirst()){
        this.accId  = cursor.getInt(0);
        this.accName = cursor.getString(1);
        this.accImage = cursor.getBlob(2);
    }
    if (cursor != null && !cursor.isClosed()) {
        cursor.close();
    }
    db.close();
    if(cursor.getCount() == 0){
        return null;
    } else {
        return this;
    }
}

Finally to load this image to a imageview

logoImage.setImageBitmap(BitmapFactory.decodeByteArray( currentAccount.accImage, 
        0,currentAccount.accImage.length));

Can we make unsigned byte in Java

Complete guide for working with unsigned bytes in Java:

Unsigned byte in Java

(Source for this answer.)


The Java Language does not provide anything like the unsigned keyword. A byte according to the language spec represents a value between -128 - 127. For instance, if a byte is cast to an int Java will interpret the first bit as the sign and use sign extension.

That being said, nothing prevents you from viewing a byte simply as 8 bits and interpret those bits as a value between 0 and 255. Just keep in mind that there's nothing you can do to force your interpretation upon someone else's method. If a method accepts a byte, then that method accepts a value between -128 and 127 unless explicitly stated otherwise.

Here are a couple of useful conversions / manipulations for your convenience:

Conversions to / from int

// From int to unsigned byte
int i = 200;                    // some value between 0 and 255
byte b = (byte) i;              // 8 bits representing that value

// From unsigned byte to int
byte b = 123;                   // 8 bits representing a value between 0 and 255
int i = b & 0xFF;               // an int representing the same value

(Or, if you're on Java 8+, use Byte.toUnsignedInt.)

Parsing / formatting

Best way is to use the above conversions:

// Parse an unsigned byte
byte b = (byte) Integer.parseInt("200");

// Print an unsigned byte
System.out.println("Value of my unsigned byte: " + (b & 0xFF));

Arithmetics

The 2-complement representation "just works" for addition, subtraction and multiplication:

// two unsigned bytes
byte b1 = (byte) 200;
byte b2 = (byte) 15;

byte sum  = (byte) (b1 + b2);  // 215
byte diff = (byte) (b1 - b2);  // 185
byte prod = (byte) (b2 * b2);  // 225

Division requires manual conversion of operands:

byte ratio = (byte) ((b1 & 0xFF) / (b2 & 0xFF));

Duplicate Entire MySQL Database

Making a Copy of a Database

# mysqldump -u root -p password db1 > dump.sql
# mysqladmin -u root -p password create db2
# mysql -u root -p password db2 < dump.sql

How to disable an input type=text?

If the data is populated from the database, you might consider not using an <input> tag to display it. Nevertheless, you can disable it right in the tag:

<input type='text' value='${magic.database.value}' disabled>

If you need to disable it with Javascript later, you can set the "disabled" attribute:

document.getElementById('theInput').disabled = true;

The reason I suggest not showing the value as an <input> is that, in my experience, it causes layout issues. If the text is long, then in an <input> the user will need to try and scroll the text, which is not something normal people would guess to do. If you just drop it into a <span> or something, you have more styling flexibility.

PHP Pass variable to next page

Sessions would be the only good way, you could also use GET/POST but that would be potentially insecure.

How to use placeholder as default value in select2 framework

Use a empty placeholder on your html like:

<select class="select2" placeholder = "">
    <option value="1">red</option>
    <option value="2">blue</option>
</select>

and in your script use:

$(".select2").select2({
        placeholder: "Select a color",
        allowClear: true
    });

how to access master page control from content page

I have a helper method for this in my System.Web.UI.Page class

protected T FindControlFromMaster<T>(string name) where T : Control
{
     MasterPage master = this.Master;
     while (master != null)
     {
         T control = master.FindControl(name) as T;
         if (control != null)
             return control;

         master = master.Master;
     }
     return null;
}

then you can access using below code.

Label lblStatus = FindControlFromMaster<Label>("lblStatus");
if(lblStatus!=null) 
    lblStatus.Text = "something";

SQL UPDATE all values in a field with appended string CONCAT not working

UPDATE mytable SET spares = CONCAT(spares, ',', '818') WHERE id = 1

not working for me.

spares is NULL by default but its varchar

What's the purpose of the LEA instruction?

As the existing answers mentioned, LEA has the advantages of performing memory addressing arithmetic without accessing memory, saving the arithmetic result to a different register instead of the simple form of add instruction. The real underlying performance benefit is that modern processor has a separate LEA ALU unit and port for effective address generation (including LEA and other memory reference address), this means the arithmetic operation in LEA and other normal arithmetic operation in ALU could be done in parallel in one core.

Check this article of Haswell architecture for some details about LEA unit: http://www.realworldtech.com/haswell-cpu/4/

Another important point which is not mentioned in other answers is LEA REG, [MemoryAddress] instruction is PIC (position independent code) which encodes the PC relative address in this instruction to reference MemoryAddress. This is different from MOV REG, MemoryAddress which encodes relative virtual address and requires relocating/patching in modern operating systems (like ASLR is common feature). So LEA can be used to convert such non PIC to PIC.

jQuery - Get Width of Element when Not Visible (Display: None)

Here is a trick I have used. It involves adding some CSS properties to make jQuery think the element is visible, but in fact it is still hidden.

var $table = $("#parent").children("table");
$table.css({ position: "absolute", visibility: "hidden", display: "block" });
var tableWidth = $table.outerWidth();
$table.css({ position: "", visibility: "", display: "" });

It is kind of a hack, but it seems to work fine for me.

UPDATE

I have since written a blog post that covers this topic. The method used above has the potential to be problematic since you are resetting the CSS properties to empty values. What if they had values previously? The updated solution uses the swap() method that was found in the jQuery source code.

Code from referenced blog post:

//Optional parameter includeMargin is used when calculating outer dimensions  
(function ($) {
$.fn.getHiddenDimensions = function (includeMargin) {
    var $item = this,
    props = { position: 'absolute', visibility: 'hidden', display: 'block' },
    dim = { width: 0, height: 0, innerWidth: 0, innerHeight: 0, outerWidth: 0, outerHeight: 0 },
    $hiddenParents = $item.parents().andSelf().not(':visible'),
    includeMargin = (includeMargin == null) ? false : includeMargin;

    var oldProps = [];
    $hiddenParents.each(function () {
        var old = {};

        for (var name in props) {
            old[name] = this.style[name];
            this.style[name] = props[name];
        }

        oldProps.push(old);
    });

    dim.width = $item.width();
    dim.outerWidth = $item.outerWidth(includeMargin);
    dim.innerWidth = $item.innerWidth();
    dim.height = $item.height();
    dim.innerHeight = $item.innerHeight();
    dim.outerHeight = $item.outerHeight(includeMargin);

    $hiddenParents.each(function (i) {
        var old = oldProps[i];
        for (var name in props) {
            this.style[name] = old[name];
        }
    });

    return dim;
}
}(jQuery));

How to force an entire layout View refresh?

To strictly answer the question: Use invalidate():

public void invalidate () Since: API Level 1

Invalidate the whole view. If the view is visible, onDraw(Canvas) will be called at some point in the future. This must be called from a UI thread. To call from a non-UI thread, call postInvalidate().

ViewGroup vg = findViewById (R.id.mainLayout);
vg.invalidate();

Now, when the Activity resumes, it makes every View to draw itself. No call to invalidate() should be needed. To apply the theme, make sure you do it before any View is drawn, i.e., before setContentView(R.layout.mainscreen);

public void setTheme (int resid) Since: API Level 1

Set the base theme for this context. Note that this should be called before any views are instantiated in the Context (for example before calling setContentView(View) or inflate(int, ViewGroup)).

The API doc reference is here: http://developer.android.com/reference/android/view/ContextThemeWrapper.html#setTheme%28int%29

Since the onDraw() method works on already instantiated Views, setTheme will not work. I have no experience with themes myself, but two alternative options I can think are:

  1. call setTheme in onCreate() instead, or
  2. redo setContentView (R.layout.mainscreen); to force reinstantiate all the layout.

Calculating days between two dates with Java

// date format, it will be like "2015-01-01"
private static final String DATE_FORMAT = "yyyy-MM-dd";

// convert a string to java.util.Date
public static Date convertStringToJavaDate(String date)
        throws ParseException {
    DateFormat dataFormat = new SimpleDateFormat(DATE_FORMAT);
    return dataFormat.parse(date);
}

// plus days to a date
public static Date plusJavaDays(Date date, int days) {
    // convert to jata-time
    DateTime fromDate = new DateTime(date);
    DateTime toDate = fromDate.plusDays(days);
    // convert back to java.util.Date
    return toDate.toDate();
}

// return a list of dates between the fromDate and toDate
public static List<Date> getDatesBetween(Date fromDate, Date toDate) {
    List<Date> dates = new ArrayList<Date>(0);
    Date date = fromDate;
    while (date.before(toDate) || date.equals(toDate)) {
        dates.add(date);
        date = plusJavaDays(date, 1);
    }
    return dates;
}

BasicHttpBinding vs WsHttpBinding vs WebHttpBinding

You're comparing apples to oranges here:

  • webHttpBinding is the REST-style binding, where you basically just hit a URL and get back a truckload of XML or JSON from the web service

  • basicHttpBinding and wsHttpBinding are two SOAP-based bindings which is quite different from REST. SOAP has the advantage of having WSDL and XSD to describe the service, its methods, and the data being passed around in great detail (REST doesn't have anything like that - yet). On the other hand, you can't just browse to a wsHttpBinding endpoint with your browser and look at XML - you have to use a SOAP client, e.g. the WcfTestClient or your own app.

So your first decision must be: REST vs. SOAP (or you can expose both types of endpoints from your service - that's possible, too).

Then, between basicHttpBinding and wsHttpBinding, there differences are as follows:

  • basicHttpBinding is the very basic binding - SOAP 1.1, not much in terms of security, not much else in terms of features - but compatible to just about any SOAP client out there --> great for interoperability, weak on features and security

  • wsHttpBinding is the full-blown binding, which supports a ton of WS-* features and standards - it has lots more security features, you can use sessionful connections, you can use reliable messaging, you can use transactional control - just a lot more stuff, but wsHttpBinding is also a lot *heavier" and adds a lot of overhead to your messages as they travel across the network

For an in-depth comparison (including a table and code examples) between the two check out this codeproject article: Differences between BasicHttpBinding and WsHttpBinding

Populate a Drop down box from a mySQL table in PHP

You will need to make sure that if you're using a test environment like WAMP set your username as root. Here is an example which connects to a MySQL database, issues your query, and outputs <option> tags for a <select> box from each row in the table.

<?php

mysql_connect('hostname', 'username', 'password');
mysql_select_db('database-name');

$sql = "SELECT PcID FROM PC";
$result = mysql_query($sql);

echo "<select name='PcID'>";
while ($row = mysql_fetch_array($result)) {
    echo "<option value='" . $row['PcID'] . "'>" . $row['PcID'] . "</option>";
}
echo "</select>";

?>

Java: How to set Precision for double value?

You can't set the precision of a double (or Double) to a specified number of decimal digits, because floating-point values don't have decimal digits. They have binary digits.

You will have to convert into a decimal radix, either via BigDecimal or DecimalFormat, depending on what you want to do with the value later.

See also my answer to this question for a refutation of the inevitable *100/100 answers.

JUnit: how to avoid "no runnable methods" in test utils classes

I was also facing a similar issue ("no runnable methods..") on running the simplest of simple piece of code (Using @Test, @Before etc.) and found the solution nowhere. I was using Junit4 and Eclipse SDK version 4.1.2. Resolved my problem by using the latest Eclipse SDK 4.2.2. I hope this helps people who are struggling with a somewhat similar issue.

How to clear variables in ipython?

In iPython you can remove a single variable like this:

del x

Syntax for a single-line Bash infinite while loop

If I can give two practical examples (with a bit of "emotion").

This writes the name of all files ended with ".jpg" in the folder "img":

for f in *; do if [ "${f#*.}" == 'jpg' ]; then echo $f; fi; done

This deletes them:

for f in *; do if [ "${f#*.}" == 'jpg' ]; then rm -r $f; fi; done

Just trying to contribute.

Declare and initialize a Dictionary in Typescript

I agree with thomaux that the initialization type checking error is a TypeScript bug. However, I still wanted to find a way to declare and initialize a Dictionary in a single statement with correct type checking. This implementation is longer, however it adds additional functionality such as a containsKey(key: string) and remove(key: string) method. I suspect that this could be simplified once generics are available in the 0.9 release.

First we declare the base Dictionary class and Interface. The interface is required for the indexer because classes cannot implement them.

interface IDictionary {
    add(key: string, value: any): void;
    remove(key: string): void;
    containsKey(key: string): bool;
    keys(): string[];
    values(): any[];
}

class Dictionary {

    _keys: string[] = new string[];
    _values: any[] = new any[];

    constructor(init: { key: string; value: any; }[]) {

        for (var x = 0; x < init.length; x++) {
            this[init[x].key] = init[x].value;
            this._keys.push(init[x].key);
            this._values.push(init[x].value);
        }
    }

    add(key: string, value: any) {
        this[key] = value;
        this._keys.push(key);
        this._values.push(value);
    }

    remove(key: string) {
        var index = this._keys.indexOf(key, 0);
        this._keys.splice(index, 1);
        this._values.splice(index, 1);

        delete this[key];
    }

    keys(): string[] {
        return this._keys;
    }

    values(): any[] {
        return this._values;
    }

    containsKey(key: string) {
        if (typeof this[key] === "undefined") {
            return false;
        }

        return true;
    }

    toLookup(): IDictionary {
        return this;
    }
}

Now we declare the Person specific type and Dictionary/Dictionary interface. In the PersonDictionary note how we override values() and toLookup() to return the correct types.

interface IPerson {
    firstName: string;
    lastName: string;
}

interface IPersonDictionary extends IDictionary {
    [index: string]: IPerson;
    values(): IPerson[];
}

class PersonDictionary extends Dictionary {
    constructor(init: { key: string; value: IPerson; }[]) {
        super(init);
    }

    values(): IPerson[]{
        return this._values;
    }

    toLookup(): IPersonDictionary {
        return this;
    }
}

And here is a simple initialization and usage example:

var persons = new PersonDictionary([
    { key: "p1", value: { firstName: "F1", lastName: "L2" } },
    { key: "p2", value: { firstName: "F2", lastName: "L2" } },
    { key: "p3", value: { firstName: "F3", lastName: "L3" } }
]).toLookup();


alert(persons["p1"].firstName + " " + persons["p1"].lastName);
// alert: F1 L2

persons.remove("p2");

if (!persons.containsKey("p2")) {
    alert("Key no longer exists");
    // alert: Key no longer exists
}

alert(persons.keys().join(", "));
// alert: p1, p3

Currency formatting in Python

My locale settings seemed incomplete, so I had too look beyond this SO answer and found:

http://docs.python.org/library/decimal.html#recipes

OS-independent

Just wanted to share here.

'Source code does not match the bytecode' when debugging on a device

You should use an Android emulator with the same api level as the compileSdkVersion. In your case you should use Android emulator with api level 21.

How to update PATH variable permanently from Windows command line?

The documentation on how to do this can be found on MSDN. The key extract is this:

To programmatically add or modify system environment variables, add them to the HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment registry key, then broadcast a WM_SETTINGCHANGE message with lParam set to the string "Environment". This allows applications, such as the shell, to pick up your updates.

Note that your application will need elevated admin rights in order to be able to modify this key.

You indicate in the comments that you would be happy to modify just the per-user environment. Do this by editing the values in HKEY_CURRENT_USER\Environment. As before, make sure that you broadcast a WM_SETTINGCHANGE message.

You should be able to do this from your Java application easily enough using the JNI registry classes.

How to get arguments with flags in Bash

This example uses Bash's built-in getopts command and is from the Google Shell Style Guide:

a_flag=''
b_flag=''
files=''
verbose='false'

print_usage() {
  printf "Usage: ..."
}

while getopts 'abf:v' flag; do
  case "${flag}" in
    a) a_flag='true' ;;
    b) b_flag='true' ;;
    f) files="${OPTARG}" ;;
    v) verbose='true' ;;
    *) print_usage
       exit 1 ;;
  esac
done

Note: If a character is followed by a colon (e.g. f:), that option is expected to have an argument.

Example usage: ./script -v -a -b -f filename

Using getopts has several advantages over the accepted answer:

  • the while condition is a lot more readable and shows what the accepted options are
  • cleaner code; no counting the number of parameters and shifting
  • you can join options (e.g. -a -b -c ? -abc)

However, a big disadvantage is that it doesn't support long options, only single-character options.

Sanitizing user input before adding it to the DOM in Javascript

Never use escape(). It's nothing to do with HTML-encoding. It's more like URL-encoding, but it's not even properly that. It's a bizarre non-standard encoding available only in JavaScript.

If you want an HTML encoder, you'll have to write it yourself as JavaScript doesn't give you one. For example:

function encodeHTML(s) {
    return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
}

However whilst this is enough to put your user_id in places like the input value, it's not enough for id because IDs can only use a limited selection of characters. (And % isn't among them, so escape() or even encodeURIComponent() is no good.)

You could invent your own encoding scheme to put any characters in an ID, for example:

function encodeID(s) {
    if (s==='') return '_';
    return s.replace(/[^a-zA-Z0-9.-]/g, function(match) {
        return '_'+match[0].charCodeAt(0).toString(16)+'_';
    });
}

But you've still got a problem if the same user_id occurs twice. And to be honest, the whole thing with throwing around HTML strings is usually a bad idea. Use DOM methods instead, and retain JavaScript references to each element, so you don't have to keep calling getElementById, or worrying about how arbitrary strings are inserted into IDs.

eg.:

function addChut(user_id) {
    var log= document.createElement('div');
    log.className= 'log';
    var textarea= document.createElement('textarea');
    var input= document.createElement('input');
    input.value= user_id;
    input.readonly= True;
    var button= document.createElement('input');
    button.type= 'button';
    button.value= 'Message';

    var chut= document.createElement('div');
    chut.className= 'chut';
    chut.appendChild(log);
    chut.appendChild(textarea);
    chut.appendChild(input);
    chut.appendChild(button);
    document.getElementById('chuts').appendChild(chut);

    button.onclick= function() {
        alert('Send '+textarea.value+' to '+user_id);
    };

    return chut;
}

You could also use a convenience function or JS framework to cut down on the lengthiness of the create-set-appends calls there.

ETA:

I'm using jQuery at the moment as a framework

OK, then consider the jQuery 1.4 creation shortcuts, eg.:

var log= $('<div>', {className: 'log'});
var input= $('<input>', {readOnly: true, val: user_id});
...

The problem I have right now is that I use JSONP to add elements and events to a page, and so I can not know whether the elements already exist or not before showing a message.

You can keep a lookup of user_id to element nodes (or wrapper objects) in JavaScript, to save putting that information in the DOM itself, where the characters that can go in an id are restricted.

var chut_lookup= {};
...

function getChut(user_id) {
    var key= '_map_'+user_id;
    if (key in chut_lookup)
        return chut_lookup[key];
    return chut_lookup[key]= addChut(user_id);
}

(The _map_ prefix is because JavaScript objects don't quite work as a mapping of arbitrary strings. The empty string and, in IE, some Object member names, confuse it.)

Calling a JavaScript function returned from an Ajax response

I've tested this and it works. What's the problem? Just put the new function inside your javascript element and then call it. It will work.

Anaconda vs. miniconda

The 2 in Anaconda2 means that the main version of Python will be 2.x rather than the 3.x installed in Anaconda3. The current release has Python 2.7.13.

The 4.4.0.1 is the version number of Anaconda. The current advertised version is 4.4.0 and I assume the .1 is a minor release or for other similar use. The Windows releases, which I use, just say 4.4.0 in the file name.

Others have now explained the difference between Anaconda and Miniconda, so I'll skip that.

What are the recommendations for html <base> tag?

My recommendation is NOT to use the <base> element in managing url paths. Why?

It just trades one problem for another. Without the base element you can use any path system you like for your relative paths and links without fear they will break. The minute you set the base element to a path you are "locked in" to designing all your url's to work off that path and will now have to change ALL paths to work from the base path. Bad idea!

That means you have to now write LONGER paths AND keep track of where each path is relative to this base. Worse.....when using the <base> element they recommend you use a fully qualified base path to support older browsers ("https://www.example.com/"), so now you've hard-coded your domain into your page or made all your links dependent on a valid domain path.

On the other hand, the minute you remove the base path again from your website, you are now free again to use shorter relative paths, which can be fully qualified, use absolute paths from the root, or use paths that are truly relative to the file and folder you are in. Its much more flexible. And best of all fragments like "#hello" work correctly without any additional fixes. Again, people are creating problems that don't exist.

Also, the argument above that your use base url's to help you migrate folders of web pages to new subfolder locations doesn't really matter today since most modern servers allow you to quickly set up any subfolder as a new application root folder under any domain. The definition or the "root" of a web application is not constrained by either folders or domains now.

It seems kind of silly this whole debate. So I say leave out base url and support the older native server-client default path system that does not use it.

Note: If the problem you have is controlling paths due to some new API system, the solution is simple...be consistent in how you path all your url's and links in your API. Don't rely on browser support of base or HTML5 or newer circus tricks like the javascript API kiddies do. Simply path all your anchor tags consistently and you will never have issues. Whats more, your web application is instantly portable to new servers regardless of path systems used.

Whats old is new again! The base element is clearly about trying to create a solution to a problem that never existed in the Web World 20 years ago, much less today.

HTML select form with option to enter custom value

You can't really. You'll have to have both the drop down, and the text box, and have them pick or fill in the form. Without javascript you could create a separate radio button set where they choose dropdown or text input, but this seems messy to me. With some javascript you could toggle disable one or the other depending on which one they choose, for instance, have an 'other' option in the dropdown that triggers the text field.

Permission denied (publickey) when deploying heroku code. fatal: The remote end hung up unexpectedly

At first make sure hidden files are visible in your Mac. If not do:

  • Open terminal and type in defaults write com.apple.Finder AppleShowAllFiles TRUE
  • killall Finder

Next steps:

  • Going to Users/user_name/.ssh/ removed all the files.
  • Opening terminal type in ssh-keygen -t dsa
  • Then heroku keys:add ~/.ssh/id_dsa.pub

N.B. I did it in Mac OSX 10.7.2 Lion. Though the procedure should be same in others too.

Programmatically set TextBlock Foreground Color

 textBlock.Foreground = new SolidColorBrush(Colors.White);

Change icons of checked and unchecked for Checkbox for Android

it's android:button="@drawable/selector_checkbox" to make it work

Use JAXB to create Object from XML String

To pass XML content, you need to wrap the content in a Reader, and unmarshal that instead:

JAXBContext jaxbContext = JAXBContext.newInstance(Person.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

StringReader reader = new StringReader("xml string here");
Person person = (Person) unmarshaller.unmarshal(reader);

Pandas read_csv low_memory and dtype options

df = pd.read_csv('somefile.csv', low_memory=False)

This should solve the issue. I got exactly the same error, when reading 1.8M rows from a CSV.

What is the inclusive range of float and double in Java?

Java's Primitive Data Types

boolean: 1-bit. May take on the values true and false only.

byte: 1 signed byte (two's complement). Covers values from -128 to 127.

short: 2 bytes, signed (two's complement), -32,768 to 32,767

int: 4 bytes, signed (two's complement). -2,147,483,648 to 2,147,483,647.

long: 8 bytes signed (two's complement). Ranges from -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807.

float: 4 bytes, IEEE 754. Covers a range from 1.40129846432481707e-45 to 3.40282346638528860e+38 (positive or negative).

double: 8 bytes IEEE 754. Covers a range from 4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative).

char: 2 bytes, unsigned, Unicode, 0 to 65,535

How do I trim whitespace?

This will remove all whitespace and newlines from both the beginning and end of a string:

>>> s = "  \n\t  \n   some \n text \n     "
>>> re.sub("^\s+|\s+$", "", s)
>>> "some \n text"

How to set the authorization header using curl

Bearer tokens look like this:

curl -H "Authorization: Bearer <ACCESS_TOKEN>" http://www.example.com

HTTP Error 503, the service is unavailable

If you have IIS URL Rewriting installed it could be to do with that. I suffered issues after a Windows 10 Update.

This StackOverflow post helped me.

Go to Windows Control Panel > Programs and Features > IIS URL Rewrite Module 2 > Repair.

Insert multiple rows WITHOUT repeating the "INSERT INTO ..." part of the statement?

If your data is already in your database you can do:

INSERT INTO MyTable(ID, Name)
SELECT ID, NAME FROM OtherTable

If you need to hard code the data then SQL 2008 and later versions let you do the following...

INSERT INTO MyTable (Name, ID)
VALUES ('First',1),
('Second',2),
('Third',3),
('Fourth',4),
('Fifth',5)

Go To Definition: "Cannot navigate to the symbol under the caret."

The following fixed this for me:

  • In Solution Explorer, right click the solution name.
  • Select "Clean Solution"

After this successfully completed, I no longer received the error, and I didn't have to close and reopen anything.

How to disable sort in DataGridView?

It's very simple:

foreach (DataGridViewColumn dgvc in dataGridView1.Columns)
{
    dgvc.SortMode = DataGridViewColumnSortMode.NotSortable;
}

Eclipse does not highlight matching variables

For PHP you can set

window > preferences > PHP > editor > mark occurrences 

Please check first checkbox (Mark occurrences of selected element in the current file)


And also check

Preferences > General > Editors > Text Editors > Annotations

'Occurrences' and 'Write Occurrences' with different style and color

Getting time and date from timestamp with php

If you dont want to change the format of date and time from the timestamp, you can use the explode function in php

$timestamp = "2012-04-02 02:57:54"
$datetime = explode(" ",$timestamp);
$date = $datetime[0];
$time = $datetime[1];

Is it possible to get only the first character of a String?

Use ld.charAt(0). It will return the first char of the String.

With ld.substring(0, 1), you can get the first character as String.

Add button to a layout programmatically

This line:

layout = (LinearLayout) findViewById(R.id.statsviewlayout);

Looks for the "statsviewlayout" id in your current 'contentview'. Now you've set that here:

setContentView(new GraphTemperature(getApplicationContext()));

And i'm guessing that new "graphTemperature" does not set anything with that id.

It's a common mistake to think you can just find any view with findViewById. You can only find a view that is in the XML (or appointed by code and given an id).

The nullpointer will be thrown because the layout you're looking for isn't found, so

layout.addView(buyButton);

Throws that exception.

addition: Now if you want to get that view from an XML, you should use an inflater:

layout = (LinearLayout) View.inflate(this, R.layout.yourXMLYouWantToLoad, null);

assuming that you have your linearlayout in a file called "yourXMLYouWantToLoad.xml"

Echo newline in Bash prints literal \n

echo $'hello\nworld'

prints

hello
world

$'' strings use ANSI C Quoting:

Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard.

npm ERR! network getaddrinfo ENOTFOUND

does your proxy require you to authenticate? because if it does, you might want you configure your proxy like this.

placeholder names. username is a placeholder for your actual username. password is a placeholder for your actual password. proxy.company.com is a placeholder for your actualy proxy *port" is your actualy port the proxy goes through. its usualy 8080

npm config set proxy "http://username:[email protected]:port"
npm config set https-proxy "http://username:[email protected]:port"

How do I find the current directory of a batch file, and then use it for the path?

Try in yourbatch

set "batchisin=%~dp0"

which should set the variable to your batch's location.

c# how to add byte to byte array

Arrays can't be resized, so you need to allocte a new array that is larger, write the new byte at the beginning of it, and use Buffer.BlockCopy to transfer the contents of the old array across.

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

Most answers are using iloc which is good for selection by position.

If you need selection-by-label loc would be more convenient.

For getting a value explicitly (equiv to deprecated df.get_value('a','A'))

# this is also equivalent to df1.at['a','A']
In [55]: df1.loc['a', 'A'] 
Out[55]: 0.13200317033032932

Tell Ruby Program to Wait some amount of time

sleep 6 will sleep for 6 seconds. For a longer duration, you can also use sleep(6.minutes) or sleep(6.hours).

COUNT DISTINCT with CONDITIONS

This may work:

SELECT Count(tag) AS 'Tag Count'
FROM Table
GROUP BY tag

and

SELECT Count(tag) AS 'Negative Tag Count'
FROM Table
WHERE entryID > 0
GROUP BY tag

How to convert POJO to JSON and vice versa?

If you are aware of Jackson 2, there is a great tutorial at mkyong.com on how to convert Java Objects to JSON and vice versa. The following code snippets have been taken from that tutorial.

Convert Java object to JSON, writeValue(...):

ObjectMapper mapper = new ObjectMapper();
Staff obj = new Staff();

//Object to JSON in file
mapper.writeValue(new File("c:\\file.json"), obj);

//Object to JSON in String
String jsonInString = mapper.writeValueAsString(obj);

Convert JSON to Java object, readValue(...):

ObjectMapper mapper = new ObjectMapper();
String jsonInString = "{'name' : 'mkyong'}";

//JSON from file to Object
Staff obj = mapper.readValue(new File("c:\\file.json"), Staff.class);

//JSON from URL to Object
Staff obj = mapper.readValue(new URL("http://mkyong.com/api/staff.json"), Staff.class);

//JSON from String to Object
Staff obj = mapper.readValue(jsonInString, Staff.class);

Jackson 2 Dependency:

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

For the full tutorial, please go to the link given above.

Eclipse JUnit - possible causes of seeing "initializationError" in Eclipse window

I just had the same problem and the same message. I was able to get it fixed by importing to the Java Building Path the hamcrest-all-1.3.jar archive. I'm using a JUnit 4.12 version.

JS file gets a net::ERR_ABORTED 404 (Not Found)

As mentionned in comments: you need a way to send your static files to the client. This can be achieved with a reverse proxy like Nginx, or simply using express.static().

Put all your "static" (css, js, images) files in a folder dedicated to it, different from where you put your "views" (html files in your case). I'll call it static for the example. Once it's done, add this line in your server code:

app.use("/static", express.static('./static/'));

This will effectively serve every file in your "static" folder via the /static route.

Querying your index.js file in the client thus becomes:

<script src="static/index.js"></script>

jQuery set radio button

Why do you need 'input:radio[name=cols]'. Don't know your html, but assuming that ids are unique, you can simply do this.

$('#'+newcol).prop('checked', true);

Spring Boot Multiple Datasource

Use multiple datasource or realizing the separation of reading & writing. you must have a knowledge of Class AbstractRoutingDataSource which support dynamic datasource choose.

Here is my datasource.yaml and I figure out how to resolve this case. You can refer to this project spring-boot + quartz. Hope this will help you.

dbServer:
  default: localhost:3306
  read: localhost:3306
  write: localhost:3306
datasource:
  default:
    type: com.zaxxer.hikari.HikariDataSource
    pool-name: default
    continue-on-error: false
    jdbc-url: jdbc:mysql://${dbServer.default}/schedule_job?useSSL=true&verifyServerCertificate=false&useUnicode=true&characterEncoding=utf8
    username: root
    password: lh1234
    connection-timeout: 30000
    connection-test-query: SELECT 1
    maximum-pool-size: 5
    minimum-idle: 2
    idle-timeout: 600000
    destroy-method: shutdown
    auto-commit: false
  read:
    type: com.zaxxer.hikari.HikariDataSource
    pool-name: read
    continue-on-error: false
    jdbc-url: jdbc:mysql://${dbServer.read}/schedule_job?useSSL=true&verifyServerCertificate=false&useUnicode=true&characterEncoding=utf8
    username: root
    password: lh1234
    connection-timeout: 30000
    connection-test-query: SELECT 1
    maximum-pool-size: 5
    minimum-idle: 2
    idle-timeout: 600000
    destroy-method: shutdown
    auto-commit: false
  write:
    type: com.zaxxer.hikari.HikariDataSource
    pool-name: write
    continue-on-error: false
    jdbc-url: jdbc:mysql://${dbServer.write}/schedule_job?useSSL=true&verifyServerCertificate=false&useUnicode=true&characterEncoding=utf8
    username: root
    password: lh1234
    connection-timeout: 30000
    connection-test-query: SELECT 1
    maximum-pool-size: 5
    minimum-idle: 2
    idle-timeout: 600000
    destroy-method: shutdown
    auto-commit: false

update to python 3.7 using anaconda

The September 4th release for 3.7 recommends the following:

conda install python=3.7 anaconda=custom

If you want to create a new environment, they recommend:

conda create -n example_env numpy scipy pandas scikit-learn notebook
anaconda-navigator
conda activate example_env

JVM option -Xss - What does it do exactly?

It indeed sets the stack size on a JVM.

You should touch it in either of these two situations:

  • StackOverflowError (the stack size is greater than the limit), increase the value
  • OutOfMemoryError: unable to create new native thread (too many threads, each thread has a large stack), decrease it.

The latter usually comes when your Xss is set too large - then you need to balance it (testing!)

Java maximum memory on Windows XP

Oracle JRockit, which can handle a non-contiguous heap, can have a Java heap size of 2.85 GB on Windows 2003/XP with the /3GB switch. It seems that fragmentation can have quite an impact on how large a Java heap can be.

How to embed a video into GitHub README.md?

I combine Alexandre Jasmin and Gab Le Roux answers like this:

[![Demo CountPages alpha](https://share.gifyoutube.com/KzB6Gb.gif)](https://www.youtube.com/watch?v=ek1j272iAmc)

Demo:

Demo CountPages alpha

You can see this demo on github.

I used gifyoutube here, but I recommend using a local gif converter (like ffmpeg, see how) instead of an online one.

To record your screen to gif directly, you may want to check ScreenToGif.

How to update json file with python

def updateJsonFile():
    jsonFile = open("replayScript.json", "r") # Open the JSON file for reading
    data = json.load(jsonFile) # Read the JSON into the buffer
    jsonFile.close() # Close the JSON file

    ## Working with buffered content
    tmp = data["location"] 
    data["location"] = path
    data["mode"] = "replay"

    ## Save our changes to JSON file
    jsonFile = open("replayScript.json", "w+")
    jsonFile.write(json.dumps(data))
    jsonFile.close()

Implementing multiple interfaces with Java - is there a way to delegate?

There is one way to implement multiple interface.

Just extend one interface from another or create interface that extends predefined interface Ex:

public interface PlnRow_CallBack extends OnDateSetListener {
    public void Plan_Removed();
    public BaseDB getDB();
}

now we have interface that extends another interface to use in out class just use this new interface who implements two or more interfaces

public class Calculator extends FragmentActivity implements PlnRow_CallBack {

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

    }

    @Override
    public void Plan_Removed() {

    }

    @Override
    public BaseDB getDB() {

    }
}

hope this helps

Convert `List<string>` to comma-separated string

static void Main(string[] args)
{
   List<string> listStrings = new List<string>(){ "C#", "Asp.Net", "SQL Server", "PHP", "Angular"};
   string CommaSeparateString = GenerateCommaSeparateStringFromList(listStrings);
   Console.Write(CommaSeparateString);
   Console.ReadKey();
}

private static string GenerateCommaSeparateStringFromList(List<string> listStrings)
{
   return String.Join(",", listStrings);  
}

Convert a list of string to comma separated string C#.

jQuery add class .active on menu

<script type="text/javascript">
    jQuery(document).ready(function($) {
    var url = window.location.pathname,
urlRegExp = new RegExp(url.replace(/\/$/,'') + "$"); 
    $("#navbar li a").each(function() {//alert('dsfgsdgfd');
    if(urlRegExp.test(this.href.replace(/\/$/,''))){
    $(this).addClass("active");}
});
}); 
</script>

How to change border color of textarea on :focus

Probably a more appropriate way of changing outline color is using the outline-color CSS rule.

textarea {
  outline-color: #719ECE;
}

or for input

input {
  outline-color: #719ECE;
}

box-shadow isn't quite the same thing and it may look different than the outline, especially if you apply custom styling to your element.

How to use getJSON, sending data with post method?

I just used post and an if:

data = getDataObjectByForm(form);
var jqxhr = $.post(url, data, function(){}, 'json')
    .done(function (response) {
        if (response instanceof Object)
            var json = response;
        else
            var json = $.parseJSON(response);
        // console.log(response);
        // console.log(json);
        jsonToDom(json);
        if (json.reload != undefined && json.reload)
            location.reload();
        $("body").delay(1000).css("cursor", "default");
    })
    .fail(function (jqxhr, textStatus, error) {
        var err = textStatus + ", " + error;
        console.log("Request Failed: " + err);
        alert("Fehler!");
    });

Does Python's time.time() return the local or UTC timestamp?

time.time() return the unix timestamp. you could use datetime library to get local time or UTC time.

import datetime

local_time = datetime.datetime.now()
print(local_time.strftime('%Y%m%d %H%M%S'))

utc_time = datetime.datetime.utcnow() 
print(utc_time.strftime('%Y%m%d %H%M%S'))

How can I move all the files from one folder to another using the command line?

use move then move <file or folder> <destination directory>

How can I change the image displayed in a UIImageView programmatically?

To set image on your imageView use below line of code,

self.imgObj.image=[UIImage imageNamed:@"yourImage.png"];                         

How to execute a remote command over ssh with arguments?

I'm using the following to execute commands on the remote from my local computer:

ssh -i ~/.ssh/$GIT_PRIVKEY user@$IP "bash -s" < localpath/script.sh $arg1 $arg2

MySQL dump by query

not mysqldump, but mysql cli...

mysql -e "select * from myTable" -u myuser -pxxxxxxxxx mydatabase

you can redirect it out to a file if you want :

mysql -e "select * from myTable" -u myuser -pxxxxxxxx mydatabase > mydumpfile.txt

Update: Original post asked if he could dump from the database by query. What he asked and what he meant were different. He really wanted to just mysqldump all tables.

mysqldump --tables myTable --where="id < 1000"

How do I set the default schema for a user in MySQL

There is no default database for user. There is default database for current session.

You can get it using DATABASE() function -

SELECT DATABASE();

And you can set it using USE statement -

USE database1;

You should set it manually - USE db_name, or in the connection string.

Angular JS break ForEach

$scope.arr = [0, 1, 2];  
$scope.dict = {}
for ( var i=0; i < $scope.arr.length; i++ ) {
    if ( $scope.arr[i] == 1 ) {
        $scope.exists = 'yes, 1 exists';
        break;
    }
 }
 if ( $scope.exists ) {
     angular.forEach ( $scope.arr, function ( value, index ) {
                      $scope.dict[index] = value;
     });
 }

Obtaining ExitCode using Start-Process and WaitForExit instead of -Wait

Two things you could do I think...

  1. Create the System.Diagnostics.Process object manually and bypass Start-Process
  2. Run the executable in a background job (only for non-interactive processes!)

Here's how you could do either:

$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = "notepad.exe"
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = ""
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
#Do Other Stuff Here....
$p.WaitForExit()
$p.ExitCode

OR

Start-Job -Name DoSomething -ScriptBlock {
    & ping.exe somehost
    Write-Output $LASTEXITCODE
}
#Do other stuff here
Get-Job -Name DoSomething | Wait-Job | Receive-Job

How to enable/disable bluetooth programmatically in android

Add the following permissions into your manifest file:

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

Enable bluetooth use this

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();    
if (!mBluetoothAdapter.isEnabled()) {
    mBluetoothAdapter.enable(); 
}else{Toast.makeText(getApplicationContext(), "Bluetooth Al-Ready Enable", Toast.LENGTH_LONG).show();}

Disable bluetooth use this

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();    
if (mBluetoothAdapter.isEnabled()) {
    mBluetoothAdapter.disable(); 
}

Disable beep of Linux Bash on Windows 10

Since the only noise terminals tend to make is the bell and if you want it off everywhere, the very simplest way to do it for bash on Windows:

  1. Mash backspace a bunch at the prompt
  2. Right click sound icon and choose Open Volume Mixer
  3. Lower volume on Console Window Host to zero

Update row values where certain condition is met in pandas

You can do the same with .ix, like this:

In [1]: df = pd.DataFrame(np.random.randn(5,4), columns=list('abcd'))

In [2]: df
Out[2]: 
          a         b         c         d
0 -0.323772  0.839542  0.173414 -1.341793
1 -1.001287  0.676910  0.465536  0.229544
2  0.963484 -0.905302 -0.435821  1.934512
3  0.266113 -0.034305 -0.110272 -0.720599
4 -0.522134 -0.913792  1.862832  0.314315

In [3]: df.ix[df.a>0, ['b','c']] = 0

In [4]: df
Out[4]: 
          a         b         c         d
0 -0.323772  0.839542  0.173414 -1.341793
1 -1.001287  0.676910  0.465536  0.229544
2  0.963484  0.000000  0.000000  1.934512
3  0.266113  0.000000  0.000000 -0.720599
4 -0.522134 -0.913792  1.862832  0.314315

EDIT

After the extra information, the following will return all columns - where some condition is met - with halved values:

>> condition = df.a > 0
>> df[condition][[i for i in df.columns.values if i not in ['a']]].apply(lambda x: x/2)

I hope this helps!

How to open a link in new tab (chrome) using Selenium WebDriver?

First open empty new Tab by using the keys Ctrl + t and then use .get() to fetch the URL you want. Your code should look something like this -

String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL,"t");
driver.findElement(By.tagName("body")).sendKeys(selectLinkOpeninNewTab);

driver.get("www.facebook.com");

If you want to open a link on the current view in a new tab then the code you've written above can be used. Instead of By.linkText() make sure you use the appropriate By selector class to select the web element.

How to add a ListView to a Column in Flutter?

I have SingleChildScrollView as a parent, and one Column Widget and then List View Widget as last child.

Adding these properties in List View Worked for me.

  physics: NeverScrollableScrollPhysics(),
  shrinkWrap: true,
  scrollDirection: Axis.vertical,

How to go up a level in the src path of a URL in HTML?

If you store stylesheets/images in a folder so that multiple websites can use them, or you want to re-use the same files on another site on the same server, I have found that my browser/Apache does not allow me to go to any parent folder above the website root URL. This seems obvious for security reasons - one should not be able to browse around on the server any place other than the specified web folders.

Eg. does not work: www.mywebsite.com/../images

As a workaround, I use Symlinks:

Go to the directory of www.mywebsite.com Run the command ln -s ../images images

Now www.mywebsite.com/images will point to www.mywebsite.com/../images

How to convert Seconds to HH:MM:SS using T-SQL

DECLARE @TimeinSecond INT
SET @TimeinSecond = 340 -- Change the seconds
SELECT RIGHT('0' + CAST(@TimeinSecond / 3600 AS VARCHAR),2) + ':' +
RIGHT('0' + CAST((@TimeinSecond / 60) % 60 AS VARCHAR),2)  + ':' +
RIGHT('0' + CAST(@TimeinSecond % 60 AS VARCHAR),2)

Disable browser 'Save Password' functionality

You can prevent the browser from matching the forms up by randomizing the name used for the password field on each show. Then the browser sees a password for the same the url, but can't be sure it's the same password. Maybe it's controlling something else.

Update: note that this should be in addition to using autocomplete or other tactics, not a replacement for them, for the reasons indicated by others.

Also note that this will only prevent the browser from auto-completing the password. It won't prevent it from storing the password in whatever level of arbitrary security the browser chooses to use.

Import local function from a module housed in another directory with relative imports in Jupyter Notebook using Python 3

All other answers here depends on adding code the the notebook(!)

In my opinion is bad practice to hardcode a specific path into the notebook code, or otherwise depend on the location, since this makes it really hard to refactor you code later on. Instead I would recommend you to add the root project folder to PYTHONPATH when starting up your Jupyter notebook server, either directly from the project folder like so

env PYTHONPATH=`pwd` jupyter notebook

or if you are starting it up from somewhere else, use the absolute path like so

env PYTHONPATH=/Users/foo/bar/project/ jupyter notebook

Using headers with the Python requests library's get method

According to the API, the headers can all be passed in using requests.get:

import requests
r=requests.get("http://www.example.com/", headers={"content-type":"text"})

Default SQL Server Port

The default port of SQL server is 1433.

selectOneMenu ajax events

The PrimeFaces ajax events sometimes are very poorly documented, so in most cases you must go to the source code and check yourself.

p:selectOneMenu supports change event:

<p:selectOneMenu ..>
    <p:ajax event="change" update="msgtext"
        listener="#{post.subjectSelectionChanged}" />
    <!--...-->
</p:selectOneMenu>

which triggers listener with AjaxBehaviorEvent as argument in signature:

public void subjectSelectionChanged(final AjaxBehaviorEvent event)  {...}

Is it worth using Python's re.compile?

Interestingly, compiling does prove more efficient for me (Python 2.5.2 on Win XP):

import re
import time

rgx = re.compile('(\w+)\s+[0-9_]?\s+\w*')
str = "average    2 never"
a = 0

t = time.time()

for i in xrange(1000000):
    if re.match('(\w+)\s+[0-9_]?\s+\w*', str):
    #~ if rgx.match(str):
        a += 1

print time.time() - t

Running the above code once as is, and once with the two if lines commented the other way around, the compiled regex is twice as fast

Why can't DateTime.ParseExact() parse "9/1/2009" using "M/d/yyyy"

Try :

Configure in web config file

<system.web> <globalization culture="ja-JP" uiCulture="zh-HK" /> </system.web>

eg: DateTime dt = DateTime.ParseExact("08/21/2013", "MM/dd/yyyy", null);

ref url : http://support.microsoft.com/kb/306162/