Programs & Examples On #Absolute path

global address for a file, independent from the working directory of the calling process

Resolve absolute path from relative path and/or file name

Files See all other answers

Directories

With .. being your relative path, and assuming you are currently in D:\Projects\EditorProject:

cd .. & cd & cd EditorProject (the relative path)

returns absolute path e.g.

D:\Projects

Get filename and path from URI from mediastore

try this get image file path from Uri

public void getImageFilePath(Context context, Uri uri) {

    Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
    cursor.moveToFirst();
    String image_id = cursor.getString(0);
    image_id = image_id.substring(image_id.lastIndexOf(":") + 1);
    cursor.close();
    cursor = context.getContentResolver().query(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, MediaStore.Images.Media._ID + " = ? ", new String[]{image_id}, null);
    cursor.moveToFirst();
    String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
    cursor.close();
    upLoadImageOrLogo(path);
}

How to get the file-path of the currently executing javascript code

Regardless of whether its a script, a html file (for a frame, for example), css file, image, whatever, if you dont specify a server/domain the path of the html doc will be the default, so you could do, for example,

<script type=text/javascript src='/dir/jsfile.js'></script>

or

<script type=text/javascript src='../../scripts/jsfile.js'></script>

If you don't provide the server/domain, the path will be relative to either the path of the page or script of the main document's path

How can I generate a list of files with their absolute path in Linux?

If you don't have symbolic links, you could try

tree -iFL 1 [DIR]

-i makes tree print filenames in each line, without the tree structure.

-f makes tree print the full path of each file.

-L 1 avoids tree from recursion.

Relative path to absolute path in C#?

It`s best way for convert the Relative path to the absolute path!

string absolutePath = System.IO.Path.GetFullPath(relativePath);

Server Document Root Path in PHP

$files = glob($_SERVER["DOCUMENT_ROOT"]."/myFolder/*");

Relative instead of Absolute paths in Excel VBA

Just to clarify what yalestar said, this will give you the relative path:

Workbooks.Open FileName:= ThisWorkbook.Path & "\TRICATEndurance Summary.html"

How to use relative/absolute paths in css URLs?

Personally, I would fix this in the .htaccess file. You should have access to that.

Define your CSS URL as such:

url(/image_dir/image.png);

In your .htacess file, put:

Options +FollowSymLinks
RewriteEngine On
RewriteRule ^image_dir/(.*) subdir/images/$1

or

RewriteRule ^image_dir/(.*) images/$1

depending on the site.

PHP absolute path to root

You can access the $_SERVER['DOCUMENT_ROOT'] variable :

<?php 
   $path = $_SERVER['DOCUMENT_ROOT'];
   $path .= "/subdir1/yourdocument.txt";
?>

src absolute path problem

Use forward slashes. See explanation here

Do I need to pass the full path of a file in another directory to open()?

Yes, you need the full path.

log = open(os.path.join(root, f), 'r')

Is the quick fix. As the comment pointed out, os.walk decends into subdirs so you do need to use the current directory root rather than indir as the base for the path join.

ASP.NET MVC - Find Absolute Path to the App_Data folder from Controller

The most correct way is to use HttpContext.Current.Server.MapPath("~/App_Data");. This means you can only retrieve the path from a method where the HttpContext is available. It makes sense: the App_Data directory is a web project folder structure [1].

If you need the path to ~/App_Data from a class where you don't have access to the HttpContext you can always inject a provider interface using your IoC container:

public interface IAppDataPathProvider
{
    string GetAppDataPath();
}

Implement it using your HttpApplication:

public class AppDataPathProvider : IAppDataPathProvider
{
    public string GetAppDataPath()
    {
        return MyHttpApplication.GetAppDataPath();
    }
}

Where MyHttpApplication.GetAppDataPath looks like:

public class MyHttpApplication : HttpApplication
{
    // of course you can fetch&store the value at Application_Start
    public static string GetAppDataPath()
    {
        return HttpContext.Current.Server.MapPath("~/App_Data");
    }
}

[1] http://msdn.microsoft.com/en-us/library/ex526337%28v=vs.100%29.aspx

How to get an absolute file path in Python

You could use the new Python 3.4 library pathlib. (You can also get it for Python 2.6 or 2.7 using pip install pathlib.) The authors wrote: "The aim of this library is to provide a simple hierarchy of classes to handle filesystem paths and the common operations users do over them."

To get an absolute path in Windows:

>>> from pathlib import Path
>>> p = Path("pythonw.exe").resolve()
>>> p
WindowsPath('C:/Python27/pythonw.exe')
>>> str(p)
'C:\\Python27\\pythonw.exe'

Or on UNIX:

>>> from pathlib import Path
>>> p = Path("python3.4").resolve()
>>> p
PosixPath('/opt/python3/bin/python3.4')
>>> str(p)
'/opt/python3/bin/python3.4'

Docs are here: https://docs.python.org/3/library/pathlib.html

Convert absolute path into relative path given a current directory using Bash

Yet another solution, pure bash + GNU readlink for easy use in following context:

ln -s "$(relpath "$A" "$B")" "$B"

Edit: Make sure that "$B" is either not existing or no softlink in that case, else relpath follows this link which is not what you want!

This works in nearly all current Linux. If readlink -m does not work at your side, try readlink -f instead. See also https://gist.github.com/hilbix/1ec361d00a8178ae8ea0 for possible updates:

: relpath A B
# Calculate relative path from A to B, returns true on success
# Example: ln -s "$(relpath "$A" "$B")" "$B"
relpath()
{
local X Y A
# We can create dangling softlinks
X="$(readlink -m -- "$1")" || return
Y="$(readlink -m -- "$2")" || return
X="${X%/}/"
A=""
while   Y="${Y%/*}"
        [ ".${X#"$Y"/}" = ".$X" ]
do
        A="../$A"
done
X="$A${X#"$Y"/}"
X="${X%/}"
echo "${X:-.}"
}

Notes:

  • Care was taken that it is safe against unwanted shell meta character expansion, in case filenames contain * or ?.
  • The output is meant to be usable as the first argument to ln -s:
    • relpath / / gives . and not the empty string
    • relpath a a gives a, even if a happens to be a directory
  • Most common cases were tested to give reasonable results, too.
  • This solution uses string prefix matching, hence readlink is required to canonicalize paths.
  • Thanks to readlink -m it works for not yet existing paths, too.

On old systems, where readlink -m is not available, readlink -f fails if the file does not exist. So you probably need some workaround like this (untested!):

readlink_missing()
{
readlink -m -- "$1" && return
readlink -f -- "$1" && return
[ -e . ] && echo "$(readlink_missing "$(dirname "$1")")/$(basename "$1")"
}

This is not really quite correct in case $1 includes . or .. for nonexisting paths (like in /doesnotexist/./a), but it should cover most cases.

(Replace readlink -m -- above by readlink_missing.)

Edit because of the downvote follows

Here is a test, that this function, indeed, is correct:

check()
{
res="$(relpath "$2" "$1")"
[ ".$res" = ".$3" ] && return
printf ':WRONG: %-10q %-10q gives %q\nCORRECT %-10q %-10q gives %q\n' "$1" "$2" "$res" "$@"
}

#     TARGET   SOURCE         RESULT
check "/A/B/C" "/A"           ".."
check "/A/B/C" "/A.x"         "../../A.x"
check "/A/B/C" "/A/B"         "."
check "/A/B/C" "/A/B/C"       "C"
check "/A/B/C" "/A/B/C/D"     "C/D"
check "/A/B/C" "/A/B/C/D/E"   "C/D/E"
check "/A/B/C" "/A/B/D"       "D"
check "/A/B/C" "/A/B/D/E"     "D/E"
check "/A/B/C" "/A/D"         "../D"
check "/A/B/C" "/A/D/E"       "../D/E"
check "/A/B/C" "/D/E/F"       "../../D/E/F"

check "/foo/baz/moo" "/foo/bar" "../bar"

Puzzled? Well, these are the correct results! Even if you think it does not fit the question, here is the proof this is correct:

check "http://example.com/foo/baz/moo" "http://example.com/foo/bar" "../bar"

Without any doubt, ../bar is the exact and only correct relative path of the page bar seen from the page moo. Everything else would be plain wrong.

It is trivial to adopt the output to the question which apparently assumes, that current is a directory:

absolute="/foo/bar"
current="/foo/baz/foo"
relative="../$(relpath "$absolute" "$current")"

This returns exactly, what was asked for.

And before you raise an eyebrow, here is a bit more complex variant of relpath (spot the small difference), which should work for URL-Syntax, too (so a trailing / survives, thanks to some bash-magic):

# Calculate relative PATH to the given DEST from the given BASE
# In the URL case, both URLs must be absolute and have the same Scheme.
# The `SCHEME:` must not be present in the FS either.
# This way this routine works for file paths an
: relpathurl DEST BASE
relpathurl()
{
local X Y A
# We can create dangling softlinks
X="$(readlink -m -- "$1")" || return
Y="$(readlink -m -- "$2")" || return
X="${X%/}/${1#"${1%/}"}"
Y="${Y%/}${2#"${2%/}"}"
A=""
while   Y="${Y%/*}"
        [ ".${X#"$Y"/}" = ".$X" ]
do
        A="../$A"
done
X="$A${X#"$Y"/}"
X="${X%/}"
echo "${X:-.}"
}

And here are the checks just to make clear: It really works as told.

check()
{
res="$(relpathurl "$2" "$1")"
[ ".$res" = ".$3" ] && return
printf ':WRONG: %-10q %-10q gives %q\nCORRECT %-10q %-10q gives %q\n' "$1" "$2" "$res" "$@"
}

#     TARGET   SOURCE         RESULT
check "/A/B/C" "/A"           ".."
check "/A/B/C" "/A.x"         "../../A.x"
check "/A/B/C" "/A/B"         "."
check "/A/B/C" "/A/B/C"       "C"
check "/A/B/C" "/A/B/C/D"     "C/D"
check "/A/B/C" "/A/B/C/D/E"   "C/D/E"
check "/A/B/C" "/A/B/D"       "D"
check "/A/B/C" "/A/B/D/E"     "D/E"
check "/A/B/C" "/A/D"         "../D"
check "/A/B/C" "/A/D/E"       "../D/E"
check "/A/B/C" "/D/E/F"       "../../D/E/F"

check "/foo/baz/moo" "/foo/bar" "../bar"
check "http://example.com/foo/baz/moo" "http://example.com/foo/bar" "../bar"

check "http://example.com/foo/baz/moo/" "http://example.com/foo/bar" "../../bar"
check "http://example.com/foo/baz/moo"  "http://example.com/foo/bar/" "../bar/"
check "http://example.com/foo/baz/moo/"  "http://example.com/foo/bar/" "../../bar/"

And here is how this can be used to give the wanted result from the question:

absolute="/foo/bar"
current="/foo/baz/foo"
relative="$(relpathurl "$absolute" "$current/")"
echo "$relative"

If you find something which does not work, please let me know in the comments below. Thanks.

PS:

Why are the arguments of relpath "reversed" in contrast to all the other answers here?

If you change

Y="$(readlink -m -- "$2")" || return

to

Y="$(readlink -m -- "${2:-"$PWD"}")" || return

then you can leave the 2nd parameter away, such that the BASE is the current directory/URL/whatever. That's only the Unix principle, as usual.

Extract parameter value from url using regular expressions

v is a query parameter, technically you need to consider cases ala: http://www.youtube.com/watch?p=DB852818BF378DAC&v=1q-k-uN73Gk

In .NET I would recommend to use System.Web.HttpUtility.ParseQueryString

HttpUtility.ParseQueryString(url)["v"];

And you don't even need to check the key, as it will return null if the key is not in the collection.

InputStream from a URL

Use java.net.URL#openStream() with a proper URL (including the protocol!). E.g.

InputStream input = new URL("http://www.somewebsite.com/a.txt").openStream();
// ...

See also:

Regex: ignore case sensitivity

As I discovered from this similar post (ignorecase in AWK), on old versions of awk (such as on vanilla Mac OS X), you may need to use 'tolower($0) ~ /pattern/'.

IGNORECASE or (?i) or /pattern/i will either generate an error or return true for every line.

Can I set subject/content of email using mailto:?

Yes:

Use this to experiment with mailto form elements and link encoding.

You can enter subject, body (i.e. content), etc. into the form, hit the button and see the mailto html link that you can paste into your page.

You can even specify elements that are rarely known and used: cc, bcc, from emails.

MySQL Select all columns from one table and some from another table

Just use the table name:

SELECT myTable.*, otherTable.foo, otherTable.bar...

That would select all columns from myTable and columns foo and bar from otherTable.

How to get date, month, year in jQuery UI datepicker?

Use the javascript Date object.

$(document).ready(function()  {
    $('#calendar').datepicker({
      dateFormat: 'yy-m-d',
      inline: true,
      onSelect: function(dateText, inst) { 
            var date = new Date(dateText);
            // change date.GetDay() to date.GetDate()
            alert(date.getDate() + date.getMonth() + date.getFullYear());
     } 
    });
});

fs.writeFile in a promise, asynchronous-synchronous stuff

Finally, the latest node.js release v10.3.0 has natively supported fs promises.

const fsPromises = require('fs').promises; // or require('fs/promises') in v10.0.0
fsPromises.writeFile(ASIN + '.json', JSON.stringify(results))
  .then(() => {
    console.log('JSON saved');
  })
  .catch(er => {
    console.log(er);
  });

You can check the official documentation for more details. https://nodejs.org/api/fs.html#fs_fs_promises_api

Hiding elements in responsive layout?

In boostrap 4.1 (run snippet because I copied whole table code from Bootstrap documentation):

_x000D_
_x000D_
.fixed_headers {_x000D_
  width: 750px;_x000D_
  table-layout: fixed;_x000D_
  border-collapse: collapse;_x000D_
}_x000D_
.fixed_headers th {_x000D_
  text-decoration: underline;_x000D_
}_x000D_
.fixed_headers th,_x000D_
.fixed_headers td {_x000D_
  padding: 5px;_x000D_
  text-align: left;_x000D_
}_x000D_
.fixed_headers td:nth-child(1),_x000D_
.fixed_headers th:nth-child(1) {_x000D_
  min-width: 200px;_x000D_
}_x000D_
.fixed_headers td:nth-child(2),_x000D_
.fixed_headers th:nth-child(2) {_x000D_
  min-width: 200px;_x000D_
}_x000D_
.fixed_headers td:nth-child(3),_x000D_
.fixed_headers th:nth-child(3) {_x000D_
  width: 350px;_x000D_
}_x000D_
.fixed_headers thead {_x000D_
  background-color: #333;_x000D_
  color: #FDFDFD;_x000D_
}_x000D_
.fixed_headers thead tr {_x000D_
  display: block;_x000D_
  position: relative;_x000D_
}_x000D_
.fixed_headers tbody {_x000D_
  display: block;_x000D_
  overflow: auto;_x000D_
  width: 100%;_x000D_
  height: 300px;_x000D_
}_x000D_
.fixed_headers tbody tr:nth-child(even) {_x000D_
  background-color: #DDD;_x000D_
}_x000D_
.old_ie_wrapper {_x000D_
  height: 300px;_x000D_
  width: 750px;_x000D_
  overflow-x: hidden;_x000D_
  overflow-y: auto;_x000D_
}_x000D_
.old_ie_wrapper tbody {_x000D_
  height: auto;_x000D_
}
_x000D_
<table class="fixed_headers">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Screen Size</th>_x000D_
      <th>Class</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>Hidden on all</td>_x000D_
      <td><code class="highlighter-rouge">.d-none</code></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Hidden only on xs</td>_x000D_
      <td><code class="highlighter-rouge">.d-none .d-sm-block</code></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Hidden only on sm</td>_x000D_
      <td><code class="highlighter-rouge">.d-sm-none .d-md-block</code></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Hidden only on md</td>_x000D_
      <td><code class="highlighter-rouge">.d-md-none .d-lg-block</code></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Hidden only on lg</td>_x000D_
      <td><code class="highlighter-rouge">.d-lg-none .d-xl-block</code></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Hidden only on xl</td>_x000D_
      <td><code class="highlighter-rouge">.d-xl-none</code></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Visible on all</td>_x000D_
      <td><code class="highlighter-rouge">.d-block</code></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Visible only on xs</td>_x000D_
      <td><code class="highlighter-rouge">.d-block .d-sm-none</code></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Visible only on sm</td>_x000D_
      <td><code class="highlighter-rouge">.d-none .d-sm-block .d-md-none</code></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Visible only on md</td>_x000D_
      <td><code class="highlighter-rouge">.d-none .d-md-block .d-lg-none</code></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Visible only on lg</td>_x000D_
      <td><code class="highlighter-rouge">.d-none .d-lg-block .d-xl-none</code></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Visible only on xl</td>_x000D_
      <td><code class="highlighter-rouge">.d-none .d-xl-block</code></td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

https://getbootstrap.com/docs/4.1/utilities/display/#hiding-elements

Node.js https pem error: routines:PEM_read_bio:no start line

I faced with the problem like this.

The problem was that I added the public key without '-----BEGIN PUBLIC KEY-----' at the beginning and without '-----END PUBLIC KEY-----'.

So it causes the error.

Initially, my public key was like this:

-----BEGIN PUBLIC KEY-----
WnsbGUXbb0GbJSCwCBAhrzT0s2KMRyqqS7QBiIG7t3H2Qtmde6UoUIcTTPJgv71
......
oNLcaK2wKKyRdcROK7ZTSCSMsJpAFOY
-----END PUBLIC KEY-----

But I used just this part:

WnsbGUXb+b0GbJSCwCBAhrzT0s2KMRyqqS7QBiIG7t3H2Qtmde6UoUIcTTPJgv71
......
oNLcaK2w+KKyRdcROK7ZTSCSMsJpAFOY

'any' vs 'Object'

Bit old, but doesn't hurt to add some notes.

When you write something like this

let a: any;
let b: Object;
let c: {};
  • a has no interface, it can be anything, the compiler knows nothing about its members so no type checking is performed when accessing/assigning both to it and its members. Basically, you're telling the compiler to "back off, I know what I'm doing, so just trust me";
  • b has the Object interface, so ONLY the members defined in that interface are available for b. It's still JavaScript, so everything extends Object;
  • c extends Object, like anything else in TypeScript, but adds no members. Since type compatibility in TypeScript is based on structural subtyping, not nominal subtyping, c ends up being the same as b because they have the same interface: the Object interface.

And that's why

a.doSomething(); // Ok: the compiler trusts you on that
b.doSomething(); // Error: Object has no doSomething member
c.doSomething(); // Error: c neither has doSomething nor inherits it from Object

and why

a.toString(); // Ok: whatever, dude, have it your way
b.toString(); // Ok: toString is defined in Object
c.toString(); // Ok: c inherits toString from Object

So Object and {} are equivalents in TypeScript.

If you declare functions like these

function fa(param: any): void {}
function fb(param: Object): void {}

with the intention of accepting anything for param (maybe you're going to check types at run-time to decide what to do with it), remember that

  • inside fa, the compiler will let you do whatever you want with param;
  • inside fb, the compiler will only let you reference Object's members.

It is worth noting, though, that if param is supposed to accept multiple known types, a better approach is to declare it using union types, as in

function fc(param: string|number): void {}

Obviously, OO inheritance rules still apply, so if you want to accept instances of derived classes and treat them based on their base type, as in

interface IPerson {
    gender: string;
}

class Person implements IPerson {
    gender: string;
}

class Teacher extends Person {}

function func(person: IPerson): void {
    console.log(person.gender);
}

func(new Person());     // Ok
func(new Teacher());    // Ok
func({gender: 'male'}); // Ok
func({name: 'male'});   // Error: no gender..

the base type is the way to do it, not any. But that's OO, out of scope, I just wanted to clarify that any should only be used when you don't know whats coming, and for anything else you should annotate the correct type.

UPDATE:

Typescript 2.2 added an object type, which specifies that a value is a non-primitive: (i.e. not a number, string, boolean, symbol, undefined, or null).

Consider functions defined as:

function b(x: Object) {}
function c(x: {}) {}
function d(x: object) {}

x will have the same available properties within all of these functions, but it's a type error to call d with a primitive:

b("foo"); //Okay
c("foo"); //Okay
d("foo"); //Error: "foo" is a primitive

How can I search (case-insensitive) in a column using LIKE wildcard?

I'm doing something like that.

Getting the values in lowercase and MySQL does the rest

    $string = $_GET['string'];
    mysqli_query($con,"SELECT *
                       FROM table_name
                       WHERE LOWER(column_name)
                       LIKE LOWER('%$string%')");

And For MySQL PDO Alternative:

        $string = $_GET['string'];
        $q = "SELECT *
              FROM table_name
              WHERE LOWER(column_name)
              LIKE LOWER(?);";
        $query = $dbConnection->prepare($q);
        $query->bindValue(1, "%$string%", PDO::PARAM_STR);
        $query->execute();

Stack Memory vs Heap Memory

In C++ the stack memory is where local variables get stored/constructed. The stack is also used to hold parameters passed to functions.

The stack is very much like the std::stack class: you push parameters onto it and then call a function. The function then knows that the parameters it expects can be found on the end of the stack. Likewise, the function can push locals onto the stack and pop them off it before returning from the function. (caveat - compiler optimizations and calling conventions all mean things aren't this simple)

The stack is really best understood from a low level and I'd recommend Art of Assembly - Passing Parameters on the Stack. Rarely, if ever, would you consider any sort of manual stack manipulation from C++.

Generally speaking, the stack is preferred as it is usually in the CPU cache, so operations involving objects stored on it tend to be faster. However the stack is a limited resource, and shouldn't be used for anything large. Running out of stack memory is called a Stack buffer overflow. It's a serious thing to encounter, but you really shouldn't come across one unless you have a crazy recursive function or something similar.

Heap memory is much as rskar says. In general, C++ objects allocated with new, or blocks of memory allocated with the likes of malloc end up on the heap. Heap memory almost always must be manually freed, though you should really use a smart pointer class or similar to avoid needing to remember to do so. Running out of heap memory can (will?) result in a std::bad_alloc.

OR operator in switch-case?

Switch is not same as if-else-if.

Switch is used when there is one expression that gets evaluated to a value and that value can be one of predefined set of values. If you need to perform multiple boolean / comparions operations run-time then if-else-if needs to be used.

What is the significance of #pragma marks? Why do we need #pragma marks?

When we have a big/lengthy class say more than couple 100 lines of code we can't see everything on Monitor screen, hence we can't see overview (also called document items) of our class. Sometime we want to see overview of our class; its all methods, constants, properties etc at a glance. You can press Ctrl+6 in XCode to see overview of your class. You'll get a pop-up kind of Window aka Jump Bar.

By default, this jump bar doesn't have any buckets/sections. It's just one long list. (Though we can just start typing when jump Bar appears and it will search among jump bar items). Here comes the need of pragma mark

If you want to create sections in your Jump Bar then you can use pragma marks with relevant description. Now refer snapshot attached in question. There 'View lifeCycle' and 'A section dedicated ..' are sections created by pragma marks

Removing cordova plugins from the project

  • access the folder
  • list the plugins (cordova plugin list)
  • ionic cordova plugin remove "pluginName"

Should be fine!

What is the difference between \r and \n?

In short \r has ASCII value 13 (CR) and \n has ASCII value 10 (LF). Mac uses CR as line delimiter (at least, it did before, I am not sure for modern macs), *nix uses LF and Windows uses both (CRLF).

MySQL user DB does not have password columns - Installing MySQL on OSX

One pitfall I fell into is there is no password field now, it has been renamed so:

update user set password=PASSWORD("YOURPASSWORDHERE") where user='root';

Should now be:

update user set authentication_string=password('YOURPASSWORDHERE') where user='root';

How can I verify if an AD account is locked?

Here's another one:

PS> Search-ADAccount -Locked | Select Name, LockedOut, LastLogonDate

Name                                       LockedOut LastLogonDate
----                                       --------- -------------
Yxxxxxxx                                        True 14/11/2014 10:19:20
Bxxxxxxx                                        True 18/11/2014 08:38:34
Administrator                                   True 03/11/2014 20:32:05

Other parameters worth mentioning:

Search-ADAccount -AccountExpired
Search-ADAccount -AccountDisabled
Search-ADAccount -AccountInactive

Get-Help Search-ADAccount -ShowWindow

Get full URL and query string in Servlet for both HTTP and HTTPS requests

I know this is a Java question, but if you're using Kotlin you can do this quite nicely:

val uri = request.run {
    if (queryString.isNullOrBlank()) requestURI else "$requestURI?$queryString"
}

Retrieve WordPress root directory path?

For retrieving the path you can use a function <?php $path = get_home_path(); ?>. I do not want to just repeat what had been already said here, but I want to add one more thing:

If you are using windows server, which is rare case for WordPress installation, but still happens sometimes, you might face a problem with the path output. It might miss a "\" somewhere and you will get an error if you will be using such a path. So when outputting make sure to sanitize the path:

<?php 

$path = get_home_path(); 
$path = wp_normalize_path ($path);

// now $path is ready to be used :)

?>

SQL recursive query on self referencing table (Oracle)

Do you want to do this?

SELECT id, parent_id, name, 
 (select Name from tbl where id = t.parent_id) parent_name
FROM tbl t start with id = 1 CONNECT BY PRIOR id = parent_id

Edit Another option based on OMG's one (but I think that will perform equally):

select 
           t1.id, 
           t1.parent_id, 
           t1.name,
           t2.name AS parent_name,
           t2.id AS parent_id
from 
    (select id, parent_id, name
    from tbl
    start with id = 1 
    connect by prior id = parent_id) t1
    left join
    tbl t2 on t2.id = t1.parent_id

UITableView Cell selected Color?

1- Add a view to the content view of your cell.
2- Right click your cell.
3- Make the added view as "selectedBackgroundView".

enter image description here

Python 3 turn range to a list

Python 3:

my_list = [*range(1001)]

C# static class why use?

If a class is declared as static then the variables and methods need to be declared as static.

A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.

Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.

->The main features of a static class are:

  • They only contain static members.
  • They cannot be instantiated.
  • They are sealed.
  • They cannot contain Instance Constructors or simply constructors as we know that they are associated with objects and operates on data when an object is created.

Example

static class CollegeRegistration
{
  //All static member variables
   static int nCollegeId; //College Id will be same for all the students studying
   static string sCollegeName; //Name will be same
   static string sColegeAddress; //Address of the college will also same

    //Member functions
   public static int GetCollegeId()
   {
     nCollegeId = 100;
     return (nCollegeID);
   }
    //similarly implementation of others also.
} //class end


public class student
{
    int nRollNo;
    string sName;

    public GetRollNo()
    {
       nRollNo += 1;
       return (nRollNo);
    }
    //similarly ....
    public static void Main()
   {
     //Not required.
     //CollegeRegistration objCollReg= new CollegeRegistration();

     //<ClassName>.<MethodName>
     int cid= CollegeRegistration.GetCollegeId();
    string sname= CollegeRegistration.GetCollegeName();


   } //Main end
}

How to display multiple notifications in android

Another way of doing it is take the current date convert it into long just take the last 4 digits. There is a high probability that the number will be unique.

    long time = new Date().getTime();
    String tmpStr = String.valueOf(time);
    String last4Str = tmpStr.substring(tmpStr.length() -5);
    int notificationId = Integer.valueOf(last4Str);

How can I add new dimensions to a Numpy array?

Alternatively to

image = image[..., np.newaxis]

in @dbliss' answer, you can also use numpy.expand_dims like

image = np.expand_dims(image, <your desired dimension>)

For example (taken from the link above):

x = np.array([1, 2])

print(x.shape)  # prints (2,)

Then

y = np.expand_dims(x, axis=0)

yields

array([[1, 2]])

and

y.shape

gives

(1, 2)

Using two values for one switch case statement

JEP 354: Switch Expressions (Preview) in JDK-13 and JEP 361: Switch Expressions (Standard) in JDK-14 will extend the switch statement so it can be used as an expression.

Now you can:

  • directly assign variable from switch expression,
  • use new form of switch label (case L ->):

    The code to the right of a "case L ->" switch label is restricted to be an expression, a block, or (for convenience) a throw statement.

  • use multiple constants per case, separated by commas,
  • and also there are no more value breaks:

    To yield a value from a switch expression, the break with value statement is dropped in favor of a yield statement.

So the demo from one of the answers might look like this:

public class SwitchExpression {

  public static void main(String[] args) {
      int month = 9;
      int year = 2018;
      int numDays = switch (month) {
        case 1, 3, 5, 7, 8, 10, 12 -> 31;
        case 4, 6, 9, 11 -> 30;
        case 2 -> {
          if (java.time.Year.of(year).isLeap()) {
            System.out.println("Wow! It's leap year!");
            yield 29;
          } else {
            yield 28;
          }
        }
        default -> {
          System.out.println("Invalid month.");
          yield 0;
        }
      };
      System.out.println("Number of Days = " + numDays);
  }
}

How can I check that two objects have the same set of property names?

To compare two objects along with all attributes of it, I followed this code and it didn't require tostring() or json compar

_x000D_
_x000D_
if(user1.equals(user2))
{
console.log("Both are equal");
}
_x000D_
_x000D_
_x000D_

e.

Ordering by specific field value first

There's also the MySQL FIELD function.

If you want complete sorting for all possible values:

SELECT id, name, priority
FROM mytable
ORDER BY FIELD(name, "core", "board", "other")

If you only care that "core" is first and the other values don't matter:

SELECT id, name, priority
FROM mytable
ORDER BY FIELD(name, "core") DESC

If you want to sort by "core" first, and the other fields in normal sort order:

SELECT id, name, priority
FROM mytable
ORDER BY FIELD(name, "core") DESC, priority

There are some caveats here, though:

First, I'm pretty sure this is mysql-only functionality - the question is tagged mysql, but you never know.

Second, pay attention to how FIELD() works: it returns the one-based index of the value - in the case of FIELD(priority, "core"), it'll return 1 if "core" is the value. If the value of the field is not in the list, it returns zero. This is why DESC is necessary unless you specify all possible values.

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

I have the same problem after update visual studio, so this is how do I solve the problem.

  1. Close visual studio.
  2. Delete all .vs folder from my project.
  3. Open visual studio.
  4. Open my project.

Hope this helpful for anyone who has this problem.

jQuery Determine if a matched class has a given id

You can bake that logic into the selector by combining multiple selectors. For instance, we could target all elements with a given id, that also have a particular class:

$("#foo.bar"); // Matches <div id="foo" class="bar">

This should look similar to something you'd write in CSS. Note that it won't apply to all #foo elements (though there should only be one), and it won't apply to all .bar elements (though there may be many). It will only reference elements that qualify on both attributes.

jQuery also has a great .is method that lets your determine whether an element has certain qualities. You can test a jQuery collection against a string selector, an HTML Element, or another jQuery object. In this case, we'll just check it against a string selector:

$(".bar:first").is("#foo"); // TRUE if first '.bar' in document is also '#foo'

release Selenium chromedriver.exe from memory

Observed on version 3.141.0:

If you initialize your ChromeDriver with just ChromeOptions, quit() will not close out chromedriver.exe.

    ChromeOptions chromeOptions = new ChromeOptions();
    ChromeDriver driver = new ChromeDriver(chromeOptions);
    // .. do stuff ..
    driver.quit()

If you create and pass in a ChromeDriverService, quit() will close chromedriver.exe out correctly.

    ChromeDriverService driverService = ChromeDriverService.CreateDefaultService();
    ChromeOptions chromeOptions = new ChromeOptions();
    ChromeDriver driver = new ChromeDriver(driverService, chromeOptions);
    // .. do stuff ..
    driver.quit()

How do I create a foreign key in SQL Server?

create table question_bank
(
    question_id uniqueidentifier primary key,
    question_exam_id uniqueidentifier not null constraint fk_exam_id foreign key references exams(exam_id),
    question_text varchar(1024) not null,
    question_point_value decimal
);

--That will work too. Pehaps a bit more intuitive construct?

Python: Maximum recursion depth exceeded

You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:

import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values

... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.

Check if element at position [x] exists in the list

if(list.ElementAtOrDefault(2) != null)
{
   // logic
}

ElementAtOrDefault() is part of the System.Linq namespace.

Although you have a List, so you can use list.Count > 2.

How to delete specific columns with VBA?

To answer the question How to delete specific columns in vba for excel. I use Array as below.

sub del_col()

dim myarray as variant
dim i as integer

myarray = Array(10, 9, 8)'Descending to Ascending
For i = LBound(myarray) To UBound(myarray)
    ActiveSheet.Columns(myarray(i)).EntireColumn.Delete
Next i

end sub

How to wrap text in LaTeX tables?

With the regular tabular environment, you want to use the p{width} column type, as marcog indicates. But that forces you to give explicit widths.

Another solution is the tabularx environment:

\usepackage{tabularx}
...
\begin{tabularx}{\linewidth}{ r X }
    right-aligned foo & long long line of blah blah that will wrap when the table fills the column width\\
\end{tabularx}

All X columns get the same width. You can influence this by setting \hsize in the format declaration:

>{\setlength\hsize{.5\hsize}} X >{\setlength\hsize{1.5\hsize}} X

but then all the factors have to sum up to 1, I suppose (I took this from the LaTeX companion). There is also the package tabulary which will adjust column widths to balance row heights. For the details, you can get the documentation for each package with texdoc tabulary (in TeXlive).

How to filter by object property in angularJS

You can try this. its working for me 'name' is a property in arr.

repeat="item in (tagWordOptions | filter:{ name: $select.search } ) track by $index

How to count the number of set bits in a 32-bit integer?

I'm particularly fond of this example from the fortune file:

#define BITCOUNT(x)    (((BX_(x)+(BX_(x)>>4)) & 0x0F0F0F0F) % 255)
#define BX_(x)         ((x) - (((x)>>1)&0x77777777)
                             - (((x)>>2)&0x33333333)
                             - (((x)>>3)&0x11111111))

I like it best because it's so pretty!

moment.js get current time in milliseconds?

From the docs: http://momentjs.com/docs/#/parsing/unix-timestamp-milliseconds/

So use either of these:


moment(...).valueOf()

to parse a preexisting date and convert the representation to a unix timestamp


moment().valueOf()

for the current unix timestamp

Height of status bar in Android

I've merged some solutions together:

public static int getStatusBarHeight(final Context context) {
    final Resources resources = context.getResources();
    final int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
    if (resourceId > 0)
        return resources.getDimensionPixelSize(resourceId);
    else
        return (int) Math.ceil((VERSION.SDK_INT >= VERSION_CODES.M ? 24 : 25) * resources.getDisplayMetrics().density);
    }

another alternative:

    final View view = findViewById(android.R.id.content);
    runJustBeforeBeingDrawn(view, new Runnable() {
        @Override
        public void run() {
            int statusBarHeight = getResources().getDisplayMetrics().heightPixels - view.getMeasuredHeight();
        }
    });

EDIT: Alternative to runJustBeforeBeingDrawn: https://stackoverflow.com/a/28136027/878126

Append date to filename in linux

a bit more convoluted solution that fully matches your spec

echo `expr $FILENAME : '\(.*\)\.[^.]*'`_`date +%d-%m-%y`.`expr $FILENAME : '.*\.\([^.]*\)'`

where first 'expr' extracts file name without extension, second 'expr' extracts extension

Failed to load resource: the server responded with a status of 404 (Not Found) error in server

It just means that the server cannot find your image.

Remember The image path must be relative to the CSS file location

Check the path and if the image file exist.

Cannot set property 'innerHTML' of null

You have to place the hello div before the script, so that it exists when the script is loaded.

How can I represent an infinite number in Python?

In python2.x there was a dirty hack that served this purpose (NEVER use it unless absolutely necessary):

None < any integer < any string

Thus the check i < '' holds True for any integer i.

It has been reasonably deprecated in python3. Now such comparisons end up with

TypeError: unorderable types: str() < int()

How can I lock the first row and first column of a table when scrolling, possibly using JavaScript and CSS?

How about a solution where you put the actual "data" of the table inside its own div, with overflow: scroll;? Then the browser will automatically create scrollbars for the portion of the "table" you do not want to lock, and you can put the "table header"/first row just above that <div>.

Not sure how that would work with scrolling horizontally though.

Get first word of string

var str = "Hello m|sss sss|mmm ss"
//Now i separate them by "|"
var str1 = str.split('|');

//Now i want to get the first word of every split-ed sting parts:

for (var i=0;i<str1.length;i++)
{
    //What to do here to get the first word :)
    var firstWord = str1[i].split(' ')[0];
    alert(firstWord);
}

CSS: background-color only inside the margin

I needed something similar, and came up with using the :before (or :after) pseudoclasses:

#mydiv {
   background-color: #fbb;
   margin-top: 100px;
   position: relative;
}
#mydiv:before {
   content: "";
   background-color: #bfb;
   top: -100px;
   height: 100px;
   width: 100%;
   position: absolute;
}

JSFiddle

Unbound classpath container in Eclipse

I got the Similar issue while importing the project.

The issue is you select "Use an execution environment JRE" and which is lower then the libraries used in the projects being imported.

There are two ways to resolve this issue:

1.While first time importing the project:

in JRE tab select "USE project specific JRE" instead of "Use an execution environment JRE".

2.Delete the Project from your work space and import again. This time:

select "Check out as a project in the workspace" instead of "Check out as a project configured using the new Project Wizard"

CodeIgniter activerecord, retrieve last insert id?

Last insert id means you can get inserted auto increment id by using this method in active record,

$this->db->insert_id() 
// it can be return insert id it is 
// similar to the mysql_insert_id in core PHP

You can refer this link you can find some more stuff.

Information from executing a query

Clang vs GCC - which produces faster binaries?

Basically speaking, the answer is: it depends. There are many many benchmarks focusing on different kinds of application.

My benchmark on my app is: gcc > icc > clang.

There are rare IO, but many CPU float and data structure operations.

compile flags is -Wall -g -DNDEBUG -O3.

https://github.com/zhangyafeikimi/ml-pack/blob/master/gbdt/profile/benchmark

convert date string to mysql datetime field

I assume we are talking about doing this in Bash?

I like to use sed to load the date values into an array so I can break down each field and do whatever I want with it. The following example assumes and input format of mm/dd/yyyy...

DATE=$2
DATE_ARRAY=(`echo $DATE | sed -e 's/\// /g'`)
MONTH=(`echo ${DATE_ARRAY[0]}`)
DAY=(`echo ${DATE_ARRAY[1]}`)
YEAR=(`echo ${DATE_ARRAY[2]}`)
LOAD_DATE=$YEAR$MONTH$DAY

you also may want to read up on the date command in linux. It can be very useful: http://unixhelp.ed.ac.uk/CGI/man-cgi?date

Hope that helps... :)

-Ryan

Python 2.7.10 error "from urllib.request import urlopen" no module named request

You are right the urllib and urllib2 packages have been split into urllib.request , urllib.parse and urllib.error packages in Python 3.x. The latter packages do not exist in Python 2.x

From documentation -

The urllib module has been split into parts and renamed in Python 3 to urllib.request, urllib.parse, and urllib.error.

From urllib2 documentation -

The urllib2 module has been split across several modules in Python 3 named urllib.request and urllib.error.

So I am pretty sure the code you downloaded has been written for Python 3.x , since they are using a library that is only present in Python 3.x .

There is a urllib package in python, but it does not have the request subpackage. Also, lets assume you do lots of work and somehow make request subpackage available in Python 2.x .

There is a very very high probability that you will run into more issues, there is lots of incompatibility between Python 2.x and Python 3.x , in the end you would most probably end up rewriting atleast half the code from github (and most probably reading and understanding the complete code from there).

Even then there may be other bugs arising from the fact that some of the implementation details changed between Python 2.x to Python 3.x (As an example - list comprehension got its own namespace in Python 3.x)

You are better off trying to download and use Python 3 , than trying to make code written for Python 3.x compatible with Python 2.x

Remove a file from the list that will be committed

if you did a git add and you haven't pushed anything yet, you just have to do this to unstage it from your commit.

git reset HEAD <file>

What is the MySQL VARCHAR max size?

From MySQL documentation:

The effective maximum length of a VARCHAR in MySQL 5.0.3 and later is subject to the maximum row size (65,535 bytes, which is shared among all columns) and the character set used. For example, utf8 characters can require up to three bytes per character, so a VARCHAR column that uses the utf8 character set can be declared to be a maximum of 21,844 characters.

Limits for the VARCHAR varies depending on charset used. Using ASCII would use 1 byte per character. Meaning you could store 65,535 characters. Using utf8 will use 3 bytes per character resulting in character limit of 21,844. BUT if you are using the modern multibyte charset utf8mb4 which you should use! It supports emojis and other special characters. It will be using 4 bytes per character. This will limit the number of characters per table to 16,383. Note that other fields such as INT will also be counted to these limits.

Conclusion:

utf8 maximum of 21,844 characters

utf8mb4 maximum of 16,383 characters

Resource blocked due to MIME type mismatch (X-Content-Type-Options: nosniff)

check your path ,this error will come if file was not exist into given path.

correct configuration for nginx to localhost?

Fundamentally you hadn't declare location which is what nginx uses to bind URL with resources.

 server {
            listen       80;
            server_name  localhost;

            access_log  logs/localhost.access.log  main;

            location / {
                root /var/www/board/public;
                index index.html index.htm index.php;
            }
       }

iOS: Multi-line UILabel in Auto Layout

I have a UITableViewCell which has a text wrap label. I worked text wrapping as follows.

1) Set UILabel constraints as follows.

enter image description here

2) Set no. of lines to 0.

3) Added UILabel height constraint to UITableViewCell.

@IBOutlet weak var priorityLabelWidth: NSLayoutConstraint!

4) On UITableViewCell:

priorityLabel.sizeToFit()
priorityLabelWidth.constant = priorityLabel.intrinsicContentSize().width+5

Filtering a data frame by values in a column

The subset command is not necessary. Just use data frame indexing

studentdata[studentdata$Drink == 'water',]

Read the warning from ?subset

This is a convenience function intended for use interactively. For programming it is better to use the standard subsetting functions like ‘[’, and in particular the non-standard evaluation of argument ‘subset’ can have unanticipated consequences.

usr/bin/ld: cannot find -l<nameOfTheLibrary>

To figure out what the linker is looking for, run it in verbose mode.

For example, I encountered this issue while trying to compile MySQL with ZLIB support. I was receiving an error like this during compilation:

/usr/bin/ld: cannot find -lzlib

I did some Googl'ing and kept coming across different issues of the same kind where people would say to make sure the .so file actually exists and if it doesn't, then create a symlink to the versioned file, for example, zlib.so.1.2.8. But, when I checked, zlib.so DID exist. So, I thought, surely that couldn't be the problem.

I came across another post on the Internets that suggested to run make with LD_DEBUG=all:

LD_DEBUG=all make

Although I got a TON of debugging output, it wasn't actually helpful. It added more confusion than anything else. So, I was about to give up.

Then, I had an epiphany. I thought to actually check the help text for the ld command:

ld --help

From that, I figured out how to run ld in verbose mode (imagine that):

ld -lzlib --verbose

This is the output I got:

==================================================
attempt to open /usr/x86_64-linux-gnu/lib64/libzlib.so failed
attempt to open /usr/x86_64-linux-gnu/lib64/libzlib.a failed
attempt to open /usr/local/lib64/libzlib.so failed
attempt to open /usr/local/lib64/libzlib.a failed
attempt to open /lib64/libzlib.so failed
attempt to open /lib64/libzlib.a failed
attempt to open /usr/lib64/libzlib.so failed
attempt to open /usr/lib64/libzlib.a failed
attempt to open /usr/x86_64-linux-gnu/lib/libzlib.so failed
attempt to open /usr/x86_64-linux-gnu/lib/libzlib.a failed
attempt to open /usr/local/lib/libzlib.so failed
attempt to open /usr/local/lib/libzlib.a failed
attempt to open /lib/libzlib.so failed
attempt to open /lib/libzlib.a failed
attempt to open /usr/lib/libzlib.so failed
attempt to open /usr/lib/libzlib.a failed
/usr/bin/ld.bfd.real: cannot find -lzlib

Ding, ding, ding...

So, to finally fix it so I could compile MySQL with my own version of ZLIB (rather than the bundled version):

sudo ln -s /usr/lib/libz.so.1.2.8 /usr/lib/libzlib.so

Voila!

Check object empty

In Java, you can verify using Object utils.

import static java.util.Objects.isNull;
if(IsNull(yourObject)){
  //your block here
}

Extract names of objects from list

Making a small tweak to the inside function and using lapply on an index instead of the actual list itself gets this doing what you want

x <- c("yes", "no", "maybe", "no", "no", "yes")
y <- c("red", "blue", "green", "green", "orange")
list.xy <- list(x=x, y=y)

WORD.C <- function(WORDS){
  require(wordcloud)

  L2 <- lapply(WORDS, function(x) as.data.frame(table(x), stringsAsFactors = FALSE))

  # Takes a dataframe and the text you want to display
  FUN <- function(X, text){
    windows() 
    wordcloud(X[, 1], X[, 2], min.freq=1)
    mtext(text, 3, padj=-4.5, col="red")  #what I'm trying that isn't working
  }

  # Now creates the sequence 1,...,length(L2)
  # Loops over that and then create an anonymous function
  # to send in the information you want to use.
  lapply(seq_along(L2), function(i){FUN(L2[[i]], names(L2)[i])})

  # Since you asked about loops
  # you could use i in seq_along(L2) 
  # instead of 1:length(L2) if you wanted to
  #for(i in 1:length(L2)){
  #  FUN(L2[[i]], names(L2)[i])
  #}
}

WORD.C(list.xy)

Throw HttpResponseException or return Request.CreateErrorResponse?

The approach I have taken is to just throw exceptions from the api controller actions and have an exception filter registered that processes the exception and sets an appropriate response on the action execution context.

The filter exposes a fluent interface that provides a means of registering handlers for specific types of exceptions prior to registering the filter with global configuration.

The use of this filter enables centralized exception handling instead of spreading it across the controller actions. There are however cases where I will catch exceptions within the controller action and return a specific response if it does not make sense to centralize the handling of that particular exception.

Example registration of filter:

GlobalConfiguration.Configuration.Filters.Add(
    new UnhandledExceptionFilterAttribute()
    .Register<KeyNotFoundException>(HttpStatusCode.NotFound)

    .Register<SecurityException>(HttpStatusCode.Forbidden)

    .Register<SqlException>(
        (exception, request) =>
        {
            var sqlException = exception as SqlException;

            if (sqlException.Number > 50000)
            {
                var response            = request.CreateResponse(HttpStatusCode.BadRequest);
                response.ReasonPhrase   = sqlException.Message.Replace(Environment.NewLine, String.Empty);

                return response;
            }
            else
            {
                return request.CreateResponse(HttpStatusCode.InternalServerError);
            }
        }
    )
);

UnhandledExceptionFilterAttribute class:

using System;
using System.Collections.Concurrent;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http.Filters;

namespace Sample
{
    /// <summary>
    /// Represents the an attribute that provides a filter for unhandled exceptions.
    /// </summary>
    public class UnhandledExceptionFilterAttribute : ExceptionFilterAttribute
    {
        #region UnhandledExceptionFilterAttribute()
        /// <summary>
        /// Initializes a new instance of the <see cref="UnhandledExceptionFilterAttribute"/> class.
        /// </summary>
        public UnhandledExceptionFilterAttribute() : base()
        {

        }
        #endregion

        #region DefaultHandler
        /// <summary>
        /// Gets a delegate method that returns an <see cref="HttpResponseMessage"/> 
        /// that describes the supplied exception.
        /// </summary>
        /// <value>
        /// A <see cref="Func{Exception, HttpRequestMessage, HttpResponseMessage}"/> delegate method that returns 
        /// an <see cref="HttpResponseMessage"/> that describes the supplied exception.
        /// </value>
        private static Func<Exception, HttpRequestMessage, HttpResponseMessage> DefaultHandler = (exception, request) =>
        {
            if(exception == null)
            {
                return null;
            }

            var response            = request.CreateResponse<string>(
                HttpStatusCode.InternalServerError, GetContentOf(exception)
            );
            response.ReasonPhrase   = exception.Message.Replace(Environment.NewLine, String.Empty);

            return response;
        };
        #endregion

        #region GetContentOf
        /// <summary>
        /// Gets a delegate method that extracts information from the specified exception.
        /// </summary>
        /// <value>
        /// A <see cref="Func{Exception, String}"/> delegate method that extracts information 
        /// from the specified exception.
        /// </value>
        private static Func<Exception, string> GetContentOf = (exception) =>
        {
            if (exception == null)
            {
                return String.Empty;
            }

            var result  = new StringBuilder();

            result.AppendLine(exception.Message);
            result.AppendLine();

            Exception innerException = exception.InnerException;
            while (innerException != null)
            {
                result.AppendLine(innerException.Message);
                result.AppendLine();
                innerException = innerException.InnerException;
            }

            #if DEBUG
            result.AppendLine(exception.StackTrace);
            #endif

            return result.ToString();
        };
        #endregion

        #region Handlers
        /// <summary>
        /// Gets the exception handlers registered with this filter.
        /// </summary>
        /// <value>
        /// A <see cref="ConcurrentDictionary{Type, Tuple}"/> collection that contains 
        /// the exception handlers registered with this filter.
        /// </value>
        protected ConcurrentDictionary<Type, Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>>> Handlers
        {
            get
            {
                return _filterHandlers;
            }
        }
        private readonly ConcurrentDictionary<Type, Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>>> _filterHandlers = new ConcurrentDictionary<Type, Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>>>();
        #endregion

        #region OnException(HttpActionExecutedContext actionExecutedContext)
        /// <summary>
        /// Raises the exception event.
        /// </summary>
        /// <param name="actionExecutedContext">The context for the action.</param>
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            if(actionExecutedContext == null || actionExecutedContext.Exception == null)
            {
                return;
            }

            var type    = actionExecutedContext.Exception.GetType();

            Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>> registration = null;

            if (this.Handlers.TryGetValue(type, out registration))
            {
                var statusCode  = registration.Item1;
                var handler     = registration.Item2;

                var response    = handler(
                    actionExecutedContext.Exception.GetBaseException(), 
                    actionExecutedContext.Request
                );

                // Use registered status code if available
                if (statusCode.HasValue)
                {
                    response.StatusCode = statusCode.Value;
                }

                actionExecutedContext.Response  = response;
            }
            else
            {
                // If no exception handler registered for the exception type, fallback to default handler
                actionExecutedContext.Response  = DefaultHandler(
                    actionExecutedContext.Exception.GetBaseException(), actionExecutedContext.Request
                );
            }
        }
        #endregion

        #region Register<TException>(HttpStatusCode statusCode)
        /// <summary>
        /// Registers an exception handler that returns the specified status code for exceptions of type <typeparamref name="TException"/>.
        /// </summary>
        /// <typeparam name="TException">The type of exception to register a handler for.</typeparam>
        /// <param name="statusCode">The HTTP status code to return for exceptions of type <typeparamref name="TException"/>.</param>
        /// <returns>
        /// This <see cref="UnhandledExceptionFilterAttribute"/> after the exception handler has been added.
        /// </returns>
        public UnhandledExceptionFilterAttribute Register<TException>(HttpStatusCode statusCode) 
            where TException : Exception
        {

            var type    = typeof(TException);
            var item    = new Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>>(
                statusCode, DefaultHandler
            );

            if (!this.Handlers.TryAdd(type, item))
            {
                Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>> oldItem = null;

                if (this.Handlers.TryRemove(type, out oldItem))
                {
                    this.Handlers.TryAdd(type, item);
                }
            }

            return this;
        }
        #endregion

        #region Register<TException>(Func<Exception, HttpRequestMessage, HttpResponseMessage> handler)
        /// <summary>
        /// Registers the specified exception <paramref name="handler"/> for exceptions of type <typeparamref name="TException"/>.
        /// </summary>
        /// <typeparam name="TException">The type of exception to register the <paramref name="handler"/> for.</typeparam>
        /// <param name="handler">The exception handler responsible for exceptions of type <typeparamref name="TException"/>.</param>
        /// <returns>
        /// This <see cref="UnhandledExceptionFilterAttribute"/> after the exception <paramref name="handler"/> 
        /// has been added.
        /// </returns>
        /// <exception cref="ArgumentNullException">The <paramref name="handler"/> is <see langword="null"/>.</exception>
        public UnhandledExceptionFilterAttribute Register<TException>(Func<Exception, HttpRequestMessage, HttpResponseMessage> handler) 
            where TException : Exception
        {
            if(handler == null)
            {
              throw new ArgumentNullException("handler");
            }

            var type    = typeof(TException);
            var item    = new Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>>(
                null, handler
            );

            if (!this.Handlers.TryAdd(type, item))
            {
                Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>> oldItem = null;

                if (this.Handlers.TryRemove(type, out oldItem))
                {
                    this.Handlers.TryAdd(type, item);
                }
            }

            return this;
        }
        #endregion

        #region Unregister<TException>()
        /// <summary>
        /// Unregisters the exception handler for exceptions of type <typeparamref name="TException"/>.
        /// </summary>
        /// <typeparam name="TException">The type of exception to unregister handlers for.</typeparam>
        /// <returns>
        /// This <see cref="UnhandledExceptionFilterAttribute"/> after the exception handler 
        /// for exceptions of type <typeparamref name="TException"/> has been removed.
        /// </returns>
        public UnhandledExceptionFilterAttribute Unregister<TException>()
            where TException : Exception
        {
            Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>> item = null;

            this.Handlers.TryRemove(typeof(TException), out item);

            return this;
        }
        #endregion
    }
}

Source code can also be found here.

Android MediaPlayer Stop and Play

I may have not got your answer correct, but you can try this:

public void MusicController(View view) throws IOException{
    switch (view.getId()){
        case R.id.play: mplayer.start();break;
        case R.id.pause: mplayer.pause(); break;
        case R.id.stop:
            if(mplayer.isPlaying()) {
                mplayer.stop();
                mplayer.prepare(); 
            }
            break;

    }// where mplayer is defined in  onCreate method}

as there is just one thread handling all, so stop() makes it die so we have to again prepare it If your intent is to start it again when your press start button(it throws IO Exception) Or for better understanding of MediaPlayer you can refer to Android Media Player

Multiple axis line chart in excel

It is possible to get both the primary and secondary axes on one side of the chart by designating the secondary axis for one of the series.

To get the primary axis on the right side with the secondary axis, you need to set to "High" the Axis Labels option in the Format Axis dialog box for the primary axis.

To get the secondary axis on the left side with the primary axis, you need to set to "Low" the Axis Labels option in the Format Axis dialog box for the secondary axis.

I know of no way to get a third set of axis labels on a single chart. You could fake in axis labels & ticks with text boxes and lines, but it would be hard to get everything aligned correctly.

The more feasible route is that suggested by zx8754: Create a second chart, turning off titles, left axes, etc. and lay it over the first chart. See my very crude mockup which hasn't been fine-tuned yet.

three axis labels chart

JavaScript DOM: Find Element Index In Container

A modern native approach could make use of 'Array.from()' - for example: `

_x000D_
_x000D_
const el = document.getElementById('get-this-index')_x000D_
const index = Array.from(document.querySelectorAll('li')).indexOf(el)_x000D_
document.querySelector('h2').textContent = `index = ${index}`
_x000D_
<ul>_x000D_
  <li>zero_x000D_
  <li>one_x000D_
  <li id='get-this-index'>two_x000D_
  <li>three_x000D_
</ul>_x000D_
<h2></h2>
_x000D_
_x000D_
_x000D_

`

How to print_r $_POST array?

Just:

foreach ( $_POST as $key => $value) {

  echo "<p>".$key."</p>";
  echo "<p>".$value."</p>";
  echo "<hr />";

} 

How to close the command line window after running a batch file?

%Started Program or Command% | taskkill /F /IM cmd.exe

Example:

notepad.exe | taskkill /F /IM cmd.exe

posting hidden value

I'm not sure what you just did there, but from what I can tell this is what you're asking for:

bookingfacilities.php

<form action="successfulbooking.php" method="post">
    <input type="hidden" name="date" value="<?php echo $date; ?>">  
    <input type="submit" value="Submit Form">
</form>

successfulbooking.php

<?php
    $date = $_POST['date'];
    // add code here
?>

Not sure what you want to do with that third page(booking_now.php) too.

Is it possible to deserialize XML into List<T>?

If you decorate the User class with the XmlType to match the required capitalization:

[XmlType("user")]
public class User
{
   ...
}

Then the XmlRootAttribute on the XmlSerializer ctor can provide the desired root and allow direct reading into List<>:

    // e.g. my test to create a file
    using (var writer = new FileStream("users.xml", FileMode.Create))
    {
        XmlSerializer ser = new XmlSerializer(typeof(List<User>),  
            new XmlRootAttribute("user_list"));
        List<User> list = new List<User>();
        list.Add(new User { Id = 1, Name = "Joe" });
        list.Add(new User { Id = 2, Name = "John" });
        list.Add(new User { Id = 3, Name = "June" });
        ser.Serialize(writer, list);
    }

...

    // read file
    List<User> users;
    using (var reader = new StreamReader("users.xml"))
    {
        XmlSerializer deserializer = new XmlSerializer(typeof(List<User>),  
            new XmlRootAttribute("user_list"));
        users = (List<User>)deserializer.Deserialize(reader);
    }

Credit: based on answer from YK1.

First letter capitalization for EditText

Statically (i.e. in your layout XML file): set android:inputType="textCapSentences" on your EditText.

Programmatically: you have to include InputType.TYPE_CLASS_TEXT in the InputType of the EditText, e.g.

EditText editor = new EditText(this); 
editor.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);

Can be combined with text and its variations to request capitalization of the first character of every sentence.

- Google Docs

Python - OpenCV - imread - Displaying Image

This can help you

namedWindow( "Display window", CV_WINDOW_AUTOSIZE );// Create a window for display.
imshow( "Display window", image );                   // Show our image inside it.

What does <> mean?

Yes, it means "not equal", either less than or greater than. e.g

If x <> y Then

can be read as

if x is less than y or x is greater than y then

The logical outcome being "If x is anything except equal to y"

Android: remove left margin from actionbar's custom layout

<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"
android:paddingLeft="0dp">

This should be good enough.

In ASP.NET, when should I use Session.Clear() rather than Session.Abandon()?

I had this issue and tried both, but had to settle for removing crap like "pageEditState", but not removing user info lest I have to look it up again.

public static void RemoveEverythingButUserInfo()
{
    foreach (String o in HttpContext.Current.Session.Keys)
    {
        if (o != "UserInfoIDontWantToAskForAgain")
            keys.Add(o);
    }
}

PHP - get base64 img string decode and save as jpg (resulting empty image )

Here's what finally worked for me. You'll have to convert the code to suit your own needs, but this will do it.

$fname = filter_input(INPUT_POST, "name");
$img = filter_input(INPUT_POST, "image");
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$img = base64_decode($img);

file_put_contents($fname, $img);

print "Image has been saved!";

PKIX path building failed: unable to find valid certification path to requested target

I had hit this when I was trying to initiate a SOAP request from Java code. What worked for me was:

  1. Get the Server certificate by hitting the URL in browser: http://docs.bvstools.com/home/ssl-documentation/exporting-certificate-authorities-cas-from-a-website This link has all the steps to get the server certificate

  2. Once you have the server certificate with you follow http://java.globinch.com/enterprise-java/security/pkix-path-building-failed-validation-sun-security-validatorexception/#Valid-Certification-Path-to-Requested-Target .

Copying the text from the link, in case this link dies:

All you need to do to fix this error is to add the server certificate to your trusted Java key store. First You need to download the document from the server.

Once you have the certificate in your hard drive you can import it to the Java trust store. To import the certificate to the trusted Java key store, you can use the java ‘keytool‘ tool. On command prompt navigate to JRE bin folder, in my case the path is : C:\Program Files\Java\jdk1.7.0_75\jre\bin . Then use keytool command as follows to import the certificate to JRE.

keytool -import -alias _alias_name_ -keystore ..\lib\security\cacerts -file _path_to_cer_file

It will ask for a password. By default the password is “changeit”. If the password is different you may not be able to import the certificate.

How to get the first day of the current week and month?

Attention!

while (calendar.get(Calendar.DAY_OF_WEEK) > calendar.getFirstDayOfWeek()) {
    calendar.add(Calendar.DATE, -1); // Substract 1 day until first day of week.
}

is good idea, but there is some issue: For example, i'm from Ukraine and calendar.getFirstDayOfWeek() in my country is 2 (Monday). And today is 1 (Sunday). In this case calendar.add not called.

So, correct way is change ">" to "!=":

while (calendar.get(Calendar.DAY_OF_WEEK) != calendar.getFirstDayOfWeek()) {...

How do I verify that a string only contains letters, numbers, underscores and dashes?

You could always use a list comprehension and check the results with all, it would be a little less resource intensive than using a regex: all([c in string.letters + string.digits + ["_", "-"] for c in mystring])

How to loop through a plain JavaScript object with the objects as members?

In my case (on the basis of the preceding) is possible any number of levels.

var myObj = {
    rrr: undefined,
    pageURL    : "BLAH",
    emailBox   : {model:"emailAddress", selector:"#emailAddress"},
    passwordBox: {model:"password"    , selector:"#password"},
    proba: {odin:{dva:"rr",trr:"tyuuu"}, od:{ff:5,ppa:{ooo:{lll:'lll'}},tyt:'12345'}}
};


function lookdeep(obj,p_Name,gg){
    var A=[], tem, wrem=[], dd=gg?wrem:A;
    for(var p in obj){
        var y1=gg?'':p_Name, y1=y1 + '.' + p;
        if(obj.hasOwnProperty(p)){
           var tem=obj[p];
           if(tem && typeof tem=='object'){
               a1=arguments.callee(tem,p_Name,true);
               if(a1 && typeof a1=='object'){for(i in a1){dd.push(y1 + a1[i])};}
            }
            else{
               dd.push(y1 + ':' + String(tem));
            }
        }
    };
    return dd
};


var s=lookdeep(myObj,'myObj',false);
for (var x=0; x < s.length; ++x) {
console.log(s[x]+'\n');}

result:

["myObj.rrr:undefined",
"myObj.pageURL:BLAH",
"myObj.emailBox.model:emailAddress",
"myObj.emailBox.selector:#emailAddress",
"myObj.passwordBox.model:password",
"myObj.passwordBox.selector:#password",
"myObj.proba.odin.dva:rr",
"myObj.proba.odin.trr:tyuuu",
"myObj.proba.od.ff:5",
"myObj.proba.od.ppa.ooo.lll:lll",
"myObj.proba.od.tyt:12345"]

How to list all installed packages and their versions in Python?

yes! you should be using pip as your python package manager ( http://pypi.python.org/pypi/pip )

with pip installed packages, you can do a

pip freeze

and it will list all installed packages. You should probably also be using virtualenv and virtualenvwrapper. When you start a new project, you can do

mkvirtualenv my_new_project

and then (inside that virtualenv), do

pip install all_your_stuff

This way, you can workon my_new_project and then pip freeze to see which packages are installed for that virtualenv/project.

for example:

?  ~  mkvirtualenv yo_dude
New python executable in yo_dude/bin/python
Installing setuptools............done.
Installing pip...............done.
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/predeactivate
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/postdeactivate
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/preactivate
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/postactivate
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/get_env_details

(yo_dude)?  ~  pip install django
Downloading/unpacking django
  Downloading Django-1.4.1.tar.gz (7.7Mb): 7.7Mb downloaded
  Running setup.py egg_info for package django

Installing collected packages: django
  Running setup.py install for django
    changing mode of build/scripts-2.7/django-admin.py from 644 to 755

    changing mode of /Users/aaylward/dev/virtualenvs/yo_dude/bin/django-admin.py to 755
Successfully installed django
Cleaning up...

(yo_dude)?  ~  pip freeze
Django==1.4.1
wsgiref==0.1.2

(yo_dude)?  ~  

or if you have a python package with a requirements.pip file,

mkvirtualenv my_awesome_project
pip install -r requirements.pip
pip freeze

will do the trick

JRE installation directory in Windows

Look the answer to my previous question here

c:\> for %i in (java.exe) do @echo.   %~$PATH:i
C:\WINDOWS\system32\java.exe

After installation of Gulp: “no command 'gulp' found”

I actually have the same issue.

This link is probably my best guess:

nodejs vs node on ubuntu 12.04

I did that to resolve my problem:

sudo apt-get --purge remove node 
sudo apt-get --purge remove nodejs 
sudo apt-get install nodejs
sudo ln -s /usr/bin/nodejs /usr/bin/node

What's the difference between tilde(~) and caret(^) in package.json?

semver is separate in to 3 major sections which is broken by dots.

major.minor.patch
1.0.0

These different major, minor and patch are using to identify different releases. tide (~) and caret (^) are using to identify which minor and patch version to be used in package versioning.

~1.0.1
 Install 1.0.1 or **latest patch versions** such as 1.0.2 ,1.0.5
^1.0.1
 Install 1.0.1 or **latest patch and minor versions** such as 1.0.2 ,1.1.0 ,1.1.1

HTML 5 Favicon - Support?

No, not all browsers support the sizes attribute:

Note that some platforms define specific sizes:

Uncaught SyntaxError: Invalid or unexpected token

The accepted answer work when you have a single line string(the email) but if you have a

multiline string, the error will remain.

Please look into this matter:

<!-- start: definition-->
@{
    dynamic item = new System.Dynamic.ExpandoObject();
    item.MultiLineString = @"a multi-line
                             string";
    item.SingleLineString = "a single-line string";
}
<!-- end: definition-->
<a href="#" onclick="Getinfo('@item.MultiLineString')">6/16/2016 2:02:29 AM</a>
<script>
    function Getinfo(text) {
        alert(text);
    }
</script>

Change the single-quote(') to backtick(`) in Getinfo as bellow and error will be fixed:

<a href="#" onclick="Getinfo(`@item.MultiLineString`)">6/16/2016 2:02:29 AM</a>

What's the difference between ISO 8601 and RFC 3339 Date Formats?

You shouldn't have to care that much. RFC 3339, according to itself, is a set of standards derived from ISO 8601. There's quite a few minute differences though, and they're all outlined in RFC 3339. I could go through them all here, but you'd probably do better just reading the document for yourself in the event you're worried:

http://tools.ietf.org/html/rfc3339

How to iterate over the keys and values with ng-repeat in AngularJS?

If you would like to edit the property value with two way binding:

<tr ng-repeat="(key, value) in data">
    <td>{{key}}<input type="text" ng-model="data[key]"></td>
</tr>

How to fix Cannot find module 'typescript' in Angular 4?

I had the same problem. If you have installed first nodejs by apt and then you use the tar.gz from nodejs.org, you have to delete the folder located in /usr/lib/node_modules.

Are HTTPS headers encrypted?

With SSL the encryption is at the transport level, so it takes place before a request is sent.

So everything in the request is encrypted.

Git checkout - switching back to HEAD

You can stash (save the changes in temporary box) then, back to master branch HEAD.

$ git add .
$ git stash
$ git checkout master

Jump Over Commits Back and Forth:

  • Go to a specific commit-sha.

      $ git checkout <commit-sha>
    
  • If you have uncommitted changes here then, you can checkout to a new branch | Add | Commit | Push the current branch to the remote.

      # checkout a new branch, add, commit, push
      $ git checkout -b <branch-name>
      $ git add .
      $ git commit -m 'Commit message'
      $ git push origin HEAD          # push the current branch to remote 
    
      $ git checkout master           # back to master branch now
    
  • If you have changes in the specific commit and don't want to keep the changes, you can do stash or reset then checkout to master (or, any other branch).

      # stash
      $ git add -A
      $ git stash
      $ git checkout master
    
      # reset
      $ git reset --hard HEAD
      $ git checkout master
    
  • After checking out a specific commit if you have no uncommitted change(s) then, just back to master or other branch.

      $ git status          # see the changes
      $ git checkout master
    
      # or, shortcut
      $ git checkout -      # back to the previous state
    

Hibernate-sequence doesn't exist

You can also put :

@GeneratedValue(strategy = GenerationType.IDENTITY)

And let the DateBase manage the incrementation of the primary key:

AUTO_INCREMENT PRIMARY KEY

The above answer helped me.

Switch php versions on commandline ubuntu 16.04

From PHP 5.6 => PHP 7.1

$ sudo a2dismod php5.6
$ sudo a2enmod php7.1

for old linux versions

 $ sudo service apache2 restart

for more recent version

$ systemctl restart apache2

How do I get a TextBox to only accept numeric input in WPF?

The following code creates a control which you will be able to use like a normal TextBox however it will only take a positive double as an input:

In the XAML you'll be able to use this control like so:

<local:UnsignedDoubleBox/>

In the C# code add the following inside the current namespace:

public class UnsignedDoubleBox : TextBox
    {
        public UnsignedDoubleBox()
        {
            this.PreviewTextInput += defaultPreviewTextInput;
            DataObject.AddPastingHandler(this, defaultTextBoxPasting);
        }

        private bool IsTextAllowed(TextBox textBox, String text)
        {
            //source: https://stackoverflow.com/questions/23397195/in-wpf-does-previewtextinput-always-give-a-single-character-only#comment89374810_23406386
            String newText = textBox.Text.Insert(textBox.CaretIndex, text);
            double res;
            return double.TryParse(newText, out res) && res >= 0;
        }
        //source: https://stackoverflow.com/a/1268648/13093413
        private void defaultTextBoxPasting(object sender, DataObjectPastingEventArgs e)
        {
            if (e.DataObject.GetDataPresent(typeof(String)))
            {
                String text = (String)e.DataObject.GetData(typeof(String));

                if (!IsTextAllowed((TextBox)sender, text))
                {
                    e.CancelCommand();
                }
            }
            else
            {
                e.CancelCommand();
            }
        }

        private void defaultPreviewTextInput(object sender, TextCompositionEventArgs e)
        {

            if (IsTextAllowed((TextBox)sender, e.Text))
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }

    }

Errno 10061 : No connection could be made because the target machine actively refused it ( client - server )

There is no relationship between error and firewall.

first, run server program,
then run client program in another shell of python

and it will work

What's the difference between identifying and non-identifying relationships?

Like well explained in the link below, an identifying relation is somewhat like a weak entity type relation to its parent in the ER conceptual model. UML style CADs for data modeling do not use ER symbols or concepts, and the kind of relations are: identifying, non-identifying and non-specific.

Identifying ones are relations parent/child where the child is kind of a weak entity (even at the traditional ER model its called identifying relationship), which does not have a real primary key by its own attributes and therefore cannot be identified uniquely by its own. Every access to the child table, on the physical model, will be dependent (inclusive semantically) on the parent's primary key, which turns into part or total of the child's primary key (also being a foreign key), generally resulting in a composite key on the child side. The eventual existing keys of the child itself are only pseudo or partial-keys, not sufficient to identify any instance of that type of Entity or Entity Set, without the parent's PK.

Non-identifying relationship are the ordinary relations (partial or total), of completely independent entity sets, whose instances do not depend on each others' primary keys to be uniquely identified, although they might need foreign keys for partial or total relationships, but not as the primary key of the child. The child has its own primary key. The parent idem. Both independently. Depending on the cardinality of the relationship, the PK of one goes as a FK to the other (N side), and if partial, can be null, if total, must be not null. But, at a relationship like this, the FK will never be also the PK of the child, as when an identifying relationship is the case.

http://docwiki.embarcadero.com/ERStudioDA/XE7/en/Creating_and_Editing_Relationships

array_push() with key value pair

If you need to add multiple key=>value, then try this.

$data = array_merge($data, array("cat"=>"wagon","foo"=>"baar"));

Configure Log4Net in web application

I also had the similar issue. Logs were not creating.

Please check logger attribute name should match with your LogManager.GetLogger("name")

<logger name="Mylog">
      <level value="All"></level>
      <appender-ref ref="RollingLogFileAppender" />
    </logger>



private static readonly ILog Log = LogManager.GetLogger("Mylog");

Cross-browser custom styling for file upload button

I just came across this problem and have written a solution for those of you who are using Angular. You can write a custom directive composed of a container, a button, and an input element with type file. With CSS you then place the input over the custom button but with opacity 0. You set the containers height and width to exactly the offset width and height of the button and the input's height and width to 100% of the container.

the directive

angular.module('myCoolApp')
  .directive('fileButton', function () {
    return {
      templateUrl: 'components/directives/fileButton/fileButton.html',
      restrict: 'E',
      link: function (scope, element, attributes) {

        var container = angular.element('.file-upload-container');
        var button = angular.element('.file-upload-button');

        container.css({
            position: 'relative',
            overflow: 'hidden',
            width: button.offsetWidth,
            height: button.offsetHeight
        })

      }

    };
  });

a jade template if you are using jade

div(class="file-upload-container") 
    button(class="file-upload-button") +
    input#file-upload(class="file-upload-input", type='file', onchange="doSomethingWhenFileIsSelected()")  

the same template in html if you are using html

<div class="file-upload-container">
   <button class="file-upload-button"></button>
   <input class="file-upload-input" id="file-upload" type="file" onchange="doSomethingWhenFileIsSelected()" /> 
</div>

the css

.file-upload-button {
    margin-top: 40px;
    padding: 30px;
    border: 1px solid black;
    height: 100px;
    width: 100px;
    background: transparent;
    font-size: 66px;
    padding-top: 0px;
    border-radius: 5px;
    border: 2px solid rgb(255, 228, 0); 
    color: rgb(255, 228, 0);
}

.file-upload-input {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 2;
    width: 100%;
    height: 100%;
    opacity: 0;
    cursor: pointer;
}

How to kill all processes matching a name?

Maybe adding the commands to executable file, setting +x permission and then executing?

ps aux | grep -ie amarok | awk '{print "kill -9 " $2}' > pk;chmod +x pk;./pk;rm pk

How to debug ORA-01775: looping chain of synonyms?

While Jarrod's answer is a good idea, and catches a broader range of related problems, I found this query found in Oracle forums to more directly address the (originally stated) issue:

select owner, synonym_name, connect_by_iscycle CYCLE
from dba_synonyms
where connect_by_iscycle > 0
connect by nocycle prior table_name = synonym_name
and prior table_owner = owner
union
select 'PUBLIC', synonym_name, 1
from dba_synonyms
where owner = 'PUBLIC'
and table_name = synonym_name
and (table_name, table_owner) not in (select object_name, owner from dba_objects
where object_type != 'SYNONYM')

https://community.oracle.com/message/4176300#4176300

You will not have to wade through other kinds of invalid objects. Just those that are actually in endless loops.

How to add Class in <li> using wp_nav_menu() in Wordpress?

I added a class to easily implement menu arguments. So you can customize and include in your function like this:

include_once get_template_directory() . DIRECTORY_SEPARATOR . "your-directory" . DIRECTORY_SEPARATOR . "Menu.php";

<?php $menu = (new Menu('your-theme-location'))
            ->setMenuClass('your-menu')
            ->setMenuID('your-menu-id')
            ->setListClass('your-menu-class')
            ->setLinkClass('your-menu-link anchor') ?>
    
            // Print your menu
            <?php $menu->showMenu() ?>
<?php

class Menu
{
    private $args = [
        'theme_location' => '',
        'container' => '',
        'menu_id' => '',
        'menu_class' => '',
        'add_li_class' => '',
        'link_class' => ''
    ];

    public function __construct($themeLocation)
    {
        add_filter('nav_menu_css_class', [$this,'add_additional_class_on_li'], 1, 3);
        add_filter( 'nav_menu_link_attributes', [$this,'add_menu_link_class'], 1, 3 );

        $this->args['theme_location'] = $themeLocation;
    }

    public function wrapWithTag($tagName){
        $this->args['container'] = $tagName;
        return $this;
    }

    public function setMenuID($id)
    {
        $this->args['menu_id'] = $id;
        return $this;
    }

    public function setMenuClass($class)
    {
        $this->args['menu_class'] = $class;
        return $this;
    }

    public function setListClass($class)
    {
        $this->args['add_li_class'] = $class;
        return $this;
    }

    public function setLinkClass($class)
    {
        $this->args['link_class'] = $class;
        return $this;
    }

    public function showMenu()
    {
        return wp_nav_menu($this->args);
    }

    function add_additional_class_on_li($classes, $item, $args) {
        if(isset($args->add_li_class)) {
            $classes[] = $args->add_li_class;
        }
        return $classes;
    }

    function add_menu_link_class( $atts, $item, $args ) {
        if (property_exists($args, 'link_class')) {
            $atts['class'] = $args->link_class;
        }
        return $atts;
    }
}

How to solve "Fatal error: Class 'MySQLi' not found"?

<?php  /* If the error is due to calling mysqli in a class */

    class dbconnect extends mysqli{

        private $host = 'localhost';
        private $user = 'root';
        private $pass = '';
        private $db = 'test';

        public function __construct() {
            parent::__construct($this->host, $this->user, $this->pass, $this->db);

            if (mysqli_connect_error()) {
                die('Connect Error (' . mysqli_connect_errno() . ') ' .
                    mysqli_connect_error());
            }
        }
    }
?>

Select multiple rows with the same value(s)

The problem is GROUP BY - if you group results by Locus, you only get one result per locus.

Try:

SELECT * FROM Genes WHERE Locus = '3' AND Chromosome = '10';

If you prefer using HAVING syntax, then GROUP BY id or something that is not repeating in the result set.

Pass parameters in setInterval function

You can pass the parameter(s) as a property of the function object, not as a parameter:

var f = this.someFunction;  //use 'this' if called from class
f.parameter1 = obj;
f.parameter2 = this;
f.parameter3 = whatever;
setInterval(f, 1000);

Then in your function someFunction, you will have access to the parameters. This is particularly useful inside classes where the scope goes to the global space automatically and you lose references to the class that called setInterval to begin with. With this approach, "parameter2" in "someFunction", in the example above, will have the right scope.

Taking inputs with BufferedReader in Java

The problem id because of inp.read(); method. Its return single character at a time and because you are storing it into int type of array so that is just storing ascii value of that.

What you can do simply

for(int i=0;i<T;i++) {
    String s= inp.readLine();
    String[] intValues = inp.readLine().split(" ");
    int[] m= new int[2];
    m[0]=Integer.parseInt(intValues[0]);
    m[1]=Integer.parseInt(intValues[1]);

    // Checking whether I am taking the inputs correctly
    System.out.println(s);
    System.out.println(m[0]);
    System.out.println(m[1]);
}

Error handling in Bash

Use a trap!

tempfiles=( )
cleanup() {
  rm -f "${tempfiles[@]}"
}
trap cleanup 0

error() {
  local parent_lineno="$1"
  local message="$2"
  local code="${3:-1}"
  if [[ -n "$message" ]] ; then
    echo "Error on or near line ${parent_lineno}: ${message}; exiting with status ${code}"
  else
    echo "Error on or near line ${parent_lineno}; exiting with status ${code}"
  fi
  exit "${code}"
}
trap 'error ${LINENO}' ERR

...then, whenever you create a temporary file:

temp_foo="$(mktemp -t foobar.XXXXXX)"
tempfiles+=( "$temp_foo" )

and $temp_foo will be deleted on exit, and the current line number will be printed. (set -e will likewise give you exit-on-error behavior, though it comes with serious caveats and weakens code's predictability and portability).

You can either let the trap call error for you (in which case it uses the default exit code of 1 and no message) or call it yourself and provide explicit values; for instance:

error ${LINENO} "the foobar failed" 2

will exit with status 2, and give an explicit message.

Receiving JSON data back from HTTP request

If you are referring to the System.Net.HttpClient in .NET 4.5, you can get the content returned by GetAsync using the HttpResponseMessage.Content property as an HttpContent-derived object. You can then read the contents to a string using the HttpContent.ReadAsStringAsync method or as a stream using the ReadAsStreamAsync method.

The HttpClient class documentation includes this example:

  HttpClient client = new HttpClient();
  HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");
  response.EnsureSuccessStatusCode();
  string responseBody = await response.Content.ReadAsStringAsync();

Hidden TextArea

An <input type=hidden> element is not a hidden input box. It is simply a form field that has a value set via markup or via scripting, not via user input. You can use it for multi-line data too, e.g.

<input type=hidden name=stuff value=
"Hello
world, how
are you?">

If the value contains the Ascii quotation mark ("), then, as for any HTML attribute, you need to use Ascii apostrophes (') as attribute value delimites or escape the quote as &quot;, e.g.

<input type=hidden name=stuff value="A &quot;funny&quot; example">

How to get hostname from IP (Linux)?

To find a hostname in your local network by IP address you can use:

nmblookup -A <ip>

To find a hostname on the internet you could use the host program:

host <ip>

Or you can install nbtscan by running:

sudo apt-get install nbtscan

And use:

nbtscan <ip>

*Taken from https://askubuntu.com/questions/205063/command-to-get-the-hostname-of-remote-server-using-ip-address/205067#205067

Update 2018-05-13

You can query a name server with nslookup. It works both ways!

nslookup <IP>
nslookup <hostname>

java howto ArrayList push, pop, shift, and unshift

maybe you want to take a look java.util.Stack class. it has push, pop methods. and implemented List interface.

for shift/unshift, you can reference @Jon's answer.

however, something of ArrayList you may want to care about , arrayList is not synchronized. but Stack is. (sub-class of Vector). If you have thread-safe requirement, Stack may be better than ArrayList.

How to get the date 7 days earlier date from current date in Java

For all date related functionality, you should consider using Joda Library. Java's date api's are very poorly designed. Joda provides very nice API.

"Input string was not in a correct format."

You have not mentioned if your textbox have values in design time or now. When form initializes text box may not hae value if you have not put it in textbox when during form design. you can put int value in form design by setting text property in desgin and this should work.

Powershell Log Off Remote Session

You can use Invoke-RDUserLogoff

An example logging off Active Directory users of a specific Organizational Unit:

$users = Get-ADUser -filter * -SearchBase "ou=YOUR_OU_NAME,dc=contoso,dc=com"

Get-RDUserSession | where { $users.sAMAccountName -contains $_.UserName } | % { $_ | Invoke-RDUserLogoff -Force }

At the end of the pipe, if you try to use only foreach (%), it will log off only one user. But using this combination of foreach and pipe:

| % { $_ | command }

will work as expected.

Ps. Run as Adm.

Get UserDetails object from Security Context in Spring MVC controller

If you already know for sure that the user is logged in (in your example if /index.html is protected):

UserDetails userDetails =
 (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();

To first check if the user is logged in, check that the current Authentication is not a AnonymousAuthenticationToken.

Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (!(auth instanceof AnonymousAuthenticationToken)) {
        // userDetails = auth.getPrincipal()
}

Loop structure inside gnuplot?

There sure is (in gnuplot 4.4+):

plot for [i=1:1000] 'data'.i.'.txt' using 1:2 title 'Flow '.i

The variable i can be interpreted as a variable or a string, so you could do something like

plot for [i=1:1000] 'data'.i.'.txt' using 1:($2+i) title 'Flow '.i

if you want to have lines offset from each other.

Type help iteration at the gnuplot command line for more info.

Also be sure to see @DarioP's answer about the do for syntax; that gives you something closer to a traditional for loop.

Eclipse/Maven error: "No compiler is provided in this environment"

I tried all the things; the one that worked for me is:

  1. Right click on Eclipse project and navigate to properties.
  2. Click on Java Build Path and go to the Libraries tab.
  3. Check which version of Java is added there; is it JRE or JDK?
  4. If you are using Maven project and want to build a solution.
  5. Select the JRE added their and click remove.
  6. Click Add external class folder and add the JDK install by selecting from the system.
  7. Click Apply and OK.
  8. Restart Eclipse.
  9. Build succeeded.

Kotlin - How to correctly concatenate a String

String Templates/Interpolation

In Kotlin, you can concatenate using String interpolation/templates:

val a = "Hello"
val b = "World"
val c = "$a $b"

The output will be: Hello World

Or you can concatenate using the StringBuilder explicitly.

val a = "Hello"
val b = "World"

val sb = StringBuilder()
sb.append(a).append(b)
val c = sb.toString()

print(c)

The output will be: HelloWorld

New String Object

Or you can concatenate using the + / plus() operator:

val a = "Hello"
val b = "World"
val c = a + b   // same as calling operator function a.plus(b)

print(c)

The output will be: HelloWorld

  • This will create a new String object.

How to send a “multipart/form-data” POST in Android with Volley

A very simple approach for the dev who just want to send POST parameters in multipart request.

Make the following changes in class which extends Request.java

First define these constants :

String BOUNDARY = "s2retfgsGSRFsERFGHfgdfgw734yhFHW567TYHSrf4yarg"; //This the boundary which is used by the server to split the post parameters.
String MULTIPART_FORMDATA = "multipart/form-data;boundary=" + BOUNDARY;

Add a helper function to create a post body for you :

private String createPostBody(Map<String, String> params) {
        StringBuilder sbPost = new StringBuilder();
        if (params != null) {
            for (String key : params.keySet()) {
                if (params.get(key) != null) {
                    sbPost.append("\r\n" + "--" + BOUNDARY + "\r\n");
                    sbPost.append("Content-Disposition: form-data; name=\"" + key + "\"" + "\r\n\r\n");
                    sbPost.append(params.get(key).toString());
                }
            }
        }
        return sbPost.toString();
    } 

Override getBody() and getBodyContentType

public String getBodyContentType() {
    return MULTIPART_FORMDATA;
}

public byte[] getBody() throws AuthFailureError {
        return createPostBody(getParams()).getBytes();
}

How do I run a Java program from the command line on Windows?

Source: javaindos.

Let's say your file is in C:\mywork\

Run Command Prompt

C:\> cd \mywork

This makes C:\mywork the current directory.

C:\mywork> dir

This displays the directory contents. You should see filenamehere.java among the files.

C:\mywork> set path=%path%;C:\Program Files\Java\jdk1.5.0_09\bin

This tells the system where to find JDK programs.

C:\mywork> javac filenamehere.java

This runs javac.exe, the compiler. You should see nothing but the next system prompt...

C:\mywork> dir

javac has created the filenamehere.class file. You should see filenamehere.java and filenamehere.class among the files.

C:\mywork> java filenamehere

This runs the Java interpreter. You should then see your program output.

If the system cannot find javac, check the set path command. If javac runs but you get errors, check your Java text. If the program compiles but you get an exception, check the spelling and capitalization in the file name and the class name and the java HelloWorld command. Java is case-sensitive!

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.

How to programmatically move, copy and delete files and directories on SD?

To move a file this api can be used but you need atleat 26 as api level -

move file

But if you want to move directory no support is there so this native code can be used

    import org.apache.commons.io.FileUtils;

    import java.io.IOException;
    import java.io.File;

    public class FileModule {

    public void moveDirectory(String src, String des) {
    File srcDir = new File(src);
    File destDir = new File(des);
     try {
        FileUtils.moveDirectory(srcDir,destDir);
    } catch (Exception e) {
      Log.e("Exception" , e.toString());
      }
    }

    public void deleteDirectory(String dir) {
      File delDir = new File(dir);
      try {
        FileUtils.deleteDirectory(delDir);
       } catch (IOException e) {
      Log.e("Exception" , e.toString());
      }
     }
    }

bool to int conversion

There seems to be no problem since the int to bool cast is done implicitly. This works in Microsoft Visual C++, GCC and Intel C++ compiler. No problem in either C or C++.

Stacked bar chart

You will need to melt your dataframe to get it into the so-called long format:

require(reshape2)
sample.data.M <- melt(sample.data)

Now your field values are represented by their own rows and identified through the variable column. This can now be leveraged within the ggplot aesthetics:

require(ggplot2)
c <- ggplot(sample.data.M, aes(x = Rank, y = value, fill = variable))
c + geom_bar(stat = "identity")

Instead of stacking you may also be interested in showing multiple plots using facets:

c <- ggplot(sample.data.M, aes(x = Rank, y = value))
c + facet_wrap(~ variable) + geom_bar(stat = "identity")

iptables LOG and DROP in one rule

nflog is better

sudo apt-get -y install ulogd2

ICMP Block rule example:

iptables=/sbin/iptables
# Drop ICMP (PING)
$iptables -t mangle -A PREROUTING -p icmp -j NFLOG --nflog-prefix 'ICMP Block'
$iptables -t mangle -A PREROUTING -p icmp -j DROP

And you can search prefix "ICMP Block" in log:

/var/log/ulog/syslogemu.log

How to insert text at beginning of a multi-line selection in vi/Vim

To insert "ABC" at the begining of each line:

1) Go to command mode

2) :% norm I ABC

Set default time in bootstrap-datetimepicker

I solved my problem like this

$('#startdatetime-from').datetimepicker({
language: 'en',
format: 'yyyy-MM-dd hh:mm',
defaultDate:new Date()
});

Does Index of Array Exist

Assuming you also want to check if the item is not null

if (array.Length > 25 && array[25] != null)
{
    //it exists
}

Executing a command stored in a variable from PowerShell

Try invoking your command with Invoke-Expression:

Invoke-Expression $cmd1

Here is a working example on my machine:

$cmd = "& 'C:\Program Files\7-zip\7z.exe' a -tzip c:\temp\test.zip c:\temp\test.txt"
Invoke-Expression $cmd

iex is an alias for Invoke-Expression so you could do:

iex $cmd1

For a full list : Visit https://ss64.com/ps/ for more Powershell stuff.

Good Luck...

How to convert a 3D point into 2D perspective projection?

You can project 3D point in 2D using: Commons Math: The Apache Commons Mathematics Library with just two classes.

Example for Java Swing.

import org.apache.commons.math3.geometry.euclidean.threed.Plane;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;


Plane planeX = new Plane(new Vector3D(1, 0, 0));
Plane planeY = new Plane(new Vector3D(0, 1, 0)); // Must be orthogonal plane of planeX

void drawPoint(Graphics2D g2, Vector3D v) {
    g2.drawLine(0, 0,
            (int) (world.unit * planeX.getOffset(v)),
            (int) (world.unit * planeY.getOffset(v)));
}

protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    drawPoint(g2, new Vector3D(2, 1, 0));
    drawPoint(g2, new Vector3D(0, 2, 0));
    drawPoint(g2, new Vector3D(0, 0, 2));
    drawPoint(g2, new Vector3D(1, 1, 1));
}

Now you only needs update the planeX and planeY to change the perspective-projection, to get things like this:

enter image description hereenter image description here

How do I exit a while loop in Java?

if you write while(true). its means that loop will not stop in any situation for stop this loop you have to use break statement between while block.

package com.java.demo;

/**
 * @author Ankit Sood Apr 20, 2017
 */
public class Demo {

    /**
     * The main method.
     *
     * @param args
     *            the arguments
     */
    public static void main(String[] args) {
        /* Initialize while loop */
        while (true) {
            /*
            * You have to declare some condition to stop while loop 

            * In which situation or condition you want to terminate while loop.
            * conditions like: if(condition){break}, if(var==10){break} etc... 
            */

            /* break keyword is for stop while loop */

            break;
        }
    }
}

How to view the dependency tree of a given npm module?

Here is the unpowerful official command:

npm view <PACKAGE> dependencies

It prints only the direct dependencies, not the whole tree.

jQuery UI Slider (setting programmatically)

For me this perfectly triggers slide event on UI Slider :

hs=$('#height_slider').slider();
hs.slider('option', 'value',h);
hs.slider('option','slide')
       .call(hs,null,{ handle: $('.ui-slider-handle', hs), value: h });

Don't forget to set value by hs.slider('option', 'value',h); before the trigger. Else slider handler will not be in sync with value.

One thing to note here is that h is index/position (not value) in case you are using html select.

Which is the preferred way to concatenate a string in Python?

You can do in different ways.

str1 = "Hello"
str2 = "World"
str_list = ['Hello', 'World']
str_dict = {'str1': 'Hello', 'str2': 'World'}

# Concatenating With the + Operator
print(str1 + ' ' + str2)  # Hello World

# String Formatting with the % Operator
print("%s %s" % (str1, str2))  # Hello World

# String Formatting with the { } Operators with str.format()
print("{}{}".format(str1, str2))  # Hello World
print("{0}{1}".format(str1, str2))  # Hello World
print("{str1} {str2}".format(str1=str_dict['str1'], str2=str_dict['str2']))  # Hello World
print("{str1} {str2}".format(**str_dict))  # Hello World

# Going From a List to a String in Python With .join()
print(' '.join(str_list))  # Hello World

# Python f'strings --> 3.6 onwards
print(f"{str1} {str2}")  # Hello World

I created this little summary through following articles.

DTO and DAO concepts and MVC

DTO is an abbreviation for Data Transfer Object, so it is used to transfer the data between classes and modules of your application.

  • DTO should only contain private fields for your data, getters, setters, and constructors.
  • DTO is not recommended to add business logic methods to such classes, but it is OK to add some util methods.

DAO is an abbreviation for Data Access Object, so it should encapsulate the logic for retrieving, saving and updating data in your data storage (a database, a file-system, whatever).

Here is an example of how the DAO and DTO interfaces would look like:

interface PersonDTO {
    String getName();
    void setName(String name);
    //.....
}

interface PersonDAO {
    PersonDTO findById(long id);
    void save(PersonDTO person);
    //.....
}

The MVC is a wider pattern. The DTO/DAO would be your model in the MVC pattern.
It tells you how to organize the whole application, not just the part responsible for data retrieval.

As for the second question, if you have a small application it is completely OK, however, if you want to follow the MVC pattern it would be better to have a separate controller, which would contain the business logic for your frame in a separate class and dispatch messages to this controller from the event handlers.
This would separate your business logic from the view.

What is the easiest way to parse an INI File in C++?

Maybe a late answer..But, worth knowing options..If you need a cross-platform solution , definitely you can try GLIB,, its interesting.. (https://developer.gnome.org/glib/stable/glib-Key-value-file-parser.html)

Disable same origin policy in Chrome

If you use your web server, you ca use Header

On Apache <VirtualHost> or in an .htaccess file.

Header set Access-Control-Allow-Origin 'origin-list'

On Nginx

add_header 'Access-Control-Allow-Origin' 'origin-list'

jQuery: serialize() form and other parameters

I fix the problem with under statement ; send data with url same GET methode

$.ajax({
    url: 'includes/get_ajax_function.php?value=jack&id='+id,
    type: 'post',
    data: $('#b-info1').serializeArray(),

and get value with $_REQUEST['value'] OR $_GET['id']

JAVA How to remove trailing zeros from a double

You should use DecimalFormat("0.#")


For 4.3000

Double price = 4.3000;
DecimalFormat format = new DecimalFormat("0.#");
System.out.println(format.format(price));

output is:

4.3

In case of 5.000 we have

Double price = 5.000;
DecimalFormat format = new DecimalFormat("0.#");
System.out.println(format.format(price));

And the output is:

5

Bash script prints "Command Not Found" on empty lines

This might be trivial and not related to the OP's question, but I often made this mistaken at the beginning when I was learning scripting

VAR_NAME = $(hostname)
echo "the hostname is ${VAR_NAME}"  

This will produce 'command not found' response. The correct way is to eliminate the spaces

VAR_NAME=$(hostname)

What is a .NET developer?

Generally what's meant by that is a fairly intimate familiarity with one (or probably more) of the .NET languages (C#, VB.NET, etc.) and one (or less probably more) of the .NET stacks (WinForms, ASP.NET, WPF, etc.).

As for a specific "formal definition", I don't think you'll find one beyond that. The job description should be specific about what they're looking for. I wouldn't consider a job listing that asks for a ".NET developer" and provides no more detail than that to be sufficiently descriptive.

See whether an item appears more than once in a database column

To expand on Solomon Rutzky's answer, if you are looking for a piece of data that shows up in a range (i.e. more than once but less than 5x), you can use

having count(*) > 1 and count(*) < 5

And you can use whatever qualifiers you desire in there - they don't have to match, it's all just included in the 'having' statement. https://webcheatsheet.com/sql/interactive_sql_tutorial/sql_having.php

Retrofit 2: Get JSON from Response body

use this

response.body().get(0).getUsername().toString();

Git: How to check if a local repo is up to date?

You must run git fetch before you can compare your local repository against the files on your remote server.

This command only updates your remote tracking branches and will not affect your worktree until you call git merge or git pull.

To see the difference between your local branch and your remote tracking branch once you've fetched you can use git diff or git cherry as explained here.

How do I create directory if it doesn't exist to create a file?

You can use File.Exists to check if the file exists and create it using File.Create if required. Make sure you check if you have access to create files at that location.

Once you are certain that the file exists, you can write to it safely. Though as a precaution, you should put your code into a try...catch block and catch for the exceptions that function is likely to raise if things don't go exactly as planned.

Additional information for basic file I/O concepts.

ORDER BY using Criteria API

You need to create an alias for the mother.kind. You do this like so.

Criteria c = session.createCriteria(Cat.class);
c.createAlias("mother.kind", "motherKind");
c.addOrder(Order.asc("motherKind.value"));
return c.list();

How to check if a character in a string is a digit or letter

     char temp = yourString.charAt(0);
     if(Character.isDigit(temp))
     {
         ..........
     }else if (Character.isLetter(temp))
     {
          ......
      }else
     {
      ....
     }

How do I sort a list of datetime or date objects?

You're getting None because list.sort() it operates in-place, meaning that it doesn't return anything, but modifies the list itself. You only need to call a.sort() without assigning it to a again.

There is a built in function sorted(), which returns a sorted version of the list - a = sorted(a) will do what you want as well.

How to check for Is not Null And Is not Empty string in SQL server?

Coalesce will fold nulls into a default:

COALESCE (fieldName, '') <> ''

Index inside map() function

Array.prototype.map() index:

One can access the index Array.prototype.map() via the second argument of the callback function. Here is an example:

_x000D_
_x000D_
const array = [1, 2, 3, 4];_x000D_
_x000D_
_x000D_
const map = array.map((x, index) => {_x000D_
  console.log(index);_x000D_
  return x + index;_x000D_
});_x000D_
_x000D_
console.log(map);
_x000D_
_x000D_
_x000D_

Other arguments of Array.prototype.map():

  • The third argument of the callback function exposes the array on which map was called upon
  • The second argument of Array.map() is a object which will be the this value for the callback function. Keep in mind that you have to use the regular function keyword in order to declare the callback since an arrow function doesn't have its own binding to the this keyword.

For example:

_x000D_
_x000D_
const array = [1, 2, 3, 4];_x000D_
_x000D_
const thisObj = {prop1: 1}_x000D_
_x000D_
_x000D_
const map = array.map( function (x, index, array) {_x000D_
  console.log(array);_x000D_
  console.log(this)_x000D_
}, thisObj);
_x000D_
_x000D_
_x000D_

How to write header row with csv.DictWriter?

Edit:
In 2.7 / 3.2 there is a new writeheader() method. Also, John Machin's answer provides a simpler method of writing the header row.
Simple example of using the writeheader() method now available in 2.7 / 3.2:

from collections import OrderedDict
ordered_fieldnames = OrderedDict([('field1',None),('field2',None)])
with open(outfile,'wb') as fou:
    dw = csv.DictWriter(fou, delimiter='\t', fieldnames=ordered_fieldnames)
    dw.writeheader()
    # continue on to write data

Instantiating DictWriter requires a fieldnames argument.
From the documentation:

The fieldnames parameter identifies the order in which values in the dictionary passed to the writerow() method are written to the csvfile.

Put another way: The Fieldnames argument is required because Python dicts are inherently unordered.
Below is an example of how you'd write the header and data to a file.
Note: with statement was added in 2.6. If using 2.5: from __future__ import with_statement

with open(infile,'rb') as fin:
    dr = csv.DictReader(fin, delimiter='\t')

# dr.fieldnames contains values from first row of `f`.
with open(outfile,'wb') as fou:
    dw = csv.DictWriter(fou, delimiter='\t', fieldnames=dr.fieldnames)
    headers = {} 
    for n in dw.fieldnames:
        headers[n] = n
    dw.writerow(headers)
    for row in dr:
        dw.writerow(row)

As @FM mentions in a comment, you can condense header-writing to a one-liner, e.g.:

with open(outfile,'wb') as fou:
    dw = csv.DictWriter(fou, delimiter='\t', fieldnames=dr.fieldnames)
    dw.writerow(dict((fn,fn) for fn in dr.fieldnames))
    for row in dr:
        dw.writerow(row)

What is the best way to create and populate a numbers table?

Some of the suggested methods are basing on system objects (for example on the 'sys.objects'). They are assuming these system objects contain enough records to generate our numbers.

I would not base on anything which does not belong to my application and over which I do not have full control. For example: the content of these sys tables may change, the tables may not be valid anymore in new version of SQL etc.

As a solution, we can create our own table with records. We then use that one instead these system related objects (table with all numbers should be fine if we know the range in advance otherwise we could go for the one to do the cross join on).

The CTE based solution is working fine but it has limits related to the nested loops.

How to insert new cell into UITableView in Swift

Here is your code for add data into both tableView:

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var table1Text: UITextField!
    @IBOutlet weak var table2Text: UITextField!
    @IBOutlet weak var table1: UITableView!
    @IBOutlet weak var table2: UITableView!

    var table1Data = ["a"]
    var table2Data = ["1"]

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    @IBAction func addData(sender: AnyObject) {

        //add your data into tables array from textField
        table1Data.append(table1Text.text)
        table2Data.append(table2Text.text)

        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            //reload your tableView
            self.table1.reloadData()
            self.table2.reloadData()
        })


        table1Text.resignFirstResponder()
        table2Text.resignFirstResponder()
    }

    //delegate methods
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableView == table1 {
            return table1Data.count
        }else if tableView == table2 {
            return table2Data.count
        }
        return Int()
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        if tableView == table1 {
            let cell = table1.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell

            let row = indexPath.row
            cell.textLabel?.text = table1Data[row]

            return cell
        }else if tableView == table2 {

            let cell = table2.dequeueReusableCellWithIdentifier("Cell1", forIndexPath: indexPath) as! UITableViewCell

            let row = indexPath.row
            cell.textLabel?.text = table2Data[row]

            return cell
        }

        return UITableViewCell()
    }
}

And your result will be:

enter image description here

Why does pycharm propose to change method to static

Rather than implementing another method just to work around this error in a particular IDE, does the following make sense? PyCharm doesn't suggest anything with this implementation.

class Animal:
    def __init__(self):
        print("Animal created")

    def eat(self):
        not self # <-- This line here
        print("I am eating")


my_animal = Animal()

How to keep an iPhone app running on background fully operational

For running on stock iOS devices, make your app an audio player/recorder or a VOIP app, a legitimate one for submitting to the App store, or a fake one if only for your own use.

Even this won't make an app "fully operational" whatever that is, but restricted to limited APIs.

What is an opaque response, and what purpose does it serve?

javascript is a bit tricky getting the answer, I fixed it by getting the api from the backend and then calling it to the frontend.

public function get_typechange () {

    $ url = "https://........";
    $ json = file_get_contents ($url);
    $ data = json_decode ($ json, true);
    $ resp = json_encode ($data);
    $ error = json_last_error_msg ();
    return $ resp;

}

How to save select query results within temporary table?

In Sqlite:

CREATE TABLE T AS
SELECT * FROM ...;
-- Use temporary table `T`
DROP TABLE T;

How to declare a global variable in JavaScript

If you have to generate global variables in production code (which should be avoided) always declare them explicitly:

window.globalVar = "This is global!";

While it is possible to define a global variable by just omitting var (assuming there is no local variable of the same name), doing so generates an implicit global, which is a bad thing to do and would generate an error in strict mode.

HTML table sort

Another approach to sort HTML table. (based on W3.JS HTML Sort)

_x000D_
_x000D_
let tid = "#usersTable";_x000D_
let headers = document.querySelectorAll(tid + " th");_x000D_
_x000D_
// Sort the table element when clicking on the table headers_x000D_
headers.forEach(function(element, i) {_x000D_
  element.addEventListener("click", function() {_x000D_
    w3.sortHTML(tid, ".item", "td:nth-child(" + (i + 1) + ")");_x000D_
  });_x000D_
});
_x000D_
th {_x000D_
  cursor: pointer;_x000D_
  background-color: coral;_x000D_
}
_x000D_
<script src="https://www.w3schools.com/lib/w3.js"></script>_x000D_
<link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet" />_x000D_
<p>Click the <strong>table headers</strong> to sort the table accordingly:</p>_x000D_
_x000D_
<table id="usersTable" class="w3-table-all">_x000D_
  <!--     _x000D_
  <tr>_x000D_
    <th onclick="w3.sortHTML('#usersTable', '.item', 'td:nth-child(1)')">Name</th>_x000D_
    <th onclick="w3.sortHTML('#usersTable', '.item', 'td:nth-child(2)')">Address</th>_x000D_
    <th onclick="w3.sortHTML('#usersTable', '.item', 'td:nth-child(3)')">Sales Person</th>_x000D_
  </tr> _x000D_
  -->_x000D_
  <tr>_x000D_
    <th>Name</th>_x000D_
    <th>Address</th>_x000D_
    <th>Sales Person</th>_x000D_
  </tr>_x000D_
_x000D_
  <tr class="item">_x000D_
    <td>user:2911002</td>_x000D_
    <td>UK</td>_x000D_
    <td>Melissa</td>_x000D_
  </tr>_x000D_
  <tr class="item">_x000D_
    <td>user:2201002</td>_x000D_
    <td>France</td>_x000D_
    <td>Justin</td>_x000D_
  </tr>_x000D_
  <tr class="item">_x000D_
    <td>user:2901092</td>_x000D_
    <td>San Francisco</td>_x000D_
    <td>Judy</td>_x000D_
  </tr>_x000D_
  <tr class="item">_x000D_
    <td>user:2801002</td>_x000D_
    <td>Canada</td>_x000D_
    <td>Skipper</td>_x000D_
  </tr>_x000D_
  <tr class="item">_x000D_
    <td>user:2901009</td>_x000D_
    <td>Christchurch</td>_x000D_
    <td>Alex</td>_x000D_
  </tr>_x000D_
_x000D_
</table>
_x000D_
_x000D_
_x000D_

Row count with PDO

When it is matter of mysql how to count or get how many rows in a table with PHP PDO I use this

// count total number of rows
$query = "SELECT COUNT(*) as total_rows FROM sometable";
$stmt = $con->prepare($query);

// execute query
$stmt->execute();

// get total rows
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$total_rows = $row['total_rows'];

credits goes to Mike @ codeofaninja.com

How do you calculate the variance, median, and standard deviation in C++ or Java?

To calculate the mean, loop through the list/array of numbers, keeping track of the partial sums and the length. Then return the sum/length.

double sum = 0.0;
int length = 0;

for( double number : numbers ) {
    sum += number;
    length++;
}

return sum/length;

Variance is calculated similarly. Standard deviation is simply the square root of the variance:

double stddev = Math.sqrt( variance );

When should an IllegalArgumentException be thrown?

The API doc for IllegalArgumentException:

Thrown to indicate that a method has been passed an illegal or inappropriate argument.

From looking at how it is used in the JDK libraries, I would say:

  • It seems like a defensive measure to complain about obviously bad input before the input can get into the works and cause something to fail halfway through with a nonsensical error message.

  • It's used for cases where it would be too annoying to throw a checked exception (although it makes an appearance in the java.lang.reflect code, where concern about ridiculous levels of checked-exception-throwing is not otherwise apparent).

I would use IllegalArgumentException to do last ditch defensive argument checking for common utilities (trying to stay consistent with the JDK usage). Or where the expectation is that a bad argument is a programmer error, similar to an NullPointerException. I wouldn't use it to implement validation in business code. I certainly wouldn't use it for the email example.

How to clear cache of Eclipse Indigo

You can always create a new Eclipse workspace. The Eclipse.exe -clean option is not sufficient in some cases, for example, if the local history becomes a problem.

Edit:

Eclipse is mostly a collection of third party plugins. And each of those plugins can add some extra useful, useless or problematic information to the central Eclipse workspace meta-data folder.

The problem is that not every plugin participates during the user-issued cleanup routine. Therefore, I'd say that it is a problem in the system design of Eclipse, that it allows plugins to misbehave like this.

And therefore, I'd recommend to make yourself comfortable with the idea of using multiple workspaces and linking-in external project entities into each workspace. Because, this is the only workaround for the given system design, to handle faulty plugins that spam your workspace.

Sending email from Command-line via outlook without having to click send

Option 1
You didn't say much about your environment, but assuming you have it available you could use a PowerShell script; one example is here. The essence of this is:

$smtp = New-Object Net.Mail.SmtpClient("ho-ex2010-caht1.exchangeserverpro.net")
$smtp.Send("[email protected]","[email protected]","Test Email","This is a test")

You could then launch the script from the command line as per this example:

powershell.exe -noexit c:\scripts\test.ps1

Note that PowerShell 2.0, which is installed by default on Windows 7 and Windows Server 2008R2, includes a simpler Send-MailMessage command, making things easier.

Option 2
If you're prepared to use third-party software, is something line this SendEmail command-line tool. It depends on your target environment, though; if you're deploying your batch file to multiple machines, that will obviously require inclusion (but not formal installation) each time.

Option 3
You could drive Outlook directly from a VBA script, which in turn you would trigger from a batch file; this would let you send an email using Outlook itself, which looks to be closest to what you're wanting. There are two parts to this; first, figure out the VBA scripting required to send an email. There are lots of examples for this online, including from Microsoft here. Essence of this is:

Sub SendMessage(DisplayMsg As Boolean, Optional AttachmentPath)
    Dim objOutlook As Outlook.Application
    Dim objOutlookMsg As Outlook.MailItem
    Dim objOutlookRecip As Outlook.Recipient
    Dim objOutlookAttach As Outlook.Attachment

    Set objOutlook = CreateObject("Outlook.Application")
    Set objOutlookMsg  = objOutlook.CreateItem(olMailItem)

    With objOutlookMsg
        Set objOutlookRecip = .Recipients.Add("Nancy Davolio")
        objOutlookRecip.Type = olTo
        ' Set the Subject, Body, and Importance of the message.
        .Subject = "This is an Automation test with Microsoft Outlook"
        .Body = "This is the body of the message." &vbCrLf & vbCrLf
        .Importance = olImportanceHigh  'High importance

        If Not IsMissing(AttachmentPath) Then
            Set objOutlookAttach = .Attachments.Add(AttachmentPath)
        End If

        For Each ObjOutlookRecip In .Recipients
            objOutlookRecip.Resolve
        Next

        .Save
        .Send
    End With
    Set objOutlook = Nothing
End Sub

Then, launch Outlook from the command line with the /autorun parameter, as per this answer (alter path/macroname as necessary):

C:\Program Files\Microsoft Office\Office11\Outlook.exe" /autorun macroname

Option 4
You could use the same approach as option 3, but move the Outlook VBA into a PowerShell script (which you would run from a command line). Example here. This is probably the tidiest solution, IMO.

Eclipse EGit Checkout conflict with files: - EGit doesn't want to continue

I guess the best way to do this is like this :

  1. Store all your changes in a separate branch.
  2. Then do a hard reset on the local master.
  3. Then merge back your changes from the locally created branch
  4. Then commit and push your changes.

That how I resolve mine, whenever it happens.

How to replace a hash key with another key

If we want to rename a specific key in hash then we can do it as follows:
Suppose my hash is my_hash = {'test' => 'ruby hash demo'}
Now I want to replace 'test' by 'message', then:
my_hash['message'] = my_hash.delete('test')

Function ereg_replace() is deprecated - How to clear this bug?

Here is more information regarding replacing ereg_replace with preg_replace

What is the size of a pointer?

The size of a pointer is the size required by your system to hold a unique memory address (since a pointer just holds the address it points to)

Negative list index?

List indexes of -x mean the xth item from the end of the list, so n[-1] means the last item in the list n. Any good Python tutorial should have told you this.

It's an unusual convention that only a few other languages besides Python have adopted, but it is extraordinarily useful; in any other language you'll spend a lot of time writing n[n.length-1] to access the last item of a list.

How to center an iframe horizontally?

If you are putting a video in the iframe and you want your layout to be fluid, you should look at this webpage: Fluid Width Video

Depending on the video source and if you want to have old videos become responsive your tactics will need to change.

If this is your first video, here is a simple solution:

_x000D_
_x000D_
<div class="videoWrapper">_x000D_
    <!-- Copy & Pasted from YouTube -->_x000D_
    <iframe width="560" height="349" src="http://www.youtube.com/embed/n_dZNLr2cME?rel=0&hd=1" frameborder="0" allowfullscreen></iframe>_x000D_
</div>
_x000D_
_x000D_
_x000D_

And add this css:

_x000D_
_x000D_
.videoWrapper {_x000D_
 position: relative;_x000D_
 padding-bottom: 56.25%; /* 16:9 */_x000D_
 padding-top: 25px;_x000D_
 height: 0;_x000D_
}_x000D_
.videoWrapper iframe {_x000D_
 position: absolute;_x000D_
 top: 0;_x000D_
 left: 0;_x000D_
 width: 100%;_x000D_
 height: 100%;_x000D_
}
_x000D_
_x000D_
_x000D_

Disclaimer: none of this is my code, but I've tested it and was happy with the results.

Text inset for UITextField?

Swift

    // adjust place holder text
    let paddingView = UIView(frame: CGRectMake(0, 0, 10, usernameOrEmailField.frame.height))
    usernameOrEmailField.leftView = paddingView
    usernameOrEmailField.leftViewMode = UITextFieldViewMode.Always

SSIS Excel Connection Manager failed to Connect to the Source

It seems like the 32-bit version of Excel was not installed. Remember that SSDT is a 32-bit IDE. Therefore, when data is access from SSDT the 32-bit data providers are used. When running the package outside of SSDT it runs in 64-bit mode (not always, but mostly) and uses the 64-bit data providers.

Always keep in mind that if you want to run your package in 64-bit (which you should aim for) you will need both the 32-bit data providers (for development in SSDT) as well as the 64-bit data providers (for executing the package in production).

I downloaded the 32-bit access drivers from:

After installation, I could see the worksheets


Source:

sort files by date in PHP

I use your exact proposed code with only some few additional lines. The idea is more or less the same of the one proposed by @elias, but in this solution there cannot be conflicts on the keys since each file in the directory has a different filename and so adding it to the key solves the conflicts. The first part of the key is the datetime string formatted in a manner such that I can lexicographically compare two of them.

if ($handle = opendir('.')) {
    $result = array();
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            $lastModified = date('F d Y, H:i:s',filemtime($file));
            if(strlen($file)-strpos($file,".swf")== 4){
                $result [date('Y-m-d H:i:s',filemtime($file)).$file] =
                    "<tr><td><input type=\"checkbox\" name=\"box[]\"></td><td><a href=\"$file\" target=\"_blank\">$file</a></td><td>$lastModified</td></tr>";
            }
        }
    }
    closedir($handle);
    krsort($result);
    echo implode('', $result);
}

how to set auto increment column with sql developer

How to do it with Oracle SQL Developer: In the Left pane, under the connections you will find "Sequences", right click and select create a new sequence from the context sensitive pop up. Fill out the details: Schema name, sequence_name, properties(start with value, min value, max value, increment value etc.) and click ok. Assuming that you have a table with a key that uses this auto_increment, while inserting in this table just give "your_sequence_name.nextval" in the field that utilizes this property. I guess this should help! :)

Using module 'subprocess' with timeout

Unfortunately, I'm bound by very strict policies on the disclosure of source code by my employer, so I can't provide actual code. But for my taste the best solution is to create a subclass overriding Popen.wait() to poll instead of wait indefinitely, and Popen.__init__ to accept a timeout parameter. Once you do that, all the other Popen methods (which call wait) will work as expected, including communicate.

How to access a DOM element in React? What is the equilvalent of document.getElementById() in React

You can replace

document.getElementById(this.state.baction).addPrecent(10);

with

this.refs[this.state.baction].addPrecent(10);


  <Progressbar completed={25} ref="Progress1" id="Progress1"/>

How to concatenate and minify multiple CSS and JavaScript files with Grunt.js (0.3.x)

I want to mention here a very, VERY, interesting technique that is being used in huge projects like jQuery and Modernizr for concatenate things.

Both of this projects are entirely developed with requirejs modules (you can see that in their github repos) and then they use the requirejs optimizer as a very smart concatenator. The interesting thing is that, as you can see, nor jQuery neither Modernizr needs on requirejs to work, and this happen because they erase the requirejs syntatic ritual in order to get rid of requirejs in their code. So they end up with a standalone library that was developed with requirejs modules! Thanks to this they are able to perform cutsom builds of their libraries, among other advantages.

For all those interested in concatenation with the requirejs optimizer, check out this post

Also there is a small tool that abstracts all the boilerplate of the process: AlbanilJS

How to add "class" to host element?

You can simply add @HostBinding('class') class = 'someClass'; inside your @Component class.

Example:

@Component({
   selector: 'body',
   template: 'app-element'       
})
export class App implements OnInit {

  @HostBinding('class') class = 'someClass';

  constructor() {}      

  ngOnInit() {}
}

Minimum rights required to run a windows service as a domain account

Two ways:

  1. Edit the properties of the service and set the Log On user. The appropriate right will be automatically assigned.

  2. Set it manually: Go to Administrative Tools -> Local Security Policy -> Local Policies -> User Rights Assignment. Edit the item "Log on as a service" and add your domain user there.

Entity Framework code first unique column

Solution for EF4.3

Unique UserName

Add data annotation over column as:

 [Index(IsUnique = true)]
 [MaxLength(255)] // for code-first implementations
 public string UserName{get;set;}

Unique ID , I have added decoration [Key] over my column and done. Same solution as described here: https://msdn.microsoft.com/en-gb/data/jj591583.aspx

IE:

[Key]
public int UserId{get;set;}

Alternative answers

using data annotation

[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Column("UserId")]

using mapping

  mb.Entity<User>()
            .HasKey(i => i.UserId);
        mb.User<User>()
          .Property(i => i.UserId)
          .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
          .HasColumnName("UserId");

Define make variable at rule execution time

In your example, the TMP variable is set (and the temporary directory created) whenever the rules for out.tar are evaluated. In order to create the directory only when out.tar is actually fired, you need to move the directory creation down into the steps:

out.tar : 
    $(eval TMP := $(shell mktemp -d))
    @echo hi $(TMP)/hi.txt
    tar -C $(TMP) cf $@ .
    rm -rf $(TMP)

The eval function evaluates a string as if it had been typed into the makefile manually. In this case, it sets the TMP variable to the result of the shell function call.

edit (in response to comments):

To create a unique variable, you could do the following:

out.tar : 
    $(eval $@_TMP := $(shell mktemp -d))
    @echo hi $($@_TMP)/hi.txt
    tar -C $($@_TMP) cf $@ .
    rm -rf $($@_TMP)

This would prepend the name of the target (out.tar, in this case) to the variable, producing a variable with the name out.tar_TMP. Hopefully, that is enough to prevent conflicts.

Room persistance library. Delete all

As of Room 1.1.0 you can use clearAllTables() which:

Deletes all rows from all the tables that are registered to this database as entities().

HTML list-style-type dash

Here is my fiddle version:

The (modernizr) class .generatedcontent on <html> practically means IE8+ and every other sane browser.

<html class="generatedcontent">
  <ul class="ul-dash hanging">
    <li>Lorem ipsum dolor sit amet stack o verflow dot com</li>
    <li>Lorem ipsum dolor sit amet stack o verflow dot com</li>
  </ul>

CSS:

.ul-dash {
  margin: 0;
}

.ul-dash {
  margin-left: 0em;
  padding-left: 1.5em;
}

.ul-dash.hanging > li { /* remove '>' for IE6 support */
  padding-left: 1em;
  text-indent: -1em;
}  

.generatedcontent .ul-dash {
  list-style: none;
}
.generatedcontent .ul-dash > li:before {
  content: "–";
  text-indent: 0;
  display: inline-block;
  width: 0;
  position: relative;
  left: -1.5em;
}

Hadoop: «ERROR : JAVA_HOME is not set»

Copy this export JAVA_HOME=/usr/lib/jvm/java-1.6.0-openjdk to hadoop-env.sh file.

JAVA_HOME is the location where java binaries are present.

Setting environment variables for accessing in PHP when using Apache

Unbelievable, but on httpd 2.2 on centos 6.4 this works.

Export env vars in /etc/sysconfig/httpd

export mydocroot=/var/www/html

Then simply do this...

<VirtualHost *:80>
  DocumentRoot ${mydocroot}
</VirtualHost>

Then finally....

service httpd restart;

Replace invalid values with None in Pandas DataFrame

Setting null values can be done with np.nan:

import numpy as np
df.replace('-', np.nan)

Advantage is that df.last_valid_index() recognizes these as invalid.

Textarea to resize based on content length

One method is to do it without JavaScript and this is something like this:

    <textarea style="overflow: visible" />

Java "?" Operator for checking null - What is it? (Not Ternary!)

If this is not a performance issue for you, you can write

public String getFirstName(Person person) {
  try {
     return person.getName().getGivenName();
  } catch (NullPointerException ignored) {
     return null;
  }
} 

Making a div vertically scrollable using CSS

Well the above answers have give a good explanations to half of the question. For the other half.

Why don't just hide the scroll bar itself. This way it will look more appealing as most of the people ( including me ) hate the scroll bar. You can use this code

::-webkit-scrollbar {
    width: 0px;  /* Remove scrollbar space */
    background: transparent;  /* Optional: just make scrollbar invisible */
}

Splitting a continuous variable into equal sized groups

Here's another solution using the bin_data() function from the mltools package.

library(mltools)

# Resulting bins have an equal number of observations in each group
das[, "wt2"] <- bin_data(das$wt, bins=3, binType = "quantile")

# Resulting bins are equally spaced from min to max
das[, "wt3"] <- bin_data(das$wt, bins=3, binType = "explicit")

# Or if you'd rather define the bins yourself
das[, "wt4"] <- bin_data(das$wt, bins=c(-Inf, 250, 322, Inf), binType = "explicit")

das
   anim    wt                                  wt2                                  wt3         wt4
1     1 181.0              [179, 200.333333333333)              [179, 250.666666666667) [-Inf, 250)
2     2 179.0              [179, 200.333333333333)              [179, 250.666666666667) [-Inf, 250)
3     3 180.5              [179, 200.333333333333)              [179, 250.666666666667) [-Inf, 250)
4     4 201.0 [200.333333333333, 245.466666666667)              [179, 250.666666666667) [-Inf, 250)
5     5 201.5 [200.333333333333, 245.466666666667)              [179, 250.666666666667) [-Inf, 250)
6     6 245.0 [200.333333333333, 245.466666666667)              [179, 250.666666666667) [-Inf, 250)
7     7 246.4              [245.466666666667, 394]              [179, 250.666666666667) [-Inf, 250)
8     8 189.3              [179, 200.333333333333)              [179, 250.666666666667) [-Inf, 250)
9     9 301.0              [245.466666666667, 394] [250.666666666667, 322.333333333333)  [250, 322)
10   10 354.0              [245.466666666667, 394]              [322.333333333333, 394]  [322, Inf]
11   11 369.0              [245.466666666667, 394]              [322.333333333333, 394]  [322, Inf]
12   12 205.0 [200.333333333333, 245.466666666667)              [179, 250.666666666667) [-Inf, 250)
13   13 199.0              [179, 200.333333333333)              [179, 250.666666666667) [-Inf, 250)
14   14 394.0              [245.466666666667, 394]              [322.333333333333, 394]  [322, Inf]
15   15 231.3 [200.333333333333, 245.466666666667)              [179, 250.666666666667) [-Inf, 250)

Comparing two java.util.Dates to see if they are in the same day

You can avoid external dependencies and the performance hit of using Calendar by calculating the Julian Day Number for each of the dates and then comparing these:

public static boolean isSameDay(Date date1, Date date2) {

    // Strip out the time part of each date.
    long julianDayNumber1 = date1.getTime() / MILLIS_PER_DAY;
    long julianDayNumber2 = date2.getTime() / MILLIS_PER_DAY;

    // If they now are equal then it is the same day.
    return julianDayNumber1 == julianDayNumber2;
}

How to write a Unit Test?

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

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

What is the best way to merge mp3 files?

The time problem has to do with the ID3 headers of the MP3 files, which is something your method isn't taking into account as the entire file is copied.

Do you have a language of choice that you want to use or doesn't it matter? That will affect what libraries are available that support the operations you want.

What is the Java equivalent of PHP var_dump?

I think something similar you could do is to create a simple method which prints the object you want to see. Something like this:

public static void dd(Object obj) { System.out.println(obj); }

It's not the same like var_dump(), but you can get an general idea of it, without the need to go to your debugger IDE.

Capturing a single image from my webcam in Java or Python

import cv2
camera = cv2.VideoCapture(0)
while True:
    return_value,image = camera.read()
    gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
    cv2.imshow('image',gray)
    if cv2.waitKey(1)& 0xFF == ord('s'):
        cv2.imwrite('test.jpg',image)
        break
camera.release()
cv2.destroyAllWindows()

Ruby - ignore "exit" in code

One hackish way to define an exit method in context:

class Bar; def exit; end; end 

This works because exit in the initializer will be resolved as self.exit1. In addition, this approach allows using the object after it has been created, as in: b = B.new.

But really, one shouldn't be doing this: don't have exit (or even puts) there to begin with.

(And why is there an "infinite" loop and/or user input in an intiailizer? This entire problem is primarily the result of poorly structured code.)


1 Remember Kernel#exit is only a method. Since Kernel is included in every Object, then it's merely the case that exit normally resolves to Object#exit. However, this can be changed by introducing an overridden method as shown - nothing fancy.

PHP Multidimensional Array Searching (Find key by specific value)

I would do like below, where $products is the actual array given in the problem at the very beginning.

print_r(
  array_search("breville-variable-temperature-kettle-BKE820XL", 
  array_map(function($product){return $product["slug"];},$products))
);