Programs & Examples On #Cedit

Why do I get the "Unhandled exception type IOException"?

I got the Error even though i was catching the exception.

    try {
        bitmap = BitmapFactory.decodeStream(getAssets().open("kitten.jpg"));
    } catch (IOException e) {
        Log.e("blabla", "Error", e);
        finish();
    }

Issue was that the IOException wasn't imported

import java.io.IOException;

How to Select Columns in Editors (Atom,Notepad++, Kate, VIM, Sublime, Textpad,etc) and IDEs (NetBeans, IntelliJ IDEA, Eclipse, Visual Studio, etc)

You didn't explicitly state emacs, but since you've highlighted lots of editors...

In emacs, you can use rectangles for this, where a column is a rectangle of width 1.

To create a rectangle, mark the top-left and bottom-right of the rectangle (where the bottom-right mark is one to the right of the further right point included in the rectangle. You can then manipulate via:

C-x r k
Kill the text of the region-rectangle, saving its contents as the "last killed rectangle" (kill-rectangle).

C-x r d
Delete the text of the region-rectangle (delete-rectangle).

C-x r y
Yank the last killed rectangle with its upper left corner at point (yank-rectangle).

C-x r o
Insert blank space to fill the space of the region-rectangle (open-rectangle). This pushes the previous contents of the region-rectangle rightward.

M-x clear-rectangle
Clear the region-rectangle by replacing its contents with spaces.

M-x delete-whitespace-rectangle
Delete whitespace in each of the lines on the specified rectangle, starting from the left edge column of the rectangle.

C-x r t string RET
Replace rectangle contents with string on each line. (string-rectangle).

M-x string-insert-rectangle RET string RET
Insert string on each line of the rectangle.

List of macOS text editors and code editors

Best open source one is Smultron in my opinion, but it doesn't a torch to TextMate.

SQL Server: Error converting data type nvarchar to numeric

You might need to revise the data in the column, but anyway you can do one of the following:-

1- check if it is numeric then convert it else put another value like 0

Select COLUMNA AS COLUMNA_s, CASE WHEN Isnumeric(COLUMNA) = 1
THEN CONVERT(DECIMAL(18,2),COLUMNA) 
ELSE 0 END AS COLUMNA

2- select only numeric values from the column

SELECT COLUMNA AS COLUMNA_s ,CONVERT(DECIMAL(18,2),COLUMNA) AS COLUMNA
where Isnumeric(COLUMNA) = 1

View array in Visual Studio debugger?

You can try this nice little trick for C++. Take the expression which gives you the array and then append a comma and the number of elements you want to see. Expanding that value will show you elements 0-(N-1) where N is the number you add after the comma.

For example if pArray is the array, type pArray,10 in the watch window.

PostgreSQL delete with inner join

DELETE 
FROM m_productprice B  
     USING m_product C 
WHERE B.m_product_id = C.m_product_id AND
      C.upc = '7094' AND                 
      B.m_pricelist_version_id='1000020';

or

DELETE 
FROM m_productprice
WHERE m_pricelist_version_id='1000020' AND 
      m_product_id IN (SELECT m_product_id 
                       FROM m_product 
                       WHERE upc = '7094'); 

matplotlib does not show my drawings although I call pyplot.show()

Adding the following two lines before importing pylab seems to work for me

import matplotlib
matplotlib.use("gtk")

import sys
import pylab
import numpy as np

Virtual Memory Usage from Java under Linux, too much memory used

Just a thought, but you may check the influence of a ulimit -v option.

That is not an actual solution since it would limit address space available for all process, but that would allow you to check the behavior of your application with a limited virtual memory.

Java: Array with loop

If all you want to do is calculate the sum of 1,2,3... n then you could use :

 int sum = (n * (n + 1)) / 2;

How can I include null values in a MIN or MAX?

The effect you want is to treat the NULL as the largest possible date then replace it with NULL again upon completion:

SELECT RecordId, MIN(StartDate), NULLIF(MAX(COALESCE(EndDate,'9999-12-31')),'9999-12-31') 
  FROM tmp GROUP BY RecordId

Per your fiddle this will return the exact results you specify under all conditions.

What is the list of valid @SuppressWarnings warning names in Java?

JSL 1.7

The Oracle documentation mentions:

  • unchecked: Unchecked warnings are identified by the string "unchecked".
  • deprecation: A Java compiler must produce a deprecation warning when a type, method, field, or constructor whose declaration is annotated with the annotation @Deprecated is used (i.e. overridden, invoked, or referenced by name), unless: [...] The use is within an entity that is annotated to suppress the warning with the annotation @SuppressWarnings("deprecation"); or

It then explains that implementations can add and document their own:

Compiler vendors should document the warning names they support in conjunction with this annotation type. Vendors are encouraged to cooperate to ensure that the same names work across multiple compilers.

How to write a PHP ternary operator

You wouldn’t: it’s messy and hard to read.

You’re looking for the switch statement in the first case. The second is fine as it is but still could be converted for consistency

Ternary statements are much more suited to boolean values and alternating logic.

executing shell command in background from script

Building off of ngoozeff's answer, if you want to make a command run completely in the background (i.e., if you want to hide its output and prevent it from being killed when you close its Terminal window), you can do this instead:

cmd="google-chrome";
"${cmd}" &>/dev/null & disown;
  • &>/dev/null sets the command’s stdout and stderr to /dev/null instead of inheriting them from the parent process.
  • & makes the shell run the command in the background.
  • disown removes the “current” job, last one stopped or put in the background, from under the shell’s job control.

In some shells you can also use &! instead of & disown; they both have the same effect. Bash doesn’t support &!, though.

Also, when putting a command inside of a variable, it's more proper to use eval "${cmd}" rather than "${cmd}":

cmd="google-chrome";
eval "${cmd}" &>/dev/null & disown;

If you run this command directly in Terminal, it will show the PID of the process which the command starts. But inside of a shell script, no output will be shown.

Here's a function for it:

#!/bin/bash

# Run a command in the background.
_evalBg() {
    eval "$@" &>/dev/null & disown;
}

cmd="google-chrome";
_evalBg "${cmd}";

Also, see: Running bash commands in the background properly

What does "-ne" mean in bash?

This is one of those things that can be difficult to search for if you don't already know where to look.

[ is actually a command, not part of the bash shell syntax as you might expect. It happens to be a Bash built-in command, so it's documented in the Bash manual.

There's also an external command that does the same thing; on many systems, it's provided by the GNU Coreutils package.

[ is equivalent to the test command, except that [ requires ] as its last argument, and test does not.

Assuming the bash documentation is installed on your system, if you type info bash and search for 'test' or '[' (the apostrophes are part of the search), you'll find the documentation for the [ command, also known as the test command. If you use man bash instead of info bash, search for ^ *test (the word test at the beginning of a line, following some number of spaces).

Following the reference to "Bash Conditional Expressions" will lead you to the description of -ne, which is the numeric inequality operator ("ne" stands for "not equal). By contrast, != is the string inequality operator.

You can also find bash documentation on the web.

The official definition of the test command is the POSIX standard (to which the bash implementation should conform reasonably well, perhaps with some extensions).

Facebook OAuth "The domain of this URL isn't included in the app's domain"

in my case, i solved this issue by adding the full URL and not only the domain as facebook ask. i hope that they will rename it for more clarification. so the Valid OAuth Redirect URIs should be like so:
Before: https://www.mobile-battles.com
After: https://www.mobile-battles.com/register

load csv into 2D matrix with numpy for plotting

You can read a CSV file with headers into a NumPy structured array with np.genfromtxt. For example:

import numpy as np

csv_fname = 'file.csv'
with open(csv_fname, 'w') as fp:
    fp.write("""\
"A","B","C","D","E","F","timestamp"
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291111964948E12
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291113113366E12
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291120650486E12
""")

# Read the CSV file into a Numpy record array
r = np.genfromtxt(csv_fname, delimiter=',', names=True, case_sensitive=True)
print(repr(r))

which looks like this:

array([(611.88243, 9089.5601, 5133., 864.07514, 1715.37476, 765.22777, 1.29111196e+12),
       (611.88243, 9089.5601, 5133., 864.07514, 1715.37476, 765.22777, 1.29111311e+12),
       (611.88243, 9089.5601, 5133., 864.07514, 1715.37476, 765.22777, 1.29112065e+12)],
      dtype=[('A', '<f8'), ('B', '<f8'), ('C', '<f8'), ('D', '<f8'), ('E', '<f8'), ('F', '<f8'), ('timestamp', '<f8')])

You can access a named column like this r['E']:

array([1715.37476, 1715.37476, 1715.37476])

Note: this answer previously used np.recfromcsv to read the data into a NumPy record array. While there was nothing wrong with that method, structured arrays are generally better than record arrays for speed and compatibility.

How to add plus one (+1) to a SQL Server column in a SQL Query

You need both a value and a field to assign it to. The value is TableField + 1, so the assignment is:

SET TableField = TableField + 1

Check/Uncheck checkbox with JavaScript

Try This:

//Check
document.getElementById('checkbox').setAttribute('checked', 'checked');

//UnCheck
document.getElementById('chk').removeAttribute('checked');

Select rows having 2 columns equal value

Actually this would go faster in most of cases:

SELECT *
FROM table ta1
JOIN table ta2 on ta1.id != ta2.id
WHERE ta1.c2 = ta2.c2 and ta1.c3 = ta2.c3 and ta1.c4 = ta2.c4

You join on different rows which have the same values. I think it should work. Correct me if I'm wrong.

Calculating width from percent to pixel then minus by pixel in LESS CSS

Or, you could use the margin attribute like this:

    {
    background:#222;
    width:100%;
    height:100px;
    margin-left: 10px;
    margin-right: 10px;
    display:block;
    }

Parameter in like clause JPQL

If you do

LIKE :code

and then do

namedQuery.setParameter("code", "%" + this.value + "%");

Then value remains free from the '%' sign. If you need to use it somewhere else in the same query simply use another parameter name other than 'code' .

Why do I need to explicitly push a new branch?

HEAD is short for current branch so git push -u origin HEAD works. Now to avoid this typing everytime I use alias:

git config --global alias.pp 'push -u origin HEAD'

After this, everytime I want to push branch created via git -b branch I can push it using:

git pp

Hope this saves time for someone!

No module named MySQLdb

I met the same situation under windows, and searched for the solution.

Seeing this post Install mysql-python (Windows).

It points out installing such a pip environment is difficult, needs many other dependencies.

But I finally know that if we use mysqlclient with a version down to 1.3.4, it don't need that requirements any more, so try:

pip install mysqlclient==1.3.4

How to scroll to an element in jQuery?

For my problem this code worked, I had to navigate to an anchor tag on page load :

$(window).scrollTop($('a#captchaAnchor').position().top);

For that matter you can use this on any element, not just an anchor tag.

How to execute function in SQL Server 2008

you may be create function before so, update your function again using.

Alter FUNCTION dbo.Afisho_rankimin(@emri_rest int)
RETURNS int
AS
  BEGIN
     Declare @rankimi int
     Select @rankimi=dbo.RESTORANTET.Rankimi
     From RESTORANTET
     Where  dbo.RESTORANTET.ID_Rest=@emri_rest
     RETURN @rankimi
END
GO

SELECT dbo.Afisho_rankimin(5) AS Rankimi
GO

How to remove stop words using nltk or python

To exclude all type of stop-words including nltk stop-words, you could do something like this:

from stop_words import get_stop_words
from nltk.corpus import stopwords

stop_words = list(get_stop_words('en'))         #About 900 stopwords
nltk_words = list(stopwords.words('english')) #About 150 stopwords
stop_words.extend(nltk_words)

output = [w for w in word_list if not w in stop_words]

Resolve absolute path from relative path and/or file name

stijn's solution works with subfolders under C:\Program Files (86)\,

@echo off
set projectDirMc=test.txt

for /f "delims=" %%a in ('powershell -Command "[System.IO.Path]::GetFullPath( '%projectDirMc%' )"') do @set resolvedPath=%%a

echo full path:    %resolvedPath%

Does the target directory for a git clone have to match the repo name?

Yes, it is possible:

git clone https://github.com/pitosalas/st3_packages Packages 

You can specify the local root directory when using git clone.

<directory> 

The name of a new directory to clone into.
The "humanish" part of the source repository is used if no directory is explicitly given (repo for /path/to/repo.git and foo for host.xz:foo/.git).
Cloning into an existing directory is only allowed if the directory is empty.


As Chris comments, you can then rename that top directory.
Git only cares about the .git within said top folder, which you can get with various commands:

git rev-parse --show-toplevel git rev-parse --git-dir 

Send multipart/form-data files with angular using $http

Here's an updated answer for Angular 4 & 5. TransformRequest and angular.identity were dropped. I've also included the ability to combine files with JSON data in one request.

Angular 5 Solution:

import {HttpClient} from '@angular/common/http';

uploadFileToUrl(files, restObj, uploadUrl): Promise<any> {
  // Note that setting a content-type header
  // for mutlipart forms breaks some built in
  // request parsers like multer in express.
  const options = {} as any; // Set any options you like
  const formData = new FormData();

  // Append files to the virtual form.
  for (const file of files) {
    formData.append(file.name, file)
  }

  // Optional, append other kev:val rest data to the form.
  Object.keys(restObj).forEach(key => {
    formData.append(key, restObj[key]);
  });

  // Send it.
  return this.httpClient.post(uploadUrl, formData, options)
    .toPromise()
    .catch((e) => {
      // handle me
    });
}

Angular 4 Solution:

// Note that these imports below are deprecated in Angular 5
import {Http, RequestOptions} from '@angular/http';

uploadFileToUrl(files, restObj, uploadUrl): Promise<any> {
  // Note that setting a content-type header
  // for mutlipart forms breaks some built in
  // request parsers like multer in express.
  const options = new RequestOptions();
  const formData = new FormData();

  // Append files to the virtual form.
  for (const file of files) {
    formData.append(file.name, file)
  }

  // Optional, append other kev:val rest data to the form.
  Object.keys(restObj).forEach(key => {
    formData.append(key, restObj[key]);
  });

  // Send it.
  return this.http.post(uploadUrl, formData, options)
    .toPromise()
    .catch((e) => {
      // handle me
    });
}

How to 'grep' a continuous stream?

I use the tail -f <file> | grep <pattern> all the time.

It will wait till grep flushes, not till it finishes (I'm using Ubuntu).

What's the advantage of a Java enum versus a class with public static final fields?

You get compile time checking of valid values when you use an enum. Look at this question.

Difference between request.getSession() and request.getSession(true)

Method with boolean argument :

  request.getSession(true);

returns new session, if the session is not associated with the request

  request.getSession(false);

returns null, if the session is not associated with the request.

Method without boolean argument :

  request.getSession();

returns new session, if the session is not associated with the request and returns the existing session, if the session is associated with the request.It won't return null.

How can I force division to be floating point? Division keeps rounding down to 0?

from operator import truediv

c = truediv(a, b)

where a is dividend and b is the divisor. This function is handy when quotient after division of two integers is a float.

How to change text transparency in HTML/CSS?

Your best solution is to look at the "opacity" tag of an element.

For example:

.image
{
    opacity:0.4;
    filter:alpha(opacity=40); /* For IE8 and earlier */
}

So in your case it should look something like :

<html><span style="opacity: 0.5;"><font color=\"black\" face=\"arial\" size=\"4\">THIS IS MY TEXT</font></html>

However don't forget the tag isn't supported in HTML5.

You should use a CSS too :)

How to Resize a Bitmap in Android?

Keeping the aspect ratio,

  public Bitmap resizeBitmap(Bitmap source, int width,int height) {
    if(source.getHeight() == height && source.getWidth() == width) return source;
    int maxLength=Math.min(width,height);
    try {
        source=source.copy(source.getConfig(),true);
        if (source.getHeight() <= source.getWidth()) {
            if (source.getHeight() <= maxLength) { // if image already smaller than the required height
                return source;
            }

            double aspectRatio = (double) source.getWidth() / (double) source.getHeight();
            int targetWidth = (int) (maxLength * aspectRatio);

            return Bitmap.createScaledBitmap(source, targetWidth, maxLength, false);
        } else {

            if (source.getWidth() <= maxLength) { // if image already smaller than the required height
                return source;
            }

            double aspectRatio = ((double) source.getHeight()) / ((double) source.getWidth());
            int targetHeight = (int) (maxLength * aspectRatio);

            return Bitmap.createScaledBitmap(source, maxLength, targetHeight, false);

        }
    }
    catch (Exception e)
    {
        return source;
    }
}

Declare and assign multiple string variables at the same time

string Camnr , Klantnr , Ordernr , Bonnr , Volgnr , Omschrijving , Startdatum , Bonprioriteit , Matsoort , Dikte , Draaibaarheid , Draaiomschrijving , Orderleverdatum , Regeltaakkode , Gebruiksvoorkeur , Regelcamprog , Regeltijd , Orderrelease;
Camnr = Klantnr = Ordernr = Bonnr = Volgnr = Omschrijving = Startdatum = Bonprioriteit = Matsoort = Dikte = Draaibaarheid = Draaiomschrijving = Orderleverdatum = Regeltaakkode = Gebruiksvoorkeur = Regelcamprog = Regeltijd = Orderrelease = string.Empty;

MySQL DISTINCT on a GROUP_CONCAT()

DISTINCT: will gives you unique values.

SELECT GROUP_CONCAT(DISTINCT(categories )) AS categories FROM table

Python: Random numbers into a list

import random
my_randoms = [random.randrange(1, 101, 1) for _ in range(10)]

writing a batch file that opens a chrome URL

start "Chrome" "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --profile-directory="Profile 2"

start "webpage name" "http://someurl.com/"

start "Chrome" "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --profile-directory="Profile 3"

start "webpage name" "http://someurl.com/"

Delete sql rows where IDs do not have a match from another table

DELETE FROM blob 
WHERE fileid NOT IN 
       (SELECT id 
        FROM files 
        WHERE id is NOT NULL/*This line is unlikely to be needed 
                               but using NOT IN...*/
      )

What's the scope of a variable initialized in an if statement?

And note that since Python types are only checked at runtime you can have code like:

if True:
    x = 2
    y = 4
else:
    x = "One"
    y = "Two"
print(x + y)

But I'm having trouble thinking of other ways in which the code would operate without an error because of type issues.

to call onChange event after pressing Enter key

React users, here's an answer for completeness.

React version 16.4.2

You either want to update for every keystroke, or get the value only at submit. Adding the key events to the component works, but there are alternatives as recommended in the official docs.

Controlled vs Uncontrolled components

Controlled

From the Docs - Forms and Controlled components:

In HTML, form elements such as input, textarea, and select typically maintain their own state and update it based on user input. In React, mutable state is typically kept in the state property of components, and only updated with setState().

We can combine the two by making the React state be the “single source of truth”. Then the React component that renders a form also controls what happens in that form on subsequent user input. An input form element whose value is controlled by React in this way is called a “controlled component”.

If you use a controlled component you will have to keep the state updated for every change to the value. For this to happen, you bind an event handler to the component. In the docs' examples, usually the onChange event.

Example:

1) Bind event handler in constructor (value kept in state)

constructor(props) {
    super(props);
    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this);
}

2) Create handler function

handleChange(event) {
    this.setState({value: event.target.value});
}

3) Create form submit function (value is taken from the state)

handleSubmit(event) {
    alert('A name was submitted: ' + this.state.value);
    event.preventDefault();
}

4) Render

<form onSubmit={this.handleSubmit}>
    <label>
      Name:
      <input type="text" value={this.state.value} onChange={this.handleChange} />
    </label>
    <input type="submit" value="Submit" />
</form>

If you use controlled components, your handleChange function will always be fired, in order to update and keep the proper state. The state will always have the updated value, and when the form is submitted, the value will be taken from the state. This might be a con if your form is very long, because you will have to create a function for every component, or write a simple one that handles every component's change of value.

Uncontrolled

From the Docs - Uncontrolled component

In most cases, we recommend using controlled components to implement forms. In a controlled component, form data is handled by a React component. The alternative is uncontrolled components, where form data is handled by the DOM itself.

To write an uncontrolled component, instead of writing an event handler for every state update, you can use a ref to get form values from the DOM.

The main difference here is that you don't use the onChange function, but rather the onSubmit of the form to get the values, and validate if neccessary.

Example:

1) Bind event handler and create ref to input in constructor (no value kept in state)

constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.input = React.createRef();
}

2) Create form submit function (value is taken from the DOM component)

handleSubmit(event) {
    alert('A name was submitted: ' + this.input.current.value);
    event.preventDefault();
}

3) Render

<form onSubmit={this.handleSubmit}>
    <label>
      Name:
      <input type="text" ref={this.input} />
    </label>
    <input type="submit" value="Submit" />
</form>

If you use uncontrolled components, there is no need to bind a handleChange function. When the form is submitted, the value will be taken from the DOM and the neccessary validations can happen at this point. No need to create any handler functions for any of the input components as well.

Your issue

Now, for your issue:

... I want it to be called when I push 'Enter when the whole number has been entered

If you want to achieve this, use an uncontrolled component. Don't create the onChange handlers if it is not necessary. The enter key will submit the form and the handleSubmit function will be fired.

Changes you need to do:

Remove the onChange call in your element

var inputProcent = React.CreateElement(bootstrap.Input, {type: "text",
    //    bsStyle: this.validationInputFactor(),
    placeholder: this.initialFactor,
    className: "input-block-level",
    // onChange: this.handleInput,
    block: true,
    addonBefore: '%',
    ref:'input',
    hasFeedback: true
});

Handle the form submit and validate your input. You need to get the value from your element in the form submit function and then validate. Make sure you create the reference to your element in the constructor.

  handleSubmit(event) {
      // Get value of input field
      let value = this.input.current.value;
      event.preventDefault();
      // Validate 'value' and submit using your own api or something
  }

Example use of an uncontrolled component:

class NameForm extends React.Component {
  constructor(props) {
    super(props);
    // bind submit function
    this.handleSubmit = this.handleSubmit.bind(this);
    // create reference to input field
    this.input = React.createRef();
  }

  handleSubmit(event) {
    // Get value of input field
    let value = this.input.current.value;
    console.log('value in input field: ' + value );
    event.preventDefault();
    // Validate 'value' and submit using your own api or something
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input type="text" ref={this.input} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

ReactDOM.render(
  <NameForm />,
  document.getElementById('root')
);

What do the python file extensions, .pyc .pyd .pyo stand for?

  1. .py: This is normally the input source code that you've written.
  2. .pyc: This is the compiled bytecode. If you import a module, python will build a *.pyc file that contains the bytecode to make importing it again later easier (and faster).
  3. .pyo: This was a file format used before Python 3.5 for *.pyc files that were created with optimizations (-O) flag. (see the note below)
  4. .pyd: This is basically a windows dll file. http://docs.python.org/faq/windows.html#is-a-pyd-file-the-same-as-a-dll

Also for some further discussion on .pyc vs .pyo, take a look at: http://www.network-theory.co.uk/docs/pytut/CompiledPythonfiles.html (I've copied the important part below)

  • When the Python interpreter is invoked with the -O flag, optimized code is generated and stored in ‘.pyo’ files. The optimizer currently doesn't help much; it only removes assert statements. When -O is used, all bytecode is optimized; .pyc files are ignored and .py files are compiled to optimized bytecode.
  • Passing two -O flags to the Python interpreter (-OO) will cause the bytecode compiler to perform optimizations that could in some rare cases result in malfunctioning programs. Currently only __doc__ strings are removed from the bytecode, resulting in more compact ‘.pyo’ files. Since some programs may rely on having these available, you should only use this option if you know what you're doing.
  • A program doesn't run any faster when it is read from a ‘.pyc’ or ‘.pyo’ file than when it is read from a ‘.py’ file; the only thing that's faster about ‘.pyc’ or ‘.pyo’ files is the speed with which they are loaded.
  • When a script is run by giving its name on the command line, the bytecode for the script is never written to a ‘.pyc’ or ‘.pyo’ file. Thus, the startup time of a script may be reduced by moving most of its code to a module and having a small bootstrap script that imports that module. It is also possible to name a ‘.pyc’ or ‘.pyo’ file directly on the command line.

Note:

On 2015-09-15 the Python 3.5 release implemented PEP-488 and eliminated .pyo files. This means that .pyc files represent both unoptimized and optimized bytecode.

Create a rounded button / button with border-radius in Flutter

You can also achieve it by using StadiumBorder shape

FlatButton(
  onPressed: () {},
  child: Text('StadiumBorder'),
  shape: StadiumBorder(),
  color: Colors.pink,
  textColor: Colors.white,
),

enter image description here

Nesting queries in SQL

If it has to be "nested", this would be one way, to get your job done:

SELECT o.name AS country, o.headofstate 
FROM   country o
WHERE  o.headofstate like 'A%'
AND   (
    SELECT i.population
    FROM   city i
    WHERE  i.id = o.capital
    ) > 100000

A JOIN would be more efficient than a correlated subquery, though. Can it be, that who ever gave you that task is not up to speed himself?

Iterating each character in a string using Python

Just to make a more comprehensive answer, the C way of iterating over a string can apply in Python, if you really wanna force a square peg into a round hole.

i = 0
while i < len(str):
    print str[i]
    i += 1

But then again, why do that when strings are inherently iterable?

for i in str:
    print i

Android: how to convert whole ImageView to Bitmap?

It works in Kotlin after buildDrawingCache() being deprecated

 // convert imageView to bitmap
val bitmap = (imageViewId.getDrawable() as BitmapDrawable).getBitmap()

Finding duplicate values in MySQL

Building off of levik's answer to get the IDs of the duplicate rows you can do a GROUP_CONCAT if your server supports it (this will return a comma separated list of ids).

SELECT GROUP_CONCAT(id), name, COUNT(*) c FROM documents GROUP BY name HAVING c > 1;

List distinct values in a vector in R

You can also use the sqldf package in R.

Z <- sqldf('SELECT DISTINCT tablename.columnname FROM tablename ')

jQuery validate Uncaught TypeError: Cannot read property 'nodeName' of null

I found this answer when I was getting a similar error for nodeName after upgrading to Bootstrap 4. The issue was that the tabs didn't have the nav and nav-tab classes; adding those to the <ul> element fixed the issue.

React - Component Full Screen (with height 100%)

html, body, #app, #app>div {
  height: 100%
}

This will ensure all the chain to be height: 100%

Is there a <meta> tag to turn off caching in all browsers?

Try using

    <META HTTP-EQUIV="Pragma" CONTENT="no-cache">
    <META HTTP-EQUIV="Expires" CONTENT="-1">

Pass a JavaScript function as parameter

I chopped all my hair off with that issue. I couldn't make the examples above working, so I ended like :

function foo(blabla){
    var func = new Function(blabla);
    func();
}
// to call it, I just pass the js function I wanted as a string in the new one...
foo("alert('test')");

And that's working like a charm ... for what I needed at least. Hope it might help some.

Making an asynchronous task in Flask

You can also try using multiprocessing.Process with daemon=True; the process.start() method does not block and you can return a response/status immediately to the caller while your expensive function executes in the background.

I experienced similar problem while working with falcon framework and using daemon process helped.

You'd need to do the following:

from multiprocessing import Process

@app.route('/render/<id>', methods=['POST'])
def render_script(id=None):
    ...
    heavy_process = Process(  # Create a daemonic process with heavy "my_func"
        target=my_func,
        daemon=True
    )
    heavy_process.start()
    return Response(
        mimetype='application/json',
        status=200
    )

# Define some heavy function
def my_func():
    time.sleep(10)
    print("Process finished")

You should get a response immediately and, after 10s you should see a printed message in the console.

NOTE: Keep in mind that daemonic processes are not allowed to spawn any child processes.

In-memory size of a Python structure

Also you can use guppy module.

>>> from guppy import hpy; hp=hpy()
>>> hp.heap()
Partition of a set of 25853 objects. Total size = 3320992 bytes.
 Index  Count   %     Size   % Cumulative  % Kind (class / dict of class)
     0  11731  45   929072  28    929072  28 str
     1   5832  23   469760  14   1398832  42 tuple
     2    324   1   277728   8   1676560  50 dict (no owner)
     3     70   0   216976   7   1893536  57 dict of module
     4    199   1   210856   6   2104392  63 dict of type
     5   1627   6   208256   6   2312648  70 types.CodeType
     6   1592   6   191040   6   2503688  75 function
     7    199   1   177008   5   2680696  81 type
     8    124   0   135328   4   2816024  85 dict of class
     9   1045   4    83600   3   2899624  87 __builtin__.wrapper_descriptor
<90 more rows. Type e.g. '_.more' to view.>

And:

>>> hp.iso(1, [1], "1", (1,), {1:1}, None)
Partition of a set of 6 objects. Total size = 560 bytes.
 Index  Count   %     Size   % Cumulative  % Kind (class / dict of class)
     0      1  17      280  50       280  50 dict (no owner)
     1      1  17      136  24       416  74 list
     2      1  17       64  11       480  86 tuple
     3      1  17       40   7       520  93 str
     4      1  17       24   4       544  97 int
     5      1  17       16   3       560 100 types.NoneType

How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?

Copy the diff file to the root of your repository, and then do:

git apply yourcoworkers.diff

More information about the apply command is available on its man page.

By the way: A better way to exchange whole commits by file is the combination of the commands git format-patch on the sender and then git am on the receiver, because it also transfers the authorship info and the commit message.

If the patch application fails and if the commits the diff was generated from are actually in your repo, you can use the -3 option of apply that tries to merge in the changes.

It also works with Unix pipe as follows:

git diff d892531 815a3b5 | git apply

Setting selected option in laravel form

You can also try this for limited options:

          <select class="form-control required" id="assignedRole">
            <option id = "employeeRole" selected ="@if($employee->employee_role=='Employee'){'selected'}else{''} @endif">Employee</option>
            <option id = "adminRole" selected ="@if($employee->employee_role=='Admin'){'selected'}else{''} @endif">Admin</option>
            <option id = "employerRole" selected ="@if($employee->employee_role=='Employer'){'selected'}else{''} @endif">Employer</option>
          </select>

Add to python path mac os x

Mathew's answer works for the terminal python shell, but it didn't work for IDLE shell in my case because many versions of python existed before I replaced them all with Python2.7.7. How I solved the problem with IDLE.

  1. In terminal, cd /Applications/Python\ 2.7/IDLE.app/Contents/Resources/
  2. then sudo nano idlemain.py, enter password if required.
  3. after os.chdir(os.path.expanduser('~/Documents')) this line, I added sys.path.append("/Users/admin/Downloads....") NOTE: replace contents of the quotes with the directory where python module to be added
  4. to save the change, ctrl+x and enter Now open idle and try to import the python module, no error for me!!!

How to scroll to an element inside a div?

This is what has finally served me

/** Set parent scroll to show element
 * @param element {object} The HTML object to show
 * @param parent {object} The HTML object where the element is shown  */
var scrollToView = function(element, parent) {
    //Algorithm: Accumulate the height of the previous elements and add half the height of the parent
    var offsetAccumulator = 0;
    parent = $(parent);
    parent.children().each(function() {
        if(this == element) {
            return false; //brake each loop
        }
        offsetAccumulator += $(this).innerHeight();
    });
    parent.scrollTop(offsetAccumulator - parent.innerHeight()/2);
}

Code signing is required for product type 'Application' in SDK 'iOS5.1'

It means you haven't assigned a provisioning profile to the configuration.

Usually it's because "Any iOS SDK" must have a profile and cannot be set to "Don't sign".

All this and more is answered in the TN2250 Tech Note about Code Signing and Troubleshooting.

MySQL error #1054 - Unknown column in 'Field List'

I had this error aswell.

I am working in mysql workbench. When giving the values they have to be inside "". That solved it for me.

Why can I ping a server but not connect via SSH?

On the server, try:

netstat -an 

and look to see if tcp port 22 is opened (use findstr in Windows or grep in Unix).

MySQL select query with multiple conditions

also you can use "AND" instead of "OR" if you want both attributes to be applied.

select * from tickets where (assigned_to='1') and (status='open') order by created_at desc;

Get bytes from std::string in C++

If you just need to read the data.

encrypt(str.data(),str.size());

If you need a read/write copy of the data put it into a vector. (Don;t dynamically allocate space that's the job of vector).

std::vector<byte>  source(str.begin(),str.end());
encrypt(&source[0],source.size());

Of course we are all assuming that byte is a char!!!

How to secure phpMyAdmin

The best way to secure phpMyAdmin is the combination of all these 4:

1. Change phpMyAdmin URL
2. Restrict access to localhost only.
3. Connect through SSH and tunnel connection to a local port on your computer
4. Setup SSL to already encrypted SSH connection. (x2 security)

Here is how to do these all with: Ubuntu 16.4 + Apache 2 Setup Windows computer + PuTTY to connect and tunnel the SSH connection to a local port:

# Secure Web Serving of phpMyAdmin (change URL of phpMyAdmin):

    sudo nano /etc/apache2/conf-available/phpmyadmin.conf
            /etc/phpmyadmin/apache.conf
        Change: phpmyadmin URL by this line:
            Alias /newphpmyadminname /usr/share/phpmyadmin
        Add: AllowOverride All
            <Directory /usr/share/phpmyadmin>
                Options FollowSymLinks
                DirectoryIndex index.php
                AllowOverride Limit
                ...
        sudo systemctl restart apache2
        sudo nano /usr/share/phpmyadmin/.htaccess
            deny from all
            allow from 127.0.0.1

        alias phpmyadmin="sudo nano /usr/share/phpmyadmin/.htaccess"
        alias myip="echo ${SSH_CONNECTION%% *}"

# Secure Web Access to phpMyAdmin:

        Make sure pma.yourdomain.com is added to Let's Encrypt SSL configuration:
            https://www.digitalocean.com/community/tutorials/how-to-secure-apache-with-let-s-encrypt-on-ubuntu-16-04

        PuTTY => Source Port (local): <local_free_port> - Destination: 127.0.0.1:443 (OR localhost:443) - Local, Auto - Add

        C:\Windows\System32\drivers\etc
            Notepad - Run As Administrator - open: hosts
                127.0.0.1 pma.yourdomain.com

        https://pma.yourdomain.com:<local_free_port>/newphpmyadminname/ (HTTPS OK, SSL VPN OK)
        https://localhost:<local_free_port>/newphpmyadminname/ (HTTPS ERROR, SSL VPN OK)

        # Check to make sure you are on SSH Tunnel
            1. Windows - CMD:
                ping pma.yourdomain.com
                ping www.yourdomain.com

                # See PuTTY ports:
                netstat -ano |find /i "listening"

            2. Test live:
                https://pma.yourdomain.com:<local_free_port>/newphpmyadminname/

If you are able to do these all successfully,

you now have your own url path for phpmyadmin,
you denied all access to phpmyadmin except localhost,
you connected to your server with SSH,
you tunneled that connection to a port locally,
you connected to phpmyadmin as if you are on your server,
you have additional SSL conenction (HTTPS) to phpmyadmin in case something leaks or breaks.

jQuery: Adding two attributes via the .attr(); method

If you what to add bootstrap attributes in anchor tag dynamically than this will helps you lot

 $(".dropdown a").attr({
      class: "dropdown-toggle",
     'data-toggle': "dropdown",
      role: "button",
     'aria-haspopup': "true",
     'aria-expanded': "true"
});

Keras, how do I predict after I trained a model?

Your can use your tokenizer and pad sequencing for a new piece of text. This is followed by model prediction. This will return the prediction as a numpy array plus the label itself.

For example:

new_complaint = ['Your service is not good']
seq = tokenizer.texts_to_sequences(new_complaint)
padded = pad_sequences(seq, maxlen=maxlen)
pred = model.predict(padded)
print(pred, labels[np.argmax(pred)])

How to fix the height of a <div> element?

If you want to keep the height of the DIV absolute, regardless of the amount of text inside use the following:

overflow: hidden;

How to download excel (.xls) file from API in postman?

You can Just save the response(pdf,doc etc..) by option on the right side of the response in postman check this image postman save response

For more Details check this

https://learning.getpostman.com/docs/postman/sending_api_requests/responses/

Change Activity's theme programmatically

As docs say you have to call setTheme before any view output. It seems that super.onCreate() takes part in view processing.

So, to switch between themes dynamically you simply need to call setTheme before super.onCreate like this:

public void onCreate(Bundle savedInstanceState) {
    setTheme(android.R.style.Theme);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);
}

Timeout function if it takes too long to finish

The process for timing out an operations is described in the documentation for signal.

The basic idea is to use signal handlers to set an alarm for some time interval and raise an exception once that timer expires.

Note that this will only work on UNIX.

Here's an implementation that creates a decorator (save the following code as timeout.py).

from functools import wraps
import errno
import os
import signal

class TimeoutError(Exception):
    pass

def timeout(seconds=10, error_message=os.strerror(errno.ETIME)):
    def decorator(func):
        def _handle_timeout(signum, frame):
            raise TimeoutError(error_message)

        def wrapper(*args, **kwargs):
            signal.signal(signal.SIGALRM, _handle_timeout)
            signal.alarm(seconds)
            try:
                result = func(*args, **kwargs)
            finally:
                signal.alarm(0)
            return result

        return wraps(func)(wrapper)

    return decorator

This creates a decorator called @timeout that can be applied to any long running functions.

So, in your application code, you can use the decorator like so:

from timeout import timeout

# Timeout a long running function with the default expiry of 10 seconds.
@timeout
def long_running_function1():
    ...

# Timeout after 5 seconds
@timeout(5)
def long_running_function2():
    ...

# Timeout after 30 seconds, with the error "Connection timed out"
@timeout(30, os.strerror(errno.ETIMEDOUT))
def long_running_function3():
    ...

How to get an ASP.NET MVC Ajax response to redirect to new page instead of inserting view into UpdateTargetId?

You can simply do some kind of ajax response filter for incomming responses with $.ajaxSetup. If the response contains MVC redirection you can evaluate this expression on JS side. Example code for JS below:

$.ajaxSetup({
    dataFilter: function (data, type) {
        if (data && typeof data == "string") {
            if (data.indexOf('window.location') > -1) {
                eval(data);
            }
        }
        return data;
    }
});

If data is: "window.location = '/Acount/Login'" above filter will catch that and evaluate to make the redirection.

Convert string to decimal, keeping fractions

You can try calling this method in you program:

static double string_double(string s)
    {
        double temp = 0;
        double dtemp = 0;
        int b = 0;
        for (int i = 0; i < s.Length; i++)
        {
            if (s[i] == '.')
            {
                i++;
                while (i < s.Length)
                {
                    dtemp = (dtemp * 10) + (int)char.GetNumericValue(s[i]);
                    i++;
                    b++;
                }
                temp = temp + (dtemp * Math.Pow(10, -b));
                return temp;
            }
            else
            {
                temp = (temp * 10) + (int)char.GetNumericValue(s[i]);
            }
        }
        return -1; //if somehow failed
    }

Example:

string s = "12.3";
double d = string_double (s);        //d = 12.3 

increase the java heap size permanently?

For Windows users, you can add a system environment variable named _JAVA_OPTIONS, and set the heap size values there. The JVM should be able to grab the virtual machine options from _JAVA_OPTIONS.

How to read a file in other directory in python

x_file = open(os.path.join(direct, '5_1.txt'), 'r')

How to forcefully set IE's Compatibility Mode off from the server-side?

I found problems with the two common ways of doing this:

  1. Doing this with custom headers (<customHeaders>) in web.config allows different deployments of the same application to have this set differently. I see this as one more thing that can go wrong, so I think it's better if the application specifies this in code. Also, IIS6 doesn't support this.

  2. Including an HTML <meta> tag in a Web Forms Master Page or MVC Layout Page seems better than the above. However, if some pages don't inherit from these then the tag needs to be duplicated, so there's a potential maintainability and reliability problem.

  3. Network traffic could be reduced by only sending the X-UA-Compatible header to Internet Explorer clients.

Well-Structured Applications

If your application is structured in a way that causes all pages to ultimately inherit from a single root page, include the <meta> tag as shown in the other answers.

Legacy Applications

Otherwise, I think the best way to do this is to automatically add the HTTP header to all HTML responses. One way to do this is using an IHttpModule:

public class IeCompatibilityModeDisabler : IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.PreSendRequestHeaders += (sender, e) => DisableCompatibilityModeIfApplicable();
    }

    private void DisableCompatibilityModeIfApplicable()
    {
        if (IsIe && IsPage)
            DisableCompatibilityMode();
    }

    private void DisableCompatibilityMode()
    {
        var response = Context.Response;
        response.AddHeader("X-UA-Compatible", "IE=edge");
    }

    private bool IsIe { get { return Context.Request.Browser.IsBrowser("IE"); } }

    private bool IsPage { get { return Context.Handler is Page; } }

    private HttpContext Context { get { return HttpContext.Current; } }

    public void Dispose() { }
}

IE=edge indicates that IE should use its latest rendering engine (rather than compatibility mode) to render the page.

It seems that HTTP modules are often registered in the web.config file, but this brings us back to the first problem. However, you can register them programmatically in Global.asax like this:

public class Global : HttpApplication
{
    private static IeCompatibilityModeDisabler module;

    void Application_Start(object sender, EventArgs e)
    {
        module = new IeCompatibilityModeDisabler();
    }

    public override void Init()
    {
        base.Init();
        module.Init(this);
    }
}

Note that it is important that the module is static and not instantiated in Init so that there is only one instance per application. Of course, in a real-world application an IoC container should probably be managing this.

Advantages

  • Overcomes the problems outlined at the start of this answer.

Disadvantages

  • Website admins don't have control over the header value. This could be a problem if a new version of Internet Explorer comes out and adversely affects the rendering of the website. However, this could be overcome by having the module read the header value from the application's configuration file instead of using a hard-coded value.
  • This may require modification to work with ASP.NET MVC.
  • This doesn't work for static HTML pages.
  • The PreSendRequestHeaders event in the above code doesn't seem to fire in IIS6. I haven't figured out how to resolve this bug yet.

C# windows application Event: CLR20r3 on application start

Have been fighting this all morning and now have it solved and why it happened. Posting with the hope it helps others

I installed the Krypton.Toolkit which added the tools to the Visual studio toolbox automatically. I then added the tools to the designer, which automatically added the dll to the projrect references, however the toolkit was marked as CopyLocal=false

I built an installer, using all dlls in the release build folder (of course the above dll wasn't there).

Setting copylocal=true, then rebuilding the installer, everything worked fine.

What is the difference between <p> and <div>?

They have semantic difference - a <div> element is designed to describe a container of data whereas a <p> element is designed to describe a paragraph of content.

The semantics make all the difference. HTML is a markup language which means that it is designed to "mark up" content in a way that is meaningful to the consumer of the markup. Most developers believe that the semantics of the document are the default styles and rendering that browsers apply to these elements but that is not the case.

The elements that you choose to mark up your content should describe the content. Don't mark up your document based on how it should look - mark it up based on what it is.

If you need a generic container purely for layout purposes then use a <div>. If you need an element to describe a paragraph of content then use a <p>.

Note: It is important to understand that both <div> and <p> are block-level elements which means that most browsers will treat them in a similar fashion.

535-5.7.8 Username and Password not accepted

Goto config/initializers/setup_mail.rb Check whether the configuration there matches the configuration written in the development.rb file.It should look like the following in both files:

config.action_mailer.smtp_settings = {
     :address =>"[email protected]",
     :port => 587,
     :domain => "gmail.com",
     :user_name => "[email protected]",
     :password => "********",
     :authentication => 'plain',
     :enable_starttls_auto => true,
     :openssl_verify_mode => 'none' 
     } 

This will most certainly solve your problem.

Removing "http://" from a string

preg_replace('/^[^:\/?]+:\/\//','',$url); 

some results:

input: http://php.net/preg_replace output: php.net/preg_replace  input: https://www.php.net/preg_replace output: www.php.net/preg_replace  input: ftp://www.php.net/preg_replace output: www.php.net/preg_replace  input: https://php.net/preg_replace?url=http://whatever.com output: php.net/preg_replace?url=http://whatever.com  input: php.net/preg_replace?url=http://whatever.com output: php.net/preg_replace?url=http://whatever.com  input: php.net?site=http://whatever.com output: php.net?site=http://whatever.com 

How can I make a thumbnail <img> show a full size image when clicked?

That sort of functionality is going to require some Javascript, but it is probably possible just to use CSS (in browsers other than IE6&7).

How to use UTF-8 in resource properties with ResourceBundle

look at this : http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html#load(java.io.Reader)

the properties accept an Reader object as arguments, which you can create from an InputStream.

at the create time, you can specify the encoding of the Reader:

InputStreamReader isr = new InputStreamReader(stream, "UTF-8");

then apply this Reader to the load method :

prop.load(isr);

BTW: get the stream from .properties file :

 InputStream stream = this.class.getClassLoader().getResourceAsStream("a.properties");

BTW: get resource bundle from InputStreamReader:

ResourceBundle rb = new PropertyResourceBundle(isr);

hope this can help you !

How can I disable selected attribute from select2() dropdown Jquery?

To disable the complete select2 box, that is no deletion of already selected values and no new insertion, use:

$("id-select2").prop("disabled", true);

where id-select2 is the unique id of select2. you can also use any particular class if defined to address the dropdown.

Formatting NSDate into particular styles for both year, month, day, and hour, minute, seconds

this is what i used:

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];

NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:@"HH:mm:ss"];

NSDate *now = [[NSDate alloc] init];

NSString *theDate = [dateFormat stringFromDate:now];
NSString *theTime = [timeFormat stringFromDate:now];

NSLog(@"\n"
      "theDate: |%@| \n"
      "theTime: |%@| \n"
      , theDate, theTime);

[dateFormat release];
[timeFormat release];
[now release];

How to save Excel Workbook to Desktop regardless of user?

Not sure if this is still relevant, but I use this way

Public bEnableEvents As Boolean
Public bclickok As Boolean
Public booRestoreErrorChecking As Boolean   'put this at the top of the module

 Private Declare Function apiGetComputerName Lib "kernel32" Alias _
"GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
Private Declare Function apiGetUserName Lib "advapi32.dll" Alias _
"GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long

Function GetUserID() As String
' Returns the network login name
On Error Resume Next
Dim lngLen As Long, lngX As Long
Dim strUserName As String
strUserName = String$(254, 0)
lngLen = 255
lngX = apiGetUserName(strUserName, lngLen)
If lngX <> 0 Then
    GetUserID = Left$(strUserName, lngLen - 1)
Else
    GetUserID = ""
End If
Exit Function
End Function

This next bit I save file as PDF, but can change to suit

Public Sub SaveToDesktop()
Dim LoginName As String
LoginName = UCase(GetUserID)

ChDir "C:\Users\" & LoginName & "\Desktop\"
Debug.Print LoginName
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
    "C:\Users\" & LoginName & "\Desktop\MyFileName.pdf", Quality:=xlQualityStandard, _
    IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
    True
End Sub

PHP to search within txt file and echo the whole line

looks like you're better off systeming out to system("grep \"$QUERY\"") since that script won't be particularly high performance either way. Otherwise http://php.net/manual/en/function.file.php shows you how to loop over lines and you can use http://php.net/manual/en/function.strstr.php for finding matches.

Python: How to use RegEx in an if statement?

First you compile the regex, then you have to use it with match, find, or some other method to actually run it against some input.

import os
import re
import shutil

def test():
    os.chdir("C:/Users/David/Desktop/Test/MyFiles")
    files = os.listdir(".")
    os.mkdir("C:/Users/David/Desktop/Test/MyFiles2")
    pattern = re.compile(regex_txt, re.IGNORECASE)
    for x in (files):
        with open((x), 'r') as input_file:
            for line in input_file:
                if pattern.search(line):
                    shutil.copy(x, "C:/Users/David/Desktop/Test/MyFiles2")
                    break

How to execute two mysql queries as one in PHP/MYSQL?

It says on the PHP site that multiple queries are NOT permitted (EDIT: This is only true for the mysql extension. mysqli and PDO allow multiple queries) . So you can't do it in PHP, BUT, why can't you just execute that query in another mysql_query call, (like Jon's example)? It should still give you the correct result if you use the same connection. Also, mysql_num_rows may help also.

how to refresh page in angular 2

If you want to reload the page , you can easily go to your component then do :

location.reload();

How to fix Array indexOf() in JavaScript for Internet Explorer browsers

You should check if it's not defined using if (!Array.prototype.indexOf).

Also, your implementation of indexOf is not correct. You must use === instead of == in your if (this[i] == obj) statement, otherwise [4,"5"].indexOf(5) would be 1 according to your implementation, which is incorrect.

I recommend you use the implementation on MDC.

Reading a file line by line in Go

EDIT: As of go1.1, the idiomatic solution is to use bufio.Scanner

I wrote up a way to easily read each line from a file. The Readln(*bufio.Reader) function returns a line (sans \n) from the underlying bufio.Reader struct.

// Readln returns a single line (without the ending \n)
// from the input buffered reader.
// An error is returned iff there is an error with the
// buffered reader.
func Readln(r *bufio.Reader) (string, error) {
  var (isPrefix bool = true
       err error = nil
       line, ln []byte
      )
  for isPrefix && err == nil {
      line, isPrefix, err = r.ReadLine()
      ln = append(ln, line...)
  }
  return string(ln),err
}

You can use Readln to read every line from a file. The following code reads every line in a file and outputs each line to stdout.

f, err := os.Open(fi)
if err != nil {
    fmt.Printf("error opening file: %v\n",err)
    os.Exit(1)
}
r := bufio.NewReader(f)
s, e := Readln(r)
for e == nil {
    fmt.Println(s)
    s,e = Readln(r)
}

Cheers!

Google Maps setCenter()

 function resize() {
        var map_obj = document.getElementById("map_canvas");

      /*  map_obj.style.width = "500px";
        map_obj.style.height = "225px";*/
        if (map) {
            map.checkResize();
            map.panTo(new GLatLng(lat,lon));
        }
    }

<body onload="initialize()" onunload="GUnload()" onresize="resize()">
<div id="map_canvas" style="width: 100%; height: 100%">
</div>

Processing $http response in service

I really don't like the fact that, because of the "promise" way of doing things, the consumer of the service that uses $http has to "know" about how to unpack the response.

I just want to call something and get the data out, similar to the old $scope.items = Data.getData(); way, which is now deprecated.

I tried for a while and didn't come up with a perfect solution, but here's my best shot (Plunker). It may be useful to someone.

app.factory('myService', function($http) {
  var _data;  // cache data rather than promise
  var myService = {};

  myService.getData = function(obj) { 
    if(!_data) {
      $http.get('test.json').then(function(result){
        _data = result.data;
        console.log(_data);  // prove that it executes once
        angular.extend(obj, _data);
      }); 
    } else {  
      angular.extend(obj, _data);
    }
  };

  return myService;
}); 

Then controller:

app.controller('MainCtrl', function( myService,$scope) {
  $scope.clearData = function() {
    $scope.data = Object.create(null);
  };
  $scope.getData = function() {
    $scope.clearData();  // also important: need to prepare input to getData as an object
    myService.getData($scope.data); // **important bit** pass in object you want to augment
  };
});

Flaws I can already spot are

  • You have to pass in the object which you want the data added to, which isn't an intuitive or common pattern in Angular
  • getData can only accept the obj parameter in the form of an object (although it could also accept an array), which won't be a problem for many applications, but it's a sore limitation
  • You have to prepare the input object $scope.data with = {} to make it an object (essentially what $scope.clearData() does above), or = [] for an array, or it won't work (we're already having to assume something about what data is coming). I tried to do this preparation step IN getData, but no luck.

Nevertheless, it provides a pattern which removes controller "promise unwrap" boilerplate, and might be useful in cases when you want to use certain data obtained from $http in more than one place while keeping it DRY.

How to Serialize a list in java?

List is just an interface. The question is: is your actual List implementation serializable? Speaking about the standard List implementations (ArrayList, LinkedList) from the Java run-time, most of them actually are already.

What is the difference between Task.Run() and Task.Factory.StartNew()

People already mentioned that

Task.Run(A);

Is equivalent to

Task.Factory.StartNew(A, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);

But no one mentioned that

Task.Factory.StartNew(A);

Is equivalent to:

Task.Factory.StartNew(A, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Current);

As you can see two parameters are different for Task.Run and Task.Factory.StartNew:

  1. TaskCreationOptions - Task.Run uses TaskCreationOptions.DenyChildAttach which means that children tasks can not be attached to the parent, consider this:

    var parentTask = Task.Run(() =>
    {
        var childTask = new Task(() =>
        {
            Thread.Sleep(10000);
            Console.WriteLine("Child task finished.");
        }, TaskCreationOptions.AttachedToParent);
        childTask.Start();
    
        Console.WriteLine("Parent task finished.");
    });
    
    parentTask.Wait();
    Console.WriteLine("Main thread finished.");
    

    When we invoke parentTask.Wait(), childTask will not be awaited, even though we specified TaskCreationOptions.AttachedToParent for it, this is because TaskCreationOptions.DenyChildAttach forbids children to attach to it. If you run the same code with Task.Factory.StartNew instead of Task.Run, parentTask.Wait() will wait for childTask because Task.Factory.StartNew uses TaskCreationOptions.None

  2. TaskScheduler - Task.Run uses TaskScheduler.Default which means that the default task scheduler (the one that runs tasks on Thread Pool) will always be used to run tasks. Task.Factory.StartNew on the other hand uses TaskScheduler.Current which means scheduler of the current thread, it might be TaskScheduler.Default but not always. In fact when developing Winforms or WPF applications it is required to update UI from the current thread, to do this people use TaskScheduler.FromCurrentSynchronizationContext() task scheduler, if you unintentionally create another long running task inside task that used TaskScheduler.FromCurrentSynchronizationContext() scheduler the UI will be frozen. A more detailed explanation of this can be found here

So generally if you are not using nested children task and always want your tasks to be executed on Thread Pool it is better to use Task.Run, unless you have some more complex scenarios.

What's the difference between __PRETTY_FUNCTION__, __FUNCTION__, __func__?

__PRETTY_FUNCTION__ handles C++ features: classes, namespaces, templates and overload

main.cpp

#include <iostream>

namespace N {
    class C {
        public:
            template <class T>
            static void f(int i) {
                (void)i;
                std::cout << "__func__            " << __func__ << std::endl
                          << "__FUNCTION__        " << __FUNCTION__ << std::endl
                          << "__PRETTY_FUNCTION__ " << __PRETTY_FUNCTION__ << std::endl;
            }
            template <class T>
            static void f(double f) {
                (void)f;
                std::cout << "__PRETTY_FUNCTION__ " << __PRETTY_FUNCTION__ << std::endl;
            }
    };
}

int main() {
    N::C::f<char>(1);
    N::C::f<void>(1.0);
}

Compile and run:

g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp
./main.out

Output:

__func__            f
__FUNCTION__        f
__PRETTY_FUNCTION__ static void N::C::f(int) [with T = char]
__PRETTY_FUNCTION__ static void N::C::f(double) [with T = void]

You may also be interested in stack traces with function names: print call stack in C or C++

Tested in Ubuntu 19.04, GCC 8.3.0.

C++20 std::source_location::function_name

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1208r5.pdf went into C++20, so we have yet another way to do it.

The documentation says:

constexpr const char* function_name() const noexcept;

6 Returns: If this object represents a position in the body of a function, returns an implementation-defined NTBS that should correspond to the function name. Otherwise, returns an empty string.

where NTBS means "Null Terminated Byte String".

I'll give it a try when support arrives to GCC, GCC 9.1.0 with g++-9 -std=c++2a still doesn't support it.

https://en.cppreference.com/w/cpp/utility/source_location claims usage will be like:

#include <iostream>
#include <string_view>
#include <source_location>
 
void log(std::string_view message,
         const std::source_location& location std::source_location::current()
) {
    std::cout << "info:"
              << location.file_name() << ":"
              << location.line() << ":"
              << location.function_name() << " "
              << message << '\n';
}
 
int main() {
    log("Hello world!");
}

Possible output:

info:main.cpp:16:main Hello world!

so note how this returns the caller information, and is therefore perfect for usage in logging, see also: Is there a way to get function name inside a C++ function?

What is the difference between venv, pyvenv, pyenv, virtualenv, virtualenvwrapper, pipenv, etc?

I would just avoid the use of virtualenv after Python3.3+ and instead use the standard shipped library venv. To create a new virtual environment you would type:

$ python3 -m venv <MYVENV>  

virtualenv tries to copy the Python binary into the virtual environment's bin directory. However it does not update library file links embedded into that binary, so if you build Python from source into a non-system directory with relative path names, the Python binary breaks. Since this is how you make a copy distributable Python, it is a big flaw. BTW to inspect embedded library file links on OS X, use otool. For example from within your virtual environment, type:

$ otool -L bin/python
python:
    @executable_path/../Python (compatibility version 3.4.0, current version 3.4.0)
    /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1238.0.0)

Consequently I would avoid virtualenvwrapper and pipenv. pyvenv is deprecated. pyenv seems to be used often where virtualenv is used but I would stay away from it also since I think venv also does what pyenv is built for.

venv creates virtual environments in the shell that are fresh and sandboxed, with user-installable libraries, and it's multi-python safe. Fresh because virtual environments only start with the standard libraries that ship with python, you have to install any other libraries all over again with pip install while the virtual environment is active. Sandboxed because none of these new library installs are visible outside the virtual environment, so you can delete the whole environment and start again without worrying about impacting your base python install. User-installable libraries because the virtual environment's target folder is created without sudo in some directory you already own, so you won't need sudo permissions to install libraries into it. Finally it is multi-python safe, since when virtual environments activate, the shell only sees the python version (3.4, 3.5 etc.) that was used to build that virtual environment.

pyenv is similar to venv in that it lets you manage multiple python environments. However with pyenv you can't conveniently rollback library installs to some start state and you will likely need admin privileges at some point to update libraries. So I think it is also best to use venv.

In the last couple of years I have found many problems in build systems (emacs packages, python standalone application builders, installers...) that ultimately come down to issues with virtualenv. I think python will be a better platform when we eliminate this additional option and only use venv.

EDIT: Tweet of the BDFL,

I use venv (in the stdlib) and a bunch of shell aliases to quickly switch.

— Guido van Rossum (@gvanrossum) October 22, 2020

Gson: How to exclude specific fields from Serialization without annotations

Kotlin's @Transientannotation also does the trick apparently.

data class Json(
    @field:SerializedName("serialized_field_1") val field1: String,
    @field:SerializedName("serialized_field_2") val field2: String,
    @Transient val field3: String
)

Output:

{"serialized_field_1":"VALUE1","serialized_field_2":"VALUE2"}

How to write multiple conditions of if-statement in Robot Framework

The below code worked fine:

Run Keyword if    '${value1}' \ \ == \ \ '${cost1}' \ and \ \ '${value2}' \ \ == \ \ 'cost2'    LOG    HELLO

Compare one String with multiple values in one expression

ArrayUtils may be helpful.

ArrayUtils.contains(new String[]{"1", "2"}, "1")

Convert date yyyyMMdd to system.datetime format

string time = "19851231";
DateTime theTime= DateTime.ParseExact(time,
                                        "yyyyMMdd",
                                        CultureInfo.InvariantCulture,
                                        DateTimeStyles.None);

Why do we use arrays instead of other data structures?

Not all programs do the same thing or run on the same hardware.

This is usually the answer why various language features exist. Arrays are a core computer science concept. Replacing arrays with lists/matrices/vectors/whatever advanced data structure would severely impact performance, and be downright impracticable in a number of systems. There are any number of cases where using one of these "advanced" data collection objects should be used because of the program in question.

In business programming (which most of us do), we can target hardware that is relatively powerful. Using a List in C# or Vector in Java is the right choice to make in these situations because these structures allow the developer to accomplish the goals faster, which in turn allows this type of software to be more featured.

When writing embedded software or an operating system an array may often be the better choice. While an array offers less functionality, it takes up less RAM, and the compiler can optimize code more efficiently for look-ups into arrays.

I am sure I am leaving out a number of the benefits for these cases, but I hope you get the point.

How to justify a single flexbox item (override justify-content)

If you aren't actually restricted to keeping all of these elements as sibling nodes you can wrap the ones that go together in another default flex box, and have the container of both use space-between.

_x000D_
_x000D_
.space-between {_x000D_
  border: 1px solid red;_x000D_
  display: flex;_x000D_
  justify-content: space-between;_x000D_
}_x000D_
.default-flex {_x000D_
  border: 1px solid blue;_x000D_
  display: flex;_x000D_
}_x000D_
.child {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  border: 1px solid;_x000D_
}
_x000D_
<div class="space-between">_x000D_
  <div class="child">1</div>_x000D_
  <div class="default-flex">_x000D_
    <div class="child">2</div>_x000D_
    <div class="child">3</div>_x000D_
    <div class="child">4</div>_x000D_
    <div class="child">5</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Or if you were doing the same thing with flex-start and flex-end reversed you just swap the order of the default-flex container and lone child.

Python using enumerate inside list comprehension

Try this:

[(i, j) for i, j in enumerate(mylist)]

You need to put i,j inside a tuple for the list comprehension to work. Alternatively, given that enumerate() already returns a tuple, you can return it directly without unpacking it first:

[pair for pair in enumerate(mylist)]

Either way, the result that gets returned is as expected:

> [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]

Contains method for a slice

You can use the reflect package to iterate over an interface whose concrete type is a slice:

func HasElem(s interface{}, elem interface{}) bool {
    arrV := reflect.ValueOf(s)

    if arrV.Kind() == reflect.Slice {
        for i := 0; i < arrV.Len(); i++ {

            // XXX - panics if slice element points to an unexported struct field
            // see https://golang.org/pkg/reflect/#Value.Interface
            if arrV.Index(i).Interface() == elem {
                return true
            }
        }
    }

    return false
}

https://play.golang.org/p/jL5UD7yCNq

Purpose of ESI & EDI registers?

In addition to the string operations (MOVS/INS/STOS/CMPS/SCASB/W/D/Q etc.) mentioned in the other answers, I wanted to add that there are also more "modern" x86 assembly instructions that implicitly use at least EDI/RDI:

The SSE2 MASKMOVDQU (and the upcoming AVX VMASKMOVDQU) instruction selectively write bytes from an XMM register to memory pointed to by EDI/RDI.

How do I detach objects in Entity Framework Code First?

This is an option:

dbContext.Entry(entity).State = EntityState.Detached;

What is the difference between `sorted(list)` vs `list.sort()`?

What is the difference between sorted(list) vs list.sort()?

  • list.sort mutates the list in-place & returns None
  • sorted takes any iterable & returns a new list, sorted.

sorted is equivalent to this Python implementation, but the CPython builtin function should run measurably faster as it is written in C:

def sorted(iterable, key=None):
    new_list = list(iterable)    # make a new list
    new_list.sort(key=key)       # sort it
    return new_list              # return it

when to use which?

  • Use list.sort when you do not wish to retain the original sort order (Thus you will be able to reuse the list in-place in memory.) and when you are the sole owner of the list (if the list is shared by other code and you mutate it, you could introduce bugs where that list is used.)
  • Use sorted when you want to retain the original sort order or when you wish to create a new list that only your local code owns.

Can a list's original positions be retrieved after list.sort()?

No - unless you made a copy yourself, that information is lost because the sort is done in-place.

"And which is faster? And how much faster?"

To illustrate the penalty of creating a new list, use the timeit module, here's our setup:

import timeit
setup = """
import random
lists = [list(range(10000)) for _ in range(1000)]  # list of lists
for l in lists:
    random.shuffle(l) # shuffle each list
shuffled_iter = iter(lists) # wrap as iterator so next() yields one at a time
"""

And here's our results for a list of randomly arranged 10000 integers, as we can see here, we've disproven an older list creation expense myth:

Python 2.7

>>> timeit.repeat("next(shuffled_iter).sort()", setup=setup, number = 1000)
[3.75168503401801, 3.7473005310166627, 3.753129180986434]
>>> timeit.repeat("sorted(next(shuffled_iter))", setup=setup, number = 1000)
[3.702025591977872, 3.709248117986135, 3.71071034099441]

Python 3

>>> timeit.repeat("next(shuffled_iter).sort()", setup=setup, number = 1000)
[2.797430992126465, 2.796825885772705, 2.7744789123535156]
>>> timeit.repeat("sorted(next(shuffled_iter))", setup=setup, number = 1000)
[2.675589084625244, 2.8019039630889893, 2.849375009536743]

After some feedback, I decided another test would be desirable with different characteristics. Here I provide the same randomly ordered list of 100,000 in length for each iteration 1,000 times.

import timeit
setup = """
import random
random.seed(0)
lst = list(range(100000))
random.shuffle(lst)
"""

I interpret this larger sort's difference coming from the copying mentioned by Martijn, but it does not dominate to the point stated in the older more popular answer here, here the increase in time is only about 10%

>>> timeit.repeat("lst[:].sort()", setup=setup, number = 10000)
[572.919036605, 573.1384446719999, 568.5923951]
>>> timeit.repeat("sorted(lst[:])", setup=setup, number = 10000)
[647.0584738299999, 653.4040515829997, 657.9457361929999]

I also ran the above on a much smaller sort, and saw that the new sorted copy version still takes about 2% longer running time on a sort of 1000 length.

Poke ran his own code as well, here's the code:

setup = '''
import random
random.seed(12122353453462456)
lst = list(range({length}))
random.shuffle(lst)
lists = [lst[:] for _ in range({repeats})]
it = iter(lists)
'''
t1 = 'l = next(it); l.sort()'
t2 = 'l = next(it); sorted(l)'
length = 10 ** 7
repeats = 10 ** 2
print(length, repeats)
for t in t1, t2:
    print(t)
    print(timeit(t, setup=setup.format(length=length, repeats=repeats), number=repeats))

He found for 1000000 length sort, (ran 100 times) a similar result, but only about a 5% increase in time, here's the output:

10000000 100
l = next(it); l.sort()
610.5015971539542
l = next(it); sorted(l)
646.7786222379655

Conclusion:

A large sized list being sorted with sorted making a copy will likely dominate differences, but the sorting itself dominates the operation, and organizing your code around these differences would be premature optimization. I would use sorted when I need a new sorted list of the data, and I would use list.sort when I need to sort a list in-place, and let that determine my usage.

Call asynchronous method in constructor?

A little late to the party, but I think many are struggling with this...

I've been searching for this as well. And to get your method/action running async without waiting or blocking the thread, you'll need to queue it via the SynchronizationContext, so I came up with this solution:

I've made a helper-class for it.

public static class ASyncHelper
{

    public static void RunAsync(Func<Task> func)
    {
        var context = SynchronizationContext.Current;

        // you don't want to run it on a threadpool. So if it is null, 
        // you're not on a UI thread.
        if (context == null)
            throw new NotSupportedException(
                "The current thread doesn't have a SynchronizationContext");

        // post an Action as async and await the function in it.
        context.Post(new SendOrPostCallback(async state => await func()), null);
    }

    public static void RunAsync<T>(Func<T, Task> func, T argument)
    {
        var context = SynchronizationContext.Current;

        // you don't want to run it on a threadpool. So if it is null, 
        // you're not on a UI thread.
        if (context == null)
            throw new NotSupportedException(
                "The current thread doesn't have a SynchronizationContext");

        // post an Action as async and await the function in it.
        context.Post(new SendOrPostCallback(async state => await func((T)state)), argument);
    }
}

Usage/Example:

public partial class Form1 : Form
{

    private async Task Initialize()
    {
        // replace code here...
        await Task.Delay(1000);
    }

    private async Task Run(string myString)
    {

        // replace code here...
        await Task.Delay(1000);
    }

    public Form1()
    {
        InitializeComponent();

        // you don't have to await nothing.. (the thread must be running)
        ASyncHelper.RunAsync(Initialize);
        ASyncHelper.RunAsync(Run, "test");

        // In your case
        ASyncHelper.RunAsync(getWritings);
    }
}

This works for Windows.Forms and WPF

How to determine the current language of a wordpress page when using polylang?

To show current language, you can use:

 <?php echo $lang=get_bloginfo("language"); ?>

Plain and simple

What is the best way to get the first letter from a string in Java, returned as a string of length 1?

Long story short, it probably doesn't matter. Use whichever you think looks nicest.

Longer answer, using Oracle's Java 7 JDK specifically, since this isn't defined at the JLS:

String.valueOf or Character.toString work the same way, so use whichever you feel looks nicer. In fact, Character.toString simply calls String.valueOf (source).

So the question is, should you use one of those or String.substring. Here again it doesn't matter much. String.substring uses the original string's char[] and so allocates one object fewer than String.valueOf. This also prevents the original string from being GC'ed until the one-character string is available for GC (which can be a memory leak), but in your example, they'll both be available for GC after each iteration, so that doesn't matter. The allocation you save also doesn't matter -- a char[1] is cheap to allocate, and short-lived objects (as the one-char string will be) are cheap to GC, too.

If you have a large enough data set that the three are even measurable, substring will probably give a slight edge. Like, really slight. But that "if... measurable" contains the real key to this answer: why don't you just try all three and measure which one is fastest?

JavaScript window resize event

Never override the window.onresize function.

Instead, create a function to add an Event Listener to the object or element. This checks and incase the listeners don't work, then it overrides the object's function as a last resort. This is the preferred method used in libraries such as jQuery.

object: the element or window object
type: resize, scroll (event type)
callback: the function reference

var addEvent = function(object, type, callback) {
    if (object == null || typeof(object) == 'undefined') return;
    if (object.addEventListener) {
        object.addEventListener(type, callback, false);
    } else if (object.attachEvent) {
        object.attachEvent("on" + type, callback);
    } else {
        object["on"+type] = callback;
    }
};

Then use is like this:

addEvent(window, "resize", function_reference);

or with an anonymous function:

addEvent(window, "resize", function(event) {
  console.log('resized');
});

Unique constraint violation during insert: why? (Oracle)

It looks like you are not providing a value for the primary key field DB_ID. If that is a primary key, you must provide a unique value for that column. The only way not to provide it would be to create a database trigger that, on insert, would provide a value, most likely derived from a sequence.

If this is a restoration from another database and there is a sequence on this new instance, it might be trying to reuse a value. If the old data had unique keys from 1 - 1000 and your current sequence is at 500, it would be generating values that already exist. If a sequence does exist for this table and it is trying to use it, you would need to reconcile the values in your table with the current value of the sequence.

You can use SEQUENCE_NAME.CURRVAL to see the current value of the sequence (if it exists of course)

Convert character to ASCII numeric value in java

You can check the ASCII´s number with this code.

String name = "admin";
char a1 = a.charAt(0);
int a2 = a1;
System.out.println("The number is : "+a2); // the value is 97

If I am wrong, apologies.

python: How do I know what type of exception occurred?

The other answers all point out that you should not catch generic exceptions, but no one seems to want to tell you why, which is essential to understanding when you can break the "rule". Here is an explanation. Basically, it's so that you don't hide:

So as long as you take care to do none of those things, it's OK to catch the generic exception. For instance, you could provide information about the exception to the user another way, like:

  • Present exceptions as dialogs in a GUI
  • Transfer exceptions from a worker thread or process to the controlling thread or process in a multithreading or multiprocessing application

So how to catch the generic exception? There are several ways. If you just want the exception object, do it like this:

try:
    someFunction()
except Exception as ex:
    template = "An exception of type {0} occurred. Arguments:\n{1!r}"
    message = template.format(type(ex).__name__, ex.args)
    print message

Make sure message is brought to the attention of the user in a hard-to-miss way! Printing it, as shown above, may not be enough if the message is buried in lots of other messages. Failing to get the users attention is tantamount to swallowing all exceptions, and if there's one impression you should have come away with after reading the answers on this page, it's that this is not a good thing. Ending the except block with a raise statement will remedy the problem by transparently reraising the exception that was caught.

The difference between the above and using just except: without any argument is twofold:

  • A bare except: doesn't give you the exception object to inspect
  • The exceptions SystemExit, KeyboardInterrupt and GeneratorExit aren't caught by the above code, which is generally what you want. See the exception hierarchy.

If you also want the same stacktrace you get if you do not catch the exception, you can get that like this (still inside the except clause):

import traceback
print traceback.format_exc()

If you use the logging module, you can print the exception to the log (along with a message) like this:

import logging
log = logging.getLogger()
log.exception("Message for you, sir!")

If you want to dig deeper and examine the stack, look at variables etc., use the post_mortem function of the pdb module inside the except block:

import pdb
pdb.post_mortem()

I've found this last method to be invaluable when hunting down bugs.

TortoiseSVN icons not showing up under Windows 7

To complete Johannes's answer, you can check this thread, which mentions another cause (the first one being installing the 32bit client instead of the 64 one) (emphasis mine):

Only more recent versions of TSVN and TCVS are able to share overlay icons, and since Explorer has a limit of 14 overlay images in total with extraneous overlay icons simply not showing up you might have too many...

If it's overlay icons are showing up you'd have to actually be using the 32-bit Windows Explorer, which of course means you'll have to also install a 32-bit version of TSVN.

The issue might come up when one install also first TortoiseVCS, because:

Looking at what got installed in the filesystem and the registry, it looks like they tried to do what I do with my Shell extensions - install both 64 and 32 -bit versions, so that nobody says "I don't see my overlays/menus"! ;)

Unfortunately, it looks like the registry entries for 32-bit got hosed, so the 32-bit extension DLL, even though present, does not have the correct registry entries.

If in doubt I suggest to deinstall TCVS and TSVN.
Then install TSVN.
Maybe after installation reboot twice, not only once.
And if they still don't show up go to software control panel and choose to repair the installation. That did the trick for me with when upgrading from the previous to the current version.

You should probably install the TortoiseXYZ variant you plan to use mainly first, to improve its chances to fall into one of those limited number of overlay icons slots before the TortoiseXYZ variant you use less.
Always keep these limited number of overlay icon slots in mind when trying to analyze malfunctions.

__init__() missing 1 required positional argument

You should possibly make data a keyword parameter with a default value of empty dictionary:

class DHT:
    def __init__(self, data=dict()):
        self.data['one'] = '1'
        self.data['two'] = '2'
        self.data['three'] = '3'
    def showData(self):
        print(self.data)

if __name__ == '__main__': 
    DHT().showData()

Parse String date in (yyyy-MM-dd) format

I convert String to Date in format ("yyyy-MM-dd") to save into Mysql data base .

 String date ="2016-05-01";
 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
 Date parsed = format.parse(date);
 java.sql.Date sql = new java.sql.Date(parsed.getTime());

sql it's my output in date format

Check if a specific value exists at a specific key in any subarray of a multidimensional array

I came upon this post looking to do the same and came up with my own solution I wanted to offer for future visitors of this page (and to see if doing this way presents any problems I had not forseen).

If you want to get a simple true or false output and want to do this with one line of code without a function or a loop you could serialize the array and then use stripos to search for the value:

stripos(serialize($my_array),$needle)

It seems to work for me.

MVC 4 Razor adding input type date

The input date value format needs the date specified as per http://tools.ietf.org/html/rfc3339#section-5.6 full-date.

So I've ended up doing:

<input type="date" id="last-start-date" value="@string.Format("{0:yyyy-MM-dd}", Model.LastStartDate)" />

I did try doing it "properly" using:

[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime LastStartDate
{
    get { return lastStartDate; }
    set { lastStartDate = value; }
}

with

@Html.TextBoxFor(model => model.LastStartDate, 
    new { type = "date" })

Unfortunately that always seemed to set the value attribute of the input to a standard date time so I've ended up applying the formatting directly as above.

Edit:

According to Jorn if you use

@Html.EditorFor(model => model.LastStartDate)

instead of TextBoxFor it all works fine.

XML Document to String

First you need to get rid of all newline characters in all your text nodes. Then you can use an identity transform to output your DOM tree. Look at the javadoc for TransformerFactory#newTransformer().

What exactly does an #if 0 ..... #endif block do?

Not only does it not get executed, it doesn't even get compiled.

#if is a preprocessor command, which gets evaluated before the actual compilation step. The code inside that block doesn't appear in the compiled binary.

It's often used for temporarily removing segments of code with the intention of turning them back on later.

What is the difference between procedural programming and functional programming?

A functional programming is identical to procedural programming in which global variables are not being used.

How do I select and store columns greater than a number in pandas?

Sample DF:

In [79]: df = pd.DataFrame(np.random.randint(5, 15, (10, 3)), columns=list('abc'))

In [80]: df
Out[80]:
    a   b   c
0   6  11  11
1  14   7   8
2  13   5  11
3  13   7  11
4  13   5   9
5   5  11   9
6   9   8   6
7   5  11  10
8   8  10  14
9   7  14  13

present only those rows where b > 10

In [81]: df[df.b > 10]
Out[81]:
   a   b   c
0  6  11  11
5  5  11   9
7  5  11  10
9  7  14  13

Minimums (for all columns) for the rows satisfying b > 10 condition

In [82]: df[df.b > 10].min()
Out[82]:
a     5
b    11
c     9
dtype: int32

Minimum (for the b column) for the rows satisfying b > 10 condition

In [84]: df.loc[df.b > 10, 'b'].min()
Out[84]: 11

UPDATE: starting from Pandas 0.20.1 the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers.

How to change the window title of a MATLAB plotting figure?

First you must create an empty figure with the following command.

figure('name','Title of the window here');

By doing this, the newly created figure becomes you active figure. Immediately after calling a plot() command, it will print your plotting onto this figure. So your window will have a title.

This is the code you must use:

figure('name','Title of the window here');

hold on

x = [0; 0.2; 0.4; 0.6; 0.8; 1; 1.2; 1.4; 1.6; 1.8; 2; 2.2; 2.4; 2.6; 2.8; 3; 3.2; 3.4; 3.6; 3.8; 4; 4.2; 4.4; 4.6; 4.8; 5; 5.2; 5.4; 5.6; 5.8; 6; 6.2; 6.4; 6.6; 6.8; 7; 7.2; 7.4; 7.6; 7.8; 8; 8.2; 8.4; 8.6; 8.8; 9; 9.2; 9.4; 9.6; 9.8; 10; 10.2; 10.4; 10.6; 10.8; 11; 11.2; 11.4; 11.6; 11.8; 12; 12.2; 12.4; 12.6; 12.8; 13; 13.2; 13.4; 13.6; 13.8; 14; 14.2; 14.4; 14.6; 14.8; 15; 15.2; 15.4; 15.6; 15.8; 16; 16.2; 16.4; 16.6; 16.8; 17; 17.2; 17.4; 17.6; 17.8; 18; 18.2; 18.4; 18.6; 18.8];
y = [0; 0.198669; 0.389418; 0.564642; 0.717356; 0.841471; 0.932039; 0.98545; 0.999574; 0.973848; 0.909297; 0.808496; 0.675463; 0.515501; 0.334988; 0.14112; -0.0583741; -0.255541; -0.44252; -0.611858; -0.756802; -0.871576; -0.951602; -0.993691; -0.996165; -0.958924; -0.883455; -0.772764; -0.631267; -0.464602; -0.279415; -0.0830894; 0.116549; 0.311541; 0.494113; 0.656987; 0.793668; 0.898708; 0.96792; 0.998543; 0.989358; 0.940731; 0.854599; 0.734397; 0.584917; 0.412118; 0.22289; 0.0247754; -0.174327; -0.366479; -0.544021; -0.699875; -0.827826; -0.922775; -0.980936; -0.99999; -0.979178; -0.919329; -0.822829; -0.693525; -0.536573; -0.358229; -0.165604; 0.033623; 0.23151; 0.420167; 0.592074; 0.740376; 0.859162; 0.943696; 0.990607; 0.998027; 0.965658; 0.894791; 0.788252; 0.650288; 0.486399; 0.303118; 0.107754; -0.0919069; -0.287903; -0.472422; -0.638107; -0.778352; -0.887567; -0.961397; -0.9969; -0.992659; -0.948844; -0.867202; -0.750987; -0.604833; -0.434566; -0.246974; -0.0495356];
plot(x, y, '--b');

x = [0; 0.2; 0.4; 0.6; 0.8; 1; 1.2; 1.4; 1.6; 1.8; 2; 2.2; 2.4; 2.6; 2.8; 3; 3.2; 3.4; 3.6; 3.8; 4; 4.2; 4.4; 4.6; 4.8; 5; 5.2; 5.4; 5.6; 5.8; 6; 6.2; 6.4; 6.6; 6.8; 7; 7.2; 7.4; 7.6; 7.8; 8; 8.2; 8.4; 8.6; 8.8; 9; 9.2; 9.4; 9.6; 9.8; 10; 10.2; 10.4; 10.6; 10.8; 11; 11.2; 11.4; 11.6; 11.8; 12; 12.2; 12.4; 12.6; 12.8; 13; 13.2; 13.4; 13.6; 13.8; 14; 14.2; 14.4; 14.6; 14.8; 15; 15.2; 15.4; 15.6; 15.8; 16; 16.2; 16.4; 16.6; 16.8; 17; 17.2; 17.4; 17.6; 17.8; 18; 18.2; 18.4; 18.6; 18.8];
y = [-1; -0.980133; -0.921324; -0.825918; -0.697718; -0.541836; -0.364485; -0.172736; 0.0257666; 0.223109; 0.411423; 0.583203; 0.731599; 0.850695; 0.935744; 0.983355; 0.991629; 0.960238; 0.890432; 0.784994; 0.648128; 0.48529; 0.302972; 0.108443; -0.0905427; -0.286052; -0.470289; -0.635911; -0.776314; -0.885901; -0.960303; -0.996554; -0.993208; -0.950399; -0.869833; -0.754723; -0.609658; -0.44042; -0.253757; -0.057111; 0.141679; 0.334688; 0.514221; 0.673121; 0.805052; 0.904756; 0.968256; 0.993023; 0.978068; 0.923987; 0.832937; 0.708548; 0.555778; 0.380717; 0.190346; -0.00774649; -0.205663; -0.395514; -0.56973; -0.721365; -0.844375; -0.933855; -0.986238; -0.999436; -0.972923; -0.907755; -0.806531; -0.673287; -0.513333; -0.333047; -0.139617; 0.0592467; 0.255615; 0.44166; 0.609964; 0.753818; 0.867487; 0.946439; 0.987526; 0.989111; 0.95113; 0.875097; 0.764044; 0.622398; 0.455806; 0.27091; 0.0750802; -0.123876; -0.318026; -0.499631; -0.66145; -0.797032; -0.900972; -0.969126; -0.998776];
plot(x, y, '-r');

hold off

title('My plot title');
xlabel('My x-axis title');
ylabel('My y-axis title');

std::cin input with spaces?

How do I read a string from input?

You can read a single, whitespace terminated word with std::cin like this:

#include<iostream>
#include<string>
using namespace std;

int main()
{
    cout << "Please enter a word:\n";

    string s;
    cin>>s;

    cout << "You entered " << s << '\n';
}

Note that there is no explicit memory management and no fixed-sized buffer that you could possibly overflow. If you really need a whole line (and not just a single word) you can do this:

#include<iostream>
#include<string>
using namespace std;

int main()
{
    cout << "Please enter a line:\n";

    string s;
    getline(cin,s);

    cout << "You entered " << s << '\n';
}

No Access-Control-Allow-Origin header is present on the requested resource

On your servlet simply override the service method of your servlet so that you can add headers for all your http methods (POST, GET, DELETE, PUT, etc...).

@Override
    protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

        if(("http://www.example.com").equals(req.getHeader("origin"))){
            res.setHeader("Access-Control-Allow-Origin", req.getHeader("origin"));
            res.setHeader("Access-Control-Allow-Headers", "Authorization");
        }

        super.service(req, res);
    }

Multiline text in JLabel

String labelText ="<html>Name :"+name+"<br>Surname :"+surname+"<br>Gender :"+gender+"</html>";
JLabel label=new JLabel(labelText);
label.setVisible(true);
label.setBounds(10, 10,300, 100);
dialog.add(label);

Warning as error - How to get rid of these

To treat all compiler warnings as compilation errors

  1. With a project selected in Solution Explorer, on the Project menu, click Properties.
  2. Click the Compile tab. (or Build Tab may be there)
  3. Select the Treat all warnings as errors check box. (or select the build setting and change the “treat warnings as errors” settings to true.)

and if you want to get rid of it

To disable all compiler warnings

  1. With a project selected in Solution Explorer, on the Project menu click Properties.
  2. Click the Compile tab. (or Build Tab may be there)
  3. Select the Disable all warnings check box. (or select the build setting and change the “treat warnings as errors” settings to false.)

R memory management / cannot allocate vector of size n Mb

Here is a presentation on this topic that you might find interesting:

http://www.bytemining.com/2010/08/taking-r-to-the-limit-part-ii-large-datasets-in-r/

I haven't tried the discussed things myself, but the bigmemory package seems very useful

Java 8 Stream API to find Unique Object matching a property value

Instead of using a collector try using findFirst or findAny.

Optional<Person> matchingObject = objects.stream().
    filter(p -> p.email().equals("testemail")).
    findFirst();

This returns an Optional since the list might not contain that object.

If you're sure that the list always contains that person you can call:

Person person = matchingObject.get();

Be careful though! get throws NoSuchElementException if no value is present. Therefore it is strongly advised that you first ensure that the value is present (either with isPresent or better, use ifPresent, map, orElse or any of the other alternatives found in the Optional class).

If you're okay with a null reference if there is no such person, then:

Person person = matchingObject.orElse(null);

If possible, I would try to avoid going with the null reference route though. Other alternatives methods in the Optional class (ifPresent, map etc) can solve many use cases. Where I have found myself using orElse(null) is only when I have existing code that was designed to accept null references in some cases.


Optionals have other useful methods as well. Take a look at Optional javadoc.

How to make a progress bar

Infinitive progress bar using pure Javascript

<div id="container" style="width:100%; height:5px; border:1px solid black;">
  <div id="progress-bar" style="width:10%;background-color: green; height:5px;"></div>
</div>

<script>
  var width = 0;
  window.onload = function(e){ 
    setInterval(function () {
        width = width >= 100 ? 0 : width+5;  
        document.getElementById('progress-bar').style.width = width + '%'; }, 200);            
  }
</script>

Example http://fiddle.jshell.net/1kmum4du/

Force flushing of output to a file while bash script is still running

This isn't a function of bash, as all the shell does is open the file in question and then pass the file descriptor as the standard output of the script. What you need to do is make sure output is flushed from your script more frequently than you currently are.

In Perl for example, this could be accomplished by setting:

$| = 1;

See perlvar for more information on this.

View content of H2 or HSQLDB in-memory database

I've a problem with H2 version 1.4.190 remote connection to inMemory (as well as in file) with Connection is broken: "unexpected status 16843008" until do not downgrade to 1.3.176. See Grails accessing H2 TCP server hangs

Notification bar icon turns white in Android 5 Lollipop

You Need to import the single color transparent PNG image. So You can set the Icon color of the small icon. Otherwise it will be shown white in some devices like MOTO

Xcode couldn't find any provisioning profiles matching

I am now able to successfully build. Not sure exactly which step "fixed" things, but this was the sequence:

  • Tried automatic signing again. No go, so reverted to manual.
  • After reverting, I had no Eligible Profiles, all were ineligible. Strange.
  • I created a new certificate and profile, imported both. This too was "ineligible".
  • Removed the iOS platform and re-added it. I had tried this previously without luck.
  • After doing this, Xcode on its own defaulted to automatic signing. And this worked! Success!

While I am not sure exactly which parts were necessary, I think the previous certificates were the problem. I hate Xcode :(

Thanks for help.

Commit only part of a file in Git

Tried out git add -p filename.x, but on a mac, I found gitx (http://gitx.frim.nl/ or https://github.com/pieter/gitx) to be much easier to commit exactly the lines I wanted to.

Error to run Android Studio

First check if the Java JDK is installed correctly:

dpkg --list | grep -i jdk

If not, install the JDK:

  1. Download the latest version of the JDK from Oracle: http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

  2. Extract it to the appropriate location in your machine. Get the extract location:

    vi ~/.bashrc or vi ~./ bash_profile

    JAVA_HOME=/home/user/installs/jdk1.7.0_40
    PATH=$JAVA_HOME/bin
    

    source ~/.bashrc or source ~/.bash_profile

  3. After the installation you can check it:

    java -version
    which java
    

    If all things are correct then the right the answer should be something like this:

    java version "1.7.0_40"
    Java(TM) SE Runtime Environment (build 1.7.0_40-b43)
    Java HotSpot(TM) 64-Bit Server VM (build 24.0-b56, mixed mode)

  4. Append the following statement to studio.sh the file in android-studio/bin directory:

    JAVA_HOME=/home/user/installs/jdk1.7.0_40
    

Finally start your Android Studio with the following command:

./studio.sh 

List of tables, db schema, dump etc using the Python sqlite3 API

After a lot of fiddling I found a better answer at sqlite docs for listing the metadata for the table, even attached databases.

meta = cursor.execute("PRAGMA table_info('Job')")
for r in meta:
    print r

The key information is to prefix table_info, not my_table with the attachment handle name.

C read file line by line

Provide a portable and generic getdelim function, test passed via msvc, clang, gcc.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

ssize_t
portabl_getdelim(char ** restrict linep,
                 size_t * restrict linecapp,
                 int delimiter,
                 FILE * restrict stream) {
    if (0 == *linep) {
        *linecapp = 8;
        *linep = malloc(*linecapp);
        if (0 == *linep) {
            return EOF;
        }
    }

    ssize_t linelen = 0;
    int c = 0;
    char *p = *linep;

    while (EOF != (c = fgetc(stream))) {
        if (linelen == (ssize_t) *linecapp - 1) {
            *linecapp <<= 1;
            char *p1 = realloc(*linep, *linecapp);
            if (0 == *p1) {
                return EOF;
            }
            p = p1 + linelen;
        }
        *p++ = c;
        linelen++;

        if (delimiter == c) {
            *p = 0;
            return linelen;
        }
    }
    return EOF == c ? EOF : linelen;
}


int
main(int argc, char **argv) {
    const char *filename = "/a/b/c.c";
    FILE *file = fopen(filename, "r");
    if (!file) {
        perror(filename);
        return 1;
    }

    char *line = 0;
    size_t linecap = 0;
    ssize_t linelen;

    while (0 < (linelen = portabl_getdelim(&line, &linecap, '\n', file))) {
        fwrite(line, linelen, 1, stdout);
    }
    if (line) {
        free(line);
    }
    fclose(file);   

    return 0;
}

Restore the mysql database from .frm files

I made use of mysqlfrm which is a great tool which generates table creation sql code from .frm files. I was getting this nasty table not found error although tables were being listed. Thus I used this tool to regenerate the tables. In ubuntu you need to install this as:

sudo apt install mysql-utilities

then,

mysqlfrm --diagnostic mysql/db_name/ > db_name.sql

Create a new database and then you can use,

mysql -u username -p < db_name.sql

However, this will give you the tables but not the data. In my case this was enough.

Viewing full output of PS command

I found this answer which is what nailed it for me as none of the above answers worked

https://unix.stackexchange.com/questions/91561/ps-full-command-is-too-long

Basically, the kernel is limiting my cmd line.

How can I get the current array index in a foreach loop?

You could get the first element in the array_keys() function as well. Or array_search() the keys for the "index" of a key. If you are inside a foreach loop, the simple incrementing counter (suggested by kip or cletus) is probably your most efficient method though.

<?php
   $array = array('test', '1', '2');
   $keys = array_keys($array);
   var_dump($keys[0]); // int(0)

   $array = array('test'=>'something', 'test2'=>'something else');
   $keys = array_keys($array);

   var_dump(array_search("test2", $keys)); // int(1)     
   var_dump(array_search("test3", $keys)); // bool(false)

How to dynamically insert a <script> tag via jQuery after page load?

A simpler way is:

$('head').append('<script type="text/javascript" src="your.js"></script>');

You can also use this form to load css.

HTML5 Form Input Pattern Currency Format

How about :

^\d+\.\d{2}$

This matches one or more digits, a dot and 2 digits after the dot.

To match also comma as thousands delimiter :

^\d+(?:,\d{3})*\.\d{2}$

Postgresql Select rows where column = array

In my case, I needed to work with a column that has the data, so using IN() didn't work. Thanks to @Quassnoi for his examples. Here is my solution:

SELECT column(s) FROM table WHERE expr|column = ANY(STRING_TO_ARRAY(column,',')::INT[])

I spent almost 6 hours before I stumble on the post.

Access And/Or exclusions

Seeing that it appears you are running using the SQL syntax, try with the correct wild card.

SELECT * FROM someTable WHERE (someTable.Field NOT LIKE '%RISK%') AND (someTable.Field NOT LIKE '%Blah%') AND someTable.SomeOtherField <> 4; 

How to fix "Root element is missing." when doing a Visual Studio (VS) Build?

In my case I upgraded to VS2017 and wanted to build all projects with MSBuild 4 with my build script (which had been using MSBuild 3.5 when we were using VS2015). That MSBuild upgrade appeared fine for the Windows desktop applications but the ones for Windows CE with compact framework would give me this confusing error. Reverting to MSBuild 3.5 for Windows CE projects fixed the issue for me.

I did have the BOM in .csproj files by the way and removed them for all projects in a solution that would not build but that did not help.

C error: Expected expression before int

This is actually a fairly interesting question. It's not as simple as it looks at first. For reference, I'm going to be basing this off of the latest C11 language grammar defined in N1570

I guess the counter-intuitive part of the question is: if this is correct C:

if (a == 1) {
  int b = 10;
}

then why is this not also correct C?

if (a == 1)
  int b = 10;

I mean, a one-line conditional if statement should be fine either with or without braces, right?

The answer lies in the grammar of the if statement, as defined by the C standard. The relevant parts of the grammar I've quoted below. Succinctly: the int b = 10 line is a declaration, not a statement, and the grammar for the if statement requires a statement after the conditional that it's testing. But if you enclose the declaration in braces, it becomes a statement and everything's well.

And just for the sake of answering the question completely -- this has nothing to do with scope. The b variable that exists inside that scope will be inaccessible from outside of it, but the program is still syntactically correct. Strictly speaking, the compiler shouldn't throw an error on it. Of course, you should be building with -Wall -Werror anyways ;-)

(6.7) declaration:
            declaration-speci?ers init-declarator-listopt ;
            static_assert-declaration

(6.7) init-declarator-list:
            init-declarator
            init-declarator-list , init-declarator

(6.7) init-declarator:
            declarator
            declarator = initializer

(6.8) statement:
            labeled-statement
            compound-statement
            expression-statement
            selection-statement
            iteration-statement
            jump-statement

(6.8.2) compound-statement:
            { block-item-listopt }

(6.8.4) selection-statement:
            if ( expression ) statement
            if ( expression ) statement else statement
            switch ( expression ) statement

What is the purpose of Looper and how to use it?

Life span of java Thread is over after completion of run() method. Same thread can't be started again.

Looper transforms normal Thread into a message loop. Key methods of Looper are :

void prepare ()

Initialize the current thread as a looper. This gives you a chance to create handlers that then reference this looper, before actually starting the loop. Be sure to call loop() after calling this method, and end it by calling quit().

void loop ()

Run the message queue in this thread. Be sure to call quit() to end the loop.

void quit()

Quits the looper.

Causes the loop() method to terminate without processing any more messages in the message queue.

This mindorks article by Janishar explains the core concepts in nice way.

enter image description here

Looper is associated with a Thread. If you need Looper on UI thread, Looper.getMainLooper() will return associated thread.

You need Looper to be associated with a Handler.

Looper, Handler, and HandlerThread are the Android’s way of solving the problems of asynchronous programming.

Once you have Handler, you can call below APIs.

post (Runnable r)

Causes the Runnable r to be added to the message queue. The runnable will be run on the thread to which this handler is attached.

boolean sendMessage (Message msg)

Pushes a message onto the end of the message queue after all pending messages before the current time. It will be received in handleMessage(Message), in the thread attached to this handler.

HandlerThread is handy class for starting a new thread that has a looper. The looper can then be used to create handler classes

In some scenarios, you can't run Runnable tasks on UI Thread. e.g. Network operations : Send message on a socket, open an URL and get content by reading InputStream

In these cases, HandlerThread is useful. You can get Looper object from HandlerThread and create a Handler on HandlerThread instead of main thread.

The HandlerThread code will be like this:

@Override
public void run() {
    mTid = Process.myTid();
    Looper.prepare();
    synchronized (this) {
        mLooper = Looper.myLooper();
        notifyAll();
    }
    Process.setThreadPriority(mPriority);
    onLooperPrepared();
    Looper.loop();
    mTid = -1;
}

Refer to below post for example code:

Android: Toast in a thread

Java ArrayList how to add elements at the beginning

you can use this code

private List myList = new ArrayList();
private void addItemToList(Object obj){
    if(myList.size()<10){
      myList.add(0,obj);
    }else{
      myList.add(0,obj);
      myList.remove(10);
    }
}

ESLint not working in VS Code?

Restarting VSCode worked for me.

How to list the contents of a package using YUM?

$ yum install -y yum-utils

$ repoquery -l packagename

How to determine the version of the C++ standard used by the compiler?

Please, run the following code to check the version.

#include<iostream>

int main() {
    if (__cplusplus == 201703L) std::cout << "C++17\n";
    else if (__cplusplus == 201402L) std::cout << "C++14\n";
    else if (__cplusplus == 201103L) std::cout << "C++11\n";
    else if (__cplusplus == 199711L) std::cout << "C++98\n";
    else std::cout << "pre-standard C++\n";
}

Finding blocking/locking queries in MS SQL (mssql)

I found this query which helped me find my locked table and query causing the issue.

SELECT  L.request_session_id AS SPID, 
        DB_NAME(L.resource_database_id) AS DatabaseName,
        O.Name AS LockedObjectName, 
        P.object_id AS LockedObjectId, 
        L.resource_type AS LockedResource, 
        L.request_mode AS LockType,
        ST.text AS SqlStatementText,        
        ES.login_name AS LoginName,
        ES.host_name AS HostName,
        TST.is_user_transaction as IsUserTransaction,
        AT.name as TransactionName,
        CN.auth_scheme as AuthenticationMethod
FROM    sys.dm_tran_locks L
        JOIN sys.partitions P ON P.hobt_id = L.resource_associated_entity_id
        JOIN sys.objects O ON O.object_id = P.object_id
        JOIN sys.dm_exec_sessions ES ON ES.session_id = L.request_session_id
        JOIN sys.dm_tran_session_transactions TST ON ES.session_id = TST.session_id
        JOIN sys.dm_tran_active_transactions AT ON TST.transaction_id = AT.transaction_id
        JOIN sys.dm_exec_connections CN ON CN.session_id = ES.session_id
        CROSS APPLY sys.dm_exec_sql_text(CN.most_recent_sql_handle) AS ST
WHERE   resource_database_id = db_id()
ORDER BY L.request_session_id

pyplot scatter plot marker size

You can use markersize to specify the size of the circle in plot method

import numpy as np
import matplotlib.pyplot as plt

x1 = np.random.randn(20)
x2 = np.random.randn(20)
plt.figure(1)
# you can specify the marker size two ways directly:
plt.plot(x1, 'bo', markersize=20)  # blue circle with size 10 
plt.plot(x2, 'ro', ms=10,)  # ms is just an alias for markersize
plt.show()

From here

enter image description here

Viewing PDF in Windows forms using C#

i think the easiest way is to use the Adobe PDF reader COM Component

  1. right click on your toolbox & select "Choose Items"
  2. Select the "COM Components" tab
  3. Select "Adobe PDF Reader" then click ok
  4. Drag & Drop the control on your form & modify the "src" Property to the PDF files you want to read

i hope this helps

Equivalent of Super Keyword in C#

C# equivalent of your code is

  class Imagedata : PDFStreamEngine
  {
     // C# uses "base" keyword whenever Java uses "super" 
     // so instead of super(...) in Java we should call its C# equivalent (base):
     public Imagedata()
       : base(ResourceLoader.loadProperties("org/apache/pdfbox/resources/PDFTextStripper.properties", true)) 
     { }

     // Java methods are virtual by default, when C# methods aren't.
     // So we should be sure that processOperator method in base class 
     // (that is PDFStreamEngine)
     // declared as "virtual"
     protected override void processOperator(PDFOperator operations, List arguments)
     {
        base.processOperator(operations, arguments);
     }
  }

How to install SQL Server Management Studio 2012 (SSMS) Express?

When I installed: ENU\x64\SQLManagementStudio_x64_ENU.exe

I had to choose the following options to get the management Tools:

  1. "New SQL Server stand-alone installation or add features to an existing installation."
  2. "Add features to an existing instance of SQL Server 2012"
  3. Accept the license.
  4. Check the box for "Management Tools - Basic".
  5. Wait a long time as it installs.

When I was done I had an option "SQL Server Management Studio" within my Start Menu.

Searching for "Management" pulled it up faster within the Start Menu.

How to load a resource bundle from a file resource in Java?

From the JavaDocs for ResourceBundle.getBundle(String baseName):

baseName - the base name of the resource bundle, a fully qualified class name

What this means in plain English is that the resource bundle must be on the classpath and that baseName should be the package containing the bundle plus the bundle name, mybundle in your case.

Leave off the extension and any locale that forms part of the bundle name, the JVM will sort that for you according to default locale - see the docs on java.util.ResourceBundle for more info.

How to refresh table contents in div using jquery/ajax

You can load HTML page partial, in your case is everything inside div#mytable.

setTimeout(function(){
   $( "#mytable" ).load( "your-current-page.html #mytable" );
}, 2000); //refresh every 2 seconds

more information read this http://api.jquery.com/load/

Update Code (if you don't want it auto-refresh)

<button id="refresh-btn">Refresh Table</button>

<script>
$(document).ready(function() {

   function RefreshTable() {
       $( "#mytable" ).load( "your-current-page.html #mytable" );
   }

   $("#refresh-btn").on("click", RefreshTable);

   // OR CAN THIS WAY
   //
   // $("#refresh-btn").on("click", function() {
   //    $( "#mytable" ).load( "your-current-page.html #mytable" );
   // });


});
</script>

How to obtain the absolute path of a file via Shell (BASH/ZSH/SH)?

I use the single line

(cd ${FILENAME%/*}; pwd)

However, this can only be used when $FILENAME has a leading path of any kind (relative or absolute) that actually exists. If there is no leading path at all, then the answer is simply $PWD. If the leading path does not exist, then the answer may be indeterminate, otherwise and the answer is simply ${FILENAME%/*} if the path is absolute.

Putting this all together I would suggest using the following function

function abspath() {
  # argument 1: file pathname (relative or absolute)
  # returns: file pathname (absolute)
  if [ "$1" == "${1##*/}" ]; then # no path at all
    echo "$PWD"
  elif [ "${1:0:1}" == "/" -a "${1/../}" == "$1" ]; then # strictly absolute path
    echo "${1%/*}"
  else # relative path (may fail if a needed folder is non-existent)
    echo "$(cd ${1%/*}; pwd)"
  fi
}

Note also that this only work in bash and compatible shells. I don't believe the substitutions work in the simple shell sh.

How to duplicate a whole line in Vim?

For those starting to learn vi, here is a good introduction to vi by listing side by side vi commands to typical Windows GUI Editor cursor movement and shortcut keys. It lists all the basic commands including yy (copy line) and p (paste after) or P(paste before).

vi (Vim) for Windows Users

Difference between int and double

int is a binary representation of a whole number, double is a double-precision floating point number.

how to get list of port which are in use on the server

If you mean what ports are listening, you can open a command prompt and write:

netstat

You can write:

netstat /?

for an explanation of all options.

How return error message in spring mvc @Controller

Here is an alternative. Create a generic exception that takes a status code and a message. Then create an exception handler. Use the exception handler to retrieve the information out of the exception and return to the caller of the service.

http://javaninja.net/2016/06/throwing-exceptions-messages-spring-mvc-controller/

public class ResourceException extends RuntimeException {

    private HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;

    public HttpStatus getHttpStatus() {
        return httpStatus;
    }

    /**
     * Constructs a new runtime exception with the specified detail message.
     * The cause is not initialized, and may subsequently be initialized by a
     * call to {@link #initCause}.
     * @param message the detail message. The detail message is saved for later retrieval by the {@link #getMessage()}
     *                method.
     */
    public ResourceException(HttpStatus httpStatus, String message) {
        super(message);
        this.httpStatus = httpStatus;
    }
}

Then use an exception handler to retrieve the information and return it to the service caller.

@ControllerAdvice
public class ExceptionHandlerAdvice { 

    @ExceptionHandler(ResourceException.class)
    public ResponseEntity handleException(ResourceException e) {
        // log exception 
        return ResponseEntity.status(e.getHttpStatus()).body(e.getMessage());
    }         
} 

Then create an exception when you need to.

throw new ResourceException(HttpStatus.NOT_FOUND, "We were unable to find the specified resource.");

Pagination response payload from a RESTful API

As someone who has written several libraries for consuming REST services, let me give you the client perspective on why I think wrapping the result in metadata is the way to go:

  • Without the total count, how can the client know that it has not yet received everything there is and should continue paging through the result set? In a UI that didn't perform look ahead to the next page, in the worst case this might be represented as a Next/More link that didn't actually fetch any more data.
  • Including metadata in the response allows the client to track less state. Now I don't have to match up my REST request with the response, as the response contains the metadata necessary to reconstruct the request state (in this case the cursor into the dataset).
  • If the state is part of the response, I can perform multiple requests into the same dataset simultaneously, and I can handle the requests in any order they happen to arrive in which is not necessarily the order I made the requests in.

And a suggestion: Like the Twitter API, you should replace the page_number with a straight index/cursor. The reason is, the API allows the client to set the page size per-request. Is the returned page_number the number of pages the client has requested so far, or the number of the page given the last used page_size (almost certainly the later, but why not avoid such ambiguity altogether)?

PHP Composer behind http proxy

If you are using Windows, you should set the same environment variables, but Windows style:

set http_proxy=<your_http_proxy:proxy_port>
set https_proxy=<your_https_proxy:proxy_port>

That will work for your current cmd.exe. If you want to do this more permanent, y suggest you to use environment variables on your system.

Auto Increment after delete in MySQL

Its definitely not recommendable. If you have a large database with multiple tables, you may probably have saved a userid as id in table 2. if you rearrange table 1 then probably the intended userid will not end up being the intended table 2 id.

Bizarre Error in Chrome Developer Console - Failed to load resource: net::ERR_CACHE_MISS

On Chrome's latest update (38.0.2125.104 m at the moment), Google added the option to know whether the files loaded to the website were newly downloaded from the server - or read from the local cache.

When an error like yours "hits" the console - you know the files were just downloaded from the server and not read from the local cache. You can recreate this error by clicking Ctrl + F5 (refresh and erase cache).

It fits your description where Firebug (or equivalents) doesn't fire any errors to the console - whilst Chrome does.

So, the bottom line is - your're just fine and you can ignore this error - it's merely an indicator.

How to get the date from jQuery UI datepicker

NamingException's answer worked for me. Except I used

var date = $("#date").dtpicker({ dateFormat: 'dd,MM,yyyy' }).val()

datepicker didn't work but dtpicker did.

Android Studio Rendering Problems : The following classes could not be found

I had to change my values/styles.xml to

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">

Before that change, it was without 'Base'.

(IntelliJ IDEA 2017.2.4)

Android - Handle "Enter" in an EditText

working perfectly

public class MainActivity extends AppCompatActivity {  
TextView t;
Button b;
EditText e;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    b = (Button) findViewById(R.id.b);
    e = (EditText) findViewById(R.id.e);

    e.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            if (before == 0 && count == 1 && s.charAt(start) == '\n') {

                b.performClick();
                e.getText().replace(start, start + 1, ""); //remove the <enter>
            }

        }
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
        @Override
        public void afterTextChanged(Editable s) {}
    });

    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            b.setText("ok");

        }
    });
}

}

working perfectly

java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation

in the manifest file set second activity parentActivityName as first activity and remove the screenOrientation parameter to the second activity. it means your first activity is the parent and decide to an orientation of your second activity.

<activity
        android:name=".view.FirstActiviy"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme" />

<activity
        android:name=".view.SecondActivity"
        android:parentActivityName=".view.FirstActiviy"
        android:theme="@style/AppTheme.Transparent" />

./configure : /bin/sh^M : bad interpreter

Your configure file contains CRLF line endings (windows style) instead of simple LF line endings (unix style). Did you transfer it using FTP mode ASCII from Windows?

You can use

dos2unix configure

to fix this, or open it in vi and use :%s/^M//g; to substitute them all (use CTRL+V, CTRL+M to get the ^M)

How to read a text file into a list or an array with Python

This question is asking how to read the comma-separated value contents from a file into an iterable list:

0,0,200,0,53,1,0,255,...,0.

The easiest way to do this is with the csv module as follows:

import csv
with open('filename.dat', newline='') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=',')

Now, you can easily iterate over spamreader like this:

for row in spamreader:
    print(', '.join(row))

See documentation for more examples.

Unable to start Service Intent

I've found the same problem. I lost almost a day trying to start a service from OnClickListener method - outside the onCreate and after 1 day, I still failed!!!! Very frustrating! I was looking at the sample example RemoteServiceController. Theirs works, but my implementation does not work!

The only way that was working for me, was from inside onCreate method. None of the other variants worked and believe me I've tried them all.

Conclusion:

  • If you put your service class in different package than the mainActivity, I'll get all kind of errors
  • Also the one "/" couldn't find path to the service, tried starting with Intent(package,className) and nothing , also other type of Intent starting

  • I moved the service class in the same package of the activity Final form that works

  • Hopefully this helps someone by defining the listerners onClick inside the onCreate method like this:

    public void onCreate() {
    //some code......
        Button btnStartSrv  = (Button)findViewById(R.id.btnStartService);
        Button btnStopSrv  = (Button)findViewById(R.id.btnStopService);
    
        btnStartSrv.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                startService(new Intent("RM_SRV_AIDL"));
            }
        });
    
        btnStopSrv.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                stopService(new Intent("RM_SRV_AIDL"));
            }
        });
    
    } // end onCreate
    

Also very important for the Manifest file, be sure that service is child of application:

<application ... >
    <activity ... >
     ...
    </activity>
    <service
        android:name="com.mainActivity.MyRemoteGPSService"
        android:label="GPSService"
        android:process=":remote">

        <intent-filter>
             <action android:name="RM_SRV_AIDL" />
        </intent-filter>
    </service>
</application>

Percentage calculation

(current / maximum) * 100. In your case, (2 / 10) * 100.

Display current path in terminal only

If you just want to get the information of current directory, you can type:

pwd

and you don't need to use the Nautilus, or you can use a teamviewer software to remote connect to the computer, you can get everything you want.

Why do we need C Unions?

Unions are used when you want to model structs defined by hardware, devices or network protocols, or when you're creating a large number of objects and want to save space. You really don't need them 95% of the time though, stick with easy-to-debug code.

Comparing arrays for equality in C++

Since nobody mentioned it yet, you can compare arrays with the std::equal algorithm:

int iar1[] = {1,2,3,4,5};
int iar2[] = {1,2,3,4,5};

if (std::equal(std::begin(iar1), std::end(iar1), std::begin(iar2)))
    cout << "Arrays are equal.";
else
    cout << "Arrays are not equal.";

You need to include <algorithm> and <iterator>. If you don't use C++11 yet, you can write:

if (std::equal(iar1, iar1 + sizeof iar1 / sizeof *iar1, iar2))

SQL Query - Change date format in query to DD/MM/YYYY

SELECT CONVERT(varchar(11),Getdate(),105)

How to return multiple rows from the stored procedure? (Oracle PL/SQL)

create procedure <procedure_name>(p_cur out sys_refcursor) as begin open p_cur for select * from <table_name> end;

Difference between ${} and $() in Bash

  1. $() means: "first evaluate this, and then evaluate the rest of the line".

    Ex :

    echo $(pwd)/myFile.txt
    

    will be interpreted as

    echo /my/path/myFile.txt
    

    On the other hand ${} expands a variable.

    Ex:

    MY_VAR=toto
    echo ${MY_VAR}/myFile.txt
    

    will be interpreted as

    echo toto/myFile.txt
    
  2. Why can't I use it as bash$ while ((i=0;i<10;i++)); do echo $i; done

    I'm afraid the answer is just that the bash syntax for while just isn't the same as the syntax for for.

Jquery DatePicker Set default date

To create the datepicker and set the date.

$('.next_date').datepicker({ dateFormat: 'dd-mm-yy'}).datepicker("setDate", new Date());

How do I declare and initialize an array in Java?

With local variable type inference you only have to specify the type once:

var values = new int[] { 1, 2, 3 };

Or

int[] values = { 1, 2, 3 }

Remote origin already exists on 'git push' to a new repository

You are getting this error because "origin" is not available. "origin" is a convention not part of the command. "origin" is the local name of the remote repository.

For example you could also write:

git remote add myorigin [email protected]:myname/oldrep.git  
git remote add testtest [email protected]:myname/oldrep.git

See the manual:

http://www.kernel.org/pub/software/scm/git/docs/git-remote.html

To remove a remote repository you enter:

git remote rm origin

Again "origin" is the name of the remote repository if you want to remove the "upstream" remote:

git remote rm upstream

word-wrap break-word does not work in this example

Use this code (taken from css-tricks) that will work on all browser

overflow-wrap: break-word;
word-wrap: break-word;

-ms-word-break: break-all;
/* This is the dangerous one in WebKit, as it breaks things wherever */
word-break: break-all;
/* Instead use this non-standard one: */
word-break: break-word;

/* Adds a hyphen where the word breaks, if supported (No Blink) */
-ms-hyphens: auto;
-moz-hyphens: auto;
-webkit-hyphens: auto;
hyphens: auto;

Convert this string to datetime

Use DateTime::createFromFormat

$date = date_create_from_format('d/m/Y:H:i:s', $s);
$date->getTimestamp();

round a single column in pandas

Use the pandas.DataFrame.round() method like this:

df = df.round({'value1': 0})

Any columns not included will be left as is.

PowerShell script to check the status of a URL

$request = [System.Net.WebRequest]::Create('http://stackoverflow.com/questions/20259251/powershell-script-to-check-the-status-of-a-url')

$response = $request.GetResponse()

$response.StatusCode

$response.Close()

How to get JavaScript caller function line number? How to get JavaScript caller source URL?

If you would like to know the line number for debugging purposes, or only during development (For a reason or another), you could use Firebug (a Firefox extension) and throw an exception.

Edit:

If you really need to do that in production for some reason, you can pre-process your javascript files in order for each function to keep track of the line it is on. I know some frameworks that find the coverage of code use this (such as JSCoverage).

For example, let's say your original call is:

function x() {
  1 + 1;
  2 + 2;
  y();
}

You could write a preprocessor to make it into:

function x() {
  var me = arguments.callee;
  me.line = 1;
  1 + 1;
  me.line = 2;
  2 + 2;
  me.line = 3;
  y();
}

Then in y(), you could use arguments.callee.caller.line to know the line from which it was called, such as:

function y() {
  alert(arguments.callee.caller.line);
}

Fastest way(s) to move the cursor on a terminal command line?

If you want to move forward a certain number of words, hit M-<n> (M- is for Meta and its usually the escape key) then hit a number. This sends a repeat argument to readline, so you can repeat whatever command you want - if you want to go forward then hit M-<n> M-f and the cursor will move forward <n> number of words.

E.g.

 $|echo "two three four five six seven"
 $ M-4
 (arg: 4) echo "two three four five six seven"
 $ M-f
 $ echo "two three four| five six seven"

So for your example from the cursor at the beginning of the line you would hit, M-26 M-f and your cursor would be at --option25| -or- from the end of the line M-26 M-b would put your cursor at --|option25

php - get numeric index of associative array

While Fosco's answer is not wrong there is a case to be considered with this one: mixed arrays. Imagine I have an array like this:

$a = array(
  "nice",
  "car" => "fast",
  "none"
);

Now, PHP allows this kind of syntax but it has one problem: if I run Fosco's code I get 0 which is wrong for me, but why this happens?
Because when doing comparisons between strings and integers PHP converts strings to integers (and this is kinda stupid in my opinion), so when array_search() searches for the index it stops at the first one because apparently ("car" == 0) is true.
Setting array_search() to strict mode won't solve the problem because then array_search("0", array_keys($a)) would return false even if an element with index 0 exists.
So my solution just converts all indexes from array_keys() to strings and then compares them correctly:

echo array_search("car", array_map("strval", array_keys($a)));

Prints 1, which is correct.

EDIT:
As Shaun pointed out in the comment below, the same thing applies to the index value, if you happen to search for an int index like this:

$a = array(
  "foo" => "bar",
  "nice",
  "car" => "fast",
  "none"
);
$ind = 0;
echo array_search($ind, array_map("strval", array_keys($a)));

You will always get 0, which is wrong, so the solution would be to cast the index (if you use a variable) to a string like this:

$ind = 0;
echo array_search((string)$ind, array_map("strval", array_keys($a)));

What is the best way to convert an array to a hash in Ruby

You can also simply convert a 2D array into hash using:

1.9.3p362 :005 > a= [[1,2],[3,4]]

 => [[1, 2], [3, 4]]

1.9.3p362 :006 > h = Hash[a]

 => {1=>2, 3=>4} 

How to calculate the sentence similarity using word2vec model of gensim with python

I am using the following method and it works well. You first need to run a POSTagger and then filter your sentence to get rid of the stop words (determinants, conjunctions, ...). I recommend TextBlob APTagger. Then you build a word2vec by taking the mean of each word vector in the sentence. The n_similarity method in Gemsim word2vec does exactly that by allowing to pass two sets of words to compare.

Converting HTML to PDF using PHP?

If you wish to create a pdf from php, pdflib will help you (as some others suggested).

Else, if you want to convert an HTML page to PDF via PHP, you'll find a little trouble outta here.. For 3 years I've been trying to do it as best as I can.

So, the options I know are:

DOMPDF : php class that wraps the html and builds the pdf. Works good, customizable (if you know php), based on pdflib, if I remember right it takes even some CSS. Bad news: slow when the html is big or complex.

HTML2PS: same as DOMPDF, but this one converts first to a .ps (ghostscript) file, then, to whatever format you need (pdf, jpg, png). For me is little better than dompdf, but has the same speed problem.. but, better compatibility with CSS.

Those two are php classes, but if you can install some software on the server, and access it throught passthru() or system(), give a look to these too:

wkhtmltopdf: based on webkit (safari's wrapper), is really fast and powerful.. seems like this is the best one (atm) for converting html pages to pdf on the fly; taking only 2 seconds for a 3 page xHTML document with CSS2. It is a recent project, anyway, the google.code page is often updated.

htmldoc : This one is a tank, it never really stops/crashes.. the project looks dead since 2007, but anyway if you don't need CSS compatibility this can be nice for you.

How can I get the source directory of a Bash script from within the script itself?

$_ is worth mentioning as an alternative to $0. If you're running a script from Bash, the accepted answer can be shortened to:

DIR="$( dirname "$_" )"

Note that this has to be the first statement in your script.

ASP.NET Identity - HttpContext has no extension method for GetOwinContext

ARGH!

I found it... I didn't have an extra package, called Microsoft.Owin.Host.SystemWeb

Once i searched and installed this, it worked.

Now - i am not sure if i just missed everything, though found NO reference to such a library or package when going through various tutorials. It also didn't get installed when i installed all this Identity framework... Not sure if it were just me..

EDIT Although it's in the Microsoft.Owin.Host.SystemWeb assembly it is an extension method in the System.Web namespace, so you need to have the reference to the former, and be using the latter.