Programs & Examples On #Multiple inclusions

How to check if a line has one of the strings in a list?

One approach is to combine the search strings into a regex pattern as in this answer.

Nodejs send file in response

You need use Stream to send file (archive) in a response, what is more you have to use appropriate Content-type in your response header.

There is an example function that do it:

const fs = require('fs');

// Where fileName is name of the file and response is Node.js Reponse. 
responseFile = (fileName, response) => {
  const filePath =  "/path/to/archive.rar" // or any file format

  // Check if file specified by the filePath exists 
  fs.exists(filePath, function(exists){
      if (exists) {     
        // Content-type is very interesting part that guarantee that
        // Web browser will handle response in an appropriate manner.
        response.writeHead(200, {
          "Content-Type": "application/octet-stream",
          "Content-Disposition": "attachment; filename=" + fileName
        });
        fs.createReadStream(filePath).pipe(response);
      } else {
        response.writeHead(400, {"Content-Type": "text/plain"});
        response.end("ERROR File does not exist");
      }
    });
  }
}

The purpose of the Content-Type field is to describe the data contained in the body fully enough that the receiving user agent can pick an appropriate agent or mechanism to present the data to the user, or otherwise deal with the data in an appropriate manner.

"application/octet-stream" is defined as "arbitrary binary data" in RFC 2046, purpose of this content-type is to be saved to disk - it is what you really need.

"filename=[name of file]" specifies name of file which will be downloaded.

For more information please see this stackoverflow topic.

Lightweight XML Viewer that can handle large files

I like Microsoft's XML Notepad 2007, but I don't know how it handles very large files, sorry.

Remove all of x axis labels in ggplot

You have to set to element_blank() in theme() elements you need to remove

ggplot(data = diamonds, mapping = aes(x = clarity)) + geom_bar(aes(fill = cut))+
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank())

Leaflet - How to find existing markers, and delete markers?

What I did to remove marker was this create a button who allow me do it

Hope i can help someone :)

_x000D_
_x000D_
//Button who active deleteBool
const button = document.getElementById('btn')

//Boolean who let me delete marker
let deleteBool = false

//Button function to enable boolean
button.addEventListener('click',()=>{
  deleteBool = true
})

// Function to delete marker 
const deleteMarker = (e) => {
    if (deleteBool) {
        e.target.removeFrom(map)
        deleteBooly = false
    }
}

//Initiate map
var map = L.map('map').setView([51.505, -0.09], 13);

//Create one marker
let marker = L.marker([51.5, -0.09]).addTo(map)
//Add Marker Function
marker.on('click', deleteMarker)
_x000D_
body {
  display: flex;
  flex-direction: column;
}

#map{
  width: 500px;
  height: 500px;
  margin: auto;
}

#btn{
  width: 50px;
  height: 50px;
  margin: 2em auto; 
}
_x000D_
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
    <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A==" crossorigin="" />
    <title>MovieCenter</title>
</head>

<body>
    <div id="map"></div>
    <button id="btn">Click me!</button>
    <script script="script" src="https://unpkg.com/[email protected]/dist/leaflet.js" integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA==" crossorigin=""></script>
    <script src="script.js"></script>
</body>

</html>
_x000D_
_x000D_
_x000D_

Reload content in modal (twitter bootstrap)

I am having the same problem, and I guess the way of doing this will be to remove the data-toggle attribute and have a custom handler for the links.

Something in the lines of:

$("a[data-target=#myModal]").click(function(ev) {
    ev.preventDefault();
    var target = $(this).attr("href");

    // load the url and show modal on success
    $("#myModal .modal-body").load(target, function() { 
         $("#myModal").modal("show"); 
    });
});

Will try it later and post comments.

Extract time from date String

let datestring = "2017-02-14 02:16:28"

let formatter = DateFormatter()
formatter.dateStyle = DateFormatter.Style.full
formatter.timeStyle = DateFormatter.Style.full

formatter.dateFormat = "yyyy-MM-dd hh:mm:ss"

let date = formatter.date(from: datestring)
let date2 = formatter.String(from: date)

How do I do an initial push to a remote repository with Git?

On server:

mkdir my_project.git
cd my_project.git
git --bare init

On client:

mkdir my_project
cd my_project
touch .gitignore
git init
git add .
git commit -m "Initial commit"
git remote add origin [email protected]:/path/to/my_project.git
git push origin master

Note that when you add the origin, there are several formats and schemas you could use. I recommend you see what your hosting service provides.

How do I commit case-sensitive only filename changes in Git?

Using SourceTree I was able to do this all from the UI

  1. Rename FILE.ext to whatever.ext
  2. Stage that file
  3. Now rename whatever.ext to file.ext
  4. Stage that file again

It's a bit tedious, but if you only need to do it to a few files it's pretty quick

How to convert string to char array in C++?

You could use strcpy(), like so:

strcpy(tab2, tmp.c_str());

Watch out for buffer overflow.

Python dictionary replace values

If you iterate over a dictionary you get the keys, so assuming your dictionary is in a variable called data and you have some function find_definition() which gets the definition, you can do something like the following:

for word in data:
    data[word] = find_definition(word)

Convert textbox text to integer

You don't need to write a converter, just do this in your handler/codebehind:

int i = Convert.ToInt32(txtMyTextBox.Text);

OR

int i = int.Parse(txtMyTextBox.Text);

The Text property of your textbox is a String type, so you have to perform the conversion in the code.

Linux/Unix command to determine if process is running?

This should work on most flavours of Unix, BSD and Linux:

PATH=/usr/ucb:${PATH} ps aux | grep httpd | grep -v grep

Tested on:

  • SunOS 5.10 [Hence the PATH=...]
  • Linux 2.6.32 (CentOS)
  • Linux 3.0.0 (Ubuntu)
  • Darwin 11.2.0
  • FreeBSD 9.0-STABLE
  • Red Hat Enterprise Linux ES release 4
  • Red Hat Enterprise Linux Server release 5

"cannot be used as a function error"

This line is the problem:

int estimatedPopulation (int currentPopulation,
                         float growthRate (birthRate, deathRate))

Make it:

int estimatedPopulation (int currentPopulation, float birthRate, float deathRate)

instead and invoke the function with three arguments like

estimatePopulation( currentPopulation, birthRate, deathRate );

OR declare it with two arguments like:

int estimatedPopulation (int currentPopulation, float growthrt ) { ... }

and call it as

estimatedPopulation( currentPopulation, growthRate (birthRate, deathRate));

Edit:

Probably more important here - C++ (and C) names have scope. You can have two things named the same but not at the same time. In your particular case your grouthRate variable in the main() hides the function with the same name. So within main() you can only access grouthRate as float. On the other hand, outside of the main() you can only access that name as a function, since that automatic variable is only visible within the scope of main().

Just hope I didn't confuse you further :)

How to unlock a file from someone else in Team Foundation Server

2019 answer, as most of the above is depracated.

tf undo /workspace:"hostname;username" "$/path/*" /s:https://yourhostname/tfs in an elevated command prompt, from a path such as C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE>

How to pass objects to functions in C++?

The following are the ways to pass a arguments/parameters to function in C++.

1. by value.

// passing parameters by value . . .

void foo(int x) 
{
    x = 6;  
}

2. by reference.

// passing parameters by reference . . .

void foo(const int &x) // x is a const reference
{
    x = 6;  
}

// passing parameters by const reference . . .

void foo(const int &x) // x is a const reference
{
    x = 6;  // compile error: a const reference cannot have its value changed!
}

3. by object.

class abc
{
    display()
    {
        cout<<"Class abc";
    }
}


// pass object by value
void show(abc S)
{
    cout<<S.display();
}

// pass object by reference
void show(abc& S)
{
    cout<<S.display();
}

How can I have a newline in a string in sh?

I'm no bash expert, but this one worked for me:

STR1="Hello"
STR2="World"
NEWSTR=$(cat << EOF
$STR1

$STR2
EOF
)
echo "$NEWSTR"

I found this easier to formatting the texts.

How to trigger a build only if changes happen on particular set of files

While this doesn't affect single jobs, you can use this script to ignore certain steps if the latest commit did not contain any changes:

/*
 * Check a folder if changed in the latest commit.
 * Returns true if changed, or false if no changes.
 */
def checkFolderForDiffs(path) {
    try {
        // git diff will return 1 for changes (failure) which is caught in catch, or
        // 0 meaning no changes 
        sh "git diff --quiet --exit-code HEAD~1..HEAD ${path}"
        return false
    } catch (err) {
        return true
    }
}

if ( checkFolderForDiffs('api/') ) {
    //API folder changed, run steps here
}

PHP header() redirect with POST variables

// from http://wezfurlong.org/blog/2006/nov/http-post-from-php-without-curl
function do_post_request($url, $data, $optional_headers = null)
{
  $params = array('http' => array(
              'method' => 'POST',
              'content' => $data
            ));
  if ($optional_headers !== null) {
    $params['http']['header'] = $optional_headers;
  }
  $ctx = stream_context_create($params);
  $fp = @fopen($url, 'rb', false, $ctx);
  if (!$fp) {
    throw new Exception("Problem with $url, $php_errormsg");
  }
  $response = @stream_get_contents($fp);
  if ($response === false) {
    throw new Exception("Problem reading data from $url, $php_errormsg");
  }
  return $response;
}

Going from MM/DD/YYYY to DD-MMM-YYYY in java

final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate localDate = LocalDate.now();
System.out.println("Formatted Date: " + formatter.format(localDate));

Java 8 LocalDate

How to check if two words are anagrams

Lots of people have presented solutions, but I just want to talk about the algorithmic complexity of some of the common approaches:

  • The simple "sort the characters using Arrays.sort()" approach is going to be O(N log N).

  • If you use radix sorting, that reduces to O(N) with O(M) space, where M is the number of distinct characters in the alphabet. (That is 26 in English ... but in theory we ought to consider multi-lingual anagrams.)

  • The "count the characters" using an array of counts is also O(N) ... and faster than radix sort because you don't need to reconstruct the sorted string. Space usage will be O(M).

  • A "count the characters" using a dictionary, hashmap, treemap, or equivalent will be slower that the array approach, unless the alphabet is huge.

  • The elegant "product-of-primes" approach is unfortunately O(N^2) in the worst case This is because for long-enough words or phrases, the product of the primes won't fit into a long. That means that you'd need to use BigInteger, and N times multiplying a BigInteger by a small constant is O(N^2).

    For a hypothetical large alphabet, the scaling factor is going to be large. The worst-case space usage to hold the product of the primes as a BigInteger is (I think) O(N*logM).

  • A hashcode based approach is usually O(N) if the words are not anagrams. If the hashcodes are equal, then you still need to do a proper anagram test. So this is not a complete solution.

What is the best way to call a script from another script?

Use import test1 for the 1st use - it will execute the script. For later invocations, treat the script as an imported module, and call the reload(test1) method.

When reload(module) is executed:

  • Python modules’ code is recompiled and the module-level code reexecuted, defining a new set of objects which are bound to names in the module’s dictionary. The init function of extension modules is not called

A simple check of sys.modules can be used to invoke the appropriate action. To keep referring to the script name as a string ('test1'), use the 'import()' builtin.

import sys
if sys.modules.has_key['test1']:
    reload(sys.modules['test1'])
else:
    __import__('test1')

VB.net: Date without time

I almost always use the standard formating ShortDateString, because I want the user to be in control of the actual output of the date.

Code

   Dim d As DateTime = Now
   Debug.WriteLine(d.ToLongDateString)
   Debug.WriteLine(d.ToShortDateString)
   Debug.WriteLine(d.ToString("d"))
   Debug.WriteLine(d.ToString("yyyy-MM-dd"))

Results

Wednesday, December 10, 2008
12/10/2008
12/10/2008
2008-12-10

Note that these results will vary depending on the culture settings on your computer.

How to import CSV file data into a PostgreSQL table?

You could also use pgAdmin, which offers a GUI to do the import. That's shown in this SO thread. The advantage of using pgAdmin is that it also works for remote databases.

Much like the previous solutions though, you would need to have your table on the database already. Each person has his own solution but what I usually do is open the CSV in Excel, copy the headers, paste special with transposition on a different worksheet, place the corresponding data type on the next column then just copy and paste that to a text editor together with the appropriate SQL table creation query like so:

CREATE TABLE my_table (
    /*paste data from Excel here for example ... */
    col_1 bigint,
    col_2 bigint,
    /* ... */
    col_n bigint 
)

jQuery toggle animation

I dont think adding dual functions inside the toggle function works for a registered click event (Unless I'm missing something)

For example:

$('.btnName').click(function() {
 top.$('#panel').toggle(function() {
   $(this).animate({ 
     // style change
   }, 500);
   },
   function() {
   $(this).animate({ 
     // style change back
   }, 500);
 });

How to Multi-thread an Operation Within a Loop in Python

Edit 2018-02-06: revision based on this comment

Edit: forgot to mention that this works on Python 2.7.x

There's multiprocesing.pool, and the following sample illustrates how to use one of them:

from multiprocessing.pool import ThreadPool as Pool
# from multiprocessing import Pool

pool_size = 5  # your "parallelness"

# define worker function before a Pool is instantiated
def worker(item):
    try:
        api.my_operation(item)
    except:
        print('error with item')

pool = Pool(pool_size)

for item in items:
    pool.apply_async(worker, (item,))

pool.close()
pool.join()

Now if you indeed identify that your process is CPU bound as @abarnert mentioned, change ThreadPool to the process pool implementation (commented under ThreadPool import). You can find more details here: http://docs.python.org/2/library/multiprocessing.html#using-a-pool-of-workers

How do I check whether a file exists without exceptions?

You can write Brian's suggestion without the try:.

from contextlib import suppress

with suppress(IOError), open('filename'):
    process()

suppress is part of Python 3.4. In older releases you can quickly write your own suppress:

from contextlib import contextmanager

@contextmanager
def suppress(*exceptions):
    try:
        yield
    except exceptions:
        pass

Append text to file from command line without using io redirection

If you don't mind using sed then,

$ cat test 
this is line 1
$ sed -i '$ a\this is line 2 without redirection' test 
$ cat test 
this is line 1
this is line 2 without redirection

As the documentation may be a bit long to go through, some explanations :

  • -i means an inplace transformation, so all changes will occur in the file you specify
  • $ is used to specify the last line
  • a means append a line after
  • \ is simply used as a delimiter

AngularJS - How to use $routeParams in generating the templateUrl?

templateUrl can be use as function with returning generated URL. We can manipulate url with passing argument which takes routeParams.

See the example.

.when('/:screenName/list',{
    templateUrl: function(params){
         return params.screenName +'/listUI'
    }
})

Hope this help.

"detached entity passed to persist error" with JPA/EJB code

If you set id in your database to be primary key and autoincrement, then this line of code is wrong:

user.setId(1);

Try with this:

public static void main(String[] args){
         UserBean user = new UserBean();
         user.setUserName("name1");
         user.setPassword("passwd1");
         em.persist(user);
  }

python location on mac osx

run the following code in a .py file:

import sys

print(sys.version)
print(sys.executable)

How do I flush the PRINT buffer in TSQL?

Just for the reference, if you work in scripts (batch processing), not in stored procedure, flushing output is triggered by the GO command, e.g.

print 'test'
print 'test'
go

In general, my conclusion is following: output of mssql script execution, executing in SMS GUI or with sqlcmd.exe, is flushed to file, stdoutput, gui window on first GO statement or until the end of the script.

Flushing inside of stored procedure functions differently, since you can not place GO inside.

Reference: tsql Go statement

Finding and removing non ascii characters from an Oracle Varchar2

Please note that whenever you use

regexp_like(column, '[A-Z]')

Oracle's regexp engine will match certain characters from the Latin-1 range as well: this applies to all characters that look similar to ASCII characters like Ä->A, Ö->O, Ü->U, etc., so that [A-Z] is not what you know from other environments like, say, Perl.

Instead of fiddling with regular expressions try changing for the NVARCHAR2 datatype prior to character set upgrade.

Another approach: instead of cutting away part of the fields' contents you might try the SOUNDEX function, provided your database contains European characters (i.e. Latin-1) characters only. Or you just write a function that translates characters from the Latin-1 range into similar looking ASCII characters, like

  • å => a
  • ä => a
  • ö => o

of course only for text blocks exceeding 4000 bytes when transformed to UTF-8.

Animate the transition between fragments

Here's a slide in/out animation between fragments:

FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.animator.enter_anim, R.animator.exit_anim);
transaction.replace(R.id.listFragment, new YourFragment());
transaction.commit();

We are using an objectAnimator.

Here are the two xml files in the animator subfolder.

enter_anim.xml

<?xml version="1.0" encoding="utf-8"?>
<set>
     <objectAnimator
         xmlns:android="http://schemas.android.com/apk/res/android"
         android:duration="1000"
         android:propertyName="x"
         android:valueFrom="2000"
         android:valueTo="0"
         android:valueType="floatType" />
</set>

exit_anim.xml

<?xml version="1.0" encoding="utf-8"?>
<set>
    <objectAnimator
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:duration="1000"
        android:propertyName="x"
        android:valueFrom="0"
        android:valueTo="-2000"
        android:valueType="floatType" />
</set>

I hope that would help someone.

Angular 2 / 4 / 5 not working in IE11

I tried every solution in this thread as well as bunch from other ones, with no success. What ended up fixing this for me was to update every package in my project, including MAJOR version changes. So:

  1. Run npm outdated
  2. Update package.json with the number shown in the current column from results (this can break your project, be careful)
  3. Run npm install
  4. Made sure I also had the polyfills uncommented as noted in the other answers.

That's it. I wish I could pinpoint which library was the culprit. The actual error I was getting was "Syntax Error" in vendor.js in Angular 6.

Best way to remove items from a collection

There is another approach you can take depending on how you're using your collection. If you're downloading the assignments one time (e.g., when the app runs), you could translate the collection on the fly into a hashtable where:

shortname => SPRoleAssignment

If you do this, then when you want to remove an item by short name, all you need to do is remove the item from the hashtable by key.

Unfortunately, if you're loading these SPRoleAssignments a lot, that obviously isn't going to be any more cost efficient in terms of time. The suggestions other people made about using Linq would be good if you're using a new version of the .NET Framework, but otherwise, you'll have to stick to the method you're using.

How do I hide certain files from the sidebar in Visual Studio Code?

Sometimes you just want to hide certain file types for a specific project. In that case, you can create a folder in your project folder called .vscode and create the settings.json file in there, (i.e. .vscode/settings.json). All settings within that file will affect your current workspace only.

For example, in a TypeScript project, this is what I have used:

// Workspace settings
{
    // The following will hide the js and map files in the editor
    "files.exclude": {
        "**/*.js": true,
        "**/*.map": true
    }
}

Concatenate chars to form String in java

Use str = ""+a+b+c;

Here the first + is String concat, so the result will be a String. Note where the "" lies is important.

Or (maybe) better, use a StringBuilder.

No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

The problem arose because you added the following code as request header in your front-end :

headers.append('Access-Control-Allow-Origin', 'http://localhost:3000');
headers.append('Access-Control-Allow-Credentials', 'true');

Those headers belong to response, not request. So remove them, including the line :

headers.append('GET', 'POST', 'OPTIONS');

Your request had 'Content-Type: application/json', hence triggered what is called CORS preflight. This caused the browser sent the request with OPTIONS method. See CORS preflight for detailed information.

Therefore in your back-end, you have to handle this preflighted request by returning the response headers which include :

Access-Control-Allow-Origin : http://localhost:3000
Access-Control-Allow-Credentials : true
Access-Control-Allow-Methods : GET, POST, OPTIONS
Access-Control-Allow-Headers : Origin, Content-Type, Accept

Of course, the actual syntax depends on the programming language you use for your back-end.

In your front-end, it should be like so :

function performSignIn() {
    let headers = new Headers();

    headers.append('Content-Type', 'application/json');
    headers.append('Accept', 'application/json');
    headers.append('Authorization', 'Basic ' + base64.encode(username + ":" +  password));
    headers.append('Origin','http://localhost:3000');

    fetch(sign_in, {
        mode: 'cors',
        credentials: 'include',
        method: 'POST',
        headers: headers
    })
    .then(response => response.json())
    .then(json => console.log(json))
    .catch(error => console.log('Authorization failed : ' + error.message));
}

Unix tail equivalent command in Windows Powershell

PowerShell Community Extensions (PSCX) provides the Get-FileTail cmdlet. It looks like a suitable solution for the task. Note: I did not try it with extremely large files but the description says it efficiently tails the contents and it is designed for large log files.

NAME
    Get-FileTail

SYNOPSIS
    PSCX Cmdlet: Tails the contents of a file - optionally waiting on new content.

SYNTAX
    Get-FileTail [-Path] <String[]> [-Count <Int32>] [-Encoding <EncodingParameter>] [-LineTerminator <String>] [-Wait] [<CommonParameters>]

    Get-FileTail [-LiteralPath] <String[]> [-Count <Int32>] [-Encoding <EncodingParameter>] [-LineTerminator <String>] [-Wait] [<CommonParameters>]

DESCRIPTION
    This implentation efficiently tails the cotents of a file by reading lines from the end rather then processing the entire file. This behavior is crucial for ef
    ficiently tailing large log files and large log files over a network.  You can also specify the Wait parameter to have the cmdlet wait and display new content
    as it is written to the file.  Use Ctrl+C to break out of the wait loop.  Note that if an encoding is not specified, the cmdlet will attempt to auto-detect the
     encoding by reading the first character from the file. If no character haven't been written to the file yet, the cmdlet will default to using Unicode encoding
    . You can override this behavior by explicitly specifying the encoding via the Encoding parameter.

facebook Uncaught OAuthException: An active access token must be used to query information about the current user

Use:

$facebook->api('/'.$facebook_uid)

instead of

$facebook->api('/me')

it works.

.NET Core vs Mono

Necromancing.
Providing an actual answer.

What is the difference between .Net Core and Mono?

.NET Core now officially is the future of .NET. It started for most part with a re-write of the ASP.NET MVC framework and console applications, which of course includes server applications. (Since it's Turing-complete and supports interop with C dlls, you could, if you absolutely wanted to, also write your own desktop applications with it, for example through 3rd-party libraries like Avalonia, which were a bit very basic at the time I first wrote this, which meant you were pretty much limited to web or server stuff.) Over time, many APIs have been added to .NET Core, so much so that after version 3.1, .NET Core will jump to version 5.0, be known as .NET 5.0 without the "Core", and that then will be the future of the .NET Framework. What used to be the full .NET Framework will linger around in maintenance mode as Full .NET Framework 4.8.x for a few decades, until it will die (maybe there are still going to be some upgrades, but I doubt it). In other words, .NET Core is the future of .NET, and Full .NET Framework will go the way of the Dodo/Silverlight/WindowsPhone.

The main point of .NET Core, apart from multi-platform support, is to improve performance, and to enable "native compilation"/self-contained-deployment (so you don't need .NET framework/VM installed on the target machine.
On the one hand, this means docker.io support on Linux, and on the other, self-contained deployment is useful in "cloud-computing", since then you can just use whatever version of the dotnet-CORE framework you like, and you don't have to worry about which version(s) of the .NET framework the sysadmin has actually installed.

While the .NET Core runtime supports multiple operating systems and processors, the SDK is a different story. And while the SDK supports multiple OS, ARM support for the SDK is/was still work in progress. .NET Core is supported by Microsoft. Dotnet-Core did not come with WinForms or WPF or anything like that.

  • As of version 3.0, WinForms and WPF is also supported by .NET Core, but only on Windows, and only by C#. Not by VB.NET (VB.NET support planned for v5 in 2020). And there is no Forms Designer in .NET Core: it's being shipped with a Visual Studio update later, at an unspecified time.
  • WebForms are still not supported by .NET Core, and there are no plans to support them, ever (Blazor is the new kid in town for that).
  • .NET Core also comes with System.Runtime, which replaces mscorelib.
  • Oftentimes, .NET Core is mixed up with NetStandard, which is a bit of a wrapper around System.Runtime/mscorelib (and some others), that allows you to write libraries that target .NET Core, Full .NET Framework and Xamarin (iOS/Android), all at the same time.
  • the .NET Core SDK does not/did not work on ARM, at least not last time I checked.

"The Mono Project" is much older than .NET Core.
Mono is Spanish and means Monkey, and as a side-remark, the name has nothing to do with mononucleosis (hint: you could get a list of staff under http://primates.ximian.com/).
Mono was started in 2005 by Miguel de Icaza (the guy that started GNOME - and a few others) as an implementation of the .NET Framework for Linux (Ximian/SuSe/Novell). Mono includes Web-Forms, Winforms, MVC, Olive, and an IDE called MonoDevelop (also knows as Xamarin Studio or Visual Studio Mac). Basically the equivalent of (OpenJDK) JVM and (OpenJDK) JDK/JRE (as opposed to SUN/Oracle JDK). You can use it to get ASP.NET-WebForms + WinForms + ASP.NET-MVC applications to work on Linux.

Mono is supported by Xamarin (the new company name of what used to be Ximian, when they focused on the Mobile market, instead of the Linux market), and not by Microsoft.
(since Xamarin was bought by Microsoft, that's technically [but not culturally] Microsoft.)
You will usually get your C# stuff to compile on mono, but not the VB.NET stuff.
Mono misses some advanced features, like WSE/WCF and WebParts.
Many of the Mono implementations are incomplete (e.g. throw NotImplementedException in ECDSA encryption), buggy (e.g. ODBC/ADO.NET with Firebird), behave differently than on .NET (for example XML-serialization) or otherwise unstable (ASP.NET MVC) and unacceptably slow (Regex). On the upside, the Mono toolchain also works on ARM.

As far as .NET Core is concerned, when they say cross-platform, don't expect that cross-platform means that you could actually just apt-get install .NET Core on ARM-Linux, like you can with ElasticSearch. You'll have to compile the entire framework from source.
That is, if you have that space (e.g. on a Chromebook, which has a 16 to 32 GB total HD).
It also used to have issues of incompatibility with OpenSSL 1.1 and libcurl.
Those have been rectified in the latest version of .NET Core Version 2.2.
So much for cross-platform.

I found a statement on the official site that said, "Code written for it is also portable across application stacks, such as Mono".

As long as that code doesn't rely on WinAPI-calls, Windows-dll-pinvokes, COM-Components, a case-insensitive file system, the default-system-encoding (codepage) and doesn't have directory separator issues, that's correct. However, .NET Core code runs on .NET Core, and not on Mono. So mixing the two will be difficult. And since Mono is quite unstable and slow (for web applications), I wouldn't recommend it anyway. Try image-processing on .NET core, e.g. WebP or moving GIF or multipage-tiff or writing text on an image, you'll be nastily surprised.

Note:
As of .NET Core 2.0, there is System.Drawing.Common (NuGet), which contains most of the functionality of System.Drawing. It should be more or less feature-complete in .NET-Core 2.1. However, System.Drawing.Common uses GDI+, and therefore won't work on Azure (System.Drawing libraries are available in Azure Cloud Service [basically just a VM], but not in Azure Web App [basically shared hosting?])
So far, System.Drawing.Common works fine on Linux/Mac, but has issues on iOS/Android - if it works at all, there.
Prior to .NET Core 2.0, that is to say sometime mid-February 2017, you could use SkiaSharp for imaging (example) (you still can).
Post .net-core 2.0, you'll notice that SixLabors ImageSharp is the way to go, since System.Drawing is not necessarely secure, and has a lot of potential or real memory leaks, which is why you shouldn't use GDI in web-applications; Note that SkiaSharp is a lot faster than ImageSharp, because it uses native-libraries (which can also be a drawback). Also, note that while GDI+ works on Linux & Mac, that doesn't mean it works on iOS/Android.

Code not written for .NET (non-Core) is not portable to .NET Core.
Meaning, if you want a non-GPL C# library like PDFSharp to create PDF-documents (very commonplace), you're out of luck (at the moment) (not anymore). Never mind ReportViewer control, which uses Windows-pInvokes (to encrypt, create mcdf documents via COM, and to get font, character, kerning, font embedding information, measure strings and do line-breaking, and for actually drawing tiffs of acceptable quality), and doesn't even run on Mono on Linux
(I'm working on that).

Also, code written in .NET Core is not portable to Mono, because Mono lacks the .NET Core runtime libraries (so far).

My goal is to use C#, LINQ, EF7, visual studio to create a website that can be ran/hosted in linux.

EF in any version that I tried so far was so goddamn slow (even on such simple things like one table with one left-join), I wouldn't recommend it ever - not on Windows either.
I would particularly not recommend EF if you have a database with unique-constrains, or varbinary/filestream/hierarchyid columns. (Not for schema-update either.)
And also not in a situation where DB-performance is critical (say 10+ to 100+ concurrent users).
Also, running a website/web-application on Linux will sooner or later mean you'll have to debug it.
There is no debugging support for .NET Core on Linux. (Not anymore, but requires JetBrains Rider.)
MonoDevelop does not (yet) support debugging .NET Core projects.
If you have problems, you're on your own. You'll have to use extensive logging.
Be careful, be advised extensive logging will fill your disk in no time, particularly if your program enters an infinite loop or recursion.
This is especially dangerous if your web-app runs as root, because log-in requires logfile-space - if there's no free space left, you won't be able to login anymore.
(Normally, about 5% of diskspace is reserved for user root [aka administrator on Windows], so at least the administrator can still log in if the disk is almost full. But if your applications run as root, that restriction does not apply for their disk usage, and so their logfiles can use 100% of the remaining free space, so not even the administrator can log in any more.)
It's therefore better not to encrypt that disk, that is, if you value your data/system.

Someone told me that he wanted it to be "in Mono", but I don't know what that means.

It either means he doesn't want to use .NET Core, or he just wants to use C# on Linux/Mac. My guess is he just wants to use C# for a Web-App on Linux. .NET Core is the way to go for that, if you absolutely want to do it in C#. Don't go with "Mono proper"; on the surface, it would seem to work at first - but believe me you will regret it because Mono's ASP.NET MVC isn't stable when your server runs long-term (longer than 1 day) - you have now been warned. See also the "did not complete" references when measuring Mono performance on the techempower benchmarks.

fortunes

I know I want to use the .Net Core 1.0 framework with the technologies I listed above. He also said he wanted to use "fast cgi". I don't know what that means either.

It means he wants to use a high-performance full-featured WebServer like nginx (Engine-X), possibly Apache.
Then he can run mono/dotnetCore with virtual name based hosting (multiple domain names on the same IP) and/or load-balancing. He can also run other websites with other technologies, without requiring a different port-number on the web-server. It means your website runs on a fastcgi-server, and nginx forwards all web-requests for a certain domain via the fastcgi-protocol to that server. It also means your website runs in a fastcgi-pipeline, and you have to be careful what you do, e.g. you can't use HTTP 1.1 when transmitting files.
Otherwise, files will be garbled at the destination.
See also here and here.

To conclude:
.NET Core at present (2016-09-28) is not really portable, nor is is really cross-platform (in particular the debug-tools).
Nor is native-compilation easy, especially for ARM.
And to me, it also does not look like its development is "really finished", yet.
For example, System.Data.DataTable/DataAdaper.Update is missing... (not anymore with .NET Core 2.0)
Together with the System.Data.Common.IDB* interfaces. (not anymore with .NET Core 1.1)
if there ever was one class that is often used, DataTable/DataAdapter would be it...
Also, the Linux-installer (.deb) fails, at least on my machine, and I'm sure I'm not the only one that has that problem.
Debug, maybe with Visual Studio Code, if you can build it on ARM (I managed to do that - do NOT follow Scott Hanselman's blog-post if you do that - there's a howto in the wiki of VS-Code on github), because they don't offer the executable.
Yeoman also fails. (I guess it has something to do with the nodejs version you installed - VS Code requires one version, Yeoman another... but it should run on the same computer. pretty lame
Never mind that it should run on the node version shipped by default on the OS.
Never mind that there should be no dependency on NodeJS in the first place.
The kestell server is also work in progress.
And judging by my experience with the mono-project, I highly doubt they ever tested .NET Core on FastCGI, or that they have any idea what FastCGI-support means for their framework, let alone that they tested it to make sure "everything works". In fact, I just tried making a fastcgi-application with .NET Core and just realized there is no FastCGI library for .NET Core "RTM"...

So when you're going to run .NET Core "RTM" behind nginx, you can only do it by proxying requests to kestrell (that semi-finished nodeJS-derived web-server) - there's no fastcgi support at present in .NET Core "RTM", AFAIK. Since there is no .net core fastcgi library, and no samples, it's also highly unlikely that anybody did any testing on the framework to make sure fastcgi works as expected.

I also question the performance.
In the (preliminary) techempower-benchmark (round 13), aspnetcore-linux ranks on 25% relative to the best performance, while comparable frameworks like Go (golang) rank at 96.9% of peak performance (and that is when returning plaintext without file-system access only). .NET Core does a little better on JSON-serialization, but it does not look compelling either (go reaches 98.5% of peak, .NET core 65%). That said, it can't possibly be worse than "mono proper".

Also, since it's still relatively new, not all of the major libraries have been ported (yet), and I doubt that some of them will ever be ported.
Imaging support is also questionable at best.
For anything encryption, use BouncyCastle instead.

Can you help me make sense of all these terms and if my expectations are realistic?

I hope i helped you making more sense with all these terms.
As far as your expecations go:
Developing a Linux application without knowing anything about Linux is a really stupid idea in the first place, and it's also bound to fail in some horrible way one way or the other. That said, because Linux comes at no licensing costs, it's a good idea in principle, BUT ONLY IF YOU KNOW WHAT YOU DO.
Developing an application for a platform where you can't debug your application on is another really bad idea.
Developing for fastcgi without knowing what consequences there are is yet another really bad idea.

Doing all these things on a "experimental" platform without any knowledge of that platform's specifics and without debugging support is suicide, if your project is more than just a personal homepage. On the other hand, I guess doing it with your personal homepage for learning purposes would probably be a very good experience - then you get to know what the framework and what the non-framework problems are.
You can for example (programmatically) loop-mount a case-insensitive fat32, hfs or JFS for your application, to get around the case-sensitivity issues (loop-mount not recommended in production).

To summarize
At present (2016-09-28), I would stay away from .NET Core (for production usage). Maybe in one to two years, you can take another look, but probably not before.
If you have a new web-project that you develop, start it in .NET Core, not mono.

If you want a framework that works on Linux (x86/AMD64/ARMhf) and Windows and Mac, that has no dependencies, i.e. only static linking and no dependency on .NET, Java or Windows, use Golang instead. It's more mature, and its performance is proven (Baidu uses it with 1 million concurrent users), and golang has a significantly lower memory footprint. Also golang is in the repositories, the .deb installs without problems, the sourcecode compiles - without requiring changes - and golang (in the meantime) has debugging support with delve and JetBrains Gogland on Linux (and Windows and Mac). Golang's build process (and runtime) also doesn't depend on NodeJS, which is yet another plus.

As far as mono goes, stay away from it.
It is nothing short of amazing how far mono has come, but unfortunately that's no substitute for its performance/scalability and stability issues for production applications.
Also, mono-development is quite dead, they largely only develop the parts relevant to Android and iOS anymore, because that's where Xamarin makes their money.
Don't expect Web-Development to be a first-class Xamarin/mono citizen.
.NET Core might be worth it, if you start a new project, but for existing large web-forms projects, porting over is largely out of the question, the changes required are huge. If you have a MVC-project, the amount of changes might be manageable, if your original application design was sane, which is mostly not the case for most existing so-called "historically grown" applications.

December 2016 Update:
Native compilation has been removed from .NET Core preview, as it is not yet ready...

Seems like they have improved pretty heavily on the raw text-file benchmark, but on the other hand, it's gotten pretty buggy. Also, it further deteriorated in the JSON benchmarks. Curious also that entity framework shall be faster for updates than Dapper - although both at record slowness. This is very unlikely to be true. Looks like there still are more than just a few bugs to hunt.

Also, there seems to be relief coming on the Linux IDE front.
JetBrains released "Project Rider", an early access preview of a C#/.NET Core IDE for Linux (and Mac and Windows), that can handle Visual Studio Project files. Finally a C# IDE that is usable & that isn't slow as hell.

Conclusion: .NET Core still is pre-release quality software as we march into 2017. Port your libraries, but stay away from it for production usage, until framework quality stabilizes.
And keep an eye on Project Rider.

buggy .net core

2017 Update
Have migrated my (brother's) homepage to .NET Core for now.
So far, the runtime on Linux seems to be stable enough (at least for small projects) - it survived a load test with ease - mono never did.
Also, it looks like I mixed up .NET-Core-native and .NET-Core-self-contained-deployment. Self-contained deployment works, but it is a bit underdocumented, although it's super easy (the build/publish tools are a bit unstable, yet - if you encounter "Positive number required. - Build FAILED." - run the same command again, and it works).

You can run

dotnet restore -r win81-x64
dotnet build -r win81-x64
dotnet publish -f netcoreapp1.1 -c Release -r win81-x64

Note: As per .NET Core 3, you can publish everything minified as a single file:

dotnet publish -r win-x64 -c Release /p:PublishSingleFile=true
dotnet publish -r linux-x64 -c Release /p:PublishSingleFile=true

However, unlike go, it's not a statically linked executable, but a self-extracting zip file, so when deploying, you might run into problems, especially if the temp directory is locked down by group policy, or some other issues. Works fine for a hello-world program, though. And if you don't minify, the executable size will clock in at something around 100 MB.

And you get a self-contained .exe-file (in the publish directory), which you can move to a Windows 8.1 machine without .NET framework installed and let it run. Nice. It's here that dotNET-Core just starts to get interesting. (mind the gaps, SkiaSharp doesn't work on Windows 8.1 / Windows Server 2012 R2, [yet] - the ecosystem has to catch up first - but interestingly, the Skia-dll-load-fail doesn't crash the entire server/application - so everything else works)

(Note: SkiaSharp on Windows 8.1 is missing the appropriate VC runtime files - msvcp140.dll and vcruntime140.dll. Copy them into the publish-directory, and Skia will work on Windows 8.1.)

August 2017 Update
.NET Core 2.0 released.
Be careful - comes with (huge breaking) changes in authentication...
On the upside, it brought the DataTable/DataAdaper/DataSet classes back, and many more.
Realized .NET Core is still missing support for Apache SparkSQL, because Mobius isn't yet ported. That's bad, because that means no SparkSQL support for my IoT Cassandra Cluster, so no joins...
Experimental ARM support (runtime only, not SDK - too bad for devwork on my Chromebook - looking forward to 2.1 or 3.0).
PdfSharp is now experimentally ported to .NET Core.
JetBrains Rider left EAP. You can now use it to develop & debug .NET Core on Linux - though so far only .NET Core 1.1 until the update for .NET Core 2.0 support goes live.

May 2018 Update
.NET Core 2.1 release imminent. Maybe this will fix NTLM-authentication on Linux (NTLM authentication doesn't work on Linux {and possibly Mac} in .NET-Core 2.0 with multiple authenticate headers, such as negotiate, commonly sent with ms-exchange, and they're apparently only fixing it in v2.1, no bugfix release for 2.0).
But I'm not installing preview releases on my machine. So waiting.
v2.1 is also said to greatly reduce compile times. That would be good.

Also, note that on Linux, .NET Core is 64-Bit only !
There is no, and there will be no, x86-32 version of .NET Core on Linux.
And the ARM port is ARM-32 only. No ARM-64, yet.
And on ARM, you (at present) only have the runtime, not the dotnet-SDK.

And one more thing:
Because .NET-Core uses OpenSSL 1.0, .NET Core on Linux doesn't run on Arch Linux, and by derivation not on Manjaro (the most popular Linux distro by far at this point in time), because Arch Linux uses OpenSSL 1.1. So if you're using Arch Linux, you're out of luck (with Gentoo, too).

Edit:

Latest version of .NET Core 2.2+ supports OpenSSL 1.1. So you can use it on Arch or (k)Ubuntu 19.04+. You might have to use the .NET-Core install script though, because there are no packages, yet.

On the upside, performance has definitely improved: fortunes

plaintext

.NET Core 3:
.NET-Core v 3.0 is said to bring WinForms and WPF to .NET-Core.
However, while WinForms and WPF will be .NET Core, WinForms and WPF in .NET-Core will run on Windows only, because WinForms/WPF will use the Windows-API.

Note:
.NET Core 3.0 is now out (RTM), and there is WinForms and WPF support, but only for C# (on Windows). There is no WinForms-Core-Designer. The designer will, eventually, come with a Visual Studio update, somewhen. WinForms support for VB.NET is not supported, but is planned for .NET 5.0 somewhen in 2020.

PS:

echo "DOTNET_CLI_TELEMETRY_OPTOUT=1" >> /etc/environment
export DOTNET_CLI_TELEMETRY_OPTOUT=1 

If you've used it on windows, you probably never saw this:

The .NET Core tools collect usage data in order to improve your experience.
The data is anonymous and does not include command-line arguments.
The data is collected by Microsoft and shared with the community.
You can opt out of telemetry by setting a DOTNET_CLI_TELEMETRY_OPTOUT environment variable to 1 using your favorite shell.
You can read more about .NET Core tools telemetry @ https://aka.ms/dotnet-cli-telemetry.

I thought I'd mention that I think monodevelop (aka Xamarin Studio, the Mono IDE, or Visual Studio Mac as it is now called on Mac) has evolved quite nicely, and is - in the meantime - largely usable.
However, JetBrains Rider (2018 EAP at this point in time) is definitely a lot nicer and more reliable (and the included decompiler is a life-safer), that is to say, if you develop .NET-Core on Linux or Mac. MonoDevelop does not support Debug-StepThrough on Linux in .NET Core, though, since MS does not license their debugging API dll (except for VisualStudio Mac ... ). However, you can use the Samsung debugger for .NET Core through the .NET Core debugger extension for Samsung Debugger for MonoDevelop

Disclaimer:
I don't use Mac, so I can't say if what I wrote here applies to FreeBSD-Unix based Mac as well. I am refering to the Linux (Debian/Ubuntu/Mint) version of JetBrains Rider, mono, MonoDevelop/VisualStudioMac/XamarinStudio and .NET-Core. Also, Apple is contemplating a move from Intel-processors to self-manufactured ARM(ARM-64?)-based processors, so much of what applies to Mac right now might not apply to Mac in the future (2020+).

Also, when I write "mono is quite unstable and slow", the unstable relates to WinFroms & WebForms applications, specifically executing web-applications via fastcgi or with XSP (on the 4.x version of mono), as well as XML-serialization-handling peculiarities, and the quite-slow relates to WinForms, and regular expressions in particular (ASP.NET-MVC uses regular expressions for routing as well).

When I write about my experience about mono 2.x, 3.x and 4.x, that also does not necessarely mean these issues haven't been resolved by now, or by the time you are reading this, nor that if they are fixed now, that there can't be a regression later that reintroduces any of these bugs/features. Nor does that mean that if you embed the mono-runtime, you'll get the same results as when you use the (dev) system's mono runtime. It also doesn't mean that embedding the mono-runtime (anywhere) is necessarely free.

All that doesn't necessarely mean mono is ill-suited for iOS or Android, or that it has the same issues there. I don't use mono on Android or IOS, so I'm in no positon to say anything about stability, usability, costs and performance on these platforms. Obviously, if you use .NET on Android, you have some other costs considerations to do as well, such as weighting xamarin-costs vs. costs and time for porting existing code to Java. One hears mono on Android and IOS shall be quite good. Take it with a grain of salt. For one, don't expect the default-system-encoding to be the same on android/ios vs. Windows, and don't expect the android filesystem to be case-insensitive, and don't expect any windows fonts to be present.

Fixed header, footer with scrollable content

If you're targeting browsers supporting flexible boxes you could do the following.. http://jsfiddle.net/meyertee/AH3pE/

HTML

<div class="container">
    <header><h1>Header</h1></header>
    <div class="body">Body</div>
    <footer><h3>Footer</h3></footer>
</div>

CSS

.container {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    flex-wrap: nowrap;
}

header {
    flex-shrink: 0;
}
.body{
    flex-grow: 1;
    overflow: auto;
    min-height: 2em;
}
footer{
    flex-shrink: 0;
}

Update:
See "Can I use" for browser support of flexible boxes.

How do I create a chart with multiple series using different X values for each series?

You need to use the Scatter chart type instead of Line. That will allow you to define separate X values for each series.

How to have css3 animation to loop forever

add this styles

animation-iteration-count:infinite;

How to decompile a whole Jar file?

First of all, it's worth remembering that all Java archive files (.jar/.war/etc...) are all basically just fancy.zip files, with a few added manifests and metadata.

Second, to tackle this problem I personally use several tools which handle this problem on all levels:

  • Jad + Jadclipse while working in IDE for decompiling .class files
  • WinRAR, my favorite compression tool natively supports Java archives (again, see first paragraph).
  • Beyond Compare, my favorite diff tool, when configured correctly can do on-the-fly comparisons between any archive file, including jars. Well worth a try.

The advantage of all the aforementioned, is that I do not need to hold any other external tool which clutters my work environment. Everything I will ever need from one of those files can be handled inside my IDE or diffed with other files natively.

git pull error "The requested URL returned error: 503 while accessing"

This problem is not only created by no_proxy, because it created by git server down issue also.

So When happening this issue first you open and check gitlab in browser.

And check if It shows any error like "503 An internal server error occured". .

The gitlab shows "503" page, this issue create by gitlab server down not in your system.

So you wait some time until the server going up and continue your work.

Is there a cross-browser onload event when clicking the back button?

Unload event is not working fine on IE 9. I tried it with load event (onload()), it is working fine on IE 9 and FF5.

Example:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
    jQuery(window).bind("load", function() {
        $("[name=customerName]").val('');
    });
</script>
</head>
<body>
    <h1>body.jsp</h1>
    <form action="success.jsp">
        <div id="myDiv">

        Your Full Name: <input name="yourName" id="fullName"
            value="Your Full Name" /><br> <br> <input type="submit"><br>

        </div>

    </form>
</body>
</html>

Callback functions in Java

Since Java 8, there are lambda and method references:

For example, if you want a functional interface A -> B such as:

import java.util.function.Function;

public MyClass {
    public static String applyFunction(String name, Function<String,String> function){
        return function.apply(name);
    }
}

then you can call it like so

MyClass.applyFunction("42", str -> "the answer is: " + str);
// returns "the answer is: 42"

Also you can pass class method. Say you have:

@Value // lombok
public class PrefixAppender {
    private String prefix;

    public String addPrefix(String suffix){
        return prefix +":"+suffix;
    }
}

Then you can do:

PrefixAppender prefixAppender= new PrefixAppender("prefix");
MyClass.applyFunction("some text", prefixAppender::addPrefix);
// returns "prefix:some text"

Note:

Here I used the functional interface Function<A,B>, but there are many others in the package java.util.function. Most notable ones are

  • Supplier: void -> A
  • Consumer: A -> void
  • BiConsumer: (A,B) -> void
  • Function: A -> B
  • BiFunction: (A,B) -> C

and many others that specialize on some of the input/output type. Then, if it doesn't provide the one you need, you can create your own functional interface like so:

@FunctionalInterface
interface Function3<In1, In2, In3, Out> { // (In1,In2,In3) -> Out
    public Out apply(In1 in1, In2 in2, In3 in3);
}

Example of use:

String computeAnswer(Function3<String, Integer, Integer, String> f){
    return f.apply("6x9=", 6, 9);
}

computeAnswer((question, a, b) -> question + "42");
// "6*9=42"

And you can also do that with thrown exception:

@FunctionalInterface
interface FallibleFunction<In, Out, Ex extends Exception> {
    Out get(In input) throws Ex;
}
public <Ex extends IOException> String yo(FallibleFunction<Integer, String, Ex> f) throws Ex {
    return f.get(42);
}

Portable way to check if directory exists [Windows/Linux, C]

You can use the GTK glib to abstract from OS stuff.

glib provides a g_dir_open() function which should do the trick.

How can I parse a string with a comma thousand separator to a number?

On modern browsers you can use the built in Intl.NumberFormat to detect the browser's number formatting and normalize the input to match.

_x000D_
_x000D_
function parseNumber(value, locales = navigator.languages) {
  const example = Intl.NumberFormat(locales).format('1.1');
  const cleanPattern = new RegExp(`[^-+0-9${ example.charAt( 1 ) }]`, 'g');
  const cleaned = value.replace(cleanPattern, '');
  const normalized = cleaned.replace(example.charAt(1), '.');

  return parseFloat(normalized);
}

const corpus = {
  '1.123': {
    expected: 1.123,
    locale: 'en-US'
  },
  '1,123': {
    expected: 1123,
    locale: 'en-US'
  },
  '2.123': {
    expected: 2123,
    locale: 'fr-FR'
  },
  '2,123': {
    expected: 2.123,
    locale: 'fr-FR'
  },
}


for (const candidate in corpus) {
  const {
    locale,
    expected
  } = corpus[candidate];
  const parsed = parseNumber(candidate, locale);

  console.log(`${ candidate } in ${ corpus[ candidate ].locale } == ${ expected }? ${ parsed === expected }`);
}
_x000D_
_x000D_
_x000D_

Their's obviously room for some optimization and caching but this works reliably in all languages.

Pause Console in C++ program

There might be a best way (like using the portable cin.get()), but a good way doesn't exist. A program that has done its job should quit and give its resources back to the computer.

And yes, any usage of system() leads to unportable code, as the parameter is passed to the shell that owns your process.

Having pausing-code in your source code sooner or later causes hassles:

  • someone forgets to delete the pausing code before checking in
    • now all working mates have to wonder why the app does not close anymore
    • version history is tainted
  • #define is hell
  • it's annoying to anyone who runs your code from the console
  • it's very, very, very annoying when trying to start and end your program from within a script; quadly annoying if your program is part of a pipeline in the shell, because if the program does not end, the shell script or pipeline won't, too

Instead, explore your IDE. It probably has an option not to close the console window after running. If not, it's a great justification to you as a developer worth her/his money to always have a console window open nearby.

Alternatively, you can make this a program option, but I personally have never seen a program with an option --keep-alive-when-dead.

Moral of the story: This is the user's problem, and not the program's problem. Don't taint your code.

How do I obtain a Query Execution Plan in SQL Server?

Starting from SQL Server 2016+, Query Store feature was introduced to monitor performance. It provides insight into query plan choice and performance. It’s not a complete replacement of trace or extended events, but as it’s evolving from version to version, we might get a fully functional query store in future releases from SQL Server. The primary flow of Query Store

  1. SQL Server existing components interact with query store by utilising Query Store Manager.
  2. Query Store Manager determines which Store should be used and then passes execution to that store (Plan or Runtime Stats or Query Wait Stats)
    • Plan Store - Persisting the execution plan information
    • Runtime Stats Store - Persisting the execution statistics information
    • Query Wait Stats Store - Persisting wait statistics information.
  3. Plan, Runtime Stats and Wait store uses Query Store as an extension to SQL Server.

enter image description here

  1. Enabling the Query Store: Query Store works at the database level on the server.

    • Query Store is not active for new databases by default.
    • You cannot enable the query store for the master or tempdb database.
    • Available DMV

      sys.database_query_store_options (Transact-SQL)

  2. Collect Information in the Query Store: We collect all the available information from the three stores using Query Store DMV (Data Management Views).

NOTE: Query Wait Stats Store is available only in SQL Server 2017+

Round a double to 2 decimal places

In your question, it seems that you want to avoid rounding the numbers as well? I think .format() will round the numbers using half-up, afaik?
so if you want to round, 200.3456 should be 200.35 for a precision of 2. but in your case, if you just want the first 2 and then discard the rest?

You could multiply it by 100 and then cast to an int (or taking the floor of the number), before dividing by 100 again.

200.3456 * 100 = 20034.56;  
(int) 20034.56 = 20034;  
20034/100.0 = 200.34;

You might have issues with really really big numbers close to the boundary though. In which case converting to a string and substring'ing it would work just as easily.

How do you replace all the occurrences of a certain character in a string?

You really should have multiple input, e.g. one for firstname, middle names, lastname and another one for age. If you want to have some fun though you could try:

>>> input_given="join smith 25"
>>> chars="".join([i for i in input_given if not i.isdigit()])
>>> age=input_given.translate(None,chars)
>>> age
'25'
>>> name=input_given.replace(age,"").strip()
>>> name
'join smith'

This would of course fail if there is multiple numbers in the input. a quick check would be:

assert(age in input_given)

and also:

assert(len(name)<len(input_given))

A child container failed during start java.util.concurrent.ExecutionException

This is what worked for me:

1) add commons-logging.jar to the WEB-INF/lib folder

2) Add this jar as a maven dependency, e.g. add this to the pom.xml:

 <dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.2</version>
 </dependency>

3) Maven install

4) Run the server.

Hope it helps.

Find duplicate values in R

You could use table, i.e.

n_occur <- data.frame(table(vocabulary$id))

gives you a data frame with a list of ids and the number of times they occurred.

n_occur[n_occur$Freq > 1,]

tells you which ids occurred more than once.

vocabulary[vocabulary$id %in% n_occur$Var1[n_occur$Freq > 1],]

returns the records with more than one occurrence.

awk without printing newline

If Perl is an option, here is a solution using fedorqui's example:

seq 5 | perl -ne 'chomp; print "$_ "; END{print "\n"}'

Explanation:
chomp removes the newline
print "$_ " prints each line, appending a space
the END{} block is used to print a newline

output: 1 2 3 4 5

convert streamed buffers to utf8-string

Single Buffer

If you have a single Buffer you can use its toString method that will convert all or part of the binary contents to a string using a specific encoding. It defaults to utf8 if you don't provide a parameter, but I've explicitly set the encoding in this example.

var req = http.request(reqOptions, function(res) {
    ...

    res.on('data', function(chunk) {
        var textChunk = chunk.toString('utf8');
        // process utf8 text chunk
    });
});

Streamed Buffers

If you have streamed buffers like in the question above where the first byte of a multi-byte UTF8-character may be contained in the first Buffer (chunk) and the second byte in the second Buffer then you should use a StringDecoder. :

var StringDecoder = require('string_decoder').StringDecoder;

var req = http.request(reqOptions, function(res) {
    ...
    var decoder = new StringDecoder('utf8');

    res.on('data', function(chunk) {
        var textChunk = decoder.write(chunk);
        // process utf8 text chunk
    });
});

This way bytes of incomplete characters are buffered by the StringDecoder until all required bytes were written to the decoder.

How to write to an existing excel file without overwriting data (using pandas)?

Old question, but I am guessing some people still search for this - so...

I find this method nice because all worksheets are loaded into a dictionary of sheet name and dataframe pairs, created by pandas with the sheetname=None option. It is simple to add, delete or modify worksheets between reading the spreadsheet into the dict format and writing it back from the dict. For me the xlsxwriter works better than openpyxl for this particular task in terms of speed and format.

Note: future versions of pandas (0.21.0+) will change the "sheetname" parameter to "sheet_name".

# read a single or multi-sheet excel file
# (returns dict of sheetname(s), dataframe(s))
ws_dict = pd.read_excel(excel_file_path,
                        sheetname=None)

# all worksheets are accessible as dataframes.

# easy to change a worksheet as a dataframe:
mod_df = ws_dict['existing_worksheet']

# do work on mod_df...then reassign
ws_dict['existing_worksheet'] = mod_df

# add a dataframe to the workbook as a new worksheet with
# ws name, df as dict key, value:
ws_dict['new_worksheet'] = some_other_dataframe

# when done, write dictionary back to excel...
# xlsxwriter honors datetime and date formats
# (only included as example)...
with pd.ExcelWriter(excel_file_path,
                    engine='xlsxwriter',
                    datetime_format='yyyy-mm-dd',
                    date_format='yyyy-mm-dd') as writer:

    for ws_name, df_sheet in ws_dict.items():
        df_sheet.to_excel(writer, sheet_name=ws_name)

For the example in the 2013 question:

ws_dict = pd.read_excel('Masterfile.xlsx',
                        sheetname=None)

ws_dict['Main'] = data_filtered[['Diff1', 'Diff2']]

with pd.ExcelWriter('Masterfile.xlsx',
                    engine='xlsxwriter') as writer:

    for ws_name, df_sheet in ws_dict.items():
        df_sheet.to_excel(writer, sheet_name=ws_name)

how to loop through rows columns in excel VBA Macro

I'd recommend the Range object's AutoFill method for this:

rngSource.AutoFill Destination:=rngDest

Specify the Source range that contains the values or formulas you want to fill down, and the Destination range as the whole range that you want the cells filled to. The Destination range must include the Source range. You can fill across as well as down.

It works exactly the same way as it would if you manually "dragged" the cells at the corner with the mouse; absolute and relative formulas work as expected.

Here's an example:

'Set some example values'
Range("A1").Value = "1"
Range("B1").Formula = "=NOW()"
Range("C1").Formula = "=B1+A1"

'AutoFill the values / formulas to row 20'
Range("A1:C1").AutoFill Destination:=Range("A1:C20")

Hope this helps.

How to import a module given the full path?

The best way, I think, is from the official documentation (29.1. imp — Access the import internals):

import imp
import sys

def __import__(name, globals=None, locals=None, fromlist=None):
    # Fast path: see if the module has already been imported.
    try:
        return sys.modules[name]
    except KeyError:
        pass

    # If any of the following calls raises an exception,
    # there's a problem we can't handle -- let the caller handle it.

    fp, pathname, description = imp.find_module(name)

    try:
        return imp.load_module(name, fp, pathname, description)
    finally:
        # Since we may exit via an exception, close fp explicitly.
        if fp:
            fp.close()

How to set default values in Go structs

One problem with option 1 in answer from Victor Zamanian is that if the type isn't exported then users of your package can't declare it as the type for function parameters etc. One way around this would be to export an interface instead of the struct e.g.

package candidate
// Exporting interface instead of struct
type Candidate interface {}
// Struct is not exported
type candidate struct {
    Name string
    Votes uint32 // Defaults to 0
}
// We are forced to call the constructor to get an instance of candidate
func New(name string) Candidate {
    return candidate{name, 0}  // enforce the default value here
}

Which lets us declare function parameter types using the exported Candidate interface. The only disadvantage I can see from this solution is that all our methods need to be declared in the interface definition, but you could argue that that is good practice anyway.

Attach a body onload event with JS

document.body.onload is a cross-browser, but a legacy mechanism that only allows a single callback (you cannot assign multiple functions to it).

The closest "standard" alternative, addEventListener is not supported by Internet Explorer (it uses attachEvent), so you will likely want to use a library (jQuery, MooTools, prototype.js, etc.) to abstract the cross-browser ugliness for you.

Multiple INNER JOIN SQL ACCESS

Access requires parentheses in the FROM clause for queries which include more than one join. Try it this way ...

FROM
    ((tbl_employee
    INNER JOIN tbl_netpay
    ON tbl_employee.emp_id = tbl_netpay.emp_id)
    INNER JOIN tbl_gross
    ON tbl_employee.emp_id = tbl_gross.emp_ID)
    INNER JOIN tbl_tax
    ON tbl_employee.emp_id = tbl_tax.emp_ID;

If possible, use the Access query designer to set up your joins. The designer will add parentheses as required to keep the db engine happy.

How to save a pandas DataFrame table as a png

Although I am not sure if this is the result you expect, you can save your DataFrame in png by plotting the DataFrame with Seaborn Heatmap with annotations on, like this:

http://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.heatmap.html#seaborn.heatmap

Example of Seaborn heatmap with annotations on

It works right away with a Pandas Dataframe. You can look at this example: Efficiently ploting a table in csv format using Python

You might want to change the colormap so it displays a white background only.

Hope this helps.

AWS S3: how do I see how much disk space is using

s3cmd can show you this by running s3cmd du, optionally passing the bucket name as an argument.

Back to previous page with header( "Location: " ); in PHP

Storing previous url in a session variable is bad, because the user might right click on multiple pages and then come back and save.

unless you save the previous url in the session variable to a hidden field in the form and after save header( "Location: save URL of calling page" );

Windows recursive grep command-line

I just searched a text with following command which listed me all the file names containing my specified 'search text'.

C:\Users\ak47\Desktop\trunk>findstr /S /I /M /C:"search text" *.*

How to make sure docker's time syncs with that of the host?

I've discovered that if your computer goes to sleep then the docker container goes out of sync.

https://forums.docker.com/t/time-in-container-is-out-of-sync/16566

I have made a post about it here Certificate always expires 5 days ago in Docker

Angular JS update input field after change

You can add ng-change directive to input fields. Have a look at the docs example.

Replacing last character in a String with java

Firstly Strings are immutable in java, you have to assign the result of the replace to a variable.

fieldName = fieldName.replace("watever","");

You can use also use regex as an option using String#replaceAll(regex, str);

fieldName = fieldName.replaceAll(",$","");

Polymorphism: Why use "List list = new ArrayList" instead of "ArrayList list = new ArrayList"?

This is also helpful when exposing a public interface. If you have a method like this,

public ArrayList getList();

Then you decide to change it to,

public LinkedList getList();

Anyone who was doing ArrayList list = yourClass.getList() will need to change their code. On the other hand, if you do,

public List getList();

Changing the implementation doesn't change anything for the users of your API.

react button onClick redirect page

I was trying to find a way with Redirect but failed. Redirecting onClick is simpler than we think. Just place the following basic JavaScript within your onClick function, no monkey business:

window.location.href="pagelink"

Get first day of week in PHP?

Here I am considering Sunday as first & Saturday as last day of the week.

$m = strtotime('06-08-2012');  
$today =   date('l', $m);  
$custom_date = strtotime( date('d-m-Y', $m) );   
if ($today == 'Sunday') {  
   $week_start = date("d-m-Y", $m);  
} else {  
  $week_start = date('d-m-Y', strtotime('this week last sunday', $custom_date));  
}  

if ($today == 'Saturday') {  
  $week_end = date("d-m-Y", $m);
} else {  
  $week_end = date('d-m-Y', strtotime('this week next saturday', $custom_date));  
}
echo '<br>Start: '. $week_start;  
echo '<br>End: '. $week_end;  

Output :

Start: 05-08-2012
End: 11-08-2012

CMake link to external library

arrowdodger's answer is correct and preferred on many occasions. I would simply like to add an alternative to his answer:

You could add an "imported" library target, instead of a link-directory. Something like:

# Your-external "mylib", add GLOBAL if the imported library is located in directories above the current.
add_library( mylib SHARED IMPORTED )
# You can define two import-locations: one for debug and one for release.
set_target_properties( mylib PROPERTIES IMPORTED_LOCATION ${CMAKE_BINARY_DIR}/res/mylib.so )

And then link as if this library was built by your project:

TARGET_LINK_LIBRARIES(GLBall mylib)

Such an approach would give you a little more flexibility: Take a look at the add_library( ) command and the many target-properties related to imported libraries.

I do not know if this will solve your problem with "updated versions of libs".

Track a new remote branch created on GitHub

First of all you have to fetch the remote repository:

git fetch remoteName

Than you can create the new branch and set it up to track the remote branch you want:

git checkout -b newLocalBranch remoteName/remoteBranch

You can also use "git branch --track" instead of "git checkout -b" as max specified.

git branch --track newLocalBranch remoteName/remoteBranch

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

You should first add a new route in global.asax:


routes.MapRoute(
                "MyNewRoute",
                "{controller}/{action}/{date}",
                new { controller="YourControllerName", action="YourActionName", date = "" }
            );

The on your Controller:



        public ActionResult MyActionName(DateTime date)
        {

        }

Remember to keep your default route at the bottom of the RegisterRoutes method. Be advised that the engine will try to cast whatever value you send in {date} as a DateTime example, so if it can't be casted then an exception will be thrown. If your date string contains spaces or : you could HTML.Encode them so the URL could be parsed correctly. If no, then you could have another DateTime representation.

What does "fatal: bad revision" mean?

If you only want to revert a single file to its state in a given commit, you actually want to use the checkout command:

git checkout HEAD~2 myFile

The revert command is used for reverting entire commits (and it doesn't revert you to that commit; it actually just reverts the changes made by that commit - if you have another commit after the one you specify, the later commit won't be reverted).

Formatting "yesterday's" date in python

This should do what you want:

import datetime
yesterday = datetime.datetime.now() - datetime.timedelta(days = 1)
print yesterday.strftime("%m%d%y")

oracle varchar to number

Since the column is of type VARCHAR, you should convert the input parameter to a string rather than converting the column value to a number:

select * from exception where exception_value = to_char(105);

Left Join without duplicate rows from left table

You can do this using generic SQL with group by:

SELECT C.Content_ID, C.Content_Title, MAX(M.Media_Id)
FROM tbl_Contents C LEFT JOIN
     tbl_Media M
     ON M.Content_Id = C.Content_Id 
GROUP BY C.Content_ID, C.Content_Title
ORDER BY MAX(C.Content_DatePublished) ASC;

Or with a correlated subquery:

SELECT C.Content_ID, C.Contt_Title,
       (SELECT M.Media_Id
        FROM tbl_Media M
        WHERE M.Content_Id = C.Content_Id
        ORDER BY M.MEDIA_ID DESC
        LIMIT 1
       ) as Media_Id
FROM tbl_Contents C 
ORDER BY C.Content_DatePublished ASC;

Of course, the syntax for limit 1 varies between databases. Could be top. Or rownum = 1. Or fetch first 1 rows. Or something like that.

How to set cornerRadius for only top-left and top-right corner of a UIView?

If you're looking for an interface builder only solution there is one for iOS 11 and higher. See my answer here: https://stackoverflow.com/a/58626264

Batch command date and time in file name

Another solution:

for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set datetime=%%I

It will give you (independent of locale settings!):

  20130802203023.304000+120
( YYYYMMDDhhmmss.<milliseconds><always 000>+/-<minutes difference to UTC>  )

From here, it is easy:

set datetime=%datetime:~0,8%-%datetime:~8,6%
20130802-203023

For Logan's request for the same outputformat for the "date-time modified" of a file:

for %%F in (test.txt) do set file=%%~fF
for /f "tokens=2 delims==" %%I in ('wmic datafile where name^="%file:\=\\%" get lastmodified /format:list') do set datetime=%%I
echo %datetime%

It is a bit more complicated, because it works only with full paths, wmic expects the backslashes to be doubled and the = has to be escaped (the first one. The second one is protected by surrounding quotes).

What is a lambda (function)?

The lambda calculus is a consistent mathematical theory of substitution. In school mathematics one sees for example x+y=5 paired with x-y=1. Along with ways to manipulate individual equations it's also possible to put the information from these two together, provided cross-equation substitutions are done logically. Lambda calculus codifies the correct way to do these substitutions.

Given that y = x-1 is a valid rearrangement of the second equation, this: ? y = x-1 means a function substituting the symbols x-1 for the symbol y. Now imagine applying ? y to each term in the first equation. If a term is y then perform the substitution; otherwise do nothing. If you do this out on paper you'll see how applying that ? y will make the first equation solvable.

That's an answer without any computer science or programming.

The simplest programming example I can think of comes from http://en.wikipedia.org/wiki/Joy_(programming_language)#How_it_works:

here is how the square function might be defined in an imperative programming language (C):

int square(int x)
{
    return x * x;
}

The variable x is a formal parameter which is replaced by the actual value to be squared when the function is called. In a functional language (Scheme) the same function would be defined:

(define square
  (lambda (x) 
    (* x x)))

This is different in many ways, but it still uses the formal parameter x in the same way.


Added: http://imgur.com/a/XBHub

lambda

Converting a date string to a DateTime object using Joda Time library

I know this is an old question, but I wanted to add that, as of JodaTime 2.0, you can do this with a one-liner:

DateTime date = DateTime.parse("04/02/2011 20:27:05", 
                  DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss"));

How to easily resize/optimize an image size with iOS?

If anyone still looking for better option

-(UIImage *)scaleImage:(UIImage *)image toSize:(CGSize)targetSize {


    UIImage *sourceImage = image;
    UIImage *newImage = nil;

    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;

    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;

    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;

    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);

    if (CGSizeEqualToSize(imageSize, targetSize) == NO) {

        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;

        if (widthFactor < heightFactor)
            scaleFactor = widthFactor;
        else
            scaleFactor = heightFactor;

        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;

        // center the image


        if (widthFactor < heightFactor) {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        } else if (widthFactor > heightFactor) {
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }


    // this is actually the interesting part:

    UIGraphicsBeginImageContext(targetSize);

    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;

    [sourceImage drawInRect:thumbnailRect];

    newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    if(newImage == nil) NSLog(@"could not scale image");


    return newImage ;

}

Java - Change int to ascii

In fact in the last answer String strAsciiTab = Character.toString((char) iAsciiValue); the essential part is (char)iAsciiValue which is doing the job (Character.toString useless)

Meaning the first answer was correct actually char ch = (char) yourInt;

if in yourint=49 (or 0x31), ch will be '1'

Convert UTF-8 to base64 string

It's a little difficult to tell what you're trying to achieve, but assuming you're trying to get a Base64 string that when decoded is abcdef==, the following should work:

byte[] bytes = Encoding.UTF8.GetBytes("abcdef==");
string base64 = Convert.ToBase64String(bytes);
Console.WriteLine(base64);

This will output: YWJjZGVmPT0= which is abcdef== encoded in Base64.

Edit:

To decode a Base64 string, simply use Convert.FromBase64String(). E.g.

string base64 = "YWJjZGVmPT0=";
byte[] bytes = Convert.FromBase64String(base64);

At this point, bytes will be a byte[] (not a string). If we know that the byte array represents a string in UTF8, then it can be converted back to the string form using:

string str = Encoding.UTF8.GetString(bytes);
Console.WriteLine(str);

This will output the original input string, abcdef== in this case.

Highlight Bash/shell code in Markdown files

Bitbucket uses CodeMirror for syntax highlighting. For Bash or shell you can use sh, bash, or zsh. More information can be found at Configuring syntax highlighting for file extensions and Code mirror language modes.

Send data from javascript to a mysql database

You will have to submit this data to the server somehow. I'm assuming that you don't want to do a full page reload every time a user clicks a link, so you'll have to user XHR (AJAX). If you are not using jQuery (or some other JS library) you can read this tutorial on how to do the XHR request "by hand".

What is &#39; and why does Google search replace it with apostrophe?

It's HTML character references for encoding a character by its decimal code point

Look at the ASCII table here and you'll see that 39 (hex 0x27, octal 47) is the code for apostrophe

ASCII table

ipython notebook clear cell output in code

You can use IPython.display.clear_output to clear the output of a cell.

from IPython.display import clear_output

for i in range(10):
    clear_output(wait=True)
    print("Hello World!")

At the end of this loop you will only see one Hello World!.

Without a code example it's not easy to give you working code. Probably buffering the latest n events is a good strategy. Whenever the buffer changes you can clear the cell's output and print the buffer again.

How do we determine the number of days for a given month in python

Alternative solution:

>>> from datetime import date
>>> (date(2012, 3, 1) - date(2012, 2, 1)).days
29

How to set up java logging using a properties file? (java.util.logging)

Are you searching for the log file in the right path: %h/one%u.log

Here %h resolves to your home : In windows this defaults to : C:\Documents and Settings(user_name).

I have tried the sample code you have posted and it works fine after you specify the configuration file path (logging.properties either through code or java args) .

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

If the strings you are concatenating are literals, use String literal concatenation

re.compile(
        "[A-Za-z_]"       # letter or underscore
        "[A-Za-z0-9_]*"   # letter, digit or underscore
    )

This is useful if you want to comment on part of a string (as above) or if you want to use raw strings or triple quotes for part of a literal but not all.

Since this happens at the syntax layer it uses zero concatenation operators.

Check if string is in a pandas dataframe

If there is any chance that you will need to search for empty strings,

    a['Names'].str.contains('') 

will NOT work, as it will always return True.

Instead, use

    if '' in a["Names"].values

to accurately reflect whether or not a string is in a Series, including the edge case of searching for an empty string.

How to set max width of an image in CSS

Given your container width 600px.

If you want only bigger images than that to fit inside, add: CSS:

#ImageContainer img {
    max-width: 600px;
}

If you want ALL images to take the avaiable (600px) space:

#ImageContainer img {
    width: 600px;
}

Powershell: convert string to number

I demonstrate how to receive a string, for example "-484876800000" and tryparse the string to make sure it can be assigned to a long. I calculate the Date from universaltime and return a string. When you convert a string to a number, you must decide the numeric type and precision and test if the string data can be parse, otherwise, it will throw and error.

function universalToDate
{
 param (
    $paramValue
  )
    $retVal=""


    if ($paramValue)
    {
        $epoch=[datetime]'1/1/1970'
        [long]$returnedLong = 0
        [bool]$result = [long]::TryParse($paramValue,[ref]$returnedLong)
        if ($result -eq 1)
        {
            $val=$returnedLong/1000.0
            $retVal=$epoch.AddSeconds($val).ToString("yyyy-MM-dd")
        }
    }
    else
    {
        $retVal=$null
    }
    return($retVal)
 }

How do I unlock a SQLite database?

In my case, I also got this error.

I already checked for other processes that might be the cause of locked database such as (SQLite Manager, other programs that connects to my database). But there's no other program that connects to it, it's just another active SQLConnection in the same application that stays connected.

Try checking your previous active SQLConnection that might be still connected (disconnect it first) before you establish a new SQLConnection and new command.

Random strings in Python

Sometimes, I've wanted random strings that are semi-pronounceable, semi-memorable.

import random

def randomWord(length=5):
    consonants = "bcdfghjklmnpqrstvwxyz"
    vowels = "aeiou"

    return "".join(random.choice((consonants, vowels)[i%2]) for i in range(length))

Then,

>>> randomWord()
nibit
>>> randomWord()
piber
>>> randomWord(10)
rubirikiro

To avoid 4-letter words, don't set length to 4.

Jim

MySQL Fire Trigger for both Insert and Update

unfortunately we can't use in MySQL after INSERT or UPDATE description, like in Oracle

How to use JavaScript variables in jQuery selectors?

var name = this.name;
$("input[name=" + name + "]").hide();

OR you can do something like this.

var id = this.id;
$('#' + id).hide();

OR you can give some effect also.

$("#" + this.id).slideUp();

If you want to remove the entire element permanently form the page.

$("#" + this.id).remove();

You can also use it in this also.

$("#" + this.id).slideUp('slow', function (){
    $("#" + this.id).remove();
});

Best way to "push" into C# array

array.push is like List<T>.Add. .NET arrays are fixed-size so you can't actually add a new element. All you can do is create a new array that is one element larger than the original and then set that last element, e.g.

Array.Resize(ref myArray, myArray.Length + 1);
myArray[myArray.GetUpperBound(0)] = newValue;

EDIT:

I'm not sure that this answer actually applies given this edit to the question:

The crux of the matter is that the element needs to be added into the first empty slot in an array, lie a Java push function would do.

The code I provided effectively appends an element. If the aim is to set the first empty element then you could do this:

int index = Array.IndexOf(myArray, null);

if (index != -1)
{
    myArray[index] = newValue;
}

EDIT:

Here's an extension method that encapsulates that logic and returns the index at which the value was placed, or -1 if there was no empty element. Note that this method will work for value types too, treating an element with the default value for that type as empty.

public static class ArrayExtensions
{
    public static int Push<T>(this T[] source, T value)
    {
        var index = Array.IndexOf(source, default(T));

        if (index != -1)
        {
            source[index] = value;
        }

        return index;
    }
}

Ignoring a class property in Entity Framework 4.1 Code First

You can use the NotMapped attribute data annotation to instruct Code-First to exclude a particular property

public class Customer
{
    public int CustomerID { set; get; }
    public string FirstName { set; get; } 
    public string LastName{ set; get; } 
    [NotMapped]
    public int Age { set; get; }
}

[NotMapped] attribute is included in the System.ComponentModel.DataAnnotations namespace.

You can alternatively do this with Fluent API overriding OnModelCreating function in your DBContext class:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
   modelBuilder.Entity<Customer>().Ignore(t => t.LastName);
   base.OnModelCreating(modelBuilder);
}

http://msdn.microsoft.com/en-us/library/hh295847(v=vs.103).aspx

The version I checked is EF 4.3, which is the latest stable version available when you use NuGet.


Edit : SEP 2017

Asp.NET Core(2.0)

Data annotation

If you are using asp.net core (2.0 at the time of this writing), The [NotMapped] attribute can be used on the property level.

public class Customer
{
    public int Id { set; get; }
    public string FirstName { set; get; } 
    public string LastName { set; get; } 
    [NotMapped]
    public int FullName { set; get; }
}

Fluent API

public class SchoolContext : DbContext
{
    public SchoolContext(DbContextOptions<SchoolContext> options) : base(options)
    {
    }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Customer>().Ignore(t => t.FullName);
        base.OnModelCreating(modelBuilder);
    }
    public DbSet<Customer> Customers { get; set; }
}

How best to read a File into List<string>

//this is only good in .NET 4
//read your file:
List<string> ReadFile = File.ReadAllLines(@"C:\TEMP\FILE.TXT").ToList();

//manipulate data here
foreach(string line in ReadFile)
{
    //do something here
}

//write back to your file:
File.WriteAllLines(@"C:\TEMP\FILE2.TXT", ReadFile);

How to get info on sent PHP curl request

The request is printed in a request.txt with details

$ch = curl_init();
$f = fopen('request.txt', 'w');
curl_setopt_array($ch, array(
CURLOPT_URL            => $url, 
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_VERBOSE        => 1,
CURLOPT_STDERR         => $f,
));
$response = curl_exec($ch);
fclose($f);
curl_close($ch);

You can also use curl_getinfo() function.

Jenkins returned status code 128 with github

I changed the permission of my .ssh/id_rsa (private key) to 604. chmod 700 id_rsa

Rails Model find where not equal

In Rails 4.x (See http://edgeguides.rubyonrails.org/active_record_querying.html#not-conditions)

GroupUser.where.not(user_id: me)

In Rails 3.x

GroupUser.where(GroupUser.arel_table[:user_id].not_eq(me))

To shorten the length, you could store GroupUser.arel_table in a variable or if using inside the model GroupUser itself e.g., in a scope, you can use arel_table[:user_id] instead of GroupUser.arel_table[:user_id]

Rails 4.0 syntax credit to @jbearden's answer

how to enable sqlite3 for php?

The SQLite3 PDO driver is named SQLite, not SQLite3, so you can do:

new SQLite("database");

For a SQLite2 database:

new SQLite2("database");

How should I print types like off_t and size_t?

As I recall, the only portable way to do it, is to cast the result to "unsigned long int" and use %lu.

printf("sizeof(int) = %lu", (unsigned long) sizeof(int));

Using ZXing to create an Android barcode scanning app

Barcode Detection is now available in Google Play services. Code lab of the setup process, here are the api docs, and a sample project.

How to catch a unique constraint error in a PL/SQL block?

I'm sure you have your reasons, but just in case... you should also consider using a "merge" query instead:

begin
    merge into some_table st
    using (select 'some' name, 'values' value from dual) v
    on (st.name=v.name)
    when matched then update set st.value=v.value
    when not matched then insert (name, value) values (v.name, v.value);
end;

(modified the above to be in the begin/end block; obviously you can run it independantly of the procedure too).

Get all table names of a particular database by SQL query?

This works Fine

SELECT * FROM information_schema.tables;

Set 4 Space Indent in Emacs in Text Mode

Customizations can shadow (setq tab width 4) so either use setq-default or let Customize know what you're doing. I also had issues similar to the OP and fixed it with this alone, did not need to adjust tab-stop-list or any insert functions:

(custom-set-variables
 '(tab-width 4 't)
 )

Found it useful to add this immediately after (a tip from emacsWiki):

(defvaralias 'c-basic-offset 'tab-width)
(defvaralias 'cperl-indent-level 'tab-width)

Pandas: Subtracting two date columns and the result being an integer

You can divide column of dtype timedelta by np.timedelta64(1, 'D'), but output is not int, but float, because NaN values:

df_test['Difference'] = df_test['Difference'] / np.timedelta64(1, 'D')
print (df_test)
  First_Date Second Date  Difference
0 2016-02-09  2015-11-19        82.0
1 2016-01-06  2015-11-30        37.0
2        NaT  2015-12-04         NaN
3 2016-01-06  2015-12-08        29.0
4        NaT  2015-12-09         NaN
5 2016-01-07  2015-12-11        27.0
6        NaT  2015-12-12         NaN
7        NaT  2015-12-14         NaN
8 2016-01-06  2015-12-14        23.0
9        NaT  2015-12-15         NaN

Frequency conversion.

Using variable in SQL LIKE statement

As Andrew Brower says, but adding a trim

ALTER PROCEDURE <Name>
(
    @PartialName VARCHAR(50) = NULL
)

SELECT Name 
    FROM <table>
    WHERE Name LIKE '%' + LTRIM(RTRIM(@PartialName)) + '%'

How to delete and update a record in Hive

Good news,Insert updates and deletes are now possible on Hive/Impala using Kudu.

You need to use IMPALA/kudu to maintain the tables and perform insert/update/delete records. Details with examples can be found here: insert-update-delete-on-hadoop

Please share the news if you are excited.

-MIK

How to style a checkbox using CSS

Here is an example, with theme support. It is a modern approach with CSS transitions. There is absolutely no JavaScript required.

I derived the following code linked in this comment; on a related question.

Edit: I added radio buttons, as maxshuty suggests.

_x000D_
_x000D_
const selector = '.grid-container > .grid-row > .grid-col[data-theme="retro"]';_x000D_
const main = () => {_x000D_
  new CheckboxStyler().run(selector);_x000D_
  new RadioStyler().run(selector);_x000D_
};_x000D_
_x000D_
/*_x000D_
 * This is only used to add the wrapper class and checkmark span to an existing DOM,_x000D_
 * to make this CSS work._x000D_
 */_x000D_
class AbstractInputStyler {_x000D_
  constructor(options) {_x000D_
    this.opts = options;_x000D_
  }_x000D_
  run(parentSelector) {_x000D_
    let wrapperClass = this.opts.wrapperClass;_x000D_
    let parent = document.querySelector(parentSelector) || document.getElementsByTagName('body')[0];_x000D_
    let labels = parent.querySelectorAll('label');_x000D_
    if (labels.length) labels.forEach(label => {_x000D_
      if (label.querySelector(`input[type="${this.opts._inputType}"]`)) {_x000D_
        if (!label.classList.contains(wrapperClass)) {_x000D_
          label.classList.add(wrapperClass);_x000D_
          label.appendChild(this.__createDefaultNode());_x000D_
        }_x000D_
      }_x000D_
    });_x000D_
    return this;_x000D_
  }_x000D_
  /* @protected */_x000D_
  __createDefaultNode() {_x000D_
    let checkmark = document.createElement('span');_x000D_
    checkmark.className = this.opts._activeClass;_x000D_
    return checkmark;_x000D_
  }_x000D_
}_x000D_
_x000D_
class CheckboxStyler extends AbstractInputStyler {_x000D_
  constructor(options) {_x000D_
    super(Object.assign({_x000D_
      _inputType: 'checkbox',_x000D_
      _activeClass: 'checkmark'_x000D_
    }, CheckboxStyler.defaultOptions, options));_x000D_
  }_x000D_
}_x000D_
CheckboxStyler.defaultOptions = {_x000D_
  wrapperClass: 'checkbox-wrapper'_x000D_
};_x000D_
_x000D_
class RadioStyler extends AbstractInputStyler {_x000D_
  constructor(options) {_x000D_
    super(Object.assign({_x000D_
      _inputType: 'radio',_x000D_
      _activeClass: 'pip'_x000D_
    }, RadioStyler.defaultOptions, options));_x000D_
  }_x000D_
}_x000D_
RadioStyler.defaultOptions = {_x000D_
  wrapperClass: 'radio-wrapper'_x000D_
};_x000D_
_x000D_
main();
_x000D_
/* Theming */_x000D_
_x000D_
:root {_x000D_
  --background-color: #FFF;_x000D_
  --font-color: #000;_x000D_
  --checkbox-default-background: #EEE;_x000D_
  --checkbox-hover-background: #CCC;_x000D_
  --checkbox-disabled-background: #AAA;_x000D_
  --checkbox-selected-background: #1A74BA;_x000D_
  --checkbox-selected-disabled-background: #6694B7;_x000D_
  --checkbox-checkmark-color: #FFF;_x000D_
  --checkbox-checkmark-disabled-color: #DDD;_x000D_
}_x000D_
_x000D_
[data-theme="dark"] {_x000D_
  --background-color: #111;_x000D_
  --font-color: #EEE;_x000D_
  --checkbox-default-background: #222;_x000D_
  --checkbox-hover-background: #444;_x000D_
  --checkbox-disabled-background: #555;_x000D_
  --checkbox-selected-background: #2196F3;_x000D_
  --checkbox-selected-disabled-background: #125487;_x000D_
  --checkbox-checkmark-color: #EEE;_x000D_
  --checkbox-checkmark-disabled-color: #999;_x000D_
}_x000D_
_x000D_
[data-theme="retro"] {_x000D_
  --background-color: #FFA;_x000D_
  --font-color: #000;_x000D_
  --checkbox-default-background: #EEE;_x000D_
  --checkbox-hover-background: #FFF;_x000D_
  --checkbox-disabled-background: #BBB;_x000D_
  --checkbox-selected-background: #EEE;_x000D_
  --checkbox-selected-disabled-background: #BBB;_x000D_
  --checkbox-checkmark-color: #F44;_x000D_
  --checkbox-checkmark-disabled-color: #D00;_x000D_
}_x000D_
_x000D_
_x000D_
/* General styles */_x000D_
_x000D_
html {_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
body {_x000D_
  /*background: var(--background-color); -- For demo, moved to column. */_x000D_
  /*color:      var(--font-color);       -- For demo, moved to column. */_x000D_
  background: #777;_x000D_
  width: calc(100% - 0.5em);_x000D_
  height: calc(100% - 0.5em);_x000D_
  padding: 0.25em;_x000D_
}_x000D_
_x000D_
h1 {_x000D_
  font-size: 1.33em !important;_x000D_
}_x000D_
_x000D_
h2 {_x000D_
  font-size: 1.15em !important;_x000D_
  margin-top: 1em;_x000D_
}_x000D_
_x000D_
_x000D_
/* Grid style - using flex */_x000D_
_x000D_
.grid-container {_x000D_
  display: flex;_x000D_
  height: 100%;_x000D_
  flex-direction: column;_x000D_
  flex: 1;_x000D_
}_x000D_
_x000D_
.grid-row {_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  flex: 1;_x000D_
  margin: 0.25em 0;_x000D_
}_x000D_
_x000D_
.grid-col {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  height: 100%;_x000D_
  padding: 0 1em;_x000D_
  flex: 1;_x000D_
  margin: 0 0.25em;_x000D_
  /* If not demo, remove and uncomment the body color rules */_x000D_
  background: var(--background-color);_x000D_
  color: var(--font-color);_x000D_
}_x000D_
_x000D_
.grid-cell {_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
_x000D_
/* The checkbox wrapper */_x000D_
_x000D_
.checkbox-wrapper,_x000D_
.radio-wrapper {_x000D_
  display: block;_x000D_
  position: relative;_x000D_
  padding-left: 1.5em;_x000D_
  margin-bottom: 0.5em;_x000D_
  cursor: pointer;_x000D_
  -webkit-user-select: none;_x000D_
  -moz-user-select: none;_x000D_
  -ms-user-select: none;_x000D_
  user-select: none;_x000D_
}_x000D_
_x000D_
_x000D_
/* Hide the browser's default checkbox and radio buttons */_x000D_
_x000D_
.checkbox-wrapper input[type="checkbox"] {_x000D_
  position: absolute;_x000D_
  opacity: 0;_x000D_
  cursor: pointer;_x000D_
  height: 0;_x000D_
  width: 0;_x000D_
}_x000D_
_x000D_
.radio-wrapper input[type="radio"] {_x000D_
  position: absolute;_x000D_
  opacity: 0;_x000D_
  cursor: pointer;_x000D_
  height: 0;_x000D_
  width: 0;_x000D_
}_x000D_
_x000D_
_x000D_
/* Create a custom checkbox */_x000D_
_x000D_
.checkbox-wrapper .checkmark {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  height: 1em;_x000D_
  width: 1em;_x000D_
  background-color: var(--checkbox-default-background);_x000D_
  transition: all 0.2s ease-in;_x000D_
}_x000D_
_x000D_
.radio-wrapper .pip {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  height: 1em;_x000D_
  width: 1em;_x000D_
  border-radius: 50%;_x000D_
  background-color: var(--checkbox-default-background);_x000D_
  transition: all 0.2s ease-in;_x000D_
}_x000D_
_x000D_
_x000D_
/* Disabled style */_x000D_
_x000D_
.checkbox-wrapper input[type="checkbox"]:disabled~.checkmark,_x000D_
.radio-wrapper input[type="radio"]:disabled~.pip {_x000D_
  cursor: not-allowed;_x000D_
  background-color: var(--checkbox-disabled-background);_x000D_
  color: var(--checkbox-checkmark-disabled-color);_x000D_
}_x000D_
_x000D_
.checkbox-wrapper input[type="checkbox"]:disabled~.checkmark:after,_x000D_
.radio-wrapper input[type="radio"]:disabled~.pip:after {_x000D_
  color: var(--checkbox-checkmark-disabled-color);_x000D_
}_x000D_
_x000D_
.checkbox-wrapper input[type="checkbox"]:disabled:checked~.checkmark,_x000D_
.radio-wrapper input[type="radio"]:disabled:checked~.pip {_x000D_
  background-color: var(--checkbox-selected-disabled-background);_x000D_
}_x000D_
_x000D_
_x000D_
/* On mouse-over, add a grey background color */_x000D_
_x000D_
.checkbox-wrapper:hover input[type="checkbox"]:not(:disabled):not(:checked)~.checkmark,_x000D_
.radio-wrapper:hover input[type="radio"]:not(:disabled):not(:checked)~.pip {_x000D_
  background-color: var(--checkbox-hover-background);_x000D_
}_x000D_
_x000D_
_x000D_
/* When the checkbox is checked, add a blue background */_x000D_
_x000D_
.checkbox-wrapper input[type="checkbox"]:checked~.checkmark,_x000D_
.radio-wrapper input[type="radio"]:checked~.pip {_x000D_
  background-color: var(--checkbox-selected-background);_x000D_
}_x000D_
_x000D_
_x000D_
/* Create the checkmark/indicator (hidden when not checked) */_x000D_
_x000D_
.checkbox-wrapper .checkmark:after {_x000D_
  display: none;_x000D_
  width: 100%;_x000D_
  position: absolute;_x000D_
  text-align: center;_x000D_
  content: "\2713";_x000D_
  color: var(--checkbox-checkmark-color);_x000D_
  line-height: 1.1em;_x000D_
}_x000D_
_x000D_
.radio-wrapper .pip:after {_x000D_
  display: none;_x000D_
  width: 100%;_x000D_
  position: absolute;_x000D_
  text-align: center;_x000D_
  content: "\2022";_x000D_
  color: var(--checkbox-checkmark-color);_x000D_
  font-size: 1.5em;_x000D_
  top: -0.2em;_x000D_
}_x000D_
_x000D_
_x000D_
/* Show the checkmark when checked */_x000D_
_x000D_
.checkbox-wrapper input[type="checkbox"]:checked~.checkmark:after {_x000D_
  display: block;_x000D_
  line-height: 1.1em;_x000D_
}_x000D_
_x000D_
.radio-wrapper input[type="radio"]:checked~.pip:after {_x000D_
  display: block;_x000D_
  line-height: 1.1em;_x000D_
}
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css" rel="stylesheet" />_x000D_
<div class="grid-container">_x000D_
  <div class="grid-row">_x000D_
    <div class="grid-col">_x000D_
      <div class="grid-cell">_x000D_
        <h1>Pure CSS</h1>_x000D_
        <h2>Checkbox</h2>_x000D_
        <label class="checkbox-wrapper">One_x000D_
          <input type="checkbox" checked="checked">_x000D_
          <span class="checkmark"></span>_x000D_
        </label>_x000D_
        <label class="checkbox-wrapper">Two_x000D_
          <input type="checkbox">_x000D_
          <span class="checkmark"></span>_x000D_
        </label>_x000D_
        <label class="checkbox-wrapper">Three_x000D_
          <input type="checkbox" checked disabled>_x000D_
          <span class="checkmark"></span>_x000D_
        </label>_x000D_
        <label class="checkbox-wrapper">Four_x000D_
          <input type="checkbox" disabled>_x000D_
          <span class="checkmark"></span>_x000D_
        </label>_x000D_
        <h2>Radio</h2>_x000D_
        <label class="radio-wrapper">One_x000D_
          <input type="radio" name="group-x">_x000D_
          <span class="pip"></span>_x000D_
        </label>_x000D_
        <label class="radio-wrapper">Two_x000D_
          <input type="radio" name="group-x">_x000D_
          <span class="pip"></span>_x000D_
        </label>_x000D_
        <label class="radio-wrapper">Three_x000D_
          <input type="radio" name="group-x" checked disabled>_x000D_
          <span class="pip"></span>_x000D_
        </label>_x000D_
        <label class="radio-wrapper">Four_x000D_
          <input type="radio" name="group-x" disabled>_x000D_
          <span class="pip"></span>_x000D_
        </label>_x000D_
      </div>_x000D_
    </div>_x000D_
    <div class="grid-col" data-theme="dark">_x000D_
      <div class="grid-cell">_x000D_
        <h1>Pure CSS</h1>_x000D_
        <h2>Checkbox</h2>_x000D_
        <label class="checkbox-wrapper">One_x000D_
          <input type="checkbox" checked="checked">_x000D_
          <span class="checkmark"></span>_x000D_
        </label>_x000D_
        <label class="checkbox-wrapper">Two_x000D_
          <input type="checkbox">_x000D_
          <span class="checkmark"></span>_x000D_
        </label>_x000D_
        <label class="checkbox-wrapper">Three_x000D_
          <input type="checkbox" checked disabled>_x000D_
          <span class="checkmark"></span>_x000D_
        </label>_x000D_
        <label class="checkbox-wrapper">Four_x000D_
          <input type="checkbox" disabled>_x000D_
          <span class="checkmark"></span>_x000D_
        </label>_x000D_
        <h2>Radio</h2>_x000D_
        <label class="radio-wrapper">One_x000D_
          <input type="radio" name="group-y">_x000D_
          <span class="pip"></span>_x000D_
        </label>_x000D_
        <label class="radio-wrapper">Two_x000D_
          <input type="radio" name="group-y">_x000D_
          <span class="pip"></span>_x000D_
        </label>_x000D_
        <label class="radio-wrapper">Three_x000D_
          <input type="radio" name="group-y" checked disabled>_x000D_
          <span class="pip"></span>_x000D_
        </label>_x000D_
        <label class="radio-wrapper">Four_x000D_
          <input type="radio" name="group-y" disabled>_x000D_
          <span class="pip"></span>_x000D_
        </label>_x000D_
      </div>_x000D_
    </div>_x000D_
    <div class="grid-col" data-theme="retro">_x000D_
      <div class="grid-cell">_x000D_
        <h1>JS + CSS</h1>_x000D_
        <h2>Checkbox</h2>_x000D_
        <label>One   <input type="checkbox" checked="checked"></label>_x000D_
        <label>Two   <input type="checkbox"></label>_x000D_
        <label>Three <input type="checkbox" checked disabled></label>_x000D_
        <label>Four  <input type="checkbox" disabled></label>_x000D_
        <h2>Radio</h2>_x000D_
        <label>One   <input type="radio" name="group-z" checked="checked"></label>_x000D_
        <label>Two   <input type="radio" name="group-z"></label>_x000D_
        <label>Three <input type="radio" name="group-z" checked disabled></label>_x000D_
        <label>Four  <input type="radio" name="group-z" disabled></label>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

jQuery check if it is clicked or not

Using jQuery, I would suggest a shorter solution.

var elementClicked;
$("element").click(function(){
   elementClicked = true;
});
if( elementClicked != true ) {
    alert("element not clicked");
}else{
    alert("element clicked");
}

("element" here is to be replaced with the actual name tag)

Remove NA values from a vector

You can call max(vector, na.rm = TRUE). More generally, you can use the na.omit() function.

How to type in textbox using Selenium WebDriver (Selenium 2) with Java?

This is simple if you only use Selenium WebDriver, and forget the usage of Selenium-RC. I'd go like this.

WebDriver driver = new FirefoxDriver();
WebElement email = driver.findElement(By.id("email"));
email.sendKeys("[email protected]");

The reason for NullPointerException however is that your variable driver has never been started, you start FirefoxDriver in a variable wb thas is never being used.

SQL - Create view from multiple tables

Thanks for the help. This is what I ended up doing in order to make it work.

CREATE VIEW V AS
    SELECT *
    FROM ((POP NATURAL FULL OUTER JOIN FOOD)
    NATURAL FULL OUTER JOIN INCOME);

Sql connection-string for localhost server

<add name="connstr" connectionString="Data Source=localhost;Initial Catalog=DBName;User Id=username;Password=password" providerName="System.Data.SqlClient"/>

The above also works. It ignores the username and password passed in in the connection string. I switched from an environment db to a local one, and it works fine even though my user in the connection string does not exist in this context.

Override hosts variable of Ansible playbook from the command line

This is a bit late, but I think you could use the --limit or -l command to limit the pattern to more specific hosts. (version 2.3.2.0)

You could have - hosts: all (or group) tasks: - some_task

and then ansible-playbook playbook.yml -l some_more_strict_host_or_pattern and use the --list-hosts flag to see on which hosts this configuration would be applied.

What is the largest possible heap size with a 64-bit JVM?

Windows imposes a memory limit per process, you can see what it is for each version here

See:

User-mode virtual address space for each 64-bit process; With IMAGE_FILE_LARGE_ADDRESS_AWARE set (default): x64: 8 TB Intel IPF: 7 TB 2 GB with IMAGE_FILE_LARGE_ADDRESS_AWARE cleared

Latex Remove Spaces Between Items in List

It's easier with the enumitem package:

\documentclass{article}
\usepackage{enumitem}
\begin{document}
Less space:
\begin{itemize}[noitemsep]
  \item foo
  \item bar
  \item baz
\end{itemize}

Even more compact:
\begin{itemize}[noitemsep,nolistsep]
  \item foo
  \item bar
  \item baz
\end{itemize}
\end{document}

example

The enumitem package provides a lot of features to customize bullets, numbering and lengths.

The paralist package provides very compact lists: compactitem, compactenum and even lists within paragraphs like inparaenum and inparaitem.

Cast Object to Generic Type for returning

I stumble upon this question and it grabbed my interest. The accepted answer is completely correct, but I thought I do provide my findings at JVM byte code level to explain why the OP encounter the ClassCastException.

I have the code which is pretty much the same as OP's code:

public static <T> T convertInstanceOfObject(Object o) {
    try {
       return (T) o;
    } catch (ClassCastException e) {
        return null;
    }
}

public static void main(String[] args) {
    String k = convertInstanceOfObject(345435.34);
    System.out.println(k);
}

and the corresponding byte code is:

public static <T> T convertInstanceOfObject(java.lang.Object);
    Code:
       0: aload_0
       1: areturn
       2: astore_1
       3: aconst_null
       4: areturn
    Exception table:
       from    to  target type
           0     1     2   Class java/lang/ClassCastException

  public static void main(java.lang.String[]);
    Code:
       0: ldc2_w        #3                  // double 345435.34d
       3: invokestatic  #5                  // Method java/lang/Double.valueOf:(D)Ljava/lang/Double;
       6: invokestatic  #6                  // Method convertInstanceOfObject:(Ljava/lang/Object;)Ljava/lang/Object;
       9: checkcast     #7                  // class java/lang/String
      12: astore_1
      13: getstatic     #8                  // Field java/lang/System.out:Ljava/io/PrintStream;
      16: aload_1
      17: invokevirtual #9                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      20: return

Notice that checkcast byte code instruction happens in the main method not the convertInstanceOfObject and convertInstanceOfObject method does not have any instruction that can throw ClassCastException. Because the main method does not catch the ClassCastException hence when you execute the main method you will get a ClassCastException and not the expectation of printing null.

Now I modify the code to the accepted answer:

public static <T> T convertInstanceOfObject(Object o, Class<T> clazz) {
        try {
            return clazz.cast(o);
        } catch (ClassCastException e) {
            return null;
        }
    }
    public static void main(String[] args) {
        String k = convertInstanceOfObject(345435.34, String.class);
        System.out.println(k);
    }

The corresponding byte code is:

public static <T> T convertInstanceOfObject(java.lang.Object, java.lang.Class<T>);
    Code:
       0: aload_1
       1: aload_0
       2: invokevirtual #2                  // Method java/lang/Class.cast:(Ljava/lang/Object;)Ljava/lang/Object;
       5: areturn
       6: astore_2
       7: aconst_null
       8: areturn
    Exception table:
       from    to  target type
           0     5     6   Class java/lang/ClassCastException

  public static void main(java.lang.String[]);
    Code:
       0: ldc2_w        #4                  // double 345435.34d
       3: invokestatic  #6                  // Method java/lang/Double.valueOf:(D)Ljava/lang/Double;
       6: ldc           #7                  // class java/lang/String
       8: invokestatic  #8                  // Method convertInstanceOfObject:(Ljava/lang/Object;Ljava/lang/Class;)Ljava/lang/Object;
      11: checkcast     #7                  // class java/lang/String
      14: astore_1
      15: getstatic     #9                  // Field java/lang/System.out:Ljava/io/PrintStream;
      18: aload_1
      19: invokevirtual #10                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      22: return

Notice that there is an invokevirtual instruction in the convertInstanceOfObject method that calls Class.cast() method which throws ClassCastException which will be catch by the catch(ClassCastException e) bock and return null; hence, "null" is printed to console without any exception.

javac : command not found

This worked for me: sudo dnf install java-<version>-devel

Conda: Installing / upgrading directly from github

The answers are outdated. You simply have to conda install pip and git. Then you can use pip normally:

  1. Activate your conda environment source activate myenv

  2. conda install git pip

  3. pip install git+git://github.com/scrappy/scrappy@master

SQL SELECT multi-columns INTO multi-variable

SELECT @var = col1,
       @var2 = col2
FROM   Table

Here is some interesting information about SET / SELECT

  • SET is the ANSI standard for variable assignment, SELECT is not.
  • SET can only assign one variable at a time, SELECT can make multiple assignments at once.
  • If assigning from a query, SET can only assign a scalar value. If the query returns multiple values/rows then SET will raise an error. SELECT will assign one of the values to the variable and hide the fact that multiple values were returned (so you'd likely never know why something was going wrong elsewhere - have fun troubleshooting that one)
  • When assigning from a query if there is no value returned then SET will assign NULL, where SELECT will not make the assignment at all (so the variable will not be changed from it's previous value)
  • As far as speed differences - there are no direct differences between SET and SELECT. However SELECT's ability to make multiple assignments in one shot does give it a slight speed advantage over SET.

PHP & MySQL: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given

$dbc is returning false. Your query has an error in it:

SELECT users.*, profile.* --You do not join with profile anywhere.
                                 FROM users 
                                 INNER JOIN contact_info 
                                 ON contact_info.user_id = users.user_id 
                                 WHERE users.user_id=3");

The fix for this in general has been described by Raveren.

How to return only the Date from a SQL Server DateTime datatype

select cast(createddate as date) as derivedate from table 

createdate is your datetime column , this works for sqlserver

What does DIM stand for in Visual Basic and BASIC?

DIM stands for Declaration In Memory DIM x As New Integer creates a space in memory where the variable x is stored

How to force Chrome browser to reload .css file while debugging in Visual Studio?

Just had this problem where one person running Chrome (on a Mac) suddenly stopped loading the CSS file. CMD + R did NOT work at all. I don't like the suggestions above that force a permanent reload on the production system.

What worked was changing the name of the CSS file in the HTML file (and renaming the CSS file of course). This forced Chrome to go get the latest CSS file.

How to get the Display Name Attribute of an Enum member via MVC Razor code?

Based on Aydin's answer I would suggest a less "duplicatious" implementation (because we could easily get the Type from the Enum value itself, instead of providing it as a parameter :

using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;

public static string GetDisplayName(this Enum enumValue)
{
    return enumValue.GetType().GetMember(enumValue.ToString())
                   .First()
                   .GetCustomAttribute<DisplayAttribute>()
                   .Name;
}

EDIT (based upon @Vahagn Nahapetyan's comment)

public static string GetDisplayName(this Enum enumValue)
{
    return enumValue.GetType()?
                    .GetMember(enumValue.ToString())?
                    .First()?
                    .GetCustomAttribute<DisplayAttribute>()?
                    .Name;
}

Now we can use it very clean in this way:

public enum Season 
{
    [Display(Name = "The Autumn")]
    Autumn,

    [Display(Name = "The Weather")]
    Winter,

    [Display(Name = "The Tease")]
    Spring,

    [Display(Name = "The Dream")]
    Summer
}

Season.Summer.GetDisplayName();

Which results in

"The Dream"

How to generate a simple popup using jQuery

Try the Magnific Popup, it's responsive and weights just around 3KB.

jQuery get values of checked checkboxes into array

Call .get() at the very end to turn the resulting jQuery object into a true array.

$("#merge_button").click(function(event){
    event.preventDefault();
    var searchIDs = $("#find-table input:checkbox:checked").map(function(){
      return $(this).val();
    }).get(); // <----
    console.log(searchIDs);
});

Per the documentation:

As the return value is a jQuery object, which contains an array, it's very common to call .get() on the result to work with a basic array.

How can I read the client's machine/computer name from the browser?

Well you could get the ip address using asp.net, then do a reverse DNS lookup on the ip to get the hostname.

From the ASP.NET Developer's cookbook ... Performing a Reverse-DNS Lookup.

Undefined symbols for architecture armv7

Another possible cause of "undefined symbol" linker errors is attempting to call a C function from a .mm file. In this case you'll need to use extern "C" {...} when you import the header files.

Linker error calling C-Function from Objective-C++

How to add a where clause in a MySQL Insert statement?

In an insert statement you wouldn't have an existing row to do a where claues on? You are inserting a new row, did you mean to do an update statment?

update users set username='JACK' and password='123' WHERE id='1';

Remove Duplicates from range of cells in excel vba

You need to tell the Range.RemoveDuplicates method what column to use. Additionally, since you have expressed that you have a header row, you should tell the .RemoveDuplicates method that.

Sub dedupe_abcd()
    Dim icol As Long

    With Sheets("Sheet1")   '<-set this worksheet reference properly!
        icol = Application.Match("abcd", .Rows(1), 0)
        With .Cells(1, 1).CurrentRegion
            .RemoveDuplicates Columns:=icol, Header:=xlYes
        End With
    End With
End Sub

Your original code seemed to want to remove duplicates from a single column while ignoring surrounding data. That scenario is atypical and I've included the surrounding data so that the .RemoveDuplicates process does not scramble your data. Post back a comment if you truly wanted to isolate the RemoveDuplicates process to a single column.

How to include a PHP variable inside a MySQL statement

That's the easy answer:

$query="SELECT * FROM CountryInfo WHERE Name = '".$name."'";

and you define $name whatever you want.
And another way, the complex way, is like that:

$query = " SELECT '" . $GLOBALS['Name'] . "' .* " .
         " FROM CountryInfo " .
         " INNER JOIN District " .
         " ON District.CountryInfoId = CountryInfo.CountryInfoId " .
         " INNER JOIN City " .
         " ON City.DistrictId = District.DistrictId " .
         " INNER JOIN '" . $GLOBALS['Name'] . "' " .
         " ON '" . $GLOBALS['Name'] . "'.CityId = City.CityId " .
         " WHERE CountryInfo.Name = '" . $GLOBALS['CountryName'] .
         "'";

How do I check if a given Python string is a substring of another one?

Try using in like this:

>>> x = 'hello'
>>> y = 'll'
>>> y in x
True

How to Read and Write from the Serial Port

I spent a lot of time to use SerialPort class and has concluded to use SerialPort.BaseStream class instead. You can see source code: SerialPort-source and SerialPort.BaseStream-source for deep understanding. I created and use code that shown below.

  • The core function public int Recv(byte[] buffer, int maxLen) has name and works like "well known" socket's recv().

  • It means that

    • in one hand it has timeout for no any data and throws TimeoutException.
    • In other hand, when any data has received,
      • it receives data either until maxLen bytes
      • or short timeout (theoretical 6 ms) in UART data flow

.

public class Uart : SerialPort

    {
        private int _receiveTimeout;

        public int ReceiveTimeout { get => _receiveTimeout; set => _receiveTimeout = value; }

        static private string ComPortName = "";

        /// <summary>
        /// It builds PortName using ComPortNum parameter and opens SerialPort.
        /// </summary>
        /// <param name="ComPortNum"></param>
        public Uart(int ComPortNum) : base()
        {
            base.BaudRate = 115200; // default value           
            _receiveTimeout = 2000;
            ComPortName = "COM" + ComPortNum;

            try
            {
                base.PortName = ComPortName;
                base.Open();
            }
            catch (UnauthorizedAccessException ex)
            {
                Console.WriteLine("Error: Port {0} is in use", ComPortName);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Uart exception: " + ex);
            }
        } //Uart()

        /// <summary>
        /// Private property returning positive only Environment.TickCount
        /// </summary>
        private int _tickCount { get => Environment.TickCount & Int32.MaxValue; }


        /// <summary>
        /// It uses SerialPort.BaseStream rather SerialPort functionality .
        /// It Receives up to maxLen number bytes of data, 
        /// Or throws TimeoutException if no any data arrived during ReceiveTimeout. 
        /// It works likes socket-recv routine (explanation in body).
        /// Returns:
        ///    totalReceived - bytes, 
        ///    TimeoutException,
        ///    -1 in non-ComPortNum Exception  
        /// </summary>
        /// <param name="buffer"></param>
        /// <param name="maxLen"></param>
        /// <returns></returns>
        public int Recv(byte[] buffer, int maxLen)
        {
            /// The routine works in "pseudo-blocking" mode. It cycles up to first 
            /// data received using BaseStream.ReadTimeout = TimeOutSpan (2 ms).
            /// If no any message received during ReceiveTimeout property, 
            /// the routine throws TimeoutException 
            /// In other hand, if any data has received, first no-data cycle
            /// causes to exit from routine.

            int TimeOutSpan = 2;
            // counts delay in TimeOutSpan-s after end of data to break receive
            int EndOfDataCnt;
            // pseudo-blocking timeout counter
            int TimeOutCnt = _tickCount + _receiveTimeout; 
            //number of currently received data bytes
            int justReceived = 0;
            //number of total received data bytes
            int totalReceived = 0;

            BaseStream.ReadTimeout = TimeOutSpan;
            //causes (2+1)*TimeOutSpan delay after end of data in UART stream
            EndOfDataCnt = 2;
            while (_tickCount < TimeOutCnt && EndOfDataCnt > 0)
            {
                try
                {
                    justReceived = 0; 
                    justReceived = base.BaseStream.Read(buffer, totalReceived, maxLen - totalReceived);
                    totalReceived += justReceived;

                    if (totalReceived >= maxLen)
                        break;
                }
                catch (TimeoutException)
                {
                    if (totalReceived > 0) 
                        EndOfDataCnt--;
                }
                catch (Exception ex)
                {                   
                    totalReceived = -1;
                    base.Close();
                    Console.WriteLine("Recv exception: " + ex);
                    break;
                }

            } //while
            if (totalReceived == 0)
            {              
                throw new TimeoutException();
            }
            else
            {               
                return totalReceived;
            }
        } // Recv()            
    } // Uart

How do I Merge two Arrays in VBA?

It work if Lbound is different than 0 or 1. You Redim once at start

Function MergeArrays(ByRef arr1 As Variant, ByRef arr2 As Variant) As Variant

'Test if not isarray then exit
If Not IsArray(arr1) And Not IsArray(arr2) Then Exit Function

Dim arr As Variant
Dim a As Long, b As Long 'index Array
Dim len1 As Long, len2 As Long 'nb of item

'get len if array don't start to 0
len1 = UBound(arr1) - LBound(arr1) + 1
len2 = UBound(arr2) - LBound(arr2) + 1

b = 1 'position of start index
'dim new array
ReDim arr(b To len1 + len2)
'merge arr1
For a = LBound(arr1) To UBound(arr1)
    arr(b) = arr1(a)       
    b = b + 1 'move index
Next a
'merge arr2
For a = LBound(arr2) To UBound(arr2)
    arr(b) = arr2(a)
    b = b + 1 'move index
Next a

'final
MergeArrays = arr

End Function

Refresh DataGridView when updating data source

Try this Code

List itemStates = new List();

for (int i = 0; i < 10; i++)
{ 
    itemStates.Add(new ItemState { Id = i.ToString() });
    dataGridView1.DataSource = itemStates;
    dataGridView1.DataBind();
    System.Threading.Thread.Sleep(500);
}

Temporary table in SQL server causing ' There is already an object named' error

You must modify the query like this

CREATE TABLE #TMPGUARDIAN(
LAST_NAME NVARCHAR(30),
FRST_NAME NVARCHAR(30))  

INSERT INTO #TMPGUARDIAN(FRST_NAME,LAST_NAME)
SELECT LAST_NAME,FRST_NAME  FROM TBL_PEOPLE

-- Make a last session for clearing the all temporary tables. always drop at end. In your case, sometimes, there might be an error happen if the table is not exists, while you trying to delete.

DROP TABLE #TMPGUARDIAN

Avoid using insert into Because If you are using insert into then in future if you want to modify the temp table by adding a new column which can be filled after some process (not along with insert). At that time, you need to rework and design it in the same manner.

Use Table Variable http://odetocode.com/articles/365.aspx

declare @userData TABLE(
 LAST_NAME NVARCHAR(30),
    FRST_NAME NVARCHAR(30)
)

Advantages No need for Drop statements, since this will be similar to variables. Scope ends immediately after the execution.

Show tables, describe tables equivalent in redshift

All the information can be found in a PG_TABLE_DEF table, documentation.

Listing all tables in a public schema (default) - show tables equivalent:

SELECT DISTINCT tablename
FROM pg_table_def
WHERE schemaname = 'public'
ORDER BY tablename;

Description of all the columns from a table called table_name - describe table equivalent:

SELECT *
FROM pg_table_def
WHERE tablename = 'table_name'
AND schemaname = 'public';

Git: How to squash all commits on branch

If you use JetBrains based IDE like IntelliJ Idea and prefare using GUI over command line:

  1. Go to Version control window (Alt + 9/Command + 9) - "Log" tab.
  2. Choose a point in the tree from which you created your branch
  3. Right click on it -> Reset current branch to here -> Pick Soft (!!!) (it's important for not to lose your changes)
  4. Push the Reset button in the bottom of the dialog window.

That's it. You uncommited all your changes. Now if you'll make a new commit it will be squashed

How do I iterate through the files in a directory in Java?

Check out the FileUtils class in Apache Commons - specifically iterateFiles:

Allows iteration over the files in given directory (and optionally its subdirectories).

Linux: where are environment variables stored?

It's stored in the process (shell) and since you've exported it, any processes that process spawns.

Doing the above doesn't store it anywhere in the filesystem like /etc/profile. You have to put it there explicitly for that to happen.

python - if not in list

Your code should work, but you can also try:

    if not item in mylist :

Inject service in app.config

Well, I struggled a little with this one, but I actually did it.

I don't know if the answers are outdated because of some change in angular, but you can do it this way:

This is your service:

.factory('beerRetrievalService', function ($http, $q, $log) {
  return {
    getRandomBeer: function() {
      var deferred = $q.defer();
      var beer = {};

      $http.post('beer-detail', {})
      .then(function(response) {
        beer.beerDetail = response.data;
      },
      function(err) {
        $log.error('Error getting random beer', err);
        deferred.reject({});
      });

      return deferred.promise;
    }
  };
 });

And this is the config

.when('/beer-detail', {
  templateUrl : '/beer-detail',
  controller  : 'productDetailController',

  resolve: {
    beer: function(beerRetrievalService) {
      return beerRetrievalService.getRandomBeer();
    }
  }
})

How to link an image and target a new window

Assuming you want to show an Image thumbnail which is 50x50 pixels and link to the the actual image you can do

<a href="path/to/image.jpg" alt="Image description" target="_blank" style="display: inline-block; width: 50px; height; 50px; background-image: url('path/to/image.jpg');"></a>

Of course it's best to give that link a class or id and put it in your css

how to customize `show processlist` in mysql?

Newer versions of SQL support the process list in information_schema:

SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST

You can ORDER BY in any way you like.

The INFORMATION_SCHEMA.PROCESSLIST table was added in MySQL 5.1.7. You can find out which version you're using with:

SELECT VERSION()

C - split string into an array of strings

Here is an example of how to use strtok borrowed from MSDN.

And the relevant bits, you need to call it multiple times. The token char* is the part you would stuff into an array (you can figure that part out).

char string[] = "A string\tof ,,tokens\nand some  more tokens";
char seps[]   = " ,\t\n";
char *token;

int main( void )
{
    printf( "Tokens:\n" );
    /* Establish string and get the first token: */
    token = strtok( string, seps );
    while( token != NULL )
    {
        /* While there are tokens in "string" */
        printf( " %s\n", token );
        /* Get next token: */
        token = strtok( NULL, seps );
    }
}

How do I initialize an empty array in C#?

As I know you can't make array without size, but you can use

List<string> l = new List<string>() 

and then l.ToArray().

How do I launch the Android emulator from the command line?

For one-click (BATCH file) launch, this is what I've done:

  • got the name of AVD from Android Studio -> Tools -> AVD Manager -> Click on Arrow Down and choose View Details ( for me it's Pixel_2_API_28, so change accordingly below)
  • create an start.bat file and put the following inside:
 c: 
 cd C:\Program Files (x86)\Android\android-sdk\emulator\ 
 emulator -avd Pixel_2_API_28

Explanations:

  • First line: for me was necessary because I am launching it from d:
  • Second line: for me was not working the tools\emulator
  • Third line: make sure you change the name of the AVD with yours (here Pixel_2_API_28)

Using:

  • launch start.bat from command line

How to prevent browser to invoke basic auth popup and handle 401 error using Jquery?

I was facing this issue recently, too. Since you can't change the browser's default behavior of showing the popup in case of a 401 (basic or digest authentication), there are two ways to fix this:

  • Change the server response to not return a 401. Return a 200 code instead and handle this in your jQuery client.
  • Change the method that you're using for authorization to a custom value in your header. Browsers will display the popup for Basic and Digest. You have to change this on both the client and the server.

    headers : {
      "Authorization" : "BasicCustom"
    }
    

Please also take a look at this for an example of using jQuery with Basic Auth.

Attach parameter to button.addTarget action in Swift

If you want to send additional parameters to the buttonClicked method, for example an indexPath or urlString, you can subclass the UIButton:

class SubclassedUIButton: UIButton {
    var indexPath: Int?
    var urlString: String?
}

Make sure to change the button's class in the identity inspector to subclassedUIButton. You can access the parameters inside the buttonClicked method using sender.indexPath or sender.urlString.

Note: If your button is inside a cell you can set the value of these additional parameters in the cellForRowAtIndexPath method (where the button is created).

How can you dynamically create variables via a while loop?

Keyword parameters allow you to pass variables from one function to another. In this way you can use the key of a dictionary as a variable name (which can be populated in your while loop). The dictionary name just needs to be preceded by ** when it is called.

# create a dictionary
>>> kwargs = {}
# add a key of name and assign it a value, later we'll use this key as a variable
>>> kwargs['name'] = 'python'

# an example function to use the variable
>>> def print_name(name):
...   print name

# call the example function
>>> print_name(**kwargs)
python

Without **, kwargs is just a dictionary:

>>> print_name(kwargs)
{'name': 'python'}

List of all unique characters in a string?

Store Unique characters in list

Method 1:

uniue_char = list(set('aaabcabccd'))
#['a', 'b', 'c', 'd']

Method 2: By Loop ( Complex )

uniue_char = []
for c in 'aaabcabccd':
    if not c in uniue_char:
        uniue_char.append(c)
print(uniue_char)
#['a', 'b', 'c', 'd']

Adding Python Path on Windows 7

  1. Hold Win and press Pause.
  2. Click Advanced System Settings.
  3. Click Environment Variables.
  4. Append ;C:\python27 to the Path variable.
  5. Restart Command Prompt.

Add a column in a table in HIVE QL

You cannot add a column with a default value in Hive. You have the right syntax for adding the column ALTER TABLE test1 ADD COLUMNS (access_count1 int);, you just need to get rid of default sum(max_count). No changes to that files backing your table will happen as a result of adding the column. Hive handles the "missing" data by interpreting NULL as the value for every cell in that column.

So now your have the problem of needing to populate the column. Unfortunately in Hive you essentially need to rewrite the whole table, this time with the column populated. It may be easier to rerun your original query with the new column. Or you could add the column to the table you have now, then select all of its columns plus value for the new column.

You also have the option to always COALESCE the column to your desired default and leave it NULL for now. This option fails when you want NULL to have a meaning distinct from your desired default. It also requires you to depend on always remembering to COALESCE.

If you are very confident in your abilities to deal with the files backing Hive, you could also directly alter them to add your default. In general I would recommend against this because most of the time it will be slower and more dangerous. There might be some case where it makes sense though, so I've included this option for completeness.

Access index of last element in data frame

It may be too late now, I use index method to retrieve last index of a DataFrame, then use [-1] to get the last values:

For example,

df = pd.DataFrame(np.zeros((4, 1)), columns=['A'])
print(f'df:\n{df}\n')

print(f'Index = {df.index}\n')
print(f'Last index = {df.index[-1]}')

The output is

df:
     A
0  0.0
1  0.0
2  0.0
3  0.0

Index = RangeIndex(start=0, stop=4, step=1)

Last index = 3

Design Documents (High Level and Low Level Design Documents)

High-Level Design (HLD) involves decomposing a system into modules, and representing the interfaces & invocation relationships among modules. An HLD is referred to as software architecture.

LLD, also known as a detailed design, is used to design internals of the individual modules identified during HLD i.e. data structures and algorithms of the modules are designed and documented.

Now, HLD and LLD are actually used in traditional Approach (Function-Oriented Software Design) whereas, in OOAD, the system is seen as a set of objects interacting with each other.

As per the above definitions, a high-level design document will usually include a high-level architecture diagram depicting the components, interfaces, and networks that need to be further specified or developed. The document may also depict or otherwise refer to work flows and/or data flows between component systems.

Class diagrams with all the methods and relations between classes come under LLD. Program specs are covered under LLD. LLD describes each and every module in an elaborate manner so that the programmer can directly code the program based on it. There will be at least 1 document for each module. The LLD will contain - a detailed functional logic of the module in pseudo code - database tables with all elements including their type and size - all interface details with complete API references(both requests and responses) - all dependency issues - error message listings - complete inputs and outputs for a module.

How to get current relative directory of your Makefile?

If you are using GNU make, $(CURDIR) is actually a built-in variable. It is the location where the Makefile resides the current working directory, which is probably where the Makefile is, but not always.

OUTPUT_PATH = /project1/bin/$(notdir $(CURDIR))

See Appendix A Quick Reference in http://www.gnu.org/software/make/manual/make.html

Python safe method to get value of nested dictionary

Since raising an key error if one of keys is missing is a reasonable thing to do, we can even not check for it and get it as single as that:

def get_dict(d, kl):
  cur = d[kl[0]]
  return get_dict(cur, kl[1:]) if len(kl) > 1 else cur

Postgresql column reference "id" is ambiguous

You need the table name/alias in the SELECT part (maybe (vg.id, name)) :

SELECT (vg.id, name) FROM v_groups vg 
inner join people2v_groups p2vg on vg.id = p2vg.v_group_id
where p2vg.people_id =0;

jQuery remove options from select

find() takes a selector, not a value. This means you need to use it in the same way you would use the regular jQuery function ($('selector')).

Therefore you need to do something like this:

$(this).find('[value="X"]').remove();

See the jQuery find docs.

How to simulate a touch event in Android?

Valentin Rocher's method works if you've extended your view, but if you're using an event listener, use this:

view.setOnTouchListener(new OnTouchListener()
{
    public boolean onTouch(View v, MotionEvent event)
    {
        Toast toast = Toast.makeText(
            getApplicationContext(), 
            "View touched", 
            Toast.LENGTH_LONG
        );
        toast.show();

        return true;
    }
});


// Obtain MotionEvent object
long downTime = SystemClock.uptimeMillis();
long eventTime = SystemClock.uptimeMillis() + 100;
float x = 0.0f;
float y = 0.0f;
// List of meta states found here: developer.android.com/reference/android/view/KeyEvent.html#getMetaState()
int metaState = 0;
MotionEvent motionEvent = MotionEvent.obtain(
    downTime, 
    eventTime, 
    MotionEvent.ACTION_UP, 
    x, 
    y, 
    metaState
);

// Dispatch touch event to view
view.dispatchTouchEvent(motionEvent);

For more on obtaining a MotionEvent object, here is an excellent answer: Android: How to create a MotionEvent?

Convert JavaScript string in dot notation into an object reference

You can use the library available at npm, which simplifies this process. https://www.npmjs.com/package/dot-object

 var dot = require('dot-object');

var obj = {
 some: {
   nested: {
     value: 'Hi there!'
   }
 }
};

var val = dot.pick('some.nested.value', obj);
console.log(val);

// Result: Hi there!

SQL: How do I SELECT only the rows with a unique value on certain column?

Utilizing the "dynamic table" capability in SQL Server (querying against a parenthesis-surrounded query), you can return 2000, 49 w/ the following. If your platform doesn't offer an equivalent to the "dynamic table" ANSI-extention, you can always utilize a temp table in two-steps/statement by inserting the results within the "dynamic table" to a temp table, and then performing a subsequent select on the temp table.

DECLARE  @T TABLE(
    [contract] INT,
    project INT,
    activity INT
)

INSERT INTO @T VALUES( 1000,    8000,    10 )
INSERT INTO @T VALUES( 1000,    8000,    20 )
INSERT INTO @T VALUES( 1000,    8001,    10 )
INSERT INTO @T VALUES( 2000,    9000,    49 )
INSERT INTO @T VALUES( 2000,    9001,    49 )
INSERT INTO @T VALUES( 3000,    9000,    79 )
INSERT INTO @T VALUES( 3000,    9000,    78 )

SELECT
    [contract],
    [Activity] =  max (activity)
FROM
    (
    SELECT
        [contract],
        [Activity]
    FROM
        @T
    GROUP BY
        [contract],
        [Activity]
    ) t
GROUP BY
    [contract]
HAVING count (*) = 1

Tomcat is not deploying my web project from Eclipse

The only way I found which works for me is adding an entry into the "Web Deployment Assembly"

Project webapp > Properties > Deployment Assembly
Add ...
Source : "/target/classes"
Deploy Path : "WEB-INF/classes"

RE error: illegal byte sequence on Mac OS X

Add the following lines to your ~/.bash_profile or ~/.zshrc file(s).

export LC_CTYPE=C 
export LANG=C

The transaction manager has disabled its support for remote/network transactions

I post the below solution here because after some searching this is where I landed, so other may too. I was trying to use EF 6 to call a stored procedure, but had a similar error because the stored procedure had a linked server being utilized.

The operation could not be performed because OLE DB provider _ for linked server _ was unable to begin a distributed transaction

The partner transaction manager has disabled its support for remote/network transactions*

Jumping over to SQL Client did fix my issue, which also confirmed for me that it was an EF thing.

EF model generated method based attempt:

db.SomeStoredProcedure();

ExecuteSqlCommand based attempt:

db.Database.ExecuteSqlCommand("exec [SomeDB].[dbo].[SomeStoredProcedure]");

With:

var connectionString = db.Database.Connection.ConnectionString;
var connection = new System.Data.SqlClient.SqlConnection(connectionString);    
var cmd = connection.CreateCommand();
cmd.CommandText = "exec [SomeDB].[dbo].[SomeStoredProcedure]";

connection.Open();
var result = cmd.ExecuteNonQuery();

That code can be shortened, but I think that version is slightly more convenient for debugging and stepping through.

I don't believe that Sql Client is necessarily a preferred choice, but I felt this was at least worth sharing if anyone else having similar problems gets landed here by google.

The above Code is C#, but the concept of trying to switch over to Sql Client still applies. At the very least it will be diagnostic to attempt to do so.

The property 'value' does not exist on value of type 'HTMLElement'

This work for me:

let inputValue = (swal.getPopup().querySelector('#inputValue ')as HTMLInputElement).value

Execute command on all files in a directory

One quick and dirty way which gets the job done sometimes is:

find directory/ | xargs  Command 

For example to find number of lines in all files in the current directory, you can do:

find . | xargs wc -l

How to use sed to extract substring

grep was born to extract things:

grep -Po 'name="\K[^"]*'

test with your data:

kent$  echo '<parameter name="PortMappingEnabled" access="readWrite" type="xsd:boolean"></parameter>
  <parameter name="PortMappingLeaseDuration" access="readWrite" activeNotify="canDeny" type="xsd:unsignedInt"></parameter>
  <parameter name="RemoteHost" access="readWrite"></parameter>
  <parameter name="ExternalPort" access="readWrite" type="xsd:unsignedInt"></parameter>
  <parameter name="ExternalPortEndRange" access="readWrite" type="xsd:unsignedInt"></parameter>
  <parameter name="InternalPort" access="readWrite" type="xsd:unsignedInt"></parameter>
  <parameter name="PortMappingProtocol" access="readWrite"></parameter>
  <parameter name="InternalClient" access="readWrite"></parameter>
  <parameter name="PortMappingDescription" access="readWrite"></parameter>
'|grep -Po 'name="\K[^"]*'
PortMappingEnabled
PortMappingLeaseDuration
RemoteHost
ExternalPort
ExternalPortEndRange
InternalPort
PortMappingProtocol
InternalClient
PortMappingDescription

Centering controls within a form in .NET (Winforms)?

In addition, if you want to align it to the center of another control:

//The "ctrlParent" is the one on which you want to align "ctrlToCenter".
//"ctrlParent" can be your "form name" or any other control such as "grid name" and etc.
ctrlToCenter.Parent = ctrlParent;

ctrlToCenter.Left = (ctrlToCenter.Parent.Width - ctrlToCenter.Width) / 2;
ctrlToCenter.Top = (ctrlToCenter.Parent.Height - ctrlToCenter.Height) / 2;

What is the difference between "INNER JOIN" and "OUTER JOIN"?

1.Inner Join: Also called as Join. It returns the rows present in both the Left table, and right table only if there is a match. Otherwise, it returns zero records.

Example:

SELECT
  e1.emp_name,
  e2.emp_salary    
FROM emp1 e1
INNER JOIN emp2 e2
  ON e1.emp_id = e2.emp_id

output1

2.Full Outer Join: Also called as Full Join. It returns all the rows present in both the Left table, and right table.

Example:

SELECT
  e1.emp_name,
  e2.emp_salary    
FROM emp1 e1
FULL OUTER JOIN emp2 e2
  ON e1.emp_id = e2.emp_id

output2

3.Left Outer join: Or simply called as Left Join. It returns all the rows present in the Left table and matching rows from the right table (if any).

4.Right Outer Join: Also called as Right Join. It returns matching rows from the left table (if any), and all the rows present in the Right table.

joins

Advantages of Joins

  1. Executes faster.

How to use querySelectorAll only for elements that have a specific attribute set?

With your example:

<input type="checkbox" id="c2" name="c2" value="DE039230952"/>

Replace $$ with document.querySelectorAll in the examples:

$$('input') //Every input
$$('[id]') //Every element with id
$$('[id="c2"]') //Every element with id="c2"
$$('input,[id]') //Every input + every element with id
$$('input[id]') //Every input including id
$$('input[id="c2"]') //Every input including id="c2"
$$('input#c2') //Every input including id="c2" (same as above)
$$('input#c2[value="DE039230952"]') //Every input including id="c2" and value="DE039230952"
$$('input#c2[value^="DE039"]') //Every input including id="c2" and value has content starting with DE039
$$('input#c2[value$="0952"]') //Every input including id="c2" and value has content ending with 0952
$$('input#c2[value*="39230"]') //Every input including id="c2" and value has content including 39230

Use the examples directly with:

const $$ = document.querySelectorAll.bind(document);

Some additions:

$$(.) //The same as $([class])
$$(div > input) //div is parent tag to input
document.querySelector() //equals to $$()[0] or $()

ERROR: Sonar server 'http://localhost:9000' can not be reached

You should configure the sonar-runner to use your existing SonarQube server. To do so, you need to update its conf/sonar-runner.properties file and specify the SonarQube server URL, username, password, and JDBC URL as well. See https://docs.sonarqube.org/display/SCAN/Analyzing+with+SonarQube+Scanner for details.

If you don't yet have an up and running SonarQube server, then you can launch one locally (with the default configuration) - it will bind to http://localhost:9000 and work with the default sonar-runner configuration. See https://docs.sonarqube.org/latest/setup/get-started-2-minutes/ for details on how to get started with the SonarQube server.

Using reflection in Java to create a new instance with the reference variable type set to the new instance class name?

//====Single Class Reference used to retrieve object for fields and initial values. Performance enhancing only====          
Class<?>    reference           =   vector.get(0).getClass();
Object      obj                 =   reference.newInstance();
Field[]     objFields           =   obj.getClass().getFields(); 

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

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

git apply yourcoworkers.diff

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

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

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

It also works with Unix pipe as follows:

git diff d892531 815a3b5 | git apply

What is the difference between include and require in Ruby?

What's the difference between "include" and "require" in Ruby?

Answer:

The include and require methods do very different things.

The require method does what include does in most other programming languages: run another file. It also tracks what you've required in the past and won't require the same file twice. To run another file without this added functionality, you can use the load method.

The include method takes all the methods from another module and includes them into the current module. This is a language-level thing as opposed to a file-level thing as with require. The include method is the primary way to "extend" classes with other modules (usually referred to as mix-ins). For example, if your class defines the method "each", you can include the mixin module Enumerable and it can act as a collection. This can be confusing as the include verb is used very differently in other languages.

Source

So if you just want to use a module, rather than extend it or do a mix-in, then you'll want to use require.

Oddly enough, Ruby's require is analogous to C's include, while Ruby's include is almost nothing like C's include.

How do you do the "therefore" (?) symbol on a Mac or in Textmate?

From System Preferences, turn on the "Show Keyboard & Character Viewer in menu bar" setting.

Then, the "Character Viewer" menu will pop up a tool that will let you search for any unicode character (by name) and insert it ? you're all set.

react-router getting this.props.location in child components

(Update) V5.1 & Hooks (Requires React >= 16.8)

You can use useHistory, useLocation and useRouteMatch in your component to get match, history and location .

const Child = () => {
  const location = useLocation();
  const history = useHistory();
  const match = useRouteMatch("write-the-url-you-want-to-match-here");

  return (
    <div>{location.pathname}</div>
  )
}

export default Child

(Update) V4 & V5

You can use withRouter HOC in order to inject match, history and location in your component props.

class Child extends React.Component {
  static propTypes = {
    match: PropTypes.object.isRequired,
    location: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired
  }

  render() {
    const { match, location, history } = this.props

    return (
      <div>{location.pathname}</div>
    )
  }
}

export default withRouter(Child)

(Update) V3

You can use withRouter HOC in order to inject router, params, location, routes in your component props.

class Child extends React.Component {

  render() {
    const { router, params, location, routes } = this.props

    return (
      <div>{location.pathname}</div>
    )
  }
}

export default withRouter(Child)

Original answer

If you don't want to use the props, you can use the context as described in React Router documentation

First, you have to set up your childContextTypes and getChildContext

class App extends React.Component{

  getChildContext() {
    return {
      location: this.props.location
    }
  }

  render() {
    return <Child/>;
  }
}

App.childContextTypes = {
    location: React.PropTypes.object
}

Then, you will be able to access to the location object in your child components using the context like this

class Child extends React.Component{

   render() {
     return (
       <div>{this.context.location.pathname}</div>
     )
   }

}

Child.contextTypes = {
    location: React.PropTypes.object
 }

Python: Random numbers into a list

This is way late but in-case someone finds this helpful.

You could use list comprehension.

rand = [random.randint(0, 100) for x in range(1, 11)]
print(rand)

Output:

[974, 440, 305, 102, 822, 128, 205, 362, 948, 751]

Cheers!

Is mathematics necessary for programming?

To answer your question as it was posed I would have to say, "No, mathematics is not necessary for programming". However, as other people have suggested in this thread, I believe there is a correlation between understanding mathematics and being able to "think algorithmically". That is, to be able to think abstractly about quantity, processes, relationships and proof.

I started programming when I was about 9 years old and it would be a stretch to say I had learnt much mathematics by that stage. However, with a bit of effort I was able to understand variables, for loops, goto statements (forgive me, I was Vic 20 BASIC and I hadn't read any Dijkstra yet) and basic co-ordinate geometry to put graphics on the screen.

I eventually went on to complete an honours degree in Pure Mathematics with a minor in Computer Science. Although I focused mainly on analysis, I also studied quite a bit of discrete maths, number theory, logic and computability theory. Apart from being able to apply a few ideas from statistics, probability theory, vector analysis and linear algebra to programming, there was little maths I studied that was directly applicable to my programming during my undergraduate degree and the commercial and research programming I did afterwards.

However, I strongly believe the formal methods of thinking that mathematics demands — careful reasoning, searching for counter-examples, building axiomatic foundations, spotting connections between concepts — has been a tremendous help when I have tackled large and complex programming projects.

Consider the way athletes train for their sport. For example, footballers no doubt spend much of their training time on basic football skills. However, to improve their general fitness they might also spend time at the gym on bicycle or rowing machines, doing weights, etc.

Studying mathematics can be likened to weight-training or cross-training to improve your mental strength and stamina for programming. It is absolutely essential that you practice your basic programming skills but studying mathematics is an incredible mental work-out that improves your core analytic ability.

Class JavaLaunchHelper is implemented in both ... libinstrument.dylib. One of the two will be used. Which one is undefined

https://groups.google.com/forum/#!topic/google-appengine-stackoverflow/QZGJg2tlfA4

From what I've found online, this is a bug introduced in JDK 1.7.0_45. I've read it will be fixed in the next release of Java, but it's not out yet. Supposedly, it was fixed in 1.7.0_60b01, but I can't find where to download it and 1.7.0_60b02 re-introduces the bug.

I managed to get around the problem by reverting back to JDK 1.7.0_25. Probably not the solution you wanted, but it's the only way I've been able to get it working. Don't forget add JDK 1.7.0_25 in Eclipse after installing the JDK.

Please DO NOT REPLY directly to this email but go to StackOverflow: Class JavaLaunchHelper is implemented in both. One of the two will be used. Which one is undefined

SQLite table constraint - unique on multiple columns

If you already have a table and can't/don't want to recreate it for whatever reason, use indexes:

CREATE UNIQUE INDEX my_index ON my_table(col_1, col_2);

PHP date yesterday

strtotime(), as in date("F j, Y", strtotime("yesterday"));

MySQL query finding values in a comma separated string

This will work for sure, and I actually tried it out:

lwdba@localhost (DB test) :: DROP TABLE IF EXISTS shirts;
Query OK, 0 rows affected (0.08 sec)

lwdba@localhost (DB test) :: CREATE TABLE shirts
    -> (<BR>
    -> id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    -> ticketnumber INT,
    -> colors VARCHAR(30)
    -> );<BR>
Query OK, 0 rows affected (0.19 sec)

lwdba@localhost (DB test) :: INSERT INTO shirts (ticketnumber,colors) VALUES
    -> (32423,'1,2,5,12,15'),
    -> (32424,'1,5,12,15,30'),
    -> (32425,'2,5,11,15,28'),
    -> (32426,'1,2,7,12,15'),
    -> (32427,'2,4,8,12,15');
Query OK, 5 rows affected (0.06 sec)
Records: 5  Duplicates: 0  Warnings: 0

lwdba@localhost (DB test) :: SELECT * FROM shirts WHERE LOCATE(CONCAT(',', 1 ,','),CONCAT(',',colors,',')) > 0;
+----+--------------+--------------+
| id | ticketnumber | colors       |
+----+--------------+--------------+
|  1 |        32423 | 1,2,5,12,15  |
|  2 |        32424 | 1,5,12,15,30 |
|  4 |        32426 | 1,2,7,12,15  |
+----+--------------+--------------+
3 rows in set (0.00 sec)

Give it a Try !!!

add column to mysql table if it does not exist

$smpt = $pdo->prepare("SHOW fields FROM __TABLE__NAME__");
$smpt->execute();
$res = $smpt->fetchAll(PDO::FETCH_ASSOC);
//print_r($res);

Then in $res by cycle look for key of your column Smth like this:

    if($field['Field'] == '_my_col_'){
       return true;
    }
+

**Below code is good for checking column existing in the WordPress tables:**
public static function is_table_col_exists($table, $col)
    {
        global $wpdb;
        $fields = $wpdb->get_results("SHOW fields FROM {$table}", ARRAY_A);
        foreach ($fields as $field)
        {
            if ($field['Field'] == $col)
            {
                return TRUE;
            }
        }

        return FALSE;
    }

Remove quotes from a character vector in R

Here is one combining noquote and paste:

noquote(paste("Argument is of length zero",sQuote("!"),"and",dQuote("double")))


#[1] Argument is of length zero ‘!’ and “double”