Programs & Examples On #Concreteclass

How to send JSON instead of a query string with $.ajax?

No, the dataType option is for parsing the received data.

To post JSON, you will need to stringify it yourself via JSON.stringify and set the processData option to false.

$.ajax({
    url: url,
    type: "POST",
    data: JSON.stringify(data),
    processData: false,
    contentType: "application/json; charset=UTF-8",
    complete: callback
});

Note that not all browsers support the JSON object, and although jQuery has .parseJSON, it has no stringifier included; you'll need another polyfill library.

Python NLTK: SyntaxError: Non-ASCII character '\xc3' in file (Sentiment Analysis -NLP)

Add the following to the top of your file # coding=utf-8

If you go to the link in the error you can seen the reason why:

Defining the Encoding

Python will default to ASCII as standard encoding if no other encoding hints are given. To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as: # coding=

In Ruby, how do I skip a loop in a .each loop, similar to 'continue'

Use next:

(1..10).each do |a|
  next if a.even?
  puts a
end

prints:

1
3   
5
7
9

For additional coolness check out also redo and retry.

Works also for friends like times, upto, downto, each_with_index, select, map and other iterators (and more generally blocks).

For more info see http://ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html#UL.

TypeError: 'module' object is not callable

Assume that the content of YourClass.py is:

class YourClass:
    # ......

If you use:

from YourClassParentDir import YourClass  # means YourClass.py

In this way, I got TypeError: 'module' object is not callable if you then tried to use YourClass().

But, if you use:

from YourClassParentDir.YourClass import YourClass   # means Class YourClass

or use YourClass.YourClass(), it works for me.

Convert string to title case with JavaScript

My one line solution:

String.prototype.capitalizeWords = function() {
    return this.split(" ").map(function(ele){ return ele[0].toUpperCase() + ele.slice(1).toLowerCase();}).join(" ");
};

Then, you can call the method capitalizeWords() on any string. For example:

var myS = "this actually works!";
myS.capitalizeWords();

>>> This Actually Works

My other solution:

function capitalizeFirstLetter(word) {
    return word[0].toUpperCase() + word.slice(1).toLowerCase();
}
String.prototype.capitalizeAllWords = function() {
    var arr = this.split(" ");
    for(var i = 0; i < arr.length; i++) {
        arr[i] = capitalizeFirstLetter(arr[i]);
    }
    return arr.join(" ");
};

Then, you can call the method capitalizeWords() on any string. For example:

var myStr = "this one works too!";
myStr.capitalizeWords();

>>> This One Works Too

Alternative solution based on Greg Dean answer:

function capitalizeFirstLetter(word) {
    return word[0].toUpperCase() + word.slice(1).toLowerCase();
}
String.prototype.capitalizeWords = function() {
    return this.replace(/\w\S*/g, capitalizeFirstLetter);
};

Then, you can call the method capitalizeWords() on any string. For example:

var myString = "yes and no";
myString.capitalizeWords()

>>> Yes And No

How to make a submit out of a <a href...>...</a> link?

What might be a handy addition to this is the possibility to change the post-url from the extra button so you can post to different urls with different buttons. This can be achieved by setting the form 'action' property. Here's the code for that when using jQuery:

$('#[href button name]').click(function(e) {
    e.preventDefault();
    $('#[form name]').attr('action', 'alternateurl.php');
    $('#[form name]').submit();
});

The action-attribute has some issues with older jQuery versions, but on the latest you'll be good to go.

How to show two figures using matplotlib?

Alternatively to calling plt.show() at the end of the script, you can also control each figure separately doing:

f = plt.figure(1)
plt.hist........
............
f.show()

g = plt.figure(2)
plt.hist(........
................
g.show()

raw_input()

In this case you must call raw_input to keep the figures alive. This way you can select dynamically which figures you want to show

Note: raw_input() was renamed to input() in Python 3

Git - how delete file from remote repository

  1. If you want to push a deleted file to remote

git add 'deleted file name'

git commit -m'message'

git push -u origin branch

  1. If you want to delete a file from remote and locally

git rm 'file name'

git commit -m'message'

git push -u origin branch

  1. If you want to delete a file from remote only

git rm --cached 'file name'

git commit -m'message'

git push -u origin branch

Why doesn't C++ have a garbage collector?

SHORT ANSWER: We don't know how to do garbage collection efficiently (with minor time and space overhead) and correctly all the time (in all possible cases).

LONG ANSWER: Just like C, C++ is a systems language; this means it is used when you are writing system code, e.g., operating system. In other words, C++ is designed, just like C, with best possible performance as the main target. The language' standard will not add any feature that might hinder the performance objective.

This pauses the question: Why garbage collection hinders performance? The main reason is that, when it comes to implementation, we [computer scientists] do not know how to do garbage collection with minimal overhead, for all cases. Hence it's impossible to the C++ compiler and runtime system to perform garbage collection efficiently all the time. On the other hand, a C++ programmer, should know his design/implementation and he's the best person to decide how to best do the garbage collection.

Last, if control (hardware, details, etc.) and performance (time, space, power, etc.) are not the main constraints, then C++ is not the write tool. Other language might serve better and offer more [hidden] runtime management, with the necessary overhead.

How to create an object property from a variable value in JavaScript?

The following demonstrates an alternative approach for returning a key pair object using the form of (a, b). The first example uses the string 'key' as the property name, and 'val' as the value.

Example #1:

(function(o,a,b){return o[a]=b,o})({},'key','val');

Example: #2:

var obj = { foo: 'bar' };
(function(o,a,b){return o[a]=b,o})(obj,'key','val');

As shown in the second example, this can modify existing objects, too (if property is already defined in the object, value will be overwritten).

Result #1: { key: 'val' }

Result #2: { foo: 'bar', key: 'val' }

How do I detect unsigned integer multiply overflow?

Clang 3.4+ and GCC 5+ offer checked arithmetic builtins. They offer a very fast solution to this problem, especially when compared to bit-testing safety checks.

For the example in OP's question, it would work like this:

unsigned long b, c, c_test;
if (__builtin_umull_overflow(b, c, &c_test))
{
    // Returned non-zero: there has been an overflow
}
else
{
    // Return zero: there hasn't been an overflow
}

The Clang documentation doesn't specify whether c_test contains the overflowed result if an overflow occurred, but the GCC documentation says that it does. Given that these two like to be __builtin-compatible, it's probably safe to assume that this is how Clang works too.

There is a __builtin for each arithmetic operation that can overflow (addition, subtraction, multiplication), with signed and unsigned variants, for int sizes, long sizes, and long long sizes. The syntax for the name is __builtin_[us](operation)(l?l?)_overflow:

  • u for unsigned or s for signed;
  • operation is one of add, sub or mul;
  • no l suffix means that the operands are ints; one l means long; two ls mean long long.

So for a checked signed long integer addition, it would be __builtin_saddl_overflow. The full list can be found on the Clang documentation page.

GCC 5+ and Clang 3.8+ additionally offer generic builtins that work without specifying the type of the values: __builtin_add_overflow, __builtin_sub_overflow and __builtin_mul_overflow. These also work on types smaller than int.

The builtins lower to what's best for the platform. On x86, they check the carry, overflow and sign flags.

Visual Studio's cl.exe doesn't have direct equivalents. For unsigned additions and subtractions, including <intrin.h> will allow you to use addcarry_uNN and subborrow_uNN (where NN is the number of bits, like addcarry_u8 or subborrow_u64). Their signature is a bit obtuse:

unsigned char _addcarry_u32(unsigned char c_in, unsigned int src1, unsigned int src2, unsigned int *sum);
unsigned char _subborrow_u32(unsigned char b_in, unsigned int src1, unsigned int src2, unsigned int *diff);

c_in/b_in is the carry/borrow flag on input, and the return value is the carry/borrow on output. It does not appear to have equivalents for signed operations or multiplications.

Otherwise, Clang for Windows is now production-ready (good enough for Chrome), so that could be an option, too.

keyCode values for numeric keypad?

You can use this to figure out keyCodes easily:

$(document).keyup(function(e) {
    // Displays the keycode of the last pressed key in the body
    $(document.body).html(e.keyCode);
});

http://jsfiddle.net/vecvc4fr/

Codeigniter $this->input->post() empty while $_POST is working correctly

Finally got the issue resolved today. The issue was with the .htaccess file.

Learning to myself: MUST READ THE CODEIGNITER DOCUMENTATION more thoroughly.

Maximum concurrent Socket.IO connections

I tried to use socket.io on AWS, I can at most keep around 600 connections stable.

And I found out it is because socket.io used long polling first and upgraded to websocket later.

after I set the config to use websocket only, I can keep around 9000 connections.

Set this config at client side:

const socket = require('socket.io-client')
const conn = socket(host, { upgrade: false, transports: ['websocket'] })

Laravel Soft Delete posts

Updated Version (Version 5.0 & Later):

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model {

    use SoftDeletes;

    protected $table = 'posts';

    // ...
}

When soft deleting a model, it is not actually removed from your database. Instead, a deleted_at timestamp is set on the record. To enable soft deletes for a model, specify the softDelete property on the model (Documentation).

For (Version 4.2):

use Illuminate\Database\Eloquent\SoftDeletingTrait; // <-- This is required

class Post extends Eloquent {

    use SoftDeletingTrait;

    protected $table = 'posts';

    // ...
}

Prior to Version 4.2 (But not 4.2 & Later)

For example (Using a posts table and Post model):

class Post extends Eloquent {

    protected $table = 'posts';
    protected $softDelete = true;
    
    // ...
}

To add a deleted_at column to your table, you may use the softDeletes method from a migration:

For example (Migration class' up method for posts table) :

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('posts', function(Blueprint $table)
    {
        $table->increments('id');
        // more fields
        $table->softDeletes(); // <-- This will add a deleted_at field
        $table->timeStamps();
    });
}

Now, when you call the delete method on the model, the deleted_at column will be set to the current timestamp. When querying a model that uses soft deletes, the "deleted" models will not be included in query results. To soft delete a model you may use:

$model = Contents::find( $id );
$model->delete();

Deleted (soft) models are identified by the timestamp and if deleted_at field is NULL then it's not deleted and using the restore method actually makes the deleted_at field NULL. To permanently delete a model you may use forceDelete method.

How to get the background color of an HTML element?

It depends which style from the div you need. Is this a background style which was defined in CSS or background style which was added through javascript(inline) to the current node?

In case of CSS style, you should use computed style. Like you do in getStyle().

With inline style you should use node.style reference: x.style.backgroundColor;

Also notice, that you pick the style by using camelCase/non hyphen reference, so not background-color, but backgroundColor;

YYYY-MM-DD format date in shell script

$(date +%F_%H-%M-%S)

can be used to remove colons (:) in between

output

2018-06-20_09-55-58

XAMPP, Apache - Error: Apache shutdown unexpectedly

Usually, xampp port error occurs because the default port 80 xampp trying to access is in use by another application. Most of the times this application is Skype.
So, you have 2 methods to solve this problem:

  1. Close or Terminate the process/application that is using the port.
  2. Use some other port for your xampp application. (I personally prefer this method).

These methods are well explained in this post How to debug xampp port 80 error

Centering the pagination in bootstrap

The previously mentioned solutions for Bootstrap 3.0 did not work for me on 3.1.1. The pagination class has display:block, and the <li> elements have float:left, which means merely wrapping the <ul> in text-center alone does not work. I have no idea how or when things changed between 3.0 and 3.1.1. Anyway, I had make the <ul> use display:inline-block instead. Here's the code:

<div class="text-center">
    <ul class="pagination" style="display: inline-block">
        <li><a href="...">...</a></li>
    </ul>
</div>

Or for a cleaner setup, omit the style attribute and put it in your stylesheet instead:

.pagination {
    display: inline-block;
}

And then use the markup previously suggested:

<div class="text-center">
    <ul class="pagination">
        <li><a href="...">...</a></li>
    </ul>
</div>

The difference between fork(), vfork(), exec() and clone()

in fork(), either child or parent process will execute based on cpu selection.. But in vfork(), surely child will execute first. after child terminated, parent will execute.

is not JSON serializable

It's worth noting that the QuerySet.values_list() method doesn't actually return a list, but an object of type django.db.models.query.ValuesListQuerySet, in order to maintain Django's goal of lazy evaluation, i.e. the DB query required to generate the 'list' isn't actually performed until the object is evaluated.

Somewhat irritatingly, though, this object has a custom __repr__ method which makes it look like a list when printed out, so it's not always obvious that the object isn't really a list.

The exception in the question is caused by the fact that custom objects cannot be serialized in JSON, so you'll have to convert it to a list first, with...

my_list = list(self.get_queryset().values_list('code', flat=True))

...then you can convert it to JSON with...

json_data = json.dumps(my_list)

You'll also have to place the resulting JSON data in an HttpResponse object, which, apparently, should have a Content-Type of application/json, with...

response = HttpResponse(json_data, content_type='application/json')

...which you can then return from your function.

Reading multiple Scanner inputs

If every input asks the same question, you should use a for loop and an array of inputs:

Scanner dd = new Scanner(System.in);
int[] vars = new int[3];

for(int i = 0; i < vars.length; i++) {
  System.out.println("Enter next var: ");
  vars[i] = dd.nextInt();
}

Or as Chip suggested, you can parse the input from one line:

Scanner in = new Scanner(System.in);
int[] vars = new int[3];

System.out.println("Enter "+vars.length+" vars: ");
for(int i = 0; i < vars.length; i++)
  vars[i] = in.nextInt();

You were on the right track, and what you did works. This is just a nicer and more flexible way of doing things.

Is it better to use std::memcpy() or std::copy() in terms to performance?

Always use std::copy because memcpy is limited to only C-style POD structures, and the compiler will likely replace calls to std::copy with memcpy if the targets are in fact POD.

Plus, std::copy can be used with many iterator types, not just pointers. std::copy is more flexible for no performance loss and is the clear winner.

Checkbox Check Event Listener

If you have a checkbox in your html something like:

<input id="conducted" type = "checkbox" name="party" value="0">

and you want to add an EventListener to this checkbox using javascript, in your associated js file, you can do as follows:

checkbox = document.getElementById('conducted');

checkbox.addEventListener('change', e => {

    if(e.target.checked){
        //do something
    }

});

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

When I want to develop insensitive case searchs, I always convert every string to lower case before do comparasion

Resource interpreted as stylesheet but transferred with MIME type text/html (seems not related with web server)

Using React

I came across this error in my react profile app. My app behaved kind of like it was trying to reference a url that doesn't exist. I believe this has something to do with how webpack behaves.

If you are linking files in your public folder you must remember to use %PUBLIC_URL% before the resource like this:

<link type="text/css" rel="stylesheet" href="%PUBLIC_URL%/bootstrap.min.css" />

How to make a machine trust a self-signed Java application

SERIOUS DISCLAIMER

This solution has a serious security flaw. Please use at your own risk.
Have a look at the comments on this post, and look at all the answers to this question.


OK, I had to go to the customer premises and found a solution. I:

  • Exported the keystore that holds the signing keys in PKCS #12 format
  • Opened control panel Java -> Security tab
  • Clicked Manage certificates
  • Imported this new keystore as a secure site CA

Then I opened the JAWS application without any warning. This is a little bit cumbersome, but much cheaper than buying a signed certificate!

Align contents inside a div

You can do it like this also:

HTML

<body>
    <div id="wrapper_1">
        <div id="container_1"></div>
    </div>
</body>

CSS

body { width: 100%; margin: 0; padding: 0; overflow: hidden; }

#wrapper_1 { clear: left; float: left; position: relative; left: 50%; }

#container_1 { display: block; float: left; position: relative; right: 50%; }

As Artem Russakovskii mentioned also, read the original article by Mattew James Taylor for full description.

Could not load file or assembly System.Web.Http.WebHost after published to Azure web site

I met the same problem and I resolved it by setting CopyLocal to true for the following libs:

System.Web.Http.dll
System.Web.Http.WebHost.dll
System.Net.Http.Formatting.dll

I must add that I use MVC4 and NET 4

How do I add an element to array in reducer of React native redux?

push does not return the array, but the length of it (docs), so what you are doing is replacing the array with its length, losing the only reference to it that you had. Try this:

import {ADD_ITEM} from '../Actions/UserActions'
const initialUserState = {

    arr:[]
}

export default function userState(state = initialUserState, action){
     console.log(arr);
     switch (action.type){
        case ADD_ITEM :
          return { 
             ...state,
             arr:[...state.arr, action.newItem]
        }

        default:return state
     }
}

Compress files while reading data from STDIN

Yes, use gzip for this. The best way is to read data as input and redirect the compressed to output file i.e.

cat test.csv | gzip > test.csv.gz

cat test.csv will send the data as stdout and using pipe-sign gzip will read that data as stdin. Make sure to redirect the gzip output to some file as compressed data will not be written to the terminal.

MySQL said: Documentation #1045 - Access denied for user 'root'@'localhost' (using password: NO)

Check your MySQL Port number 3306.

Is there any other MySQL Install in your system on same port ?

If any installation found the change the port number to any number between 3301-3309 (except 3306)

user name : root
password : ' ' (Empty)

jQuery Scroll to bottom of page/iframe

A simple function that jumps (instantly scrolls) to the bottom of the whole page. It uses the built-in .scrollTop(). I haven’t tried to adapt this to work with individual page elements.

function jumpToPageBottom() {
    $('html, body').scrollTop( $(document).height() - $(window).height() );
}

Using onBackPressed() in Android Fragments

Why don't you want to use the back stack? If there is an underlying problem or confusion maybe we can clear it up for you.

If you want to stick with your requirement just override your Activity's onBackPressed() method and call whatever method you're calling when the back arrow in your ActionBar gets clicked.

EDIT: How to solve the "black screen" fragment back stack problem:

You can get around that issue by adding a backstack listener to the fragment manager. That listener checks if the fragment back stack is empty and finishes the Activity accordingly:

You can set that listener in your Activity's onCreate method:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FragmentManager fm = getFragmentManager();
    fm.addOnBackStackChangedListener(new OnBackStackChangedListener() {
        @Override
        public void onBackStackChanged() {
            if(getFragmentManager().getBackStackEntryCount() == 0) finish();
        }
    });
}

What is the proper #include for the function 'sleep()'?

The sleep man page says it is declared in <unistd.h>.

Synopsis:

#include <unistd.h>

unsigned int sleep(unsigned int seconds);

How to count the number of files in a directory using Python

This is where fnmatch comes very handy:

import fnmatch

print len(fnmatch.filter(os.listdir(dirpath), '*.txt'))

More details: http://docs.python.org/2/library/fnmatch.html

Javascript extends class

Take a look at Simple JavaScript Inheritance and Inheritance Patterns in JavaScript.

The simplest method is probably functional inheritance but there are pros and cons.

Setting width to wrap_content for TextView through code

I am posting android Java base multi line edittext.

EditText editText = findViewById(R.id.editText);/* edittext access */

ViewGroup.LayoutParams params  =  editText.getLayoutParams(); 
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
editText.setLayoutParams(params); /* Gives as much height for multi line*/

editText.setSingleLine(false); /* Makes it Multi line */

New lines inside paragraph in README.md

You can use a backslash at the end of a line.
So this:

a\
b\
c

will then look like:

a
b
c

Notice that there is no backslash at the end of the last line (after the 'c' character).

Difference between variable declaration syntaxes in Javascript (including global variables)?

<title>Index.html</title>
<script>
    var varDeclaration = true;
    noVarDeclaration = true;
    window.hungOnWindow = true;
    document.hungOnDocument = true;
</script>
<script src="external.js"></script>

/* external.js */

console.info(varDeclaration == true); // could be .log, alert etc
// returns false in IE8

console.info(noVarDeclaration == true); // could be .log, alert etc
// returns false in IE8

console.info(window.hungOnWindow == true); // could be .log, alert etc
// returns true in IE8

console.info(document.hungOnDocument == true); // could be .log, alert etc
// returns ??? in IE8 (untested!)  *I personally find this more clugy than hanging off window obj

Is there a global object that all vars are hung off of by default? eg: 'globals.noVar declaration'

HTML5 Video not working in IE 11

I know this is old, but here is a additional thing if you still encounter problems with the solution above.

Just put in your <head> :

<meta http-equiv="X-UA-Compatible" content="IE=edge"> 

It will prevent IE to jump back to IE9 compatibility, thus breaking the video function. Worked for me, so if you still have problems, consider checking this out.

Alternatively you can add this in PHP :

header('x-ua-compatible: ie=edge');

Or in a .htaccess file:

header set X-UA-Compatible "IE=Edge"

Java way to check if a string is palindrome

 public boolean isPalindrom(String text) {
    StringBuffer stringBuffer = new StringBuffer(text);
     return stringBuffer.reverse().toString().equals(text);
}

ruby LoadError: cannot load such file

I created my own Gem, but I did it in a directory that is not in my load path:

$ pwd
/Users/myuser/projects
$ gem build my_gem/my_gem.gemspec

Then I ran irb and tried to load the Gem:

> require 'my_gem'
LoadError: cannot load such file -- my_gem

I used the global variable $: to inspect my load path and I realized I am using RVM. And rvm has specific directories in my load path $:. None of those directories included my ~/projects directory where I created the custom gem.

So one solution is to modify the load path itself:

$: << "/Users/myuser/projects/my_gem/lib"

Note that the lib directory is in the path, which holds the my_gem.rb file which will be required in irb:

> require 'my_gem'
 => true 

Now if you want to install the gem in RVM path, then you would need to run:

$ gem install my_gem

But it will need to be in a repository like rubygems.org.

$ gem push my_gem-0.0.0.gem
Pushing gem to RubyGems.org...
Successfully registered gem my_gem

How can I remove the last character of a string in python?

To remove the last character, just use a slice: my_file_path[:-1]. If you only want to remove a specific set of characters, use my_file_path.rstrip('/'). If you see the string as a file path, the operation is os.path.dirname. If the path is in fact a filename, I rather wonder where the extra slash came from in the first place.

npm install Error: rollbackFailedOptional

In some rarer occasions, check that the project can be built using regular npm commands. I ran into one that is configured to work with bower, so bower install <github_url> works while npm install <github_url> gives that unhelpful cryptic error message on all platforms...

The response content cannot be parsed because the Internet Explorer engine is not available, or

I have had this issue also, and while -UseBasicParsing will work for some, if you actually need to interact with the dom it wont work. Try using a a group policy to stop the initial configuration window from ever appearing and powershell won't stop you anymore. See here https://wahlnetwork.com/2015/11/17/solving-the-first-launch-configuration-error-with-powershells-invoke-webrequest-cmdlet/

Took me just a few minutes once I found this page, once the GP is set, powershell will allow you through.

Markdown open a new window link

Using sed

If one would like to do this systematically for all external links, CSS is no option. However, one could run the following sed command once the (X)HTML has been created from Markdown:

sed -i 's|href="http|target="_blank" href="http|g' index.html

This can be further automated in a single workflow when a Makefile with build instructions is employed.

PS: This answer was written at a time when extension link_attributes was not yet available in Pandoc.

http://localhost:50070 does not work HADOOP

If you can open the http://localhost:8088/cluster but can't open http://localhost:50070/. Maybe datanode didn't start-up or namenode didn't formate.

Hadoop version 2.6.4

  • step 1:

check whether your namenode has been formated, if not type:

$ stop-all.sh
$ /path/to/hdfs namenode -format
$ start-all.sh
  • step 2:

check your namenode tmp file path, to see in /tmp, if the namenode directory is in /tmp, you need set tmp path in core-site.xml, because every time when you reboot or start your machine, the files in /tmp will be removed, you need set a tmp dir path.

add the following to it.

<property>
    <name>hadoop.tmp.dir</name>
    <value>/path/to/hadoop/tmp</value>
</property>
  • step 3:

check step 2, stop hadoop and remove the namenode tmp dir in /tmp, then type /path/to/hdfs namenode -format, and start the hadoop. The is also a tmp dir in $HADOOP_HOME

If all the above don't help, please comment below!

How do I get the directory that a program is running from?

Here's code to get the full path to the executing app:

Windows:

char pBuf[256];
size_t len = sizeof(pBuf); 
int bytes = GetModuleFileName(NULL, pBuf, len);
return bytes ? bytes : -1;

Linux:

int bytes = MIN(readlink("/proc/self/exe", pBuf, len), len - 1);
if(bytes >= 0)
    pBuf[bytes] = '\0';
return bytes;

Initializing an Array of Structs in C#

Firstly, do you really have to have a mutable struct? They're almost always a bad idea. Likewise public fields. There are some very occasional contexts in which they're reasonable (usually both parts together, as with ValueTuple) but they're pretty rare in my experience.

Other than that, I'd just create a constructor taking the two bits of data:

class SomeClass
{

    struct MyStruct
    {
        private readonly string label;
        private readonly int id;

        public MyStruct (string label, int id)
        {
            this.label = label;
            this.id = id;
        }

        public string Label { get { return label; } }
        public string Id { get { return id; } }

    }

    static readonly IList<MyStruct> MyArray = new ReadOnlyCollection<MyStruct>
        (new[] {
             new MyStruct ("a", 1),
             new MyStruct ("b", 5),
             new MyStruct ("q", 29)
        });
}

Note the use of ReadOnlyCollection instead of exposing the array itself - this will make it immutable, avoiding the problem exposing arrays directly. (The code show does initialize an array of structs - it then just passes the reference to the constructor of ReadOnlyCollection<>.)

Xcode: Could not locate device support files

Same issue, go to App Store and update Xcode

How do I merge changes to a single file, rather than merging commits?

My edit got rejected, so I'm attaching how to handle merging changes from a remote branch here.

If you have to do this after an incorrect merge, you can do something like this:

# If you did a git pull and it broke something, do this first
# Find the one before the merge, copy the SHA1
git reflog
git reset --hard <sha1>

# Get remote updates but DONT auto merge it
git fetch github 

# Checkout to your mainline so your branch is correct.
git checkout develop 

# Make a new branch where you'll be applying matches
git checkout -b manual-merge-github-develop

# Apply your patches
git checkout --patch github/develop path/to/file
...

# Merge changes back in
git checkout develop
git merge manual-merge-github-develop # optionally add --no-ff

# You'll probably have to
git push -f # make sure you know what you're doing.

CSS endless rotation animation

<style>
div
{  
     height:200px;
     width:200px;
     -webkit-animation: spin 2s infinite linear;    
}
@-webkit-keyframes spin {
    0%  {-webkit-transform: rotate(0deg);}
    100% {-webkit-transform: rotate(360deg);}   
}

</style>
</head>

<body>
<div><img src="1.png" height="200px" width="200px"/></div>
</body>

Excel formula to display ONLY month and year?

Try the formula

=TEXT(TODAY(),"MMYYYY")

Custom Cell Row Height setting in storyboard is not responding

I've built the code the various answers/comments hint at so that this works for storyboards that use prototype cells.

This code:

  • Does not require the cell height to be set anywhere other than the obvious place in the storyboard
  • Caches the height for performance reasons
  • Uses a common function to get the cell identifier for an index path to avoid duplicated logic

Thanks to Answerbot, Brennan and lensovet.

- (NSString *)cellIdentifierForIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellIdentifier = nil;

    switch (indexPath.section)
    {
        case 0:
            cellIdentifier = @"ArtworkCell";
            break;
         <... and so on ...>
    }

    return cellIdentifier;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellIdentifier = [self cellIdentifierForIndexPath:indexPath];
    static NSMutableDictionary *heightCache;
    if (!heightCache)
        heightCache = [[NSMutableDictionary alloc] init];
    NSNumber *cachedHeight = heightCache[cellIdentifier];
    if (cachedHeight)
        return cachedHeight.floatValue;

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    CGFloat height = cell.bounds.size.height;
    heightCache[cellIdentifier] = @(height);
    return height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellIdentifier = [self cellIdentifierForIndexPath:indexPath];

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];

    <... configure cell as usual...>

.htaccess redirect http to https

Searching for the best way to redirect, i've found this (coming from html5boilerplate) :

# ----------------------------------------------------------------------
# | HTTP Strict Transport Security (HSTS)                              |
# ----------------------------------------------------------------------

# Force client-side SSL redirection.
#
# If a user types `example.com` in their browser, even if the server
# redirects them to the secure version of the website, that still leaves
# a window of opportunity (the initial HTTP connection) for an attacker
# to downgrade or redirect the request.
#
# The following header ensures that browser will ONLY connect to your
# server via HTTPS, regardless of what the users type in the browser's
# address bar.
#
# (!) Remove the `includeSubDomains` optional directive if the website's
# subdomains are not using HTTPS.
#
# http://www.html5rocks.com/en/tutorials/security/transport-layer-security/
# https://tools.ietf.org/html/draft-ietf-websec-strict-transport-sec-14#section-6.1
# http://blogs.msdn.com/b/ieinternals/archive/2014/08/18/hsts-strict-transport-security-attacks-mitigations-deployment-https.aspx

Header set Strict-Transport-Security "max-age=16070400; includeSubDomains"

Maybe it will help someone in 2017 ! :)

Select multiple columns in data.table by their numeric indices

It's a bit verbose, but i've gotten used to using the hidden .SD variable.

b<-data.table(a=1,b=2,c=3,d=4)
b[,.SD,.SDcols=c(1:2)]

It's a bit of a hassle, but you don't lose out on other data.table features (I don't think), so you should still be able to use other important functions like join tables etc.

Finding common rows (intersection) in two Pandas dataframes

In SQL, this problem could be solved by several methods:

select * from df1 where exists (select * from df2 where df2.user_id = df1.user_id)
union all
select * from df2 where exists (select * from df1 where df1.user_id = df2.user_id)

or join and then unpivot (possible in SQL server)

select
    df1.user_id,
    c.rating
from df1
    inner join df2 on df2.user_i = df1.user_id
    outer apply (
        select df1.rating union all
        select df2.rating
    ) as c

Second one could be written in pandas with something like:

>>> df1 = pd.DataFrame({"user_id":[1,2,3], "rating":[10, 15, 20]})
>>> df2 = pd.DataFrame({"user_id":[3,4,5], "rating":[30, 35, 40]})
>>>
>>> df4 = df[['user_id', 'rating_1']].rename(columns={'rating_1':'rating'})
>>> df = pd.merge(df1, df2, on='user_id', suffixes=['_1', '_2'])
>>> df3 = df[['user_id', 'rating_1']].rename(columns={'rating_1':'rating'})
>>> df4 = df[['user_id', 'rating_2']].rename(columns={'rating_2':'rating'})
>>> pd.concat([df3, df4], axis=0)
   user_id  rating
0        3      20
0        3      30

Convert Datetime column from UTC to local time in select statement

Here's a simpler one that takes dst in to account

CREATE FUNCTION [dbo].[UtcToLocal] 
(
    @p_utcDatetime DATETIME 
)
RETURNS DATETIME
AS
BEGIN
    RETURN DATEADD(MINUTE, DATEDIFF(MINUTE, GETUTCDATE(), @p_utcDatetime), GETDATE())
END

How to place div in top right hand corner of page

the style is:

<style type="text/css">
 .topcorner{
   position:absolute;
   top:0;
   right:0;
  }
</style>

hope it will work. Thanks

Bootstrap date and time picker

If you are still interested in a javascript api to select both date and time data, have a look at these projects which are forks of bootstrap datepicker:

The first fork is a big refactor on the parsing/formatting codebase and besides providing all views to select date/time using mouse/touch, it also has a mask option (by default) which lets the user to quickly type the date/time based on a pre-specified format.

Launch an event when checking a checkbox in Angular2

StackBlitz

Template: You can either use the native change event or NgModel directive's ngModelChange.

<input type="checkbox" (change)="onNativeChange($event)"/>

or

<input type="checkbox" ngModel (ngModelChange)="onNgModelChange($event)"/>

TS:

onNativeChange(e) { // here e is a native event
  if(e.target.checked){
    // do something here
  }
}

onNgModelChange(e) { // here e is a boolean, true if checked, otherwise false
  if(e){
    // do something here
  }
}

What is Hive: Return Code 2 from org.apache.hadoop.hive.ql.exec.MapRedTask

Adding some information here, as it took me awhile to find the hadoop jobtracker web-dashboard in HDInsight (Azure's Hadoop), and a colleague finally showed me where it was. There is a shortcut on the head node called "Hadoop Yarn Status" which is just a link to a local http page (http://headnodehost:9014/cluster in my case). When opened the dashboard looked like this:

enter image description here

In that dashboard you can find your failed application, and then after clicking into it you can look at the logs of the individual map and reduce jobs.

In my case it seemed to still be running out of memory in the reducers, even though I had cranked the memory in the configuration already. For some reason it was not surfacing the "java outofmemory" errors I got earlier though.

Granting DBA privileges to user in Oracle

You need only to write:

GRANT DBA TO NewDBA;

Because this already makes the user a DB Administrator

how to read xml file from url using php

$url = 'http://www.example.com'; $xml = simpleXML_load_file($url,"SimpleXMLElement",LIBXML_NOCDATA);

$url can be php file, as long as the file generate xml format data as output.

How to select a single child element using jQuery?

<html>
<title>

    </title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="assets/css/bootstrap.css">
<body>




<!-- <asp:LinkButton ID="MoreInfoButton" runat="server" Text="<%#MoreInfo%>" > -->
 <!-- </asp:LinkButton> -->
<!-- </asp:LinkButton> -->

<br />
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1">
<div>
<a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a>
<div id="parent" class="dataContentSectionMessages" style="display:none">
    <!-- repeater1 starts -->
        <!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> -->
            <ul  >
                <li ><h6><strong>lorem</strong></h6></li>
                <li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li>
                <li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li>
                <li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li>
                <li ><h6><strong>Full Service Contracts</strong></h6></li>
                <li ><h6><strong>Maintenance Contracts</strong></h6></li>
            </ul>
    <!-- repeater1 ends -->
</div>
</div>
<div>
<a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a>
<div id="parent" class="dataContentSectionMessages" style="display:none">
    <!-- repeater1 starts -->
        <!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> -->
            <ul  >
                <li ><h6><strong>lorem</strong></h6></li>
                <li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li>
                <li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li>
                <li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li>
                <li ><h6><strong>Full Service Contracts</strong></h6></li>
                <li ><h6><strong>Maintenance Contracts</strong></h6></li>
            </ul>
    <!-- repeater1 ends -->
</div>
</div>
<div>
<a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a>
<div id="parent" class="dataContentSectionMessages" style="display:none">
    <!-- repeater1 starts -->
        <!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> -->
            <ul  >
                <li ><h6><strong>lorem</strong></h6></li>
                <li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li>
                <li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li>
                <li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li>
                <li ><h6><strong>Full Service Contracts</strong></h6></li>
                <li ><h6><strong>Maintenance Contracts</strong></h6></li>
            </ul>
    <!-- repeater1 ends -->
</div>
</div>
<div>
<a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a>
<div id="parent" class="dataContentSectionMessages" style="display:none">
    <!-- repeater1 starts -->
        <!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> -->
            <ul  >
                <li ><h6><strong>lorem</strong></h6></li>
                <li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li>
                <li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li>
                <li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li>
                <li ><h6><strong>Full Service Contracts</strong></h6></li>
                <li ><h6><strong>Maintenance Contracts</strong></h6></li>
            </ul>
    <!-- repeater1 ends -->
</div>
</div>




</asp:Repeater>


</body>
<!-- Predefined JavaScript -->
<script src="jquery.js"></script>
<script src="bootstrap.js"></script>

<script>

 $(function () {
        $('a').click(function() {
            $(this).parent().children('.dataContentSectionMessages').slideToggle();
        });
    });

    </script>


</html>

What is the difference between a field and a property?

Using Properties, you can raise an event, when the value of the property is changed (aka. PropertyChangedEvent) or before the value is changed to support cancellation.

This is not possible with (direct access to) fields.

public class Person {
 private string _name;

 public event EventHandler NameChanging;     
 public event EventHandler NameChanged;

 public string Name{
  get
  {
     return _name;
  }
  set
  {
     OnNameChanging();
     _name = value;
     OnNameChanged();
  }
 }

 private void OnNameChanging(){       
     NameChanging?.Invoke(this,EventArgs.Empty);       
 }

 private void OnNameChanged(){
     NameChanged?.Invoke(this,EventArgs.Empty);
 }
}

How to implement the Softmax function in Python

Everybody seems to post their solution so I'll post mine:

def softmax(x):
    e_x = np.exp(x.T - np.max(x, axis = -1))
    return (e_x / e_x.sum(axis=0)).T

I get the exact same results as the imported from sklearn:

from sklearn.utils.extmath import softmax

How to test if a string contains one of the substrings in a list, in pandas?

Here is a one line lambda that also works:

df["TrueFalse"] = df['col1'].apply(lambda x: 1 if any(i in x for i in searchfor) else 0)

Input:

searchfor = ['og', 'at']

df = pd.DataFrame([('cat', 1000.0), ('hat', 2000000.0), ('dog', 1000.0), ('fog', 330000.0),('pet', 330000.0)], columns=['col1', 'col2'])

   col1  col2
0   cat 1000.0
1   hat 2000000.0
2   dog 1000.0
3   fog 330000.0
4   pet 330000.0

Apply Lambda:

df["TrueFalse"] = df['col1'].apply(lambda x: 1 if any(i in x for i in searchfor) else 0)

Output:

    col1    col2        TrueFalse
0   cat     1000.0      1
1   hat     2000000.0   1
2   dog     1000.0      1
3   fog     330000.0    1
4   pet     330000.0    0

KeyListener, keyPressed versus keyTyped

keyPressed - when the key goes down
keyReleased - when the key comes up
keyTyped - when the unicode character represented by this key is sent by the keyboard to system input.

I personally would use keyReleased for this. It will fire only when they lift their finger up.

Note that keyTyped will only work for something that can be printed (I don't know if F5 can or not) and I believe will fire over and over again if the key is held down. This would be useful for something like... moving a character across the screen or something.

jQuery's .on() method combined with the submit event

The problem here is that the "on" is applied to all elements that exists AT THE TIME. When you create an element dynamically, you need to run the on again:

$('form').on('submit',doFormStuff);

createNewForm();

// re-attach to all forms
$('form').off('submit').on('submit',doFormStuff);

Since forms usually have names or IDs, you can just attach to the new form as well. If I'm creating a lot of dynamic stuff, I'll include a setup or bind function:

function bindItems(){
    $('form').off('submit').on('submit',doFormStuff); 
    $('button').off('click').on('click',doButtonStuff);
}   

So then whenever you create something (buttons usually in my case), I just call bindItems to update everything on the page.

createNewButton();
bindItems();

I don't like using 'body' or document elements because with tabs and modals they tend to hang around and do things you don't expect. I always try to be as specific as possible unless its a simple 1 page project.

changing the language of error message in required field in html5 contact form

TLDR: Usually, you don't need to change the validation message but if you do use this:

<input
    oninvalid="this.setCustomValidity('Your custom message / ???????')"
    oninput="this.setCustomValidity('')"
    required="required"
    type="text"
    name="text"
>

The validation messages are coming from your browser and if your browser is in English the message will be in English, if the browser is in French the message will be in French and so on.

If you an input for which the default validation messages doesn't work for you, the easiest solution is to provide your custom message to setCustomValidity as a parameter.

...
oninvalid="this.setCustomValidity('Your custom message / ???????')"
...

This is a native input's method which overwrites the default message. But now we have one problem, once the validation is triggered, the message will keep showing while the user is typing. So to stop the message from showing you can set the validity message to empty string using the oninput attribute.

...
oninput="this.setCustomValidity('')"
...

Remove border from IFrame

In addition to adding the frameBorder attribute you might want to consider setting the scrolling attribute to "no" to prevent scrollbars from appearing.

<iframe src="myURL" width="300" height="300" frameBorder="0" scrolling="no">Browser not compatible. </iframe > 

Bootstrap 3.0 Sliding Menu from left

I believe that although javascript is an option here, you have a smoother animation through forcing hardware accelerate with CSS3. You can achieve this by setting the following CSS3 properties on the moving div:

div.hardware-accelarate {
     -webkit-transform: translate3d(0,0,0);
        -moz-transform: translate3d(0,0,0);
         -ms-transform: translate3d(0,0,0);
          -o-transform: translate3d(0,0,0);
             transform: translate3d(0,0,0);
}

I've made a plunkr setup for ya'll to test and tweak...

Python POST binary data

Basically what you do is correct. Looking at redmine docs you linked to, it seems that suffix after the dot in the url denotes type of posted data (.json for JSON, .xml for XML), which agrees with the response you get - Processing by AttachmentsController#upload as XML. I guess maybe there's a bug in docs and to post binary data you should try using http://redmine/uploads url instead of http://redmine/uploads.xml.

Btw, I highly recommend very good and very popular Requests library for http in Python. It's much better than what's in the standard lib (urllib2). It supports authentication as well but I skipped it for brevity here.

import requests
with open('./x.png', 'rb') as f:
    data = f.read()
res = requests.post(url='http://httpbin.org/post',
                    data=data,
                    headers={'Content-Type': 'application/octet-stream'})

# let's check if what we sent is what we intended to send...
import json
import base64

assert base64.b64decode(res.json()['data'][len('data:application/octet-stream;base64,'):]) == data

UPDATE

To find out why this works with Requests but not with urllib2 we have to examine the difference in what's being sent. To see this I'm sending traffic to http proxy (Fiddler) running on port 8888:

Using Requests

import requests

data = 'test data'
res = requests.post(url='http://localhost:8888',
                    data=data,
                    headers={'Content-Type': 'application/octet-stream'})

we see

POST http://localhost:8888/ HTTP/1.1
Host: localhost:8888
Content-Length: 9
Content-Type: application/octet-stream
Accept-Encoding: gzip, deflate, compress
Accept: */*
User-Agent: python-requests/1.0.4 CPython/2.7.3 Windows/Vista

test data

and using urllib2

import urllib2

data = 'test data'    
req = urllib2.Request('http://localhost:8888', data)
req.add_header('Content-Length', '%d' % len(data))
req.add_header('Content-Type', 'application/octet-stream')
res = urllib2.urlopen(req)

we get

POST http://localhost:8888/ HTTP/1.1
Accept-Encoding: identity
Content-Length: 9
Host: localhost:8888
Content-Type: application/octet-stream
Connection: close
User-Agent: Python-urllib/2.7

test data

I don't see any differences which would warrant different behavior you observe. Having said that it's not uncommon for http servers to inspect User-Agent header and vary behavior based on its value. Try to change headers sent by Requests one by one making them the same as those being sent by urllib2 and see when it stops working.

Native query with named parameter fails with "Not all named parameters have been set"

This was a bug fixed in version 4.3.11 https://hibernate.atlassian.net/browse/HHH-2851

EDIT: Best way to execute a native query is still to use NamedParameterJdbcTemplate It allows you need to retrieve a result that is not a managed entity ; you can use a RowMapper and even a Map of named parameters!

private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

@Autowired
public void setDataSource(DataSource dataSource) {
    this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
}

final List<Long> resultList = namedParameterJdbcTemplate.query(query, 
            mapOfNamedParamters, 
            new RowMapper<Long>() {
        @Override
        public Long mapRow(ResultSet rs, int rowNum) throws SQLException {
            return rs.getLong(1);
        }
    });

Insert the same fixed value into multiple rows

This is because in relational database terminology, what you want to do is not called "inserting", but "UPDATING" - you are updating an existing row's field from one value (NULL in your case) to "test"

UPDATE your_table SET table_column = "test" 
WHERE table_column = NULL 

You don't need the second line if you want to update 100% of rows.

How to convert a DataFrame back to normal RDD in pyspark?

Answer given by kennyut/Kistian works very well but to get exact RDD like output when RDD consist of list of attributes e.g. [1,2,3,4] we can use flatmap command as below,

rdd = df.rdd.flatMap(list)
or 
rdd = df.rdd.flatmap(lambda x: list(x))

add maven repository to build.gradle

After

apply plugin: 'com.android.application'

You should add this:

  repositories {
        mavenCentral()
        maven {
            url "https://repository-achartengine.forge.cloudbees.com/snapshot/"
        }
    }

@Benjamin explained the reason.

If you have a maven with authentication you can use:

repositories {
            mavenCentral()
            maven {
               credentials {
                   username xxx
                   password xxx
               }
               url    'http://mymaven/xxxx/repositories/releases/'
            }
}

It is important the order.

Java JTable getting the data of the selected row

if you want to get the data in the entire row, you can use this combination below

tableModel.getDataVector().elementAt(jTable.getSelectedRow());

Where "tableModel" is the model for the table that can be accessed like so

(DefaultTableModel) jTable.getModel();

this will return the entire row data.

I hope this helps somebody

How to use MD5 in javascript to transmit a password

I would suggest you to use CryptoJS in this case.

Basically CryptoJS is a growing collection of standard and secure cryptographic algorithms implemented in JavaScript using best practices and patterns. They are fast, and they have a consistent and simple interface.

So In case you want calculate hash(MD5) of your password string then do as follows :

<script src="http://crypto-js.googlecode.com/svn/tags/3.0.2/build/rollups/md5.js"></script>
<script>
    var passhash = CryptoJS.MD5(password).toString();

    $.post(
      'includes/login.php', 
      { user: username, pass: passhash },
      onLogin, 
      'json' );
</script>

So this script will post hash of your password string to the server.

For further info and support on other hash calculating algorithms you can visit at:

http://code.google.com/p/crypto-js/

Return zero if no record is found

I'm not familiar with postgresql, but in SQL Server or Oracle, using a subquery would work like below (in Oracle, the SELECT 0 would be SELECT 0 FROM DUAL)

SELECT SUM(sub.value)
FROM
( 
  SELECT SUM(columnA) as value FROM my_table
  WHERE columnB = 1
  UNION
  SELECT 0 as value
) sub

Maybe this would work for postgresql too?

Calling a Sub and returning a value

You should be using a Property:

Private _myValue As String
Public Property MyValue As String
    Get
        Return _myValue
    End Get
    Set(value As String)
        _myValue = value
     End Set
End Property

Then use it like so:

MyValue = "Hello"
Console.write(MyValue)

Using jQuery to compare two arrays of Javascript objects

I also found this when looking to do some array comparisons with jQuery. In my case I had strings which I knew to be arrays:

var needle = 'apple orange';
var haystack = 'kiwi orange banana apple plum';

But I cared if it was a complete match or only a partial match, so I used something like the following, based off of Sudhakar R's answer:

function compareStrings( needle, haystack ){
  var needleArr = needle.split(" "),
    haystackArr = haystack.split(" "),
    compare = $(haystackArr).not(needleArr).get().length;

  if( compare == 0 ){
    return 'all';
  } else if ( compare == haystackArr.length  ) {
    return 'none';
  } else {
    return 'partial';
  }
}

Django 1.7 throws django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet

Just encountered the same issue. The problem is because of django-registration incompatible with django 1.7 user model.

A simple fix is to change these lines of code, at your installed django-registration module::

try:
    from django.contrib.auth import get_user_model
    User = get_user_model()
except ImportError:
    from django.contrib.auth.models import User  

to::

from django.conf import settings
try:
    from django.contrib.auth import get_user_model
    User = settings.AUTH_USER_MODEL
except ImportError:
    from django.contrib.auth.models import User 

Mine is at .venv/local/lib/python2.7/site-packages/registration/models.py (virtualenv)

mysql datatype for telephone number and address

INT(10) does not mean a 10-digit number, it means an integer with a display width of 10 digits. The maximum value for an INT in MySQL is 2147483647 (or 4294967295 if unsigned).

You can use a BIGINT instead of INT to store it as a numeric. Using BIGINT will save you 3 bytes per row over VARCHAR(10).

To Store "Country + area + number separately". You can try using a VARCHAR(20), this allows you the ability to store international phone numbers properly, should that need arise.

Handler "ExtensionlessUrlHandler-Integrated-4.0" has a bad module "ManagedPipelineHandler" in its module list

Making this its own post because this had me going for hours.

I saw maybe a dozen of similar posts here and elsewhere about this problema and the aspnet_regiis fix. They weren't working for me, and aspnet_regiis was acting odd, just listing options etc.

As user ryan-anderson above indicated, you cannot enter .exe

For those less comfy with things outside IIS on the server, here's what you do in simple steps.

  1. Find aspnet_regiis in a folder similar to this path. c:\Windows\Microsoft.NET\Framework\v4.0.30319\

  2. Right-click command prompt in the start menu or wherever and tell it to run as administrator. Using the windows "Run" feature just won't work, or didn't for me.

  3. Go back to the aspnet_regiis executable. Click-drag it right into the command prompt or copy-paste the address into the command prompt.

  4. Remove, if it's there, the .exe at the end. This is key. Add the -i (space minus eye) at the end. Enter.

If you did this correctly, you will see that it starts to install asp.net, and then tells you it succeeded.

Troubleshooting "program does not contain a static 'Main' method" when it clearly does...?

That's odd. Does your program compile and run successfully and only fail on 'Publish' or does it fail on every compile now?

Also, have you perhaps changed the file's properties' Build Action to something other than Compile?

UnicodeEncodeError: 'ascii' codec can't encode character u'\xef' in position 0: ordinal not in range(128)

It seems you are hitting a UTF-8 byte order mark (BOM). Try using this unicode string with BOM extracted out:

import codecs

content = unicode(q.content.strip(codecs.BOM_UTF8), 'utf-8')
parser.parse(StringIO.StringIO(content))

I used strip instead of lstrip because in your case you had multiple occurences of BOM, possibly due to concatenated file contents.

SELECT INTO a table variable in T-SQL

You can also use common table expressions to store temporary datasets. They are more elegant and adhoc friendly:

WITH userData (name, oldlocation)
AS
(
  SELECT name, location 
  FROM   myTable    INNER JOIN 
         otherTable ON ...
  WHERE  age>30
)
SELECT * 
FROM   userData -- you can also reuse the recordset in subqueries and joins

How do I get the calling method name and type using reflection?

Yes, in principe it is possible, but it doesn't come for free.

You need to create a StackTrace, and then you can have a look at the StackFrame's of the call stack.

Fit image into ImageView, keep aspect ratio and then resize ImageView to image dimensions?

I needed to have an ImageView and an Bitmap, so the Bitmap is scaled to ImageView size, and size of the ImageView is the same of the scaled Bitmap :).

I was looking through this post for how to do it, and finally did what I want, not the way described here though.

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/acpt_frag_root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/imageBackground"
android:orientation="vertical">

<ImageView
    android:id="@+id/acpt_image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:adjustViewBounds="true"
    android:layout_margin="@dimen/document_editor_image_margin"
    android:background="@color/imageBackground"
    android:elevation="@dimen/document_image_elevation" />

and then in onCreateView method

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_scanner_acpt, null);

    progress = view.findViewById(R.id.progress);

    imageView = view.findViewById(R.id.acpt_image);
    imageView.setImageBitmap( bitmap );

    imageView.getViewTreeObserver().addOnGlobalLayoutListener(()->
        layoutImageView()
    );

    return view;
}

and then layoutImageView() code

private void layoutImageView(){

    float[] matrixv = new float[ 9 ];

    imageView.getImageMatrix().getValues(matrixv);

    int w = (int) ( matrixv[Matrix.MSCALE_X] * bitmap.getWidth() );
    int h = (int) ( matrixv[Matrix.MSCALE_Y] * bitmap.getHeight() );

    imageView.setMaxHeight(h);
    imageView.setMaxWidth(w);

}

And the result is that image fits inside perfectly, keeping aspect ratio, and doesn't have extra leftover pixels from ImageView when the Bitmap is inside.

Result

It's important ImageView to have wrap_content and adjustViewBounds to true, then setMaxWidth and setMaxHeight will work, this is written in the source code of ImageView,

/*An optional argument to supply a maximum height for this view. Only valid if
 * {@link #setAdjustViewBounds(boolean)} has been set to true. To set an image to be a
 * maximum of 100 x 100 while preserving the original aspect ratio, do the following: 1) set
 * adjustViewBounds to true 2) set maxWidth and maxHeight to 100 3) set the height and width
 * layout params to WRAP_CONTENT. */

How to dynamically create columns in datatable and assign values to it?

What have you tried, what was the problem?

Creating DataColumns and add values to a DataTable is straight forward:

Dim dt = New DataTable()
Dim dcID = New DataColumn("ID", GetType(Int32))
Dim dcName = New DataColumn("Name", GetType(String))
dt.Columns.Add(dcID)
dt.Columns.Add(dcName)
For i = 1 To 1000
    dt.Rows.Add(i, "Row #" & i)
Next

Edit:

If you want to read a xml file and load a DataTable from it, you can use DataTable.ReadXml.

Detect backspace and del on "input" event?

keydown with event.key === "Backspace" or "Delete"

More recent and much cleaner: use event.key. No more arbitrary number codes!

input.addEventListener('keydown', function(event) {
    const key = event.key; // const {key} = event; ES6+
    if (key === "Backspace" || key === "Delete") {
        return false;
    }
});

Modern style:

input.addEventListener('keydown', ({key}) => {
    if (["Backspace", "Delete"].includes(key)) {
        return false
    }
})

Mozilla Docs

Supported Browsers

How to display images from a folder using php - PHP

Here is a possible solution the solution #3 on my comments to blubill's answer:

yourscript.php
========================
<?php
    $dir = '/home/user/Pictures';
    $file_display = array('jpg', 'jpeg', 'png', 'gif');

    if (file_exists($dir) == false) 
    {
        echo 'Directory "', $dir, '" not found!';
    } 
    else 
    {
        $dir_contents = scandir($dir);

        foreach ($dir_contents as $file) 
        {
            $file_type = strtolower(end(explode('.', $file)));
            if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true)     
            {
                $name = basename($file);
                echo "<img src='img.php?name={$name}' />";
            }
        }
    }
?>


img.php
========================
<?php
    $name = $_GET['name'];
    $mimes = array
    (
        'jpg' => 'image/jpg',
        'jpeg' => 'image/jpg',
        'gif' => 'image/gif',
        'png' => 'image/png'
    );

    $ext = strtolower(end(explode('.', $name)));

    $file = '/home/users/Pictures/'.$name;
    header('content-type: '. $mimes[$ext]);
    header('content-disposition: inline; filename="'.$name.'";');
    readfile($file);
?>

Using print statements only to debug

First off, I will second the nomination of python's logging framework. Be a little careful about how you use it, however. Specifically: let the logging framework expand your variables, don't do it yourself. For instance, instead of:

logging.debug("datastructure: %r" % complex_dict_structure)

make sure you do:

logging.debug("datastructure: %r", complex_dict_structure)

because while they look similar, the first version incurs the repr() cost even if it's disabled. The second version avoid this. Similarly, if you roll your own, I'd suggest something like:

def debug_stdout(sfunc):
    print(sfunc())

debug = debug_stdout

called via:

debug(lambda: "datastructure: %r" % complex_dict_structure)

which will, again, avoid the overhead if you disable it by doing:

def debug_noop(*args, **kwargs):
    pass

debug = debug_noop

The overhead of computing those strings probably doesn't matter unless they're either 1) expensive to compute or 2) the debug statement is in the middle of, say, an n^3 loop or something. Not that I would know anything about that.

Remove substring from the string

If you are using rails or at less activesupport you got String#remove and String#remove! method

def remove!(*patterns)
  patterns.each do |pattern|
    gsub! pattern, ""
  end

  self
end

source: http://api.rubyonrails.org/classes/String.html#method-i-remove

How to overcome root domain CNAME restrictions?

I don't know how they are getting away with it, or what negative side effects their may be, but I'm using Hover.com to host some of my domains, and recently setup the apex of my domain as a CNAME there. Their DNS editing tool did not complain at all, and my domain happily resolves via the CNAME assigned.

Here is what Dig shows me for this domain (actual domain obfuscated as mydomain.com):

; <<>> DiG 9.8.3-P1 <<>> mydomain.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 2056
;; flags: qr rd ra; QUERY: 1, ANSWER: 3, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;mydomain.com.          IN  A

;; ANSWER SECTION:
mydomain.com.       394 IN  CNAME   myapp.parseapp.com.
myapp.parseapp.com. 300 IN  CNAME   parseapp.com.
parseapp.com.       60  IN  A   54.243.93.102

What and where are the stack and heap?

Others have directly answered your question, but when trying to understand the stack and the heap, I think it is helpful to consider the memory layout of a traditional UNIX process (without threads and mmap()-based allocators). The Memory Management Glossary web page has a diagram of this memory layout.

The stack and heap are traditionally located at opposite ends of the process's virtual address space. The stack grows automatically when accessed, up to a size set by the kernel (which can be adjusted with setrlimit(RLIMIT_STACK, ...)). The heap grows when the memory allocator invokes the brk() or sbrk() system call, mapping more pages of physical memory into the process's virtual address space.

In systems without virtual memory, such as some embedded systems, the same basic layout often applies, except the stack and heap are fixed in size. However, in other embedded systems (such as those based on Microchip PIC microcontrollers), the program stack is a separate block of memory that is not addressable by data movement instructions, and can only be modified or read indirectly through program flow instructions (call, return, etc.). Other architectures, such as Intel Itanium processors, have multiple stacks. In this sense, the stack is an element of the CPU architecture.

Display a angular variable in my html page

In your template, you have access to all the variables that are members of the current $scope. So, tobedone should be $scope.tobedone, and then you can display it with {{tobedone}}, or [[tobedone]] in your case.

What is the difference between Numpy's array() and asarray() functions?

The difference can be demonstrated by this example:

  1. generate a matrix

    >>> A = numpy.matrix(numpy.ones((3,3)))
    >>> A
    matrix([[ 1.,  1.,  1.],
            [ 1.,  1.,  1.],
            [ 1.,  1.,  1.]])
    
  2. use numpy.array to modify A. Doesn't work because you are modifying a copy

    >>> numpy.array(A)[2]=2
    >>> A
    matrix([[ 1.,  1.,  1.],
            [ 1.,  1.,  1.],
            [ 1.,  1.,  1.]])
    
  3. use numpy.asarray to modify A. It worked because you are modifying A itself

    >>> numpy.asarray(A)[2]=2
    >>> A
    matrix([[ 1.,  1.,  1.],
            [ 1.,  1.,  1.],
            [ 2.,  2.,  2.]])
    

Hope this helps!

Using python's eval() vs. ast.literal_eval()?

datamap = eval(input('Provide some data here: ')) means that you actually evaluate the code before you deem it to be unsafe or not. It evaluates the code as soon as the function is called. See also the dangers of eval.

ast.literal_eval raises an exception if the input isn't a valid Python datatype, so the code won't be executed if it's not.

Use ast.literal_eval whenever you need eval. You shouldn't usually evaluate literal Python statements.

Changing .gitconfig location on Windows

I have solved this problem using a slightly different approach that I have seen work for other configuration files. Git Config supports includes that allows you to point to a configuration file in another location. That alternate location is then imported and expanded in place as if it was part of .gitconfig file. So now I just have a single entry in .gitconfig:

[include]
   path = c:\\path\\to\\my.config

Any updates written by Git to the .gitconfig file will not overwrite my include path. It does mean that occasionally I may need to move values from .gitconfig to my.config.

Import and Export Excel - What is the best library?

I've tried CSharpJExcel and wouldn't recommend it, at least not until there is some documentation available. Contrary to the developers comments it is not a straight native port.

Get multiple elements by Id

Today you can select elements with the same id attribute this way:

document.querySelectorAll('[id=test]');

Or this way with jQuery:

$('[id=test]');

CSS selector #test { ... } should work also for all elements with id = "test". ?ut the only thing: document.querySelectorAll('#test') (or $('#test') ) - will return only a first element with this id. Is it good, or not - I can't tell . But sometimes it is difficult to follow unique id standart .

For example you have the comment widget, with HTML-ids, and JS-code, working with these HTML-ids. Sooner or later you'll need to render this widget many times, to comment a different objects into a single page: and here the standart will broken (often there is no time or not allow - to rewrite built-in code).

One liner to check if element is in the list

You could try using Strings with a separator which does not appear in any element.

if ("|a|b|c|".contains("|a|"))

Adding background image to div using CSS

Add height & width properties to your .css file.

What is the purpose of Android's <merge> tag in XML layouts?

Another reason to use merge is when using custom viewgroups in ListViews or GridViews. Instead of using the viewHolder pattern in a list adapter, you can use a custom view. The custom view would inflate an xml whose root is a merge tag. Code for adapter:

public class GridViewAdapter extends BaseAdapter {
     // ... typical Adapter class methods
     @Override
     public View getView(int position, View convertView, ViewGroup parent) {
        WallpaperView wallpaperView;
        if (convertView == null)
           wallpaperView = new WallpaperView(activity);
        else
            wallpaperView = (WallpaperView) convertView;

        wallpaperView.loadWallpaper(wallpapers.get(position), imageWidth);
        return wallpaperView;
    }
}

here is the custom viewgroup:

public class WallpaperView extends RelativeLayout {

    public WallpaperView(Context context) {
        super(context);
        init(context);
    }
    // ... typical constructors

    private void init(Context context) {
        View.inflate(context, R.layout.wallpaper_item, this);
        imageLoader = AppController.getInstance().getImageLoader();
        imagePlaceHolder = (ImageView) findViewById(R.id.imgLoader2);
        thumbnail = (NetworkImageView) findViewById(R.id.thumbnail2);
        thumbnail.setScaleType(ImageView.ScaleType.CENTER_CROP);
    }

    public void loadWallpaper(Wallpaper wallpaper, int imageWidth) {
        // ...some logic that sets the views
    }
}

and here is the XML:

<merge xmlns:android="http://schemas.android.com/apk/res/android">

    <ImageView
        android:id="@+id/imgLoader"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_centerInParent="true"
        android:src="@drawable/ico_loader" />

    <com.android.volley.toolbox.NetworkImageView
        android:id="@+id/thumbnail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</merge>

Show DialogFragment with animation growing from a point

Check it out this code, it works for me

// Slide up animation

<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" >

    <translate
        android:duration="@android:integer/config_mediumAnimTime"
        android:fromYDelta="100%"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:toXDelta="0" />

</set>

// Slide dowm animation

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >

    <translate
        android:duration="@android:integer/config_mediumAnimTime"
        android:fromYDelta="0%p"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:toYDelta="100%p" />

</set>

// Style

<style name="DialogAnimation">
    <item name="android:windowEnterAnimation">@anim/slide_up</item>
    <item name="android:windowExitAnimation">@anim/slide_down</item>
</style>

// Inside Dialog Fragment

@Override
public void onActivityCreated(Bundle arg0) {
    super.onActivityCreated(arg0);
    getDialog().getWindow()
    .getAttributes().windowAnimations = R.style.DialogAnimation;
}

How do I convert an array object to a string in PowerShell?

I found that piping the array to the Out-String cmdlet works well too.

For example:

PS C:\> $a  | out-string

This
Is
a
cat

It depends on your end goal as to which method is the best to use.

Show values from a MySQL database table inside a HTML table on a webpage

Surely a better solution would by dynamic so that it would work for any query without having to know the column names?

If so, try this (obviously the query should match your database):

// You'll need to put your db connection details in here.
$conn = new mysqli($server_hostname, $server_username, $server_password, $server_database);

// Run the query.
$result = $conn->query("SELECT * FROM table LIMIT 10");

// Get the result in to a more usable format.
$query = array();
while($query[] = mysqli_fetch_assoc($result));
array_pop($query);

// Output a dynamic table of the results with column headings.
echo '<table border="1">';
echo '<tr>';
foreach($query[0] as $key => $value) {
    echo '<td>';
    echo $key;
    echo '</td>';
}
echo '</tr>';
foreach($query as $row) {
    echo '<tr>';
    foreach($row as $column) {
        echo '<td>';
        echo $column;
        echo '</td>';
    }
    echo '</tr>';
}
echo '</table>';

Taken from here: https://www.antropy.co.uk/blog/handy-php-snippets/

Reference jars inside a jar

Add the jar files to your library(if using netbeans) and modify your manifest's file classpath as follows:

Class-Path: lib/derby.jar lib/derbyclient.jar lib/derbynet.jar lib/derbytools.jar

a similar answer exists here

android.content.Context.getPackageName()' on a null object reference

My class is not extends to Activiti. I solved the problem this way.

class MyOnBindViewHolder : LogicViewAdapterModel.LogicAdapter {
          ...
 holder.title.setOnClickListener({v->
                v.context.startActivity(Intent(context,  HomeActivity::class.java))
            })
          ...
    }

Characters allowed in a URL

The full list of the 66 unreserved characters is in RFC3986, here: http://tools.ietf.org/html/rfc3986#section-2.3

This is any character in the following regex set:

[A-Za-z0-9_.\-~]

How to change owner of PostgreSql database?

Frank Heikens answer will only update database ownership. Often, you also want to update ownership of contained objects (including tables). Starting with Postgres 8.2, REASSIGN OWNED is available to simplify this task.

IMPORTANT EDIT!

Never use REASSIGN OWNED when the original role is postgres, this could damage your entire DB instance. The command will update all objects with a new owner, including system resources (postgres0, postgres1, etc.)


First, connect to admin database and update DB ownership:

psql
postgres=# REASSIGN OWNED BY old_name TO new_name;

This is a global equivalent of ALTER DATABASE command provided in Frank's answer, but instead of updating a particular DB, it change ownership of all DBs owned by 'old_name'.

The next step is to update tables ownership for each database:

psql old_name_db
old_name_db=# REASSIGN OWNED BY old_name TO new_name;

This must be performed on each DB owned by 'old_name'. The command will update ownership of all tables in the DB.

numpy matrix vector multiplication

Simplest solution

Use numpy.dot or a.dot(b). See the documentation here.

>>> a = np.array([[ 5, 1 ,3], 
                  [ 1, 1 ,1], 
                  [ 1, 2 ,1]])
>>> b = np.array([1, 2, 3])
>>> print a.dot(b)
array([16, 6, 8])

This occurs because numpy arrays are not matrices, and the standard operations *, +, -, / work element-wise on arrays. Instead, you could try using numpy.matrix, and * will be treated like matrix multiplication.


Other Solutions

Also know there are other options:

  • As noted below, if using python3.5+ the @ operator works as you'd expect:

    >>> print(a @ b)
    array([16, 6, 8])
    
  • If you want overkill, you can use numpy.einsum. The documentation will give you a flavor for how it works, but honestly, I didn't fully understand how to use it until reading this answer and just playing around with it on my own.

    >>> np.einsum('ji,i->j', a, b)
    array([16, 6, 8])
    
  • As of mid 2016 (numpy 1.10.1), you can try the experimental numpy.matmul, which works like numpy.dot with two major exceptions: no scalar multiplication but it works with stacks of matrices.

    >>> np.matmul(a, b)
    array([16, 6, 8])
    
  • numpy.inner functions the same way as numpy.dot for matrix-vector multiplication but behaves differently for matrix-matrix and tensor multiplication (see Wikipedia regarding the differences between the inner product and dot product in general or see this SO answer regarding numpy's implementations).

    >>> np.inner(a, b)
    array([16, 6, 8])
    
    # Beware using for matrix-matrix multiplication though!
    >>> b = a.T
    >>> np.dot(a, b)
    array([[35,  9, 10],
           [ 9,  3,  4],
           [10,  4,  6]])
    >>> np.inner(a, b) 
    array([[29, 12, 19],
           [ 7,  4,  5],
           [ 8,  5,  6]])
    

Rarer options for edge cases

  • If you have tensors (arrays of dimension greater than or equal to one), you can use numpy.tensordot with the optional argument axes=1:

    >>> np.tensordot(a, b, axes=1)
    array([16,  6,  8])
    
  • Don't use numpy.vdot if you have a matrix of complex numbers, as the matrix will be flattened to a 1D array, then it will try to find the complex conjugate dot product between your flattened matrix and vector (which will fail due to a size mismatch n*m vs n).

MongoDB: How to update multiple documents with a single command?

The following command can update multiple records of a collection

db.collection.update({}, 
{$set:{"field" : "value"}}, 
{ multi: true, upsert: false}
)

angular2: how to copy object into another object

As suggested before, the clean way of deep copying objects having nested objects inside is by using lodash's cloneDeep method.

For Angular, you can do it like this:

Install lodash with yarn add lodash or npm install lodash.

In your component, import cloneDeep and use it:

import * as cloneDeep from 'lodash/cloneDeep';
...
clonedObject = cloneDeep(originalObject);

It's only 18kb added to your build, well worth for the benefits.

I've also written an article here, if you need more insight on why using lodash's cloneDeep.

How to draw vertical lines on a given plot in matplotlib

Calling axvline in a loop, as others have suggested, works, but can be inconvenient because

  1. Each line is a separate plot object, which causes things to be very slow when you have many lines.
  2. When you create the legend each line has a new entry, which may not be what you want.

Instead you can use the following convenience functions which create all the lines as a single plot object:

import matplotlib.pyplot as plt
import numpy as np


def axhlines(ys, ax=None, lims=None, **plot_kwargs):
    """
    Draw horizontal lines across plot
    :param ys: A scalar, list, or 1D array of vertical offsets
    :param ax: The axis (or none to use gca)
    :param lims: Optionally the (xmin, xmax) of the lines
    :param plot_kwargs: Keyword arguments to be passed to plot
    :return: The plot object corresponding to the lines.
    """
    if ax is None:
        ax = plt.gca()
    ys = np.array((ys, ) if np.isscalar(ys) else ys, copy=False)
    if lims is None:
        lims = ax.get_xlim()
    y_points = np.repeat(ys[:, None], repeats=3, axis=1).flatten()
    x_points = np.repeat(np.array(lims + (np.nan, ))[None, :], repeats=len(ys), axis=0).flatten()
    plot = ax.plot(x_points, y_points, scalex = False, **plot_kwargs)
    return plot


def axvlines(xs, ax=None, lims=None, **plot_kwargs):
    """
    Draw vertical lines on plot
    :param xs: A scalar, list, or 1D array of horizontal offsets
    :param ax: The axis (or none to use gca)
    :param lims: Optionally the (ymin, ymax) of the lines
    :param plot_kwargs: Keyword arguments to be passed to plot
    :return: The plot object corresponding to the lines.
    """
    if ax is None:
        ax = plt.gca()
    xs = np.array((xs, ) if np.isscalar(xs) else xs, copy=False)
    if lims is None:
        lims = ax.get_ylim()
    x_points = np.repeat(xs[:, None], repeats=3, axis=1).flatten()
    y_points = np.repeat(np.array(lims + (np.nan, ))[None, :], repeats=len(xs), axis=0).flatten()
    plot = ax.plot(x_points, y_points, scaley = False, **plot_kwargs)
    return plot

How to show math equations in general github's markdown(not github's blog)

A "quick and dirty" solution is to maintain a standard .md file using standard TeX equations, e.g. _README.md. When you are satisfied, pass the entire file through Pandoc to convert from standard Markdown to Markdown (Github flavour), and copy the output to README.md.

You can do this online for a quick turnaround, or install/configure Pandoc locally.

How to run PyCharm in Ubuntu - "Run in Terminal" or "Run"?

As mentioned in the above answer, by updating the bashrc file you can run the pycharm.sh from anywhere on the linux terminal.

But if you love the icon and wants the Desktop shortcuts for the Pycharm on Ubuntu OS then follow the Below steps,

 Quick way to create Pycharm launcher. 
     1. Start Pycharm using the pycharm.sh cmd from anywhere on the terminal or start the pycharm.sh located under bin folder of the pycharm artifact.
     2. Once the Pycharm application loads, navigate to tools menu and select “Create Desktop Entry..”
     3. Check the box if you want the launcher for all users.
     4. If you Check the box i.e “Create entry for all users”, you will be asked for your password.
     5. A message should appear informing you that it was successful.
     6. Now Restart Pycharm application and you will find Pycharm in Unity dash and Application launcher.."

Referencing system.management.automation.dll in Visual Studio

The assembly coming with Powershell SDK (C:\Program Files\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0) does not come with Powershell 2 specific types.

Manually editing the csproj file solved my problem.

force css grid container to fill full screen of device

If you want the .wrapper to be fullscreen, just add the following in the wrapper class:

position: absolute; width: 100%; height: 100%;

You can also add top: 0 and left:0

How to generate a HTML page dynamically using PHP?

Just in case someone wants to generate/create actual HTML file...

$myFile = "filename.html"; // or .php   
$fh = fopen($myFile, 'w'); // or die("error");  
$stringData = "your html code php code goes here";   
fwrite($fh, $stringData);
fclose($fh);

Enjoy!

How does the "final" keyword in Java work? (I can still modify an object.)

The final keyword can be interpreted in two different ways depending on what it's used on:

Value types: For ints, doubles etc, it will ensure that the value cannot change,

Reference types: For references to objects, final ensures that the reference will never change, meaning that it will always refer to the same object. It makes no guarantees whatsoever about the values inside the object being referred to staying the same.

As such, final List<Whatever> foo; ensures that foo always refers to the same list, but the contents of said list may change over time.

How to put the legend out of the plot

The solution that worked for me when I had huge legend was to use extra empty image layout. In following example I made 4 rows and at the bottom I plot image with offset for legend (bbox_to_anchor) at the top it does not get cut.

f = plt.figure()
ax = f.add_subplot(414)
lgd = ax.legend(loc='upper left', bbox_to_anchor=(0, 4), mode="expand", borderaxespad=0.3)
ax.autoscale_view()
plt.savefig(fig_name, format='svg', dpi=1200, bbox_extra_artists=(lgd,), bbox_inches='tight')

How do I create a slug in Django?

There is corner case with some utf-8 characters

Example:

>>> from django.template.defaultfilters import slugify
>>> slugify(u"test aescóln")
u'test-aescon' # there is no "l"

This can be solved with Unidecode

>>> from unidecode import unidecode
>>> from django.template.defaultfilters import slugify
>>> slugify(unidecode(u"test aescóln"))
u'test-aescoln'

SignalR - Sending a message to a specific user using (IUserIdProvider) *NEW 2.0.0*

Here's a start.. Open to suggestions/improvements.

Server

public class ChatHub : Hub
{
    public void SendChatMessage(string who, string message)
    {
        string name = Context.User.Identity.Name;
        Clients.Group(name).addChatMessage(name, message);
        Clients.Group("[email protected]").addChatMessage(name, message);
    }

    public override Task OnConnected()
    {
        string name = Context.User.Identity.Name;
        Groups.Add(Context.ConnectionId, name);

        return base.OnConnected();
    }
}

JavaScript

(Notice how addChatMessage and sendChatMessage are also methods in the server code above)

    $(function () {
    // Declare a proxy to reference the hub.
    var chat = $.connection.chatHub;
    // Create a function that the hub can call to broadcast messages.
    chat.client.addChatMessage = function (who, message) {
        // Html encode display name and message.
        var encodedName = $('<div />').text(who).html();
        var encodedMsg = $('<div />').text(message).html();
        // Add the message to the page.
        $('#chat').append('<li><strong>' + encodedName
            + '</strong>:&nbsp;&nbsp;' + encodedMsg + '</li>');
    };

    // Start the connection.
    $.connection.hub.start().done(function () {
        $('#sendmessage').click(function () {
            // Call the Send method on the hub.
            chat.server.sendChatMessage($('#displayname').val(), $('#message').val());
            // Clear text box and reset focus for next comment.
            $('#message').val('').focus();
        });
    });
});

Testing enter image description here

How to copy Docker images from one host to another without using a repository

Run

docker images

to see a list of the images on the host. Let's say you have an image called awesomesauce. In your terminal, cd to the directory where you want to export the image to. Now run:

docker save awesomesauce:latest > awesomesauce.tar

Copy the tar file to a thumb drive or whatever, and then copy it to the new host computer.

Now from the new host do:

docker load < awesomesauce.tar

Now go have a coffee and read Hacker News...

not finding android sdk (Unity)

Easier solution: set the environment variable USE_SDK_WRAPPER=1, or hack tools/android.bat to add the line "set USE_SDK_WRAPPER=1". This prevents android.bat from popping up a "y/n" prompt, which is what's confusing Unity.

Simple pagination in javascript

So you can use a library for pagination logic https://github.com/pagino/pagino-js

How to have an automatic timestamp in SQLite?

To complement answers above...

If you are using EF, adorn the property with Data Annotation [Timestamp], then go to the overrided OnModelCreating, inside your context class, and add this Fluent API code:

modelBuilder.Entity<YourEntity>()
                .Property(b => b.Timestamp)
                .ValueGeneratedOnAddOrUpdate()
                .IsConcurrencyToken()
                .ForSqliteHasDefaultValueSql("CURRENT_TIMESTAMP");

It will make a default value to every data that will be insert into this table.

What is the difference between SQL Server 2012 Express versions?

Scroll down on that page and you'll see:

Express with Tools (with LocalDB) Includes the database engine and SQL Server Management Studio Express)
This package contains everything needed to install and configure SQL Server as a database server. Choose either LocalDB or Express depending on your needs above.

That's the SQLEXPRWT_x64_ENU.exe download.... (WT = with tools)


Express with Advanced Services (contains the database engine, Express Tools, Reporting Services, and Full Text Search)
This package contains all the components of SQL Express. This is a larger download than “with Tools,” as it also includes both Full Text Search and Reporting Services.

That's the SQLEXPRADV_x64_ENU.exe download ... (ADV = Advanced Services)


The SQLEXPR_x64_ENU.exe file is just the database engine - no tools, no Reporting Services, no fulltext-search - just barebones engine.

Get width/height of SVG element

Use getBBox function

http://jsfiddle.net/Xkv3X/1/

var bBox = svg1.getBBox();
console.log('XxY', bBox.x + 'x' + bBox.y);
console.log('size', bBox.width + 'x' + bBox.height);

Which selector do I need to select an option by its text?

This worked for me: $("#test").find("option:contains('abc')");

ASP.NET MVC: Custom Validation by DataAnnotation

A bit late to answer, but for who is searching. You can easily do this by using an extra property with the data annotation:

public string foo { get; set; }
public string bar { get; set; }

[MinLength(20, ErrorMessage = "too short")]
public string foobar 
{ 
    get
    {
        return foo + bar;
    }
}

That's all that is too it really. If you really want to display in a specific place the validation error as well, you can add this in your view:

@Html.ValidationMessage("foobar", "your combined text is too short")

doing this in the view can come in handy if you want to do localization.

Hope this helps!

Jasmine JavaScript Testing - toBe vs toEqual

Looking at the Jasmine source code sheds more light on the issue.

toBe is very simple and just uses the identity/strict equality operator, ===:

  function(actual, expected) {
    return {
      pass: actual === expected
    };
  }

toEqual, on the other hand, is nearly 150 lines long and has special handling for built in objects like String, Number, Boolean, Date, Error, Element and RegExp. For other objects it recursively compares properties.

This is very different from the behavior of the equality operator, ==. For example:

var simpleObject = {foo: 'bar'};
expect(simpleObject).toEqual({foo: 'bar'}); //true
simpleObject == {foo: 'bar'}; //false

var castableObject = {toString: function(){return 'bar'}};
expect(castableObject).toEqual('bar'); //false
castableObject == 'bar'; //true

Required attribute HTML5

Note that

<input type="text" id="car" required="true" />

is wrong, it should be one of

<input type="text" id="car" required />
<input type="text" id="car" required="" />
<input type="text" id="car" required='' />
<input type="text" id="car" required=required />
<input type="text" id="car" required="required" />
<input type="text" id="car" required='required' />

This is because the true value suggests that the false value will make the form control optional, which is not the case.

Height equal to dynamic width (CSS fluid layout)

It is possible without any Javascript :)

The HTML:

<div class='box'>
    <div class='content'>Aspect ratio of 1:1</div>
</div> 

The CSS:

.box {
    position: relative;
    width:    50%; /* desired width */
}

.box:before {
    content:     "";
    display:     block;
    padding-top: 100%; /* initial ratio of 1:1*/
}

.content {
    position: absolute;
    top:      0;
    left:     0;
    bottom:   0;
    right:    0;
}

/* Other ratios - just apply the desired class to the "box" element */
.ratio2_1:before{
    padding-top: 50%;
}
.ratio1_2:before{
    padding-top: 200%;
}
.ratio4_3:before{
    padding-top: 75%;
}
.ratio16_9:before{
    padding-top: 56.25%;
}

Intel X86 emulator accelerator (HAXM installer) VT/NX not enabled

Version 1.1.1 is the correct version for Yosemite. You need to download this directly from intel's site: https://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager.

The one downloaded by SDK Manager is the older version (1.1.0). If you still want to run with version 1.1.0 - refer to the solution here - http://www.csell.net/2014/09/03/VTNX_Not_Enabled/

Remove trailing comma from comma-separated string

You can do something like this using 'Java 8'

private static void appendNamesWithComma() {
    List<String> namesList = Arrays.asList("test1", "tester2", "testers3", "t4");
    System.out.println(namesList.stream()
                                .collect(Collectors.joining(", ")));

}

Create a file if it doesn't exist

Be warned, each time the file is opened with this method the old data in the file is destroyed regardless of 'w+' or just 'w'.

import os

with open("file.txt", 'w+') as f:
    f.write("file is opened for business")

How to get response using cURL in PHP

The crux of the solution is setting

CURLOPT_RETURNTRANSFER => true

then

$response = curl_exec($ch);

CURLOPT_RETURNTRANSFER tells PHP to store the response in a variable instead of printing it to the page, so $response will contain your response. Here's your most basic working code (I think, didn't test it):

// init curl object        
$ch = curl_init();

// define options
$optArray = array(
    CURLOPT_URL => 'http://www.google.com',
    CURLOPT_RETURNTRANSFER => true
);

// apply those options
curl_setopt_array($ch, $optArray);

// execute request and get response
$result = curl_exec($ch);

What is the 'instanceof' operator used for in Java?

Best explanation is jls. Always try to check what source says. There you will get the best answer plus much more. Reproducing some parts here:

The type of the RelationalExpression operand of the instanceof operator must be a reference type or the null type; otherwise, a compile-time error occurs.

It is a compile-time error if the ReferenceType mentioned after the instanceof operator does not denote a reference type that is reifiable (§4.7).

If a cast (§15.16) of the RelationalExpression to the ReferenceType would be rejected as a compile-time error, then the instanceof relational expression likewise produces a compile-time error. In such a situation, the result of the instanceof expression could never be true.

How do I break a string across more than one line of code in JavaScript?

Break up the string into two pieces 

alert ("Please select file " +
       "to delete");

What is the best way to test for an empty string with jquery-out-of-the-box?

if((a.trim()=="")||(a=="")||(a==null))
{
    //empty condition
}
else
{
    //working condition
}

sklearn error ValueError: Input contains NaN, infinity or a value too large for dtype('float64')

try

mat.sum()

If the sum of your data is infinity (greater that the max float value which is 3.402823e+38) you will get that error.

see the _assert_all_finite function in validation.py from the scikit source code:

if is_float and np.isfinite(X.sum()):
    pass
elif is_float:
    msg_err = "Input contains {} or a value too large for {!r}."
    if (allow_nan and np.isinf(X).any() or
            not allow_nan and not np.isfinite(X).all()):
        type_err = 'infinity' if allow_nan else 'NaN, infinity'
        # print(X.sum())
        raise ValueError(msg_err.format(type_err, X.dtype))

Create table (structure) from existing table

FOR MYSQL:

You can use:

CREATE TABLE foo LIKE bar;

Documentation here.

How can I access Oracle from Python?

Ensure these two and it should work:-

  1. Python, Oracle instantclient and cx_Oracle are 32 bit.
  2. Set the environment variables.

Fixes this issue on windows like a charm.

issue ORA-00001: unique constraint violated coming in INSERT/UPDATE

The error message will include the name of the constraint that was violated (there may be more than one unique constraint on a table). You can use that constraint name to identify the column(s) that the unique constraint is declared on

SELECT column_name, position
  FROM all_cons_columns
 WHERE constraint_name = <<name of constraint from the error message>>
   AND owner           = <<owner of the table>>
   AND table_name      = <<name of the table>>

Once you know what column(s) are affected, you can compare the data you're trying to INSERT or UPDATE against the data already in the table to determine why the constraint is being violated.

How do I find out my python path using python?

Can't seem to edit the other answer. Has a minor error in that it is Windows-only. The more generic solution is to use os.sep as below:

sys.path might include items that aren't specifically in your PYTHONPATH environment variable. To query the variable directly, use:

import os
os.environ['PYTHONPATH'].split(os.pathsep)

cmake error 'the source does not appear to contain CMakeLists.txt'

Since you add .. after cmake, it will jump up and up (just like cd ..) in the directory. But if you want to run cmake under the same folder with CMakeLists.txt, please use . instead of ...

How to use in jQuery :not and hasClass() to get a specific element without a class

It's much easier to do like this:

if(!$('#foo').hasClass('bar')) { 
  ...
}

The ! in front of the criteria means false, works in most programming languages.

ActiveXObject is not defined and can't find variable: ActiveXObject

ActiveXObject is available only on IE browser. So every other useragent will throw an error

On modern browser you could use instead File API or File writer API (currently implemented only on Chrome)

Rounding SQL DateTime to midnight

SELECT getdate()

Result: 2012-12-14 16:03:33.360

SELECT convert(datetime,convert(bigint, getdate()))

Result 2012-12-15 00:00:00.000

Setting up and using environment variables in IntelliJ Idea

Path Variables dialog has nothing to do with the environment variables.

Environment variables can be specified in your OS or customized in the Run configuration:

env

Simple way to understand Encapsulation and Abstraction

Encapsulation can be thought of as wrapping paper used to bind data and function together as a single unit which protects it from all kinds of external dirt (I mean external functions).

Abstraction involves absence of details and the use of a simple interface to control a complex system.

For example we can light a bulb by the pressing of a button without worrying about the underlying electrical engineering (Abstraction) .

However u cannot light the bulb in any other way. (Encapsulation)

How to iterate (keys, values) in JavaScript?

Try this:

var value;
for (var key in dictionary) {
    value = dictionary[key];
    // your code here...
}

Append to string variable

var str1 = "add";
str1 = str1 + " ";

Hope that helps,

Dan

How to read data from excel file using c#

I don't have a machine available to test this but it should work. First you will probably need to install the either the 2007 Office System Driver: Data Connectivity Components or the Microsoft Access Database Engine 2010 Redistributable. Then try the following code, note you will need to change the name of the Sheet in the Select statement below to match sheetname in your excel file:

using System.Data;
using System.Data.OleDb;

namespace Data_Migration_Process_Creator
{
    class Class1
    {
        private DataTable GetDataTable(string sql, string connectionString)
        {
            DataTable dt = null;

            using (OleDbConnection conn = new OleDbConnection(connectionString))
            {
                conn.Open();
                using (OleDbCommand cmd = new OleDbCommand(sql, conn))
                {
                    using (OleDbDataReader rdr = cmd.ExecuteReader())
                    {
                        dt.Load(rdr);
                        return dt;
                    }
                }
            }
        }

        private void GetExcel()
        {
            string fullPathToExcel = "<Path to Excel file>"; //ie C:\Temp\YourExcel.xls
            string connString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=yes'", fullPathToExcel);
            DataTable dt = GetDataTable("SELECT * from [SheetName$]", connString);

            foreach (DataRow dr in dt.Rows)
            {
                //Do what you need to do with your data here
            }
        }
    }
}

Note: I don't have an environment to test this in (One with Office installed) so I can't say if it will work in your environment or not but I don't see why it shouldn't work.

Get the value of a dropdown in jQuery

Pass the id and hold into a variable and pass the variable where ever you want.

var temp = $('select[name=ID Name]').val();

Objective-C: Extract filename from path string

If you're displaying a user-readable file name, you do not want to use lastPathComponent. Instead, pass the full path to NSFileManager's displayNameAtPath: method. This basically does does the same thing, only it correctly localizes the file name and removes the extension based on the user's preferences.

Response Content type as CSV

I suggest to insert an '/' character in front of 'myfilename.cvs'

Response.AddHeader("Content-Disposition", "attachment;filename=/myfilename.csv");

I hope you get better results.

MySQL: Grant **all** privileges on database

I had this challenge when working on MySQL Ver 8.0.21

I wanted to grant permissions of a database named my_app_db to the root user running on localhost host.

But when I run the command:

use my_app_db;

GRANT ALL PRIVILEGES ON my_app_db.* TO 'root'@'localhost';

I get the error:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'my_app_db.* TO 'root'@'localhost'' at line 1>

Here's how I fixed:

Login to your MySQL console. You can change root to the user you want to login with:

mysql -u root -p

Enter your mysql root password

Next, list out all the users and their host on the MySQL server. Unlike PostgreSQL this is often stored in the mysql database. So we need to select the mysql database first:

use mysql;
SELECT user, host FROM user;

Note: if you don't run the use mysql, you get the no database selected error.

This should give you an output of this sort:

+------------------+-----------+
| user             | host      |
+------------------+-----------+
| mysql.infoschema | localhost |
| mysql.session    | localhost |
| mysql.sys        | localhost |
| root             | localhost |
+------------------+-----------+
4 rows in set (0.00 sec)

Next, based on the information gotten from the list, grant privileges to the user that you want. We will need to first select the database before granting permission to it. For me, I am using the root user that runs on the localhost host:

use my_app_db;
GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost';

Note: The GRANT ALL PRIVILEGES ON database_name.* TO 'root'@'localhost'; command may not work for modern versions of MySQL. Most modern versions of MyQL replace the database_name with * in the grant privileges command after you select the database that you want to use.

You can then exit the MySQL console:

exit

That's it.

I hope this helps

Apache could not be started - ServerRoot must be a valid directory and Unable to find the specified module

I checked the line 35 of xampp/apache/conf/httpd.conf and it was:

ServerRoot "/xampp/apache"

Which doesn't exist. ...

Create the directory, or change the path to the directory that contains your hypertext documents.

How do I URL encode a string

Swift 2.0 Example (iOS 9 Compatiable)

extension String {

  func stringByURLEncoding() -> String? {

    let characters = NSCharacterSet.URLQueryAllowedCharacterSet().mutableCopy() as! NSMutableCharacterSet

    characters.removeCharactersInString("&")

    guard let encodedString = self.stringByAddingPercentEncodingWithAllowedCharacters(characters) else {
      return nil
    }

    return encodedString

  }

}

Convert a byte array to integer in Java and vice versa

A basic implementation would be something like this:

public class Test {
    public static void main(String[] args) {
        int[] input = new int[] { 0x1234, 0x5678, 0x9abc };
        byte[] output = new byte[input.length * 2];

        for (int i = 0, j = 0; i < input.length; i++, j+=2) {
            output[j] = (byte)(input[i] & 0xff);
            output[j+1] = (byte)((input[i] >> 8) & 0xff);
        }

        for (int i = 0; i < output.length; i++)
            System.out.format("%02x\n",output[i]);
    }
}

In order to understand things you can read this WP article: http://en.wikipedia.org/wiki/Endianness

The above source code will output 34 12 78 56 bc 9a. The first 2 bytes (34 12) represent the first integer, etc. The above source code encodes integers in little endian format.

Install Qt on Ubuntu

The ubuntu package name is qt5-default, not qt.

Comparison of C++ unit test frameworks

CPUnit (http://cpunit.sourceforge.net) is a framework that is similar to Google Test, but which relies on less macos (asserts are functions), and where the macros are prefixed to avoid the usual macro pitfall. Tests look like:

#include <cpunit>

namespace MyAssetTest {
    using namespace cpunit;

    CPUNIT_FUNC(MyAssetTest, test_stuff) {
        int some_value = 42;
        assert_equals("Wrong value!", 666, some_value);
    }

    // Fixtures go as follows:
    CPUNIT_SET_UP(MyAssetTest) {
        // Setting up suite here...
        // And the same goes for tear-down.
    }

}

They auto-register, so you need not more than this. Then it is just compile and run. I find using this framework very much like using JUnit, for those who have had to spend some time programming Java. Very nice!

What's the most elegant way to cap a number to a segment?

a less "Math" oriented approach ,but should also work , this way, the < / > test is exposed (maybe more understandable than minimaxing) but it really depends on what you mean by "readable"

function clamp(num, min, max) {
  return num <= min ? min : num >= max ? max : num;
}

Find UNC path of a network drive?

$CurrentFolder = "H:\Documents"
$Query = "Select * from Win32_NetworkConnection where LocalName = '" + $CurrentFolder.Substring( 0, 2 ) + "'"
( Get-WmiObject -Query $Query ).RemoteName

OR

$CurrentFolder = "H:\Documents"
$Tst = $CurrentFolder.Substring( 0, 2 )
( Get-WmiObject -Query "Select * from Win32_NetworkConnection where LocalName = '$Tst'" ).RemoteName

MVC web api: No 'Access-Control-Allow-Origin' header is present on the requested resource

That problem happens when you try to access from a different domain or different port.

If you're using Visual Studio, then go to Tools > NuGet Package Manager > Package Manager Console. There you have to install the NuGet Package Microsoft.AspNet.WebApi.Cors

Install-Package Microsoft.AspNet.WebApi.Cors

Then, in PROJECT > App_Start > WebApiConfig, enable CORS

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        
        //Enable CORS. Note that the domain doesn't have / in the end.
        config.EnableCors(new EnableCorsAttribute("https://tiagoperes.eu",headers:"*",methods:"*"));

        ....

    }
}

Once installed successfully, build the solution and that should suffice

Algorithm to detect overlapping periods

Simple check to see if two time periods overlap:

bool overlap = a.start < b.end && b.start < a.end;

or in your code:

bool overlap = tStartA < tEndB && tStartB < tEndA;

(Use <= instead of < if you change your mind about wanting to say that two periods that just touch each other overlap.)

How do I turn off autocommit for a MySQL client?

Perhaps the best way is to write a script that starts the mysql command line client and then automatically runs whatever sql you want before it hands over the control to you.

linux comes with an application called 'expect'. it interacts with the shell in such a way as to mimic your key strokes. it can be set to start mysql, wait for you to enter your password. run further commands such as SET autocommit = 0; then go into interactive mode so you can run any command you want.

for more on the command SET autocommit = 0; see.. http://dev.mysql.com/doc/refman/5.0/en/innodb-transaction-model.html

I use expect to log in to a command line utility in my case it starts ssh, connects to the remote server, starts the application enters my username and password then turns over control to me. saves me heaps of typing :)

http://linux.die.net/man/1/expect

DC

Expect script provided by Michael Hinds

spawn /usr/local/mysql/bin/mysql 
expect "mysql>" 
send "set autocommit=0;\r" 
expect "mysql>" interact

expect is pretty powerful and can make life a lot easier as in this case.

if you want to make the script run without calling expect use the shebang line

insert this as the first line in your script (hint: use which expect to find the location of your expect executable)

#! /usr/bin/expect

then change the permissions of your script with..

chmod 0744 myscript

then call the script

./myscript

DC

What does the Java assert keyword do, and when should it be used?

Basically, "assert true" will pass and "assert false" will fail. Let's looks at how this will work:

public static void main(String[] args)
{
    String s1 = "Hello";
    assert checkInteger(s1);
}

private static boolean checkInteger(String s)
{
    try {
        Integer.parseInt(s);
        return true;
    }
    catch(Exception e)
    {
        return false;
    }
}

What are the main differences between JWT and OAuth authentication?

JWT is an open standard that defines a compact and self-contained way for securely transmitting information between parties. It is an authentication protocol where we allow encoded claims (tokens) to be transferred between two parties (client and server) and the token is issued upon the identification of a client. With each subsequent request we send the token.

Whereas OAuth2 is an authorization framework, where it has a general procedures and setups defined by the framework. JWT can be used as a mechanism inside OAuth2.

You can read more on this here

OAuth or JWT? Which one to use and why?

Changing permissions via chmod at runtime errors with "Operation not permitted"

You, or most likely your sysadmin, will need to login as root and run the chown command: http://www.computerhope.com/unix/uchown.htm

Through this command you will become the owner of the file.

Or, you can be a member of a group that owns this file and then you can use chmod.

But, talk with your sysadmin.

Extract substring using regexp in plain bash

If your string is

foo="US/Central - 10:26 PM (CST)"

then

echo "${foo}" | cut -d ' ' -f3

will do the job.

Checking whether a string starts with XXXX

Can also be done this way..

regex=re.compile('^hello')

## THIS WAY YOU CAN CHECK FOR MULTIPLE STRINGS
## LIKE
## regex=re.compile('^hello|^john|^world')

if re.match(regex, somestring):
    print("Yes")

Spring configure @ResponseBody JSON format

Yes but what happens if you start using mixins for example, you cant be having ObjectMapper as a singleton because you will be applying the configuration globally. So you will be adding or setting the mixin classes on the same ObjectMapper instance?

What does the 'b' character do in front of a string literal?

From server side, if we send any response, it will be sent in the form of byte type, so it will appear in the client as b'Response from server'

In order get rid of b'....' simply use below code:

Server file:

stri="Response from server"    
c.send(stri.encode())

Client file:

print(s.recv(1024).decode())

then it will print Response from server

What is the C++ function to raise a number to a power?

pow() in the cmath library. More info here. Don't forget to put #include<cmath> at the top of the file.

Last Key in Python Dictionary

sorted(dict.keys())[-1]

Otherwise, the keys is just an unordered list, and the "last one" is meaningless, and even can be different on various python versions.

Maybe you want to look into OrderedDict.

How can I render HTML from another file in a React component?

You can use the dangerouslySetInnerHTML property to inject arbitrary HTML:

_x000D_
_x000D_
// Assume from another require()'ed module:_x000D_
var html = '<h1>Hello, world!</h1>'_x000D_
_x000D_
var MyComponent = React.createClass({_x000D_
  render: function() {_x000D_
    return React.createElement("h1", {dangerouslySetInnerHTML: {__html: html}})_x000D_
  }_x000D_
})_x000D_
_x000D_
ReactDOM.render(React.createElement(MyComponent), document.getElementById('app'))
_x000D_
<script src="https://fb.me/react-0.14.3.min.js"></script>_x000D_
<script src="https://fb.me/react-dom-0.14.3.min.js"></script>_x000D_
<div id="app"></div>
_x000D_
_x000D_
_x000D_

You could even componentize this template behavior (untested):

class TemplateComponent extends React.Component {
  constructor(props) {
    super(props)
    this.html = require(props.template)
  }

  render() {
    return <div dangerouslySetInnerHTML={{__html: this.html}}/>
  }

}

TemplateComponent.propTypes = {
  template: React.PropTypes.string.isRequired
}

// use like
<TemplateComponent template='./template.html'/>

And with this, template.html (in the same directory) looks something like (again, untested):

// ./template.html
module.exports = '<h1>Hello, world!</h1>'

How can I convert a string to an int in Python?

def addition(a, b): return a + b

def subtraction(a, b): return a - b

def multiplication(a, b): return a * b

def division(a, b): return a / b

keepProgramRunning = True

print "Welcome to the Calculator!"

while keepProgramRunning:
 print "Please choose what you'd like to do:"

With ng-bind-html-unsafe removed, how do I inject HTML?

  1. You need to make sure that sanitize.js is loaded. For example, load it from https://ajax.googleapis.com/ajax/libs/angularjs/[LAST_VERSION]/angular-sanitize.min.js
  2. you need to include ngSanitize module on your app eg: var app = angular.module('myApp', ['ngSanitize']);
  3. you just need to bind with ng-bind-html the original html content. No need to do anything else in your controller. The parsing and conversion is automatically done by the ngBindHtml directive. (Read the How does it work section on this: $sce). So, in your case <div ng-bind-html="preview_data.preview.embed.html"></div> would do the work.

Two Divs on the same row and center align both of them

Could this do for you? Check my JSFiddle

And the code:

HTML

<div class="container">
    <div class="div1">Div 1</div>
    <div class="div2">Div 2</div>
</div>

CSS

div.container {
    background-color: #FF0000;
    margin: auto;   
    width: 304px;
}

div.div1 {
    border: 1px solid #000;
    float: left;
    width: 150px;
}

div.div2 {
    border: 1px solid red;
    float: left;
    width: 150px;
}

How do you get an iPhone's device name

For xamarin user, use this

UIKit.UIDevice.CurrentDevice.Name

Select rows which are not present in other table

SELECT * FROM testcases1 t WHERE NOT EXISTS ( SELECT 1
FROM executions1 i WHERE t.tc_id = i.tc_id and t.pro_id=i.pro_id and pro_id=7 and version_id=5 ) and pro_id=7 ;

Here testcases1 table contains all datas and executions1 table contains some data among testcases1 table. I am retrieving only the datas which are not present in exections1 table. ( and even I am giving some conditions inside that you can also give.) specify condition which should not be there in retrieving data should be inside brackets.

Should Jquery code go in header or footer?

Nimbuz provides a very good explanation of the issue involved, but I think the final answer depends on your page: what's more important for the user to have sooner - scripts or images?

There are some pages that don't make sense without the images, but only have minor, non-essential scripting. In that case it makes sense to put scripts at the bottom, so the user can see the images sooner and start making sense of the page. Other pages rely on scripting to work. In that case it's better to have a working page without images than a non-working page with images, so it makes sense to put scripts at the top.

Another thing to consider is that scripts are typically smaller than images. Of course, this is a generalisation and you have to see whether it applies to your page. If it does then that, to me, is an argument for putting them first as a rule of thumb (ie. unless there's a good reason to do otherwise), because they won't delay images as much as images would delay the scripts. Finally, it's just much easier to have script at the top, because you don't have to worry about whether they're loaded yet when you need to use them.

In summary, I tend to put scripts at the top by default and only consider whether it's worthwhile moving them to the bottom after the page is complete. It's an optimisation - and I don't want to do it prematurely.

What does the term "Tuple" Mean in Relational Databases?

A tuple is used to define a slice of data from a cube; it is composed of an ordered collection of one member from one or more dimensions. A tuple is used to identify specific sections of multidimensional data from a cube; a tuple composed of one member from each dimension in a cube completely describes a cell value.

How can I use async/await at the top level?

The actual solution to this problem is to approach it differently.

Probably your goal is some sort of initialization which typically happens at the top level of an application.

The solution is to ensure that there is only ever one single JavaScript statement at the top level of your application. If you have only one statement at the top of your application, then you are free to use async/await at every other point everwhere (subject of course to normal syntax rules)

Put another way, wrap your entire top level in a function so that it is no longer the top level and that solves the question of how to run async/await at the top level of an application - you don't.

This is what the top level of your application should look like:

import {application} from './server'

application();

How to set default font family for entire Android app

Not talk about performance, for custom font you can have a recursive method loop through all the views and set typeface if it's a TextView:

public class Font {
    public static void setAllTextView(ViewGroup parent) {
        for (int i = parent.getChildCount() - 1; i >= 0; i--) {
            final View child = parent.getChildAt(i);
            if (child instanceof ViewGroup) {
                setAllTextView((ViewGroup) child);
            } else if (child instanceof TextView) {
                ((TextView) child).setTypeface(getFont());
            }
        }
    }

    public static Typeface getFont() {
        return Typeface.createFromAsset(YourApplicationContext.getInstance().getAssets(), "fonts/whateverfont.ttf");
    }
}

In all your activity, pass current ViewGroup to it after setContentView and it's done:

ViewGroup group = (ViewGroup) getWindow().getDecorView().findViewById(android.R.id.content);
Font.setAllTextView(group);

For fragment you can do something similar.

Force SSL/https using .htaccess and mod_rewrite

PHP Solution

Borrowing directly from Gordon's very comprehensive answer, I note that your question mentions being page-specific in forcing HTTPS/SSL connections.

function forceHTTPS(){
  $httpsURL = 'https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
  if( count( $_POST )>0 )
    die( 'Page should be accessed with HTTPS, but a POST Submission has been sent here. Adjust the form to point to '.$httpsURL );
  if( !isset( $_SERVER['HTTPS'] ) || $_SERVER['HTTPS']!=='on' ){
    if( !headers_sent() ){
      header( "Status: 301 Moved Permanently" );
      header( "Location: $httpsURL" );
      exit();
    }else{
      die( '<script type="javascript">document.location.href="'.$httpsURL.'";</script>' );
    }
  }
}

Then, as close to the top of these pages which you want to force to connect via PHP, you can require() a centralised file containing this (and any other) custom functions, and then simply run the forceHTTPS() function.

HTACCESS / mod_rewrite Solution

I have not implemented this kind of solution personally (I have tended to use the PHP solution, like the one above, for it's simplicity), but the following may be, at least, a good start.

RewriteEngine on

# Check for POST Submission
RewriteCond %{REQUEST_METHOD} !^POST$

# Forcing HTTPS
RewriteCond %{HTTPS} !=on [OR]
RewriteCond %{SERVER_PORT} 80
# Pages to Apply
RewriteCond %{REQUEST_URI} ^something_secure [OR]
RewriteCond %{REQUEST_URI} ^something_else_secure
RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]

# Forcing HTTP
RewriteCond %{HTTPS} =on [OR]
RewriteCond %{SERVER_PORT} 443
# Pages to Apply
RewriteCond %{REQUEST_URI} ^something_public [OR]
RewriteCond %{REQUEST_URI} ^something_else_public
RewriteRule .* http://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]

Integer division: How do you produce a double?

just use this.

int fxd=1;
double percent= (double)(fxd*40)/100;

Replace non-ASCII characters with a single space

For you the get the most alike representation of your original string I recommend the unidecode module:

from unidecode import unidecode
def remove_non_ascii(text):
    return unidecode(unicode(text, encoding = "utf-8"))

Then you can use it in a string:

remove_non_ascii("Ceñía")
Cenia

Why does npm install say I have unmet dependencies?

I encountered this problem when I was installing react packages and this worked for me: npm install --save <package causing this error>