Programs & Examples On #Reflector

.NET Reflector® is a proprietary software utility for Microsoft .NET combining class browsing, static analysis and decompilation, originally written by Lutz Roeder. Red Gate acquired it in 2011 and have since added live debugging of assemblies without requiring original source!

Something better than .NET Reflector?

The .NET source code is available now.

See this link or this

Or if you look for a decompiler, I was using DisSharper. It was good enough for me.

How can I protect my .NET assemblies from decompilation?

One thing to keep in mind is that you want to do this in a way that makes business sense. To do that, you need to define your goals. So, exactly what are your goals?

Preventing piracy? That goal is not achievable. Even native code can be decompiled or cracked; the multitude of warez available online (even for products like Windows and Photoshop) is proof a determined hacker can always gain access.

If you can't prevent piracy, then how about merely reducing it? This, too, is misguided. It only takes one person cracking your code for it to be available to everyone. You have to be lucky every time. The pirates only have to be lucky once.

I put it to you the goal should be to maximize profits. You appear to believe that stopping piracy is necessary to this endeavor. It is not. Profit is simply revenue minus costs. Stopping piracy increases costs. It takes effort, which means adding cost somewhere in the process, and so reduces that side of the equation. Protecting your product also fails to increase your revenue. I know you look at all those pirates and see all the money you could make if only they would pay your license fees instead, but the reality is this will never happen. There is some hyperbole here, but it generally holds that pirates who are unable to crack your security will either find a similar product they can crack or do without. They will never buy it instead, and therefore they do not represent lost sales.

Additionally, securing your product actually reduces revenue. There are two reasons for this. One is the small percentage of customers who have trouble with your activation or security, and therefore decide not to buy again or ask for their money back. The other is the small percentage of people who actually try a pirated version of software to make sure it works before buying. Limiting the pirated distribution of your product (if you are somehow able to succeed at this) prevents these people from ever trying your product, and so they will never buy it. Moreover, piracy can also help your product spread to a wider audience, thus reaching more people who will be willing to pay for it.

A better strategy is to assume that your product will be pirated, and think about ways to take advantage of the situation. A couple more links on the topic:
How do i prevent my code from being stolen?
Securing a .NET Application

Open Source Alternatives to Reflector?

The main reason I used Reflector (and, I think, the main reason most people used it) was for its decompiler: it can translate a method's IL back into source code.

On that count, Monoflector would be the project to watch. It uses Cecil, which does the reflection, and Cecil.Decompiler, which does the decompilation. But Monoflector layers a UI on top of both libraries, which should give you a very good idea of how to use the API.

Monoflector is also a decent alternative to Reflector outright. It lets you browse the types and decompile the methods, which is 99% of what people used Reflector for. It's very rough around the edges, but I'm thinking that will change quickly.

Is multiplication and division using shift operators in C actually faster?

Whether it is actually faster depends on the hardware and compiler actually used.

Check if SQL Connection is Open or Closed

This code is a little more defensive, before opening a connection, check state. If connection state is Broken then we should try to close it. Broken means that the connection was previously opened and not functioning correctly. The second condition determines that connection state must be closed before attempting to open it again so the code can be called repeatedly.

// Defensive database opening logic.

if (_databaseConnection.State == ConnectionState.Broken) {
    _databaseConnection.Close();
}

if (_databaseConnection.State == ConnectionState.Closed) {
    _databaseConnection.Open();
}

Insert into a MySQL table or update if exists

Try this out:

INSERT INTO table (id, name, age) VALUES (1, 'A', 19) ON DUPLICATE KEY UPDATE id = id + 1;

Hope this helps.

Focus Next Element In Tab Index

refer this pure js npm library for such tab navigation strategies.
keyboard-navigator
this small library handles tab key,arrow key navigation,retaining focus on dom updates,modal focus trap, fallback focus.

Recursive directory listing in DOS

You can use various options with FINDSTR to remove the lines do not want, like so:

DIR /S | FINDSTR "\-" | FINDSTR /VI DIR

Normal output contains entries like these:

28-Aug-14  05:14 PM    <DIR>          .
28-Aug-14  05:14 PM    <DIR>          ..

You could remove these using the various filtering options offered by FINDSTR. You can also use the excellent unxutils, but it converts the output to UNIX by default, so you no longer get CR+LF; FINDSTR offers the best Windows option.

Library not loaded: libmysqlclient.16.dylib error when trying to run 'rails server' on OS X 10.6 with mysql2 gem

In OSX El Capitan update when you do this:

sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib

it throws an error like

ln: /usr/lib/libmysqlclient.18.dylib: Operation not permitted

So to avoid this, what you can do is first locate libmysqlclient.18.dylib using the command

User$ locate libmysqlclient.18.dylib

In my case it returned /usr/local/mysql-5.5.24-osx10.5-x86_64/lib/libmysqlclient.18.dylib

So instead of usr/lib/ we will create symlink to usr/local/lib/ like this :

sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/local/lib/libmysqlclient.18.dylib

More details : https://forums.developer.apple.com/thread/7935

AssertContains on strings in jUnit

assertj variant

import org.assertj.core.api.Assertions;
Assertions.assertThat(actualStr).contains(subStr);

Only on Firefox "Loading failed for the <script> with source"

I just had the same issue on an application that is loading a script with a relative path.

It appeared the script was simply blocked by Adblock Plus.

Try to disable your ad/script blocker (Adblock, uBlock Origin, Privacy Badger…) or relocate the script such that it does not match your ad blocker's rules.

If you don't have such a plugin installed, try to reproduce the issue while running Firefox in safe mode.

  • If you cannot reproduce it in safe mode, it means your issue is linked to one of your plugins or settings.
  • Otherwise, it might be a different issue. Make sure you have the same error message as in the question. Also look at the network tab of the developer tools to check if your script is listed (reload the page first if needed).

Set cURL to use local virtual hosts

Making a request to

C:\wnmp\curl>curl.exe --trace-ascii -H 'project1.loc' -d "uuid=d99a49d846d5ae570
667a00825373a7b5ae8e8e2" http://project1.loc/Users/getSettings.xml

Resulted in the -H log file containing:

== Info: Could not resolve host: 'project1.loc'; Host not found
== Info: Closing connection #0
== Info: About to connect() to project1.loc port 80 (#0)
== Info:   Trying 127.0.0.1... == Info: connected
== Info: Connected to project1.loc (127.0.0.1) port 80 (#0)
=> Send header, 230 bytes (0xe6)
0000: POST /Users/getSettings.xml HTTP/1.1
0026: User-Agent: curl/7.19.5 (i586-pc-mingw32msvc) libcurl/7.19.5 Ope
0066: nSSL/1.0.0a zlib/1.2.3
007e: Host: project1.loc
0092: Accept: */*
009f: Content-Length: 45
00b3: Content-Type: application/x-www-form-urlencoded
00e4: 
=> Send data, 45 bytes (0x2d)
0000: uuid=d99a49d846d5ae570667a00825373a7b5ae8e8e2
<= Recv header, 24 bytes (0x18)
0000: HTTP/1.1 403 Forbidden
<= Recv header, 22 bytes (0x16)
0000: Server: nginx/0.7.66
<= Recv header, 37 bytes (0x25)
0000: Date: Wed, 11 Aug 2010 15:37:06 GMT
<= Recv header, 25 bytes (0x19)
0000: Content-Type: text/html
<= Recv header, 28 bytes (0x1c)
0000: Transfer-Encoding: chunked
<= Recv header, 24 bytes (0x18)
0000: Connection: keep-alive
<= Recv header, 25 bytes (0x19)
0000: X-Powered-By: PHP/5.3.2
<= Recv header, 56 bytes (0x38)
0000: Set-Cookie: SESSION=m9j6caghb223uubiddolec2005; path=/
<= Recv header, 57 bytes (0x39)
0000: P3P: CP="NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM"
<= Recv header, 2 bytes (0x2)
0000: 
<= Recv data, 118 bytes (0x76)
0000: 6b
0004: <html><head><title>HTTP/1.1 403 Forbidden</title></head><body><h
0044: 1>HTTP/1.1 403 Forbidden</h1></body></html>
0071: 0
0074: 
== Info: Connection #0 to host project1.loc left intact
== Info: Closing connection #0

My hosts file looks like:

# Copyright (c) 1993-1999 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
#      102.54.94.97     rhino.acme.com          # source server
#       38.25.63.10     x.acme.com              # x client host

127.0.0.1       localhost
...
...
127.0.0.1   project1.loc

Fatal error: Call to a member function query() on null

put this line in parent construct : $this->load->database();

function  __construct() {
    parent::__construct();
    $this->load->library('lib_name');
    $model=array('model_name');
    $this->load->model($model);
    $this->load->database();
}

this way.. it should work..

How to get the position of a character in Python?

There are two string methods for this, find() and index(). The difference between the two is what happens when the search string isn't found. find() returns -1 and index() raises ValueError.

Using find()

>>> myString = 'Position of a character'
>>> myString.find('s')
2
>>> myString.find('x')
-1

Using index()

>>> myString = 'Position of a character'
>>> myString.index('s')
2
>>> myString.index('x')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found

From the Python manual

string.find(s, sub[, start[, end]])
Return the lowest index in s where the substring sub is found such that sub is wholly contained in s[start:end]. Return -1 on failure. Defaults for start and end and interpretation of negative values is the same as for slices.

And:

string.index(s, sub[, start[, end]])
Like find() but raise ValueError when the substring is not found.

How to replace string in Groovy

You need to escape the backslash \:

println yourString.replace("\\", "/")

How to put individual tags for a scatter plot

Perhaps use plt.annotate:

import numpy as np
import matplotlib.pyplot as plt

N = 10
data = np.random.random((N, 4))
labels = ['point{0}'.format(i) for i in range(N)]

plt.subplots_adjust(bottom = 0.1)
plt.scatter(
    data[:, 0], data[:, 1], marker='o', c=data[:, 2], s=data[:, 3] * 1500,
    cmap=plt.get_cmap('Spectral'))

for label, x, y in zip(labels, data[:, 0], data[:, 1]):
    plt.annotate(
        label,
        xy=(x, y), xytext=(-20, 20),
        textcoords='offset points', ha='right', va='bottom',
        bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
        arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))

plt.show()

enter image description here

Why do people say that Ruby is slow?

People say that Ruby is slow because they compare Ruby programs to programs written in other languages. Maybe the programs you write don't need to be faster. Maybe for the programs you write Ruby isn't the bottleneck that's slowing things down.

Ruby 2.1 compared to Javascript V8

Ruby 2.1 compared to ordinary Lua

Ruby 2.1 compared to Python 3

preg_match in JavaScript?

var thisRegex = new RegExp('\[(\d+)\]\[(\d+)\]');

if(!thisRegex.test(text)){
    alert('fail');
}

I found test to act more preg_match as it provides a Boolean return. However you do have to declare a RegExp var.

TIP: RegExp adds it's own / at the start and finish, so don't pass them.

Keeping session alive with Curl and PHP

Yup, often called a 'cookie jar' Google should provide many examples:

http://devzone.zend.com/16/php-101-part-10-a-session-in-the-cookie-jar/

http://curl.haxx.se/libcurl/php/examples/cookiejar.html <- good example IMHO

Copying that last one here so it does not go away...

Login to on one page and then get another page passing all cookies from the first page along Written by Mitchell

<?php
/*
This script is an example of using curl in php to log into on one page and 
then get another page passing all cookies from the first page along with you.
If this script was a bit more advanced it might trick the server into 
thinking its netscape and even pass a fake referer, yo look like it surfed 
from a local page.
*/

$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/cookieFileName");
curl_setopt($ch, CURLOPT_URL,"http://www.myterminal.com/checkpwd.asp");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "UserID=username&password=passwd");

ob_start();      // prevent any output
curl_exec ($ch); // execute the curl command
ob_end_clean();  // stop preventing output

curl_close ($ch);
unset($ch);

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_COOKIEFILE, "/tmp/cookieFileName");
curl_setopt($ch, CURLOPT_URL,"http://www.myterminal.com/list.asp");

$buf2 = curl_exec ($ch);

curl_close ($ch);

echo "<PRE>".htmlentities($buf2);
?>  

How to convert a byte array to its numeric value (Java)?

If this is an 8-bytes numeric value, you can try:

BigInteger n = new BigInteger(byteArray);

If this is an UTF-8 character buffer, then you can try:

BigInteger n = new BigInteger(new String(byteArray, "UTF-8"));

How can I put the current running linux process in background?

Suspend the process with CTRL+Z then use the command bg to resume it in background. For example:

sleep 60
^Z  #Suspend character shown after hitting CTRL+Z
[1]+  Stopped  sleep 60  #Message showing stopped process info
bg  #Resume current job (last job stopped)

More about job control and bg usage in bash manual page:

JOB CONTROL
Typing the suspend character (typically ^Z, Control-Z) while a process is running causes that process to be stopped and returns control to bash. [...] The user may then manipulate the state of this job, using the bg command to continue it in the background, [...]. A ^Z takes effect immediately, and has the additional side effect of causing pending output and typeahead to be discarded.

bg [jobspec ...]
Resume each suspended job jobspec in the background, as if it had been started with &. If jobspec is not present, the shell's notion of the current job is used.

EDIT

To start a process where you can even kill the terminal and it still carries on running

nohup [command] [-args] > [filename] 2>&1 &

e.g.

nohup /home/edheal/myprog -arg1 -arg2 > /home/edheal/output.txt 2>&1 &

To just ignore the output (not very wise) change the filename to /dev/null

To get the error message set to a different file change the &1 to a filename.

In addition: You can use the jobs command to see an indexed list of those backgrounded processes. And you can kill a backgrounded process by running kill %1 or kill %2 with the number being the index of the process.

How to prevent vim from creating (and leaving) temporary files?

I'd strongly recommend to keep working with swap files (in case Vim crashes).

You can set the directory where the swap files are stored, so they don't clutter your normal directories:

set swapfile
set dir=~/tmp

See also

:help swap-file

How do I style a <select> dropdown with only CSS?

Here is a version that works in all modern browsers. The key is using appearance:none which removes the default formatting. Since all of the formatting is gone, you have to add back in the arrow that visually differentiates the select from the input.

Working example: https://jsfiddle.net/gs2q1c7p/

_x000D_
_x000D_
select:not([multiple]) {_x000D_
    -webkit-appearance: none;_x000D_
    -moz-appearance: none;_x000D_
    background-position: right 50%;_x000D_
    background-repeat: no-repeat;_x000D_
    background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAMCAYAAABSgIzaAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYwIDYxLjEzNDc3NywgMjAxMC8wMi8xMi0xNzozMjowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNSBNYWNpbnRvc2giIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6NDZFNDEwNjlGNzFEMTFFMkJEQ0VDRTM1N0RCMzMyMkIiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6NDZFNDEwNkFGNzFEMTFFMkJEQ0VDRTM1N0RCMzMyMkIiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDo0NkU0MTA2N0Y3MUQxMUUyQkRDRUNFMzU3REIzMzIyQiIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDo0NkU0MTA2OEY3MUQxMUUyQkRDRUNFMzU3REIzMzIyQiIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PuGsgwQAAAA5SURBVHjaYvz//z8DOYCJgUxAf42MQIzTk0D/M+KzkRGPoQSdykiKJrBGpOhgJFYTWNEIiEeAAAMAzNENEOH+do8AAAAASUVORK5CYII=);_x000D_
    padding: .5em;_x000D_
    padding-right: 1.5em_x000D_
}_x000D_
_x000D_
#mySelect {_x000D_
    border-radius: 0_x000D_
}
_x000D_
<select id="mySelect">_x000D_
    <option>Option 1</option>_x000D_
    <option>Option 2</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

"Adaptive Server is unavailable or does not exist" error connecting to SQL Server from PHP

I had the same issue, my problem was that the firewall on the server wasn't open from the current ip address.

Maven package/install without test (skip tests)

You can pass the maven.test.skip flag as a JVM argument, to skip running tests when the package phase (and the previous ones in the default lifecycle) is run:

mvn package -Dmaven.test.skip=true

You can also pass the skipTests flag alone to the mvn executable. If you want to include this information in your POM, you can create a new profile where you can configure the maven-surefire-plugin to skip tests.

How to hide the title bar for an Activity in XML with existing custom theme

Add theme @style/Theme.AppCompat.Light.NoActionBar in your activity on AndroidManifest.xml like this

<activity
        android:name=".activities.MainActivity"
        android:theme="@style/Theme.AppCompat.Light.NoActionBar">
    </activity>

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

The first benefit of enums, as you have already noticed, is syntax simplicity. But the main point of enums is to provide a well-known set of constants which, by default, form a range and help to perform more comprehensive code analysis through type & value safety checks.

Those attributes of enums help both a programmer and a compiler. For example, let's say you see a function that accepts an integer. What that integer could mean? What kind of values can you pass in? You don't really know right away. But if you see a function that accepts enum, you know very well all possible values you can pass in.

For the compiler, enums help to determine a range of values and unless you assign special values to enum members, they are well ranges from 0 and up. This helps to automatically track down errors in the code through type safety checks and more. For example, compiler may warn you that you don't handle all possible enum values in your switch statement (i.e. when you don't have default case and handle only one out of N enum values). It also warns you when you convert an arbitrary integer into enum because enum's range of values is less than integer's and that in turn may trigger errors in the function that doesn't really accept an integer. Also, generating a jump table for the switch becomes easier when values are from 0 and up.

This is not only true for Java, but for other languages with a strict type-checking as well. C, C++, D, C# are good examples.

Use of "this" keyword in C++

For the example case above, it is usually omitted, yes. However, either way is syntactically correct.

Read Excel File in Python

Although I almost always just use pandas for this, my current little tool is being packaged into an executable and including pandas is overkill. So I created a version of poida's solution that resulted in a list of named tuples. His code with this change would look like this:

from xlrd import open_workbook
from collections import namedtuple
from pprint import pprint

wb = open_workbook('sample.xls')

FORMAT = ['Arm_id', 'DSPName', 'PinCode']
OneRow = namedtuple('OneRow', ' '.join(FORMAT))
all_rows = []

for s in wb.sheets():
    headerRow = s.row(0)
    columnIndex = [x for y in FORMAT for x in range(len(headerRow)) if y == headerRow[x].value]

    for row in range(1,s.nrows):
        currentRow = s.row(row)
        currentRowValues = [currentRow[x].value for x in columnIndex]
        all_rows.append(OneRow(*currentRowValues))

pprint(all_rows)

How to accept Date params in a GET request to Spring MVC Controller?

Ok, I solved it. Writing it for anyone who might be tired after a full day of non-stop coding & miss such a silly thing.

@RequestMapping(value="/fetch" , method=RequestMethod.GET)
    public @ResponseBody String fetchResult(@RequestParam("from") @DateTimeFormat(pattern="yyyy-MM-dd") Date fromDate) {
        //Content goes here
    }

Yes, it's simple. Just add the DateTimeFormat annotation.

Is there a way to automatically generate getters and setters in Eclipse?

Yes. Right-click on code and you see a menu pop up; there "Source", "Generate Getters and Setters" and next to it you can see the shortcut, which is Alt+Shift+S and R on my system.

Similarly you can navigate to other submenus in that main menu, by typing the appropriate shortcut you go straight the submenu instead of main context menu, and can then either pick from menu or type another letter to pick from the list.

Mac install and open mysql using terminal

If you have your MySQL server up and running, then you just need a client to connect to it and start practicing. One is the mysql-client, which is a command-line tool, or you can use phpMyAdmin, which is a web-based tool.

Limiting Python input strings to certain characters and lengths

if any( [ i>'z' or i<'a' for i in raw_input]):
    print "Error: Contains illegal characters"
elif len(raw_input)>15:
    print "Very long string"

html select only one checkbox in a group

There are already a few answers to this based on pure JS but none of them are quite as concise as I would like them to be.

Here is my solution based on using name tags (as with radio buttons) and a few lines of javascript.

_x000D_
_x000D_
function onlyOne(checkbox) {_x000D_
    var checkboxes = document.getElementsByName('check')_x000D_
    checkboxes.forEach((item) => {_x000D_
        if (item !== checkbox) item.checked = false_x000D_
    })_x000D_
}
_x000D_
<input type="checkbox" name="check" onclick="onlyOne(this)">_x000D_
<input type="checkbox" name="check" onclick="onlyOne(this)">_x000D_
<input type="checkbox" name="check" onclick="onlyOne(this)">_x000D_
<input type="checkbox" name="check" onclick="onlyOne(this)">
_x000D_
_x000D_
_x000D_

Can I change the color of Font Awesome's icon color?

To change the font awesome icons color for your entire project use this in your css

.fa {
  color : red;
}

urllib2 and json

This is what worked for me:

import json
import requests
url = 'http://xxx.com'
payload = {'param': '1', 'data': '2', 'field': '4'}
headers = {'content-type': 'application/json'}
r = requests.post(url, data = json.dumps(payload), headers = headers)

How to remove all event handlers from an event

If you reaallly have to do this... it'll take reflection and quite some time to do this. Event handlers are managed in an event-to-delegate-map inside a control. You would need to

  • Reflect and obtain this map in the control instance.
  • Iterate for each event, get the delegate
    • each delegate in turn could be a chained series of event handlers. So call obControl.RemoveHandler(event, handler)

In short, a lot of work. It is possible in theory... I never tried something like this.

See if you can have better control/discipline over the subscribe-unsubscribe phase for the control.

if variable contains

The fastest way to check if a string contains another string is using indexOf:

if (code.indexOf('ST1') !== -1) {
    // string code has "ST1" in it
} else {
    // string code does not have "ST1" in it
}

What does cmd /C mean?

CMD.exe

Start a new CMD shell

Syntax
      CMD [charset] [options] [My_Command] 

Options       

**/C     Carries out My_Command and then
terminates**

From the help.

SQL select join: is it possible to prefix all columns as 'prefix.*'?

There is no SQL standard for this.

However With code generation (either on demand as the tables are created or altered or at runtime), you can do this quite easily:

CREATE TABLE [dbo].[stackoverflow_329931_a](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [col2] [nchar](10) NULL,
    [col3] [nchar](10) NULL,
    [col4] [nchar](10) NULL,
 CONSTRAINT [PK_stackoverflow_329931_a] PRIMARY KEY CLUSTERED 
(
    [id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

CREATE TABLE [dbo].[stackoverflow_329931_b](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [col2] [nchar](10) NULL,
    [col3] [nchar](10) NULL,
    [col4] [nchar](10) NULL,
 CONSTRAINT [PK_stackoverflow_329931_b] PRIMARY KEY CLUSTERED 
(
    [id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

DECLARE @table1_name AS varchar(255)
DECLARE @table1_prefix AS varchar(255)
DECLARE @table2_name AS varchar(255)
DECLARE @table2_prefix AS varchar(255)
DECLARE @join_condition AS varchar(255)
SET @table1_name = 'stackoverflow_329931_a'
SET @table1_prefix = 'a_'
SET @table2_name = 'stackoverflow_329931_b'
SET @table2_prefix = 'b_'
SET @join_condition = 'a.[id] = b.[id]'

DECLARE @CRLF AS varchar(2)
SET @CRLF = CHAR(13) + CHAR(10)

DECLARE @a_columnlist AS varchar(MAX)
DECLARE @b_columnlist AS varchar(MAX)
DECLARE @sql AS varchar(MAX)

SELECT @a_columnlist = COALESCE(@a_columnlist + @CRLF + ',', '') + 'a.[' + COLUMN_NAME + '] AS [' + @table1_prefix + COLUMN_NAME + ']'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @table1_name
ORDER BY ORDINAL_POSITION

SELECT @b_columnlist = COALESCE(@b_columnlist + @CRLF + ',', '') + 'b.[' + COLUMN_NAME + '] AS [' + @table2_prefix + COLUMN_NAME + ']'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @table2_name
ORDER BY ORDINAL_POSITION

SET @sql = 'SELECT ' + @a_columnlist + '
,' + @b_columnlist + '
FROM [' + @table1_name + '] AS a
INNER JOIN [' + @table2_name + '] AS b
ON (' + @join_condition + ')'

PRINT @sql
-- EXEC (@sql)

Invalid length for a Base-64 char array

    string stringToDecrypt = CypherText.Replace(" ", "+");
    int len = stringToDecrypt.Length;
    byte[] inputByteArray = Convert.FromBase64String(stringToDecrypt); 

Android Fragment onClick button Method

Another option may be to have your fragment implement View.OnClickListener and override onClick(View v) within your fragment. If you need to have your fragment talk to the activity simply add an interface with desired method(s) and have the activity implement the interface and override its method(s).

public class FragName extends Fragment implements View.OnClickListener { 
    public FragmentCommunicator fComm;
    public ImageButton res1, res2;
    int c;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_test, container, false);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            fComm = (FragmentCommunicator) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement FragmentCommunicator");
        }
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        res1 = (ImageButton) getActivity().findViewById(R.id.responseButton1);
        res1.setOnClickListener(this);
        res2 = (ImageButton) getActivity().findViewById(R.id.responseButton2);
        res2.setOnClickListener(this);
    }
    public void onClick(final View v) { //check for what button is pressed
            switch (v.getId()) {
                case R.id.responseButton1:
                  c *= fComm.fragmentContactActivity(2);
                  break;
                case R.id.responseButton2:
                  c *= fComm.fragmentContactActivity(4);
                  break;
                default:
                  c *= fComm.fragmentContactActivity(100);
                  break;
    }
    public interface FragmentCommunicator{
        public int fragmentContactActivity(int b);
    }



public class MainActivity extends FragmentActivity implements FragName.FragmentCommunicator{
    int a = 10;
    //variable a is update by fragment. ex. use to change textview or whatever else you'd like.

    public int fragmentContactActivity(int b) {
        //update info on activity here
        a += b;
        return a;
    }
}

http://developer.android.com/training/basics/firstapp/starting-activity.html http://developer.android.com/training/basics/fragments/communicating.html

How to exclude records with certain values in sql select

SELECT StoreId
FROM StoreClients
WHERE StoreId NOT IN (
  SELECT StoreId
  FROM StoreClients
  Where ClientId=5
)

SQL Fiddle

How do I write a backslash (\) in a string?

Just escape the "\" by using + "\\Tasks" or use a verbatim string like @"\Tasks"

How to find EOF through fscanf?

while (fscanf(input,"%s",arr) != EOF && count!=7) {
  len=strlen(arr); 
  count++; 
}

XML Serialize generic list of serializable objects

See Introducing XML Serialization:

Items That Can Be Serialized

The following items can be serialized using the XmlSerializer class:

  • Public read/write properties and fields of public classes
  • Classes that implement ICollection or IEnumerable
  • XmlElement objects
  • XmlNode objects
  • DataSet objects

In particular, ISerializable or the [Serializable] attribute does not matter.


Now that you've told us what your problem is ("it doesn't work" is not a problem statement), you can get answers to your actual problem, instead of guesses.

When you serialize a collection of a type, but will actually be serializing a collection of instances of derived types, you need to let the serializer know which types you will actually be serializing. This is also true for collections of object.

You need to use the XmlSerializer(Type,Type[]) constructor to give the list of possible types.

Singleton: How should it be used

One thing with patterns: don't generalize. They have all cases when they're useful, and when they fail.

Singleton can be nasty when you have to test the code. You're generally stuck with one instance of the class, and can choose between opening up a door in constructor or some method to reset the state and so on.

Other problem is that the Singleton in fact is nothing more than a global variable in disguise. When you have too much global shared state over your program, things tend to go back, we all know it.

It may make dependency tracking harder. When everything depends on your Singleton, it's harder to change it, split to two, etc. You're generally stuck with it. This also hampers flexibility. Investigate some Dependency Injection framework to try to alleviate this issue.

How do I show a running clock in Excel?

Found the code that I referred to in my comment above. To test it, do this:

  1. In Sheet1 change the cell height and width of say A1 as shown in the snapshot below.
  2. Format the cell by right clicking on it to show time format
  3. Add two buttons (form controls) on the worksheet and name them as shown in the snapshot
  4. Paste this code in a module
  5. Right click on the Start Timer button on the sheet and click on Assign Macros. Select StartTimer macro.
  6. Right click on the End Timer button on the sheet and click on Assign Macros. Select EndTimer macro.

Now click on Start Timer button and you will see the time getting updated in cell A1. To stop time updates, Click on End Timer button.

Code (TRIED AND TESTED)

Public Declare Function SetTimer Lib "user32" ( _
ByVal HWnd As Long, ByVal nIDEvent As Long, _
ByVal uElapse As Long, ByVal lpTimerFunc As Long) As Long

Public Declare Function KillTimer Lib "user32" ( _
ByVal HWnd As Long, ByVal nIDEvent As Long) As Long

Public TimerID As Long, TimerSeconds As Single, tim As Boolean
Dim Counter As Long

'~~> Start Timer
Sub StartTimer()
    '~~ Set the timer for 1 second
    TimerSeconds = 1
    TimerID = SetTimer(0&, 0&, TimerSeconds * 1000&, AddressOf TimerProc)
End Sub

'~~> End Timer
Sub EndTimer()
    On Error Resume Next
    KillTimer 0&, TimerID
End Sub

Sub TimerProc(ByVal HWnd As Long, ByVal uMsg As Long, _
ByVal nIDEvent As Long, ByVal dwTimer As Long)
    '~~> Update value in Sheet 1
    Sheet1.Range("A1").Value = Time
End Sub

SNAPSHOT

enter image description here

How do I get elapsed time in milliseconds in Ruby?

To get time in milliseconds, it's better to add .round(3), so it will be more accurate in some cases:

puts Time.now.to_f # => 1453402722.577573

(Time.now.to_f.round(3)*1000).to_i  # => 1453402722578

If '<selector>' is an Angular component, then verify that it is part of this module

In your components.module.ts you should import IonicModule like this:

import { IonicModule } from '@ionic/angular';

Then import IonicModule like this:

  imports: [
    CommonModule,
    IonicModule
  ],

so your components.module.ts will be like this:

import { CommonModule } from '@angular/common';
import {PostComponent} from './post/post.component'
import { IonicModule } from '@ionic/angular';

@NgModule({
  declarations: [PostComponent],
  imports: [
    CommonModule,
    IonicModule
  ],
  exports: [PostComponent]
})
export class ComponentsModule { }```

sweet-alert display HTML code in text

Sweet alerts also has an 'html' option, set it to true.

var hh = "<b>test</b>";
swal({
    title: "" + txt + "", 
    html: true,
    text: "Testno  sporocilo za objekt " + hh + "",  
    confirmButtonText: "V redu", 
    allowOutsideClick: "true" 
});

Calling constructors in c++ without new

Ideally, a compiler would optimize the second, but it's not required. The first is the best way. However, it's pretty critical to understand the distinction between stack and heap in C++, sine you must manage your own heap memory.

How to draw circle by canvas in Android?

You can override the onDraw method of your view and draw the circle.

protected void onDraw(Canvas canvas) {
 super.onDraw(canvas);

 canvas.drawCircle(x, y, radius, paint);

}

For a better reference on drawing custom views check out the official Android documentation.

http://developer.android.com/training/custom-views/custom-drawing.html

Flask Value error view function did not return a response

You are not returning a response object from your view my_form_post. The function ends with implicit return None, which Flask does not like.

Make the function my_form_post return an explicit response, for example

return 'OK'

at the end of the function.

What reference do I need to use Microsoft.Office.Interop.Excel in .NET?

Answers didn't help me to solve my problem, I couldn't find (and browse) the assemblies although I installed them using Microsoft's msi installer. For me, the excel assembly is located under C:\Windows\assembly\GAC_MSIL\Microsoft.Office.Interop.Excel\14.0.0.0__71e9bce111e9429c\Microsoft.Office.Interop.Excel.dll

NSURLConnection Using iOS Swift

Swift 3.0

AsynchonousRequest

let urlString = "http://heyhttp.org/me.json"
var request = URLRequest(url: URL(string: urlString)!)
let session = URLSession.shared

session.dataTask(with: request) {data, response, error in
  if error != nil {
    print(error!.localizedDescription)
    return
  }

  do {
    let jsonResult: NSDictionary? = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary
    print("Synchronous\(jsonResult)")
  } catch {
    print(error.localizedDescription)
  }
}.resume()

How to make inline functions in C#

You can use Func which encapsulates a method that has one parameter and returns a value of the type specified by the TResult parameter.

void Method()
{
    Func<string,string> inlineFunction = source => 
    {
        // add your functionality here
        return source ;
     };


    // call the inline function
   inlineFunction("prefix");
}

How to put img inline with text

Images have display: inline by default.
You might want to put the image inside the paragraph.
<p><img /></p>

Axios handling errors

If I understand correctly you want then of the request function to be called only if request is successful, and you want to ignore errors. To do that you can create a new promise resolve it when axios request is successful and never reject it in case of failure.

Updated code would look something like this:

export function request(method, uri, body, headers) {
  let config = {
    method: method.toLowerCase(),
    url: uri,
    baseURL: API_URL,
    headers: { 'Authorization': 'Bearer ' + getToken() },
    validateStatus: function (status) {
      return status >= 200 && status < 400
    }
  }


  return new Promise(function(resolve, reject) {
    axios(config).then(
      function (response) {
        resolve(response.data)
      }
    ).catch(
      function (error) {
        console.log('Show error notification!')
      }
    )
  });

}

How to set an environment variable from a Gradle build?

If you are using an IDE, go to run, edit configurations, gradle, select gradle task and update the environment variables. See the picture below.

enter image description here

Alternatively, if you are executing gradle commands using terminal, just type 'export KEY=VALUE', and your job is done.

Print very long string completely in pandas dataframe

In the newer version of pandas, use:

pd.set_option('display.max_colwidth', None)

JAVA_HOME directory in Linux

I know this is late, but this command searches the /usr/ directory to find java for you

sudo find /usr/ -name *jdk

Results to

/usr/lib/jvm/java-6-openjdk
/usr/lib/jvm/java-1.6.0-openjdk

FYI, if you are on a Mac, currently JAVA_HOME is located at

/System/Library/Frameworks/JavaVM.framework/Home

Editor does not contain a main type

I just had this problem too. The solution is to make sure eclipse created the project as Java project. Just create a new Java project and copy your class into the src folder (and import the eventual dependencies). This should fix the problem.

Open file dialog box in JavaScript

I dont't know why nobody has pointed this out but here's is a way of doing it without any Javascript and it's also compatible with any browser.


EDIT: In Safari, the input gets disabled when hidden with display: none. A better approach would be to use position: fixed; top: -100em.


<label>
  Open file dialog
  <input type="file" style="position: fixed; top: -100em">
</label>

If you prefer you can go the "correct way" by using for in the label pointing to the id of the input like this:

<label for="inputId">file dialog</label>
<input id="inputId" type="file" style="position: fixed; top: -100em">

Use and meaning of "in" in an if statement?

the reserved word "in" is used to look inside an object that can be iterated over.

list_obj = ['a', 'b', 'c']
tuple_obj = ('a', 1, 2.0)
dict_obj = {'a': 1, 'b': 2.0}
obj_to_find = 'c'
if obj_to_find in list_obj:
    print('Object {0} is in {1}'.format(obj_to_find, list_obj))
obj_to_find = 2.0
if obj_to_find in tuple_obj:
    print('Object {0} is in {1}'.format(obj_to_find, tuple_obj))
obj_to_find = 'b'
if obj_to_find in dict_obj:
    print('Object {0} is in {1}'.format(obj_to_find, dict_obj))

Output:

Object c is in ['a', 'b', 'c']
Object 2.0 is in ('a', 1, 2.0)
Object b is in {'a': 1, 'b': 2.0}

However

cannot_iterate_over = 5.5
obj_to_find = 5.5
if obj_to_find in cannot_iterate_over:
    print('Object {0} is in {1}'.format(obj_to_find, cannot_iterate_over))

will throw

Traceback (most recent call last):
File "/home/jgranger/workspace/sandbox/src/csv_file_creator.py", line 43, in <module>
if obj_to_find in cannot_iterate_over:
TypeError: argument of type 'float' is not iterable

In your case, raw_input("> ") returns iterable object or it will throw TypeError

MySQL Error 1093 - Can't specify target table for update in FROM clause

As far as concerns, you want to delete rows in story_category that do not exist in category.

Here is your original query to identify the rows to delete:

SELECT * 
FROM  story_category 
WHERE category_id NOT IN (
    SELECT DISTINCT category.id 
    FROM category INNER JOIN 
       story_category ON category_id=category.id
);

Combining NOT IN with a subquery that JOINs the original table seems unecessarily convoluted. This can be expressed in a more straight-forward manner with not exists and a correlated subquery:

select sc.*
from story_category sc
where not exists (select 1 from category c where c.id = sc.category_id);

Now it is easy to turn this to a delete statement:

delete from story_category
where not exists (select 1 from category c where c.id = story_category.category_id);    

This quer would run on any MySQL version, as well as in most other databases that I know.

Demo on DB Fiddle:

-- set-up
create table story_category(category_id int);
create table category (id int);
insert into story_category values (1), (2), (3), (4), (5);
insert into category values (4), (5), (6), (7);

-- your original query to identify offending rows
SELECT * 
FROM  story_category 
WHERE category_id NOT IN (
    SELECT DISTINCT category.id 
    FROM category INNER JOIN 
       story_category ON category_id=category.id);
| category_id |
| ----------: |
|           1 |
|           2 |
|           3 |
-- a functionally-equivalent, simpler query for this
select sc.*
from story_category sc
where not exists (select 1 from category c where c.id = sc.category_id)
| category_id |
| ----------: |
|           1 |
|           2 |
|           3 |
-- the delete query
delete from story_category
where not exists (select 1 from category c where c.id = story_category.category_id);

-- outcome
select * from story_category;
| category_id |
| ----------: |
|           4 |
|           5 |

Can scrapy be used to scrape dynamic content from websites that are using AJAX?

yes, Scrapy can scrap dynamic websites, website that are rendered through javaScript.

There are Two approaches to scrapy these kind of websites.

First,

you can use splash to render Javascript code and then parse the rendered HTML. you can find the doc and project here Scrapy splash, git

Second,

As everyone is stating, by monitoring the network calls, yes, you can find the api call that fetch the data and mock that call in your scrapy spider might help you to get desired data.

Getting Cannot bind argument to parameter 'Path' because it is null error in powershell

  1. PM>Uninstall-Package EntityFramework -Force
  2. PM>Iinstall-Package EntityFramework -Pre -Version 6.0.0

I solve this problem with this code in NugetPackageConsole.and it works.The problem was in the version. i thikn it will help others.

Spring 3.0: Unable to locate Spring NamespaceHandler for XML schema namespace

If using mvn, check that you have the correct scope (if you have that defined) in your pom.xml. I once had it incorrectly set to test but needed it for runtime.

How do you run a command as an administrator from the Windows command line?

Simple pipe trick, ||, with some .vbs used at top of your batch. It will exit regular and restart as administrator.

@AT>NUL||echo set shell=CreateObject("Shell.Application"):shell.ShellExecute "%~dpnx0",,"%CD%", "runas", 1:set shell=nothing>%~n0.vbs&start %~n0.vbs /realtime& timeout 1 /NOBREAK>nul& del /Q %~n0.vbs&cls&exit

It also del /Q the temp.vbs when it's done using it.

Event listener for when element becomes visible?

If you just want to run some code when an element becomes visible in the viewport:

function onVisible(element, callback) {
  new IntersectionObserver((entries, observer) => {
    entries.forEach(entry => {
      if(entry.intersectionRatio > 0) {
        callback(element);
        observer.disconnect();
      }
    });
  }).observe(element);
}

When the element has become visible the intersection observer calls callback and then destroys itself with .disconnect().

Use it like this:

onVisible(document.querySelector("#myElement"), () => console.log("it's visible"));

Find duplicate records in a table using SQL Server

SQL> SELECT JOB,COUNT(JOB) FROM EMP GROUP BY JOB;

JOB       COUNT(JOB)
--------- ----------
ANALYST            2
CLERK              4
MANAGER            3
PRESIDENT          1
SALESMAN           4

How do I trim whitespace?

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

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

Read large files in Java

To save memory, do not unnecessarily store/duplicate the data in memory (i.e. do not assign them to variables outside the loop). Just process the output immediately as soon as the input comes in.

It really doesn't matter whether you're using BufferedReader or not. It will not cost significantly much more memory as some implicitly seem to suggest. It will at highest only hit a few % from performance. The same applies on using NIO. It will only improve scalability, not memory use. It will only become interesting when you've hundreds of threads running on the same file.

Just loop through the file, write every line immediately to other file as you read in, count the lines and if it reaches 100, then switch to next file, etcetera.

Kickoff example:

String encoding = "UTF-8";
int maxlines = 100;
BufferedReader reader = null;
BufferedWriter writer = null;

try {
    reader = new BufferedReader(new InputStreamReader(new FileInputStream("/bigfile.txt"), encoding));
    int count = 0;
    for (String line; (line = reader.readLine()) != null;) {
        if (count++ % maxlines == 0) {
            close(writer);
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("/smallfile" + (count / maxlines) + ".txt"), encoding));
        }
        writer.write(line);
        writer.newLine();
    }
} finally {
    close(writer);
    close(reader);
}

HTML: How to limit file upload to be only images?

Here is the HTML for image upload. By default it will show image files only in the browsing window because we have put accept="image/*". But we can still change it from the dropdown and it will show all files. So the Javascript part validates whether or not the selected file is an actual image.

 <div class="col-sm-8 img-upload-section">
     <input name="image3" type="file" accept="image/*" id="menu_images"/>
     <img id="menu_image" class="preview_img" />
     <input type="submit" value="Submit" />
 </div> 

Here on the change event we first check the size of the image. And in the second if condition we check whether or not it is an image file.

this.files[0].type.indexOf("image") will be -1 if it is not an image file.

document.getElementById("menu_images").onchange = function () {
    var reader = new FileReader();
    if(this.files[0].size>528385){
        alert("Image Size should not be greater than 500Kb");
        $("#menu_image").attr("src","blank");
        $("#menu_image").hide();  
        $('#menu_images').wrap('<form>').closest('form').get(0).reset();
        $('#menu_images').unwrap();     
        return false;
    }
    if(this.files[0].type.indexOf("image")==-1){
        alert("Invalid Type");
        $("#menu_image").attr("src","blank");
        $("#menu_image").hide();  
        $('#menu_images').wrap('<form>').closest('form').get(0).reset();
        $('#menu_images').unwrap();         
        return false;
    }   
    reader.onload = function (e) {
        // get loaded data and render thumbnail.
        document.getElementById("menu_image").src = e.target.result;
        $("#menu_image").show(); 
    };

    // read the image file as a data URL.
    reader.readAsDataURL(this.files[0]);
};

Change NULL values in Datetime format to empty string

CASE and CAST should work:

CASE WHEN mycol IS NULL THEN '' ELSE CONVERT(varchar(50), mycol, 121) END

Apply CSS to jQuery Dialog Buttons

If still noting is working for you add the following styles on your page style sheet

.ui-widget-content .ui-state-default {
  border: 0px solid #d3d3d3;
  background: #00ACD6 50% 50% repeat-x;
  font-weight: normal;
  color: #fff;
}

It will change the background color of the dialog buttons.

Subtracting two lists in Python

Here's a relatively long but efficient and readable solution. It's O(n).

def list_diff(list1, list2):
    counts = {}
    for x in list1:
        try:
            counts[x] += 1
        except:
            counts[x] = 1
    for x in list2:
        try:
            counts[x] -= 1
            if counts[x] < 0:
                raise ValueError('All elements of list2 not in list2')
        except:
            raise ValueError('All elements of list2 not in list1') 
    result = []
    for k, v in counts.iteritems():
        result += v*[k] 
    return result

a = [0, 1, 1, 2, 0]
b = [0, 1, 1]
%timeit list_diff(a, b)
%timeit list_diff(1000*a, 1000*b)
%timeit list_diff(1000000*a, 1000000*b)
100000 loops, best of 3: 4.8 µs per loop
1000 loops, best of 3: 1.18 ms per loop
1 loops, best of 3: 1.21 s per loop

Matplotlib discrete colorbar

To set a values above or below the range of the colormap, you'll want to use the set_over and set_under methods of the colormap. If you want to flag a particular value, mask it (i.e. create a masked array), and use the set_bad method. (Have a look at the documentation for the base colormap class: http://matplotlib.org/api/colors_api.html#matplotlib.colors.Colormap )

It sounds like you want something like this:

import matplotlib.pyplot as plt
import numpy as np

# Generate some data
x, y, z = np.random.random((3, 30))
z = z * 20 + 0.1

# Set some values in z to 0...
z[:5] = 0

cmap = plt.get_cmap('jet', 20)
cmap.set_under('gray')

fig, ax = plt.subplots()
cax = ax.scatter(x, y, c=z, s=100, cmap=cmap, vmin=0.1, vmax=z.max())
fig.colorbar(cax, extend='min')

plt.show()

enter image description here

Split data frame string column into multiple columns

Another approach if you want to stick with strsplit() is to use the unlist() command. Here's a solution along those lines.

tmp <- matrix(unlist(strsplit(as.character(before$type), '_and_')), ncol=2,
   byrow=TRUE)
after <- cbind(before$attr, as.data.frame(tmp))
names(after) <- c("attr", "type_1", "type_2")

git is not installed or not in the PATH

Installing git and running npm install from git-bash worked for me. Make sure you are in the correct directory.

HTML - Arabic Support

The W3C has a good introduction.

In short:

HTML is a text markup language. Text means any characters, not just ones in ASCII.

  1. Save your text using a character encoding that includes the characters you want (UTF-8 is a good bet). This will probably require configuring your editor in a way that is specific to the particular editor you are using. (Obviously it also requires that you have a way to input the characters you want)
  2. Make sure your server sends the correct character encoding in the headers (how you do this depends on the server software you us)
  3. If the document you serve over HTTP specifies its encoding internally, then make sure that is correct too
  4. If anything happens to the document between you saving it and it being served up (e.g. being put in a database, being munged by a server side script, etc) then make sure that the encoding isn't mucked about with on the way.

You can also represent any unicode character with ASCII

Pip freeze vs. pip list

pip list

List installed packages: show ALL installed packages that even pip installed implictly

pip freeze

List installed packages: - list of packages that are installed using pip command

pip freeze has --all flag to show all the packages.

Other difference is the output it renders, that you can check by running the commands.

Back button and refreshing previous activity

I think onRestart() works better for this.

@Override
public void onRestart() { 
    super.onRestart();
    //When BACK BUTTON is pressed, the activity on the stack is restarted
    //Do what you want on the refresh procedure here
}

You could code what you want to do when the Activity is restarted (called again from the event 'back button pressed') inside onRestart().

For example, if you want to do the same thing you do in onCreate(), paste the code in onRestart() (eg. reconstructing the UI with the updated values).

List Git commits not pushed to the origin yet

git log origin/master..master

or, more generally:

git log <since>..<until>

You can use this with grep to check for a specific, known commit:

git log <since>..<until> | grep <commit-hash>

Or you can also use git-rev-list to search for a specific commit:

git rev-list origin/master | grep <commit-hash>

Can you Run Xcode in Linux?

The easiest option to do that is running a VM with a OSX copy.

Change image size via parent div

I am doing this way:

<div class="card-logo">
    <img height="100%" width="100%" src="http://someimage.jpg">
</div>

and CSS:

.card-logo {
    width: 20%;
}

I prefer this way, as if I need to upscale - I can use 150% as well

jQuery: checking if the value of a field is null (empty)

Try

_x000D_
_x000D_
if( this["person_data[document_type]"].value != '') { _x000D_
  console.log('not empty');_x000D_
}
_x000D_
<input id="person_data[document_type]" value="test" />
_x000D_
_x000D_
_x000D_

How to enable local network users to access my WAMP sites?

go to... 
C:\wamp\alias

Inside alias folder you will see some files like phpmyadmin,phpsysinfo,etc...

open each file, and you can see inside file some commented instruction are give to access from outside ,like to give access to phpmyadmin from outside replace the lines

Require local

by

Require all granted

How can I remove all my changes in my SVN working directory?

I used a combination of other peoples' answers to come up with this solution:

Revert normal local SVN changes

svn revert -R .

Remove any other change and supports removing files/folders with spaces, etc.

svn status --no-ignore | grep -E '(^\?)|(^\I)' | sed -e 's/^. *//' | sed -e 's/\(.*\)/"\1"/' | xargs rm -rf

Don't forget to get the latest files from SVN

svn update --force

How to make --no-ri --no-rdoc the default for gem install?

For Windows users, Ruby doesn't set up .gemrc file. So you have to create .gemrc file in your home directory (echo %USERPROFILE%) and put following line in it:

gem: --no-document

As already mentioned in previous answers, don't use --no-ri and --no-rdoc cause its deprecated. See it yourself:

gem help install

Cannot connect to SQL Server named instance from another SQL Server

I need to do 2 things to connect with instance name

1. Enable SQL Server Browser (in SQL server config manager)
2. Enable UDP, port 1434 trong file wall (if you using amazon EC2 or other service you need open port in their setting too)

Restart sql and done

Dynamically select data frame columns using $ and a character value

too late.. but I guess I have the answer -

Here's my sample study.df dataframe -

   >study.df
   study   sample       collection_dt other_column
   1 DS-111 ES768098 2019-01-21:04:00:30         <NA>
   2 DS-111 ES768099 2018-12-20:08:00:30   some_value
   3 DS-111 ES768100                <NA>   some_value

And then -

> ## Selecting Columns in an Given order
> ## Create ColNames vector as per your Preference
> 
> selectCols <- c('study','collection_dt','sample')
> 
> ## Select data from Study.df with help of selection vector
> selectCols %>% select(.data=study.df,.)
   study       collection_dt   sample
1 DS-111 2019-01-21:04:00:30 ES768098
2 DS-111 2018-12-20:08:00:30 ES768099
3 DS-111                <NA> ES768100
> 

MySQL default datetime through phpmyadmin

You can't set CURRENT_TIMESTAMP as default value with DATETIME.

But you can do it with TIMESTAMP.

See the difference here.

Words from this blog

The DEFAULT value clause in a data type specification indicates a default value for a column. With one exception, the default value must be a constant; it cannot be a function or an expression.

This means, for example, that you cannot set the default for a date column to be the value of a function such as NOW() or CURRENT_DATE.

The exception is that you can specify CURRENT_TIMESTAMP as the default for a TIMESTAMP column.

Build a basic Python iterator

If you looking for something short and simple, maybe it will be enough for you:

class A(object):
    def __init__(self, l):
        self.data = l

    def __iter__(self):
        return iter(self.data)

example of usage:

In [3]: a = A([2,3,4])

In [4]: [i for i in a]
Out[4]: [2, 3, 4]

Redirecting a request using servlets and the "setHeader" method not working

As you can see, the response is still HTTP/1.1 200 OK. To indicate a redirect, you need to send back a 302 status code:

response.setStatus(HttpServletResponse.SC_FOUND); // SC_FOUND = 302

"Parser Error Message: Could not load type" in Global.asax

Try modifying your global.asax file (simple add a space somewhere) and re-run. this will force the built in webserver to refresh and recompile the global.asax file.

Also do a clean and rebuild - should fix the problem

Linq to Sql: Multiple left outer joins

I think you should be able to follow the method used in this post. It looks really ugly, but I would think you could do it twice and get the result you want.

I wonder if this is actually a case where you'd be better off using DataContext.ExecuteCommand(...) instead of converting to linq.

Mapping many-to-many association table with extra column(s)

As said before, with JPA, in order to have the chance to have extra columns, you need to use two OneToMany associations, instead of a single ManyToMany relationship. You can also add a column with autogenerated values; this way, it can work as the primary key of the table, if useful.

For instance, the implementation code of the extra class should look like that:

@Entity
@Table(name = "USER_SERVICES")
public class UserService{

    // example of auto-generated ID
    @Id
    @Column(name = "USER_SERVICES_ID", nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long userServiceID;



    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "USER_ID")
    private User user;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "SERVICE_ID")
    private Service service;



    // example of extra column
    @Column(name="VISIBILITY")    
    private boolean visibility;



    public long getUserServiceID() {
        return userServiceID;
    }


    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public Service getService() {
        return service;
    }

    public void setService(Service service) {
        this.service = service;
    }

    public boolean getVisibility() {
        return visibility;
    }

    public void setVisibility(boolean visibility) {
        this.visibility = visibility;
    }

}

How to generate range of numbers from 0 to n in ES2015 only?

For numbers 0 to 5

[...Array(5).keys()];
=> [0, 1, 2, 3, 4]

Store a cmdlet's result value in a variable in Powershell

Just access the Priority property of the object returned from the pipeline:

$var = (Get-WSManInstance -enumerate wmicimv2/win32_process).Priority

(This won't work if Get-WSManInstance returns multiple objects.2)

For the second question: to get two properties there are several options, problably the simplest is to have have one variable* containing an object with two separate properties:

$var = (Get-WSManInstance -enumerate wmicimv2/win32_process | select -first 1 Priority, ProcessID)

and then use, assuming only one process:

$var.Priority

and

$var.ProcessID

If there are multiple processes $var will be an array which you can index, so to get the properties of the first process (using the array literal syntax @(...) so it is always a collection1):

$var = @(Get-WSManInstance -enumerate wmicimv2/win32_process | select -first 1 Priority, ProcessID)

and then use:

$var[0].Priority
$var[0].ProcessID

1 PowerShell helpfully for the command line, but not so helpfully in scripts has some extra logic when assigning the result of a pipeline to a variable: if no objects are returned then set $null, if one is returned then that object is assigned, otherwise an array is assigned. Forcing an array returns an array with zero, one or more (respectively) elements.

2 This changes in PowerShell V3 (at the time of writing in Release Candidate), using a member property on an array of objects will return an array of the value of those properties.

Array to String PHP?

You can use the PHP string function implode()

Like,

<?php
  $sports=$_POST['sports'];;
  $festival=$_POST['festival'];
  $food=$_POST['food'];
  $array=[$sports,$festival,$food];
  $string=implode('|',$array);
  echo $string;
?>

If, for example, $sports='football'; $festival='janmastami'; $food='biriyani';

Then output would be:

football|janmastami|biriyani

For more details on PHP implode() function refer to w3schools

How to make the main content div fill height of screen with css

Not sure exactly what your after, but I think I get it.

A header - stays at the top of the screen? A footer - stays at the bottom of the screen? Content area -> fits the space between the footer and the header?

You can do this by absolute positioning or with fixed positioning.

Here is an example with absolute positioning: http://jsfiddle.net/FMYXY/1/

Markup:

<div class="header">Header</div>
<div class="mainbody">Main Body</div>
<div class="footer">Footer</div>

CSS:

.header {outline:1px solid red; height: 40px; position:absolute; top:0px; width:100%;}
.mainbody {outline:1px solid green; min-height:200px; position:absolute; top:40px; width:100%; height:90%;}
.footer {outline:1px solid blue; height:20px; position:absolute; height:25px;bottom:0; width:100%; } 

To make it work best, I'd suggest using % instead of pixels, as you will run into problems with different screen/device sizes.

HTML-Tooltip position relative to mouse pointer

For default tooltip behavior simply add the title attribute. This can't contain images though.

<div title="regular tooltip">Hover me</div>

Before you clarified the question I did this up in pure JavaScript, hope you find it useful. The image will pop up and follow the mouse.

jsFiddle

JavaScript

var tooltipSpan = document.getElementById('tooltip-span');

window.onmousemove = function (e) {
    var x = e.clientX,
        y = e.clientY;
    tooltipSpan.style.top = (y + 20) + 'px';
    tooltipSpan.style.left = (x + 20) + 'px';
};

CSS

.tooltip span {
    display:none;
}
.tooltip:hover span {
    display:block;
    position:fixed;
    overflow:hidden;
}

Extending for multiple elements

One solution for multiple elements is to update all tooltip span's and setting them under the cursor on mouse move.

jsFiddle

var tooltips = document.querySelectorAll('.tooltip span');

window.onmousemove = function (e) {
    var x = (e.clientX + 20) + 'px',
        y = (e.clientY + 20) + 'px';
    for (var i = 0; i < tooltips.length; i++) {
        tooltips[i].style.top = y;
        tooltips[i].style.left = x;
    }
};

How to fix Subversion lock error

Old question, but none of the above solutions worked for me. What did work was to close eclipse, then using Tortoise, right click on the project in Windows Explorer and choose 'TortoiseSVN' -> 'Clean up', then just use the default checkboxed items (Clean up working copy status, include externals), then hit OK.

This cleaned up the folder, then I was able to update and commit files as normal.

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

This very helpful feature is now available starting at version 1.1.2 of AngularJS. It's considered unstable but I have used it (1.1.3) and it works fine.

Basically you can use a function to generate a templateUrl string. The function is passed the route parameters that you can use to build and return the templateUrl string.

var app = angular.module('app',[]);

app.config(
    function($routeProvider) {
        $routeProvider.
            when('/', {templateUrl:'/home'}).
            when('/users/:user_id', 
                {   
                    controller:UserView, 
                    templateUrl: function(params){ return '/users/view/' + params.user_id; }
                }
            ).
            otherwise({redirectTo:'/'});
    }
);

Many thanks to https://github.com/lrlopez for the pull request.

https://github.com/angular/angular.js/pull/1524

What's with the dollar sign ($"string")

String Interpolation

is a concept that languages like Perl have had for quite a while, and now we’ll get this ability in C# as well. In String Interpolation, we simply prefix the string with a $ (much like we use the @ for verbatim strings). Then, we simply surround the expressions we want to interpolate with curly braces (i.e. { and }):

It looks a lot like the String.Format() placeholders, but instead of an index, it is the expression itself inside the curly braces. In fact, it shouldn’t be a surprise that it looks like String.Format() because that’s really all it is – syntactical sugar that the compiler treats like String.Format() behind the scenes.

A great part is, the compiler now maintains the placeholders for you so you don’t have to worry about indexing the right argument because you simply place it right there in the string.

C# string interpolation is a method of concatenating,formatting and manipulating strings. This feature was introduced in C# 6.0. Using string interpolation, we can use objects and expressions as a part of the string interpolation operation.

Syntax of string interpolation starts with a ‘$’ symbol and expressions are defined within a bracket {} using the following syntax.

{<interpolatedExpression>[,<alignment>][:<formatString>]}  

Where:

  • interpolatedExpression - The expression that produces a result to be formatted
  • alignment - The constant expression whose value defines the minimum number of characters in the string representation of the result of the interpolated expression. If positive, the string representation is right-aligned; if negative, it's left-aligned.
  • formatString - A format string that is supported by the type of the expression result.

The following code example concatenates a string where an object, author as a part of the string interpolation.

string author = "Mohit";  
string hello = $"Hello {author} !";  
Console.WriteLine(hello);  // Hello Mohit !

Read more on C#/.NET Little Wonders: String Interpolation in C# 6

How to get package name from anywhere?

If with the word "anywhere" you mean without having an explicit Context (for example from a background thread) you should define a class in your project like:

public class MyApp extends Application {
    private static MyApp instance;

    public static MyApp getInstance() {
        return instance;
    }

    public static Context getContext(){
        return instance;
        // or return instance.getApplicationContext();
    }

    @Override
    public void onCreate() {
        instance = this;
        super.onCreate();
    }
}

Then in your manifest you need to add this class to the Name field at the Application tab. Or edit the xml and put

<application
    android:name="com.example.app.MyApp"
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    .......
    <activity
        ......

and then from anywhere you can call

String packagename= MyApp.getContext().getPackageName();

Hope it helps.

What's the UIScrollView contentInset property for?

It sets the distance of the inset between the content view and the enclosing scroll view.

Obj-C

aScrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 7.0);

Swift 5.0

aScrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 7.0)

Here's a good iOS Reference Library article on scroll views that has an informative screenshot (fig 1-3) - I'll replicate it via text here:

  _|?_cW_?_|_?_
   |       | 
---------------
   |content| ?
 ? |content| contentInset.top
cH |content|
 ? |content| contentInset.bottom
   |content| ?
---------------
  _|_______|___ 
             ?


   (cH = contentSize.height; cW = contentSize.width)

The scroll view encloses the content view plus whatever padding is provided by the specified content insets.

Is it necessary to write HEAD, BODY and HTML tags?

Contrary to @Liza Daly's note about HTML5, that spec is actually quite specific about which tags can be omitted, and when (and the rules are a bit different from HTML 4.01, mostly to clarify where ambiguous elements like comments and whitespace belong)

The relevant reference is http://www.w3.org/TR/2011/WD-html5-20110525/syntax.html#optional-tags, and it says:

  • An html element's start tag may be omitted if the first thing inside the html element is not a comment.

  • An html element's end tag may be omitted if the html element is not immediately followed by a comment.

  • A head element's start tag may be omitted if the element is empty, or if the first thing inside the head element is an element.

  • A head element's end tag may be omitted if the head element is not immediately followed by a space character or a comment.

  • A body element's start tag may be omitted if the element is empty, or if the first thing inside the body element is not a space character or a comment, except if the first thing inside the body element is a script or style element.

  • A body element's end tag may be omitted if the body element is not immediately followed by a comment.

So your example is valid HTML5, and would be parsed like this, with the html, head and body tags in their implied positions:

<!DOCTYPE html><HTML><HEAD>     
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <title>Page Title</title>
    <link rel="stylesheet" type="text/css" href="css/reset.css">
    <script src="js/head_script.js"></script></HEAD><BODY><!-- this script will be in head //-->


<div>Some html</div> <!-- here body starts //-->

    <script src="js/body_script.js"></script></BODY></HTML>

Note that the comment "this script will be in head" is actually parsed as part of the body, although the script itself is part of the head. According to the spec, if you want that to be different at all, then the </HEAD> and <BODY> tags may not be omitted. (Although the corresponding <HEAD> and </BODY> tags still can be)

Ruby: Merging variables in to a string

["The", animal, action, "the", second_animal].join(" ")

is another way to do it.

Kubernetes how to make Deployment to update image

It seems that k8s expects us to provide a different image tag for every deployment. My default strategy would be to make the CI system generate and push the docker images, tagging them with the build number: xpmatteo/foobar:456.

For local development it can be convenient to use a script or a makefile, like this:

# create a unique tag    
VERSION:=$(shell date +%Y%m%d%H%M%S)
TAG=xpmatteo/foobar:$(VERSION)

deploy:
    npm run-script build
    docker build -t $(TAG) . 
    docker push $(TAG)
    sed s%IMAGE_TAG_PLACEHOLDER%$(TAG)% foobar-deployment.yaml | kubectl apply -f - --record

The sed command replaces a placeholder in the deployment document with the actual generated image tag.

Android Studio not showing modules in project structure

Go to File->Project Structure-> Project Settings -> Modules.

Click on the green colored + and add new module. select Application module and set the content root to your project module.

Click next and then finish.

Reference

C++ undefined reference to defined function

If you are including a library which depends on another library, then the order of inclusion is also important:

g++ -o MyApp MyMain.o -lMyLib1 -lMyLib2

In this case, it is okay if MyLib1 depends on MyLib2. However, if there reverse is true, you will get undefined references.

How to generate UML diagrams (especially sequence diagrams) from Java code?

I developed a maven plugin that can both, be run from CLI as a plugin goal, or import as dependency and programmatically use the parser, @see Main#main() to get the idea on how.

It renders PlantUML src code of desired packages recursively that you can edit manually if needed (hopefully you won't). Then, by pasting the code in the plantUML page, or by downloading plant's jar you can render the UML diagram as a png image.

Check it out here https://github.com/juanmf/Java2PlantUML

Example output diagram: enter image description here

Any contribution is more than welcome. It has a set of filters that customize output but I didn't expose these yet in the plugin CLI params.

It's important to note that it's not limited to your *.java files, it can render UML diagrams src from you maven dependencies as well. This is very handy to understand libraries you depend on. It actually inspects compiled classes with reflection so no source needed

Be the 1st to star it at GitHub :P

Styling multi-line conditions in 'if' statements?

Here's another approach:

cond_list = ['cond1 == "val1"','cond2=="val2"','cond3=="val3"','cond4=="val4"']
if all([eval(i) for i in cond_list]):
 do something

This also makes it easy to add another condition easily without changing the if statement by simply appending another condition to the list:

cond_list.append('cond5=="val5"')

How to convert vector to array

What for? You need to clarify: Do you need a pointer to the first element of an array, or an array?

If you're calling an API function that expects the former, you can do do_something(&v[0], v.size()), where v is a vector of doubles. The elements of a vector are contiguous.

Otherwise, you just have to copy each element:

double arr[100];
std::copy(v.begin(), v.end(), arr);

Ensure not only thar arr is big enough, but that arr gets filled up, or you have uninitialized values.

javascript set cookie with expire time

Use like this (source):

function setCookie(c_name,value,exdays)
{

var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie = c_name+"="+c_value+"; path=/";
}

Can I write or modify data on an RFID tag?

We have recently started looking into RFID solutions at my work place and we found a cheap solution for testing purposes.

One of the units from here:

http://www.sdid.com/products.shtml

Plugs into any windows mobile device with an SD slot and allows reading / writing. There is also a development kit to get you on your way with your own apps.

Hope this helps

Checking if any elements in one list are in another

There is a built in function to compare lists:

Following is the syntax for cmp() method -

cmp(list1, list2)

#!/usr/bin/python

list1, list2 = [123, 'xyz'], [123, 'xyz']

print cmp(list1,list2)

When we run above program, it produces following result -

0

If the result is a tie, meaning that 0 is returned

Do while loop in SQL Server 2008

Only While Loop is officially supported by SQL server. Already there is answer for DO while loop. I am detailing answer on ways to achieve different types of loops in SQL server.

If you know, you need to complete first iteration of loop anyway, then you can try DO..WHILE or REPEAT..UNTIL version of SQL server.

DO..WHILE Loop

DECLARE @X INT=1;

WAY:  --> Here the  DO statement

  PRINT @X;

  SET @X += 1;

IF @X<=10 GOTO WAY;

REPEAT..UNTIL Loop

DECLARE @X INT = 1;

WAY:  -- Here the REPEAT statement

  PRINT @X;

  SET @X += 1;

IFNOT(@X > 10) GOTO WAY;

FOR Loop

DECLARE @cnt INT = 0;

WHILE @cnt < 10
BEGIN
   PRINT 'Inside FOR LOOP';
   SET @cnt = @cnt + 1;
END;

PRINT 'Done FOR LOOP';

Reference

Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 1, current count = 0

If you have a TRY/CATCH block then the likely cause is that you are catching a transaction abort exception and continue. In the CATCH block you must always check the XACT_STATE() and handle appropriate aborted and uncommitable (doomed) transactions. If your caller starts a transaction and the calee hits, say, a deadlock (which aborted the transaction), how is the callee going to communicate to the caller that the transaction was aborted and it should not continue with 'business as usual'? The only feasible way is to re-raise an exception, forcing the caller to handle the situation. If you silently swallow an aborted transaction and the caller continues assuming is still in the original transaction, only mayhem can ensure (and the error you get is the way the engine tries to protect itself).

I recommend you go over Exception handling and nested transactions which shows a pattern that can be used with nested transactions and exceptions:

create procedure [usp_my_procedure_name]
as
begin
    set nocount on;
    declare @trancount int;
    set @trancount = @@trancount;
    begin try
        if @trancount = 0
            begin transaction
        else
            save transaction usp_my_procedure_name;

        -- Do the actual work here

lbexit:
        if @trancount = 0
            commit;
    end try
    begin catch
        declare @error int, @message varchar(4000), @xstate int;
        select @error = ERROR_NUMBER(), @message = ERROR_MESSAGE(), @xstate = XACT_STATE();
        if @xstate = -1
            rollback;
        if @xstate = 1 and @trancount = 0
            rollback
        if @xstate = 1 and @trancount > 0
            rollback transaction usp_my_procedure_name;

        raiserror ('usp_my_procedure_name: %d: %s', 16, 1, @error, @message) ;
    end catch
end
go

How to enter command with password for git pull?

I did not find the answer to my question after searching Google & stackoverflow for a while so I would like to share my solution here.

git config --global credential.helper "/bin/bash /git_creds.sh"
echo '#!/bin/bash' > /git_creds.sh
echo "sleep 1" >> /git_creds.sh
echo "echo username=$SERVICE_USER" >> /git_creds.sh
echo "echo password=$SERVICE_PASS" >> /git_creds.sh

# to test it
git clone https://my-scm-provider.com/project.git

I did it for Windows too. Full answer here

How to convert HTML to PDF using iTextSharp

I use the following code to create PDF

protected void CreatePDF(Stream stream)
        {
            using (var document = new Document(PageSize.A4, 40, 40, 40, 30))
            {
                var writer = PdfWriter.GetInstance(document, stream);
                writer.PageEvent = new ITextEvents();
                document.Open();

                // instantiate custom tag processor and add to `HtmlPipelineContext`.
                var tagProcessorFactory = Tags.GetHtmlTagProcessorFactory();
                tagProcessorFactory.AddProcessor(
                    new TableProcessor(),
                    new string[] { HTML.Tag.TABLE }
                );

                //Register Fonts.
                XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
                fontProvider.Register(HttpContext.Current.Server.MapPath("~/Content/Fonts/GothamRounded-Medium.ttf"), "Gotham Rounded Medium");
                CssAppliers cssAppliers = new CssAppliersImpl(fontProvider);

                var htmlPipelineContext = new HtmlPipelineContext(cssAppliers);
                htmlPipelineContext.SetTagFactory(tagProcessorFactory);

                var pdfWriterPipeline = new PdfWriterPipeline(document, writer);
                var htmlPipeline = new HtmlPipeline(htmlPipelineContext, pdfWriterPipeline);

                // get an ICssResolver and add the custom CSS
                var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true);
                cssResolver.AddCss(CSSSource, "utf-8", true);
                var cssResolverPipeline = new CssResolverPipeline(
                    cssResolver, htmlPipeline
                );

                var worker = new XMLWorker(cssResolverPipeline, true);
                var parser = new XMLParser(worker);
                using (var stringReader = new StringReader(HTMLSource))
                {
                    parser.Parse(stringReader);
                    document.Close();
                    HttpContext.Current.Response.ContentType = "application /pdf";
                    if (base.View)
                        HttpContext.Current.Response.AddHeader("content-disposition", "inline;filename=\"" + OutputFileName + ".pdf\"");
                    else
                        HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=\"" + OutputFileName + ".pdf\"");
                    HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    HttpContext.Current.Response.WriteFile(OutputPath);
                    HttpContext.Current.Response.End();
                }
            }
        }

Google Chrome display JSON AJAX response as tree and not as a plain text

You can use Google Chrome Extension: JSONView All formatted json result will be displayed directly on the browser.

What is the difference between Sprint and Iteration in Scrum and length of each Sprint?

All sprints are iterations but not all iterations are sprints. Iteration is a common term in iterative and incremental development (IID). Scrum is one specialized flavor of IID so it makes sense to specialize the terminology as well. It also helps brand the methodology different from other IID methodologies :)

As to the sprint length: anything goes as long as the sprint is timeboxed i.e. it is finished on the planned date and not "when it's ready". (Or alternatively, in rare occasions, the sprint is terminated prematurely to start a new sprint in case some essential boundary conditions are changed.)

It does help to have the sprints of similar durations. There's less to remember about the sprint schedule and your planning gets more accurate. I like to keep mine at 2 calendar weeks, which will resolve into 8..10 business days outside holiday seasons.

jQuery looping .each() JSON key/value not working

Since you have an object, not a jQuery wrapper, you need to use a different variant of $.each()

$.each(json, function (key, data) {
    console.log(key)
    $.each(data, function (index, data) {
        console.log('index', data)
    })
})

Demo: Fiddle

How to replace a string in a SQL Server Table Column

all answers are great but I just want to give you a good example

select replace('this value from table', 'table',  'table but updated')

this SQL statement will replace the existence of the word "table" (second parameter) inside the given statement(first parameter) with the third parameter

the initial value is this value from table but after executing replace function it will be this value from table but updated

and here is a real example

UPDATE publication
SET doi = replace(doi, '10.7440/perifrasis', '10.25025/perifrasis')
WHERE doi like '10.7440/perifrasis%'

for example if we have this value

10.7440/perifrasis.2010.1.issue-1

it will become

10.25025/perifrasis.2010.1.issue-1

hope this gives you better visualization

What does axis in pandas mean?

The easiest way for me to understand is to talk about whether you are calculating a statistic for each column (axis = 0) or each row (axis = 1). If you calculate a statistic, say a mean, with axis = 0 you will get that statistic for each column. So if each observation is a row and each variable is in a column, you would get the mean of each variable. If you set axis = 1 then you will calculate your statistic for each row. In our example, you would get the mean for each observation across all of your variables (perhaps you want the average of related measures).

axis = 0: by column = column-wise = along the rows

axis = 1: by row = row-wise = along the columns

Debian 8 (Live-CD) what is the standard login and password?

Although this is an old question, I had the same question when using the Standard console version. The answer can be found in the Debian Live manual under the section 10.1 Customizing the live user. It says:

It is also possible to change the default username "user" and the default password "live".

I tried the username user and password live and it did work. If you want to run commands as root you can preface each command with sudo

exit application when click button - iOS

You can use exit method to quit an ios app :

exit(0);

You should say same alert message and ask him to quit

Another way is by using [[NSThread mainThread] exit]

However you should not do this way

According to Apple, your app should not terminate on its own. Since the user did not hit the Home button, any return to the Home screen gives the user the impression that your app crashed. This is confusing, non-standard behavior and should be avoided.

How to get base url with jquery or javascript?

You mentioned that the example.com may change so I suspect that actually you need the base url just to be able to use relative path notation for your scripts. In this particular case there is no need to use scripting - instead add the base tag to your header:

<head>
  <base href="http://www.example.com/">
</head>

I usually generate the link via PHP.

Using LINQ to group by multiple properties and sum

Use the .Select() after grouping:

var agencyContracts = _agencyContractsRepository.AgencyContracts
    .GroupBy(ac => new
                   {
                       ac.AgencyContractID, // required by your view model. should be omited
                                            // in most cases because group by primary key
                                            // makes no sense.
                       ac.AgencyID,
                       ac.VendorID,
                       ac.RegionID
                   })
    .Select(ac => new AgencyContractViewModel
                   {
                       AgencyContractID = ac.Key.AgencyContractID,
                       AgencyId = ac.Key.AgencyID,
                       VendorId = ac.Key.VendorID,
                       RegionId = ac.Key.RegionID,
                       Amount = ac.Sum(acs => acs.Amount),
                       Fee = ac.Sum(acs => acs.Fee)
                   });

Restrict SQL Server Login access to only one database

this is to topup to what was selected as the correct answer. It has one missing step that when not done, the user will still be able to access the rest of the database. First, do as @DineshDB suggested

  1. Connect to your SQL server instance using management studio
   2. Goto Security -> Logins -> (RIGHT CLICK) New Login
   3. fill in user details
   4. Under User Mapping, select the databases you want the user to be able to access and configure

the missing step is below:

5. Under user mapping, ensure that "sysadmin" is NOT CHECKED and select "db_owner" as the role for the new user.

And thats it.

Using (Ana)conda within PyCharm

Continuum Analytics now provides instructions on how to setup Anaconda with various IDEs including Pycharm here. However, with Pycharm 5.0.1 running on Unbuntu 15.10 Project Interpreter settings were found via the File | Settings and then under the Project branch of the treeview on the Settings dialog.

Use of for_each on map elements

Will it work for you ?

class MyClass;
typedef std::pair<int,MyClass> MyPair;
class MyClass
{
  private:
  void foo() const{};
public:
static void Method(MyPair const& p) 
{
    //......
        p.second.foo();
};
}; 
// ...
std::map<int, MyClass> Map;
//.....
std::for_each(Map.begin(), Map.end(), (&MyClass::Method));

How do I create a right click context menu in Java Swing?

I will correct usage for that method that @BullyWillPlaza suggested. Reason is that when I try to add add textArea to only contextMenu it's not visible, and if i add it to both to contextMenu and some panel it ecounters: Different parent double association if i try to switch to Design editor.

TexetObjcet.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            if (SwingUtilities.isRightMouseButton(e)){
                contextmenu.add(TexetObjcet);
                contextmenu.show(TexetObjcet, 0, 0);
            }
        }
    }); 

Make mouse listener like this for text object you need to have popup on. What this will do is when you right click on your text object it will then add that popup and display it. This way you don't encounter that error. Solution that @BullyWillPlaza made is very good, rich and fast to implement in your program so you should try it our see how you like it.

How to remove outliers from a dataset

Outliers are quite similar to peaks, so a peak detector can be useful for identifying outliers. The method described here has quite good performance using z-scores. The animation part way down the page illustrates the method signaling on outliers, or peaks.

Peaks are not always the same as outliers, but they're similar frequently.

An example is shown here: This dataset is read from a sensor via serial communications. Occasional serial communication errors, sensor error or both lead to repeated, clearly erroneous data points. There is no statistical value in these point. They are arguably not outliers, they are errors. The z-score peak detector was able to signal on spurious data points and generated a clean resulting dataset: enter image description here

What's the difference between struct and class in .NET?

Structs are the actual value - they can be empty but never null

This is true, however also note that as of .NET 2 structs support a Nullable version and C# supplies some syntactic sugar to make it easier to use.

int? value = null;
value  = 1;

Set min-width in HTML table's <td>

One way should be to add a <div style="min-width:XXXpx"> within the td, and let the <td style="width:100%">

Convert string to Date in java

String str_date="13-09-2011";
DateFormat formatter ; 
Date date ; 
formatter = new SimpleDateFormat("dd-MM-yyyy");
date = (Date)formatter.parse(str_date); 
System.out.println("Today is " +date.getTime());

Try this

Store multiple values in single key in json

{
  "number" : ["1","2","3"],
  "alphabet" : ["a", "b", "c"]
}

Difference between attr_accessor and attr_accessible

attr_accessor is a Ruby method that gives you setter and getter methods to an instance variable of the same name. So it is equivalent to

class MyModel
  def my_variable
    @my_variable
  end
  def my_variable=(value)
    @my_variable = value
  end
end

attr_accessible is a Rails method that determines what variables can be set in a mass assignment.

When you submit a form, and you have something like MyModel.new params[:my_model] then you want to have a little bit more control, so that people can't submit things that you don't want them to.

You might do attr_accessible :email so that when someone updates their account, they can change their email address. But you wouldn't do attr_accessible :email, :salary because then a person could set their salary through a form submission. In other words, they could hack their way to a raise.

That kind of information needs to be explicitly handled. Just removing it from the form isn't enough. Someone could go in with firebug and add the element into the form to submit a salary field. They could use the built in curl to submit a new salary to the controller update method, they could create a script that submits a post with that information.

So attr_accessor is about creating methods to store variables, and attr_accessible is about the security of mass assignments.

Why do I need to override the equals and hashCode methods in Java?

class A {
    int i;
    // Hashing Algorithm
    if even number return 0 else return 1
    // Equals Algorithm,
    if i = this.i return true else false
}
  • put('key','value') will calculate the hash value using hashCode() to determine the bucket and uses equals() method to find whether the value is already present in the Bucket. If not it will added else it will be replaced with current value
  • get('key') will use hashCode() to find the Entry (bucket) first and equals() to find the value in Entry

if Both are overridden,

Map<A>

Map.Entry 1 --> 1,3,5,...
Map.Entry 2 --> 2,4,6,...

if equals is not overridden

Map<A>

Map.Entry 1 --> 1,3,5,...,1,3,5,... // Duplicate values as equals not overridden
Map.Entry 2 --> 2,4,6,...,2,4,..

If hashCode is not overridden

Map<A>

Map.Entry 1 --> 1
Map.Entry 2 --> 2
Map.Entry 3 --> 3
Map.Entry 4 --> 1
Map.Entry 5 --> 2
Map.Entry 6 --> 3 // Same values are Stored in different hasCodes violates Contract 1
So on...

HashCode Equal Contract

  1. Two keys equal according to equal method should generate same hashCode
  2. Two Keys generating same hashCode need not be equal (In above example all even numbers generate same hash Code)

What is the difference between .py and .pyc files?

Python compiles the .py and saves files as .pyc so it can reference them in subsequent invocations.

There's no harm in deleting them, but they will save compilation time if you're doing lots of processing.

How to slice an array in Bash

See the Parameter Expansion section in the Bash man page. A[@] returns the contents of the array, :1:2 takes a slice of length 2, starting at index 1.

A=( foo bar "a  b c" 42 )
B=("${A[@]:1:2}")
C=("${A[@]:1}")       # slice to the end of the array
echo "${B[@]}"        # bar a  b c
echo "${B[1]}"        # a  b c
echo "${C[@]}"        # bar a  b c 42
echo "${C[@]: -2:2}"  # a  b c 42 # The space before the - is necesssary

Note that the fact that "a b c" is one array element (and that it contains an extra space) is preserved.

"register" keyword in C?

Just a little demo (without any real-world purpose) for comparison: when removing the register keywords before each variable, this piece of code takes 3.41 seconds on my i7 (GCC), with register the same code completes in 0.7 seconds.

#include <stdio.h>

int main(int argc, char** argv) {

     register int numIterations = 20000;    

     register int i=0;
     unsigned long val=0;

    for (i; i<numIterations+1; i++)
    {
        register int j=0;
        for (j;j<i;j++) 
        {
            val=j+i;
        }
    }
    printf("%d", val);
    return 0;
}

MySQL command line client for Windows

When you go to the MySQL download page, choose the platform "Microsoft Windows". Then download the "Windows (x86, xx-bit), ZIP Archive" (be sure to select the one with size over 140M.

The binaries will be in the "bin" folder.

I understand that this is not just the client binaries, but at least you don't have to install and setup the entire server.

Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers

I am new to spring spent an hour trying to figure this out.

go to --- > application.properties

add these :

spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

git still shows files as modified after adding to .gitignore

  1. Git add .

  2. Git status //Check file that being modified

    // git reset HEAD --- replace to which file you want to ignore

  3. git reset HEAD .idea/ <-- Those who wanted to exclude .idea from before commit // git check status and the idea file will be gone, and you're ready to go!

  4. git commit -m ''

  5. git push

Multiple conditions in a C 'for' loop

There is an operator in C called the comma operator. It executes each expression in order and returns the value of the last statement. It's also a sequence point, meaning each expression is guaranteed to execute in completely and in order before the next expression in the series executes, similar to && or ||.

Ant error when trying to build file, can't find tools.jar?

Java ships in 2 versions: JRE & SDK (used to be called JDK)

The JRE in addition to not containing the compiler, also doesn't contain all of the libraries available in the JDK (tools.jar is one of them)

When you download Java at: http://java.sun.com/javase/downloads/index.jsp, make sure to select the JDK version and install it. If you have both a JDK & JRE, make sure that ANT is using the JDK, you can check JAVA_HOME (environment variable), and on the commandline if you do "javac -version" you should get a version description.

load scripts asynchronously

Well, x.parentNode returns the HEAD element, so you are inserting the script just before the head tag. Maybe that's the problem.

Try x.parentNode.appendChild() instead.

How to draw polygons on an HTML5 canvas?

//poly [x,y, x,y, x,y.....];
var poly=[ 5,5, 100,50, 50,100, 10,90 ];
var canvas=document.getElementById("canvas")
var ctx = canvas.getContext('2d');
ctx.fillStyle = '#f00';

ctx.beginPath();
ctx.moveTo(poly[0], poly[1]);
for( item=2 ; item < poly.length-1 ; item+=2 ){ctx.lineTo( poly[item] , poly[item+1] )}

ctx.closePath();
ctx.fill();

How to uninstall a Windows Service when there is no executable for it left on the system?

Remove Windows Service via Registry

Its very easy to remove a service from registry if you know the right path. Here is how I did that:

  1. Run Regedit or Regedt32

  2. Go to the registry entry "HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services"

  3. Look for the service that you want delete and delete it. You can look at the keys to know what files the service was using and delete them as well (if necessary).

Delete Windows Service via Command Window

Alternatively, you can also use command prompt and delete a service using following command:

sc delete

You can also create service by using following command

sc create "MorganTechService" binpath= "C:\Program Files\MorganTechSPace\myservice.exe"

Note: You may have to reboot the system to get the list updated in service manager.

Alternative to google finance api

If you are still looking to use Google Finance for your data you can check this out.

I recently needed to test if SGX data is indeed retrievable via google finance (and of course i met with the same problem as you)

Output to the same line overwriting previous output?

I found that for a simple print statement in python 2.7, just put a comma at the end after your '\r'.

print os.path.getsize(file_name)/1024, 'KB / ', size, 'KB downloaded!\r',

This is shorter than other non-python 3 solutions, but also more difficult to maintain.

How can I disable inherited css styles?

You can use the unset keyword to reset a property.

div.rounded div div div {
    background-image: unset; /* reset background */
    padding: unset; /* reset padding */
}

More info on developer.mozilla.org

Full Page <iframe>

This is what I have used in the past.

html, body {
  height: 100%;
  overflow: auto;
}

Also in the iframe add the following style

border: 0; position:fixed; top:0; left:0; right:0; bottom:0; width:100%; height:100%

Spring Boot, Spring Data JPA with multiple DataSources

There is another way to have multiple dataSources by using @EnableAutoConfiguration and application.properties.

Basically put multiple dataSource configuration info on application.properties and generate default setup (dataSource and entityManagerFactory) automatically for first dataSource by @EnableAutoConfiguration. But for next dataSource, create dataSource, entityManagerFactory and transactionManager all manually by the info from property file.

Below is my example to setup two dataSources. First dataSource is setup by @EnableAutoConfiguration which can be assigned only for one configuration, not multiple. And that will generate 'transactionManager' by DataSourceTransactionManager, that looks default transactionManager generated by the annotation. However I have seen the transaction not beginning issue on the thread from scheduled thread pool only for the default DataSourceTransactionManager and also when there are multiple transaction managers. So I create transactionManager manually by JpaTransactionManager also for the first dataSource with assigning 'transactionManager' bean name and default entityManagerFactory. That JpaTransactionManager for first dataSource surely resolves the weird transaction issue on the thread from ScheduledThreadPool.

Update for Spring Boot 1.3.0.RELEASE

I found my previous configuration with @EnableAutoConfiguration for default dataSource has issue on finding entityManagerFactory with Spring Boot 1.3 version. Maybe default entityManagerFactory is not generated by @EnableAutoConfiguration, once after I introduce my own transactionManager. So now I create entityManagerFactory by myself. So I don't need to use @EntityScan. So it looks I'm getting more and more out of the setup by @EnableAutoConfiguration.

Second dataSource is setup without @EnableAutoConfiguration and create 'anotherTransactionManager' by manual way.

Since there are multiple transactionManager extends from PlatformTransactionManager, we should specify which transactionManager to use on each @Transactional annotation

Default Repository Config

@Configuration
@EnableTransactionManagement
@EnableAutoConfiguration
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactory",
        transactionManagerRef = "transactionManager",
        basePackages = {"com.mysource.repository"})
public class RepositoryConfig {
    @Autowired
    JpaVendorAdapter jpaVendorAdapter;

    @Autowired
    DataSource dataSource;

    @Bean(name = "entityManager")
    public EntityManager entityManager() {
        return entityManagerFactory().createEntityManager();
    }

    @Primary
    @Bean(name = "entityManagerFactory")
    public EntityManagerFactory entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
        emf.setDataSource(dataSource);
        emf.setJpaVendorAdapter(jpaVendorAdapter);
        emf.setPackagesToScan("com.mysource.model");
        emf.setPersistenceUnitName("default");   // <- giving 'default' as name
        emf.afterPropertiesSet();
        return emf.getObject();
    }

    @Bean(name = "transactionManager")
    public PlatformTransactionManager transactionManager() {
        JpaTransactionManager tm = new JpaTransactionManager();
        tm.setEntityManagerFactory(entityManagerFactory());
        return tm;
    }
}

Another Repository Config

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "anotherEntityManagerFactory",
        transactionManagerRef = "anotherTransactionManager",
        basePackages = {"com.mysource.anothersource.repository"})
public class AnotherRepositoryConfig {
    @Autowired
    JpaVendorAdapter jpaVendorAdapter;

    @Value("${another.datasource.url}")
    private String databaseUrl;

    @Value("${another.datasource.username}")
    private String username;

    @Value("${another.datasource.password}")
    private String password;

    @Value("${another.dataource.driverClassName}")
    private String driverClassName;

    @Value("${another.datasource.hibernate.dialect}")
    private String dialect;

    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource(databaseUrl, username, password);
        dataSource.setDriverClassName(driverClassName);
        return dataSource;
    }

    @Bean(name = "anotherEntityManager")
    public EntityManager entityManager() {
        return entityManagerFactory().createEntityManager();
    }

    @Bean(name = "anotherEntityManagerFactory")
    public EntityManagerFactory entityManagerFactory() {
        Properties properties = new Properties();
        properties.setProperty("hibernate.dialect", dialect);

        LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
        emf.setDataSource(dataSource());
        emf.setJpaVendorAdapter(jpaVendorAdapter);
        emf.setPackagesToScan("com.mysource.anothersource.model");   // <- package for entities
        emf.setPersistenceUnitName("anotherPersistenceUnit");
        emf.setJpaProperties(properties);
        emf.afterPropertiesSet();
        return emf.getObject();
    }

    @Bean(name = "anotherTransactionManager")
    public PlatformTransactionManager transactionManager() {
        return new JpaTransactionManager(entityManagerFactory());
    }
}

application.properties

# database configuration
spring.datasource.url=jdbc:h2:file:~/main-source;AUTO_SERVER=TRUE
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.continueOnError=true
spring.datasource.initialize=false

# another database configuration
another.datasource.url=jdbc:sqlserver://localhost:1433;DatabaseName=another;
another.datasource.username=username
another.datasource.password=
another.datasource.hibernate.dialect=org.hibernate.dialect.SQLServer2008Dialect 
another.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver

Choose proper transactionManager for @Transactional annotation

Service for first datasource

@Service("mainService")
@Transactional("transactionManager")
public class DefaultDataSourceServiceImpl implements DefaultDataSourceService       
{

   //

}

Service for another datasource

@Service("anotherService")
@Transactional("anotherTransactionManager")
public class AnotherDataSourceServiceImpl implements AnotherDataSourceService 
{

   //

}

ADB Install Fails With INSTALL_FAILED_TEST_ONLY

None of the previous post solve my issue. Here is what's happening with me:
I normally load the app from android studio by clicking on the "Run" button. When you do this, android would create an app that's good for debug but not for install. If you try to install using:

adb install -r yourapk

you will get a message that says:

Failure [INSTALL_FAILED_TEST_ONLY]

When this happens, you will need to rebuilt the apk by first clean the build, then select Build->Build APK. See the image bellow:

build android apk

This APK is ready to be installed either through adb install command or any other methods

Hope this helps

David

Default property value in React component using TypeScript

From a comment by @pamelus on the accepted answer:

You either have to make all interface properties optional (bad) or specify default value also for all required fields (unnecessary boilerplate) or avoid specifying type on defaultProps.

Actually you can use Typescript's interface inheritance. The resulting code is only a little bit more verbose.

interface OptionalGoogleAdsProps {
    format?: string;
    className?: string;
    style?: any;
    scriptSrc?: string
}

interface GoogleAdsProps extends OptionalGoogleAdsProps {
    client: string;
    slot: string;
}


/**
 * Inspired by https://github.com/wonism/react-google-ads/blob/master/src/google-ads.js
 */
export default class GoogleAds extends React.Component<GoogleAdsProps, void> {
    public static defaultProps: OptionalGoogleAdsProps = {
        format: "auto",
        style: { display: 'block' },
        scriptSrc: "//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"
    };

How to add,set and get Header in request of HttpClient?

You can use HttpPost, there are methods to add Header to the Request.

DefaultHttpClient httpclient = new DefaultHttpClient();
String url = "http://localhost";
HttpPost httpPost = new HttpPost(url);

httpPost.addHeader("header-name" , "header-value");

HttpResponse response = httpclient.execute(httpPost);

jQuery Ajax simple call

You could also make the ajax call more generic, reusable, so you can call it from different CRUD(create, read, update, delete) tasks for example and treat the success cases from those calls.

makePostCall = function (url, data) { // here the data and url are not hardcoded anymore
   var json_data = JSON.stringify(data);

    return $.ajax({
        type: "POST",
        url: url,
        data: json_data,
        dataType: "json",
        contentType: "application/json;charset=utf-8"
    });
}

// and here a call example
makePostCall("index.php?action=READUSERS", {'city' : 'Tokio'})
    .success(function(data){
               // treat the READUSERS data returned
   })
    .fail(function(sender, message, details){
           alert("Sorry, something went wrong!");
  });

Why is the Android emulator so slow? How can we speed up the Android emulator?

Now on ADT 21, it provides more options for a fast emulator... You should use 512 MB RAM, lower CPU Time, Device Selection and VM Heap Size high. For better results, you should use Intel Atom in CPU/ABI... Using Snapshot and CPU Host may not increase your speed of the emulator, but there are useful ones for other purposes.

Nested ng-repeat

If you have a big nested JSON object and using it across several screens, you might face performance issues in page loading. I always go for small individual JSON objects and query the related objects as lazy load only where they are required.

you can achieve it using ng-init

<td class="lectureClass" ng-repeat="s in sessions" ng-init='presenters=getPresenters(s.id)'>
      {{s.name}}
      <div class="presenterClass" ng-repeat="p in presenters">
          {{p.name}}
      </div>
</td> 

The code on the controller side should look like below

$scope.getPresenters = function(id) {
    return SessionPresenters.get({id: id});
};

While the API factory is as follows:

angular.module('tryme3App').factory('SessionPresenters', function ($resource, DateUtils) {

        return $resource('api/session.Presenters/:id', {}, {
            'query': { method: 'GET', isArray: true},
            'get': {
                method: 'GET', isArray: true
            },
            'update': { method:'PUT' }
        });
    });

jQuery-UI datepicker default date

Try passing in a Date object instead. I can't see why it doesn't work in the format you have entered:

<script type="text/javascript">
$(function() {               
    $("#birthdate" ).datepicker({
        changeMonth: true,
        changeYear: true,
        yearRange: '1920:2010',
        dateFormat : 'dd-mm-yy',
        defaultDate: new Date(1985, 00, 01)
    });
});
</script>

http://api.jqueryui.com/datepicker/#option-defaultDate

Specify either an actual date via a Date object or as a string in the current dateFormat, or a number of days from today (e.g. +7) or a string of values and periods ('y' for years, 'm' for months, 'w' for weeks, 'd' for days, e.g. '+1m +7d'), or null for today.

angular 2 how to return data from subscribe

You just can't return the value directly because it is an async call. An async call means it is running in the background (actually scheduled for later execution) while your code continues to execute.

You also can't have such code in the class directly. It needs to be moved into a method or the constructor.

What you can do is not to subscribe() directly but use an operator like map()

export class DataComponent{
    someMethod() {
      return this.http.get(path).map(res => {
        return res.json();
      });
    }
}

In addition, you can combine multiple .map with the same Observables as sometimes this improves code clarity and keeps things separate. Example:

validateResponse = (response) => validate(response);

parseJson = (json) => JSON.parse(json);

fetchUnits() {
    return this.http.get(requestUrl).map(this.validateResponse).map(this.parseJson);
}

This way an observable will be return the caller can subscribe to

export class DataComponent{
    someMethod() {
      return this.http.get(path).map(res => {
        return res.json();
      });
    }

    otherMethod() {
      this.someMethod().subscribe(data => this.data = data);
    }
}

The caller can also be in another class. Here it's just for brevity.

data => this.data = data

and

res => return res.json()

are arrow functions. They are similar to normal functions. These functions are passed to subscribe(...) or map(...) to be called from the observable when data arrives from the response. This is why data can't be returned directly, because when someMethod() is completed, the data wasn't received yet.

How to list the files in current directory?

There is nothing wrong with your code. It should list all of the files and directories directly contained by the nominated directory.

The problem is most likely one of the following:

  • The "." directory is not what you expect it to be. The "." pathname actually means the "current directory" or "working directory" for the JVM. You can verify what directory "." actually is by printing out dir.getCanonicalPath().

  • You are misunderstanding what dir.listFiles() returns. It doesn't return all objects in the tree beneath dir. It only returns objects (files, directories, symlinks, etc) that are directly in dir.

The ".classpath" file suggests that you are looking at an Eclipse project directory, and Eclipse projects are normally configured with the Java files in a subdirectory such as "./src". I wouldn't expect to see any Java source code in the "." directory.


Can anyone explain to me why src isn't the current folder?"

Assuming that you are launching an application in Eclipse, then the current folder defaults to the project directory. You can change the default current directory via one of the panels in the Launcher configuration wizard.

Is there an "if -then - else " statement in XPath?

Somewhat simpler XPath 1.0 solution, adapted from Tomalek's (posted here) and Dimitre's (here):

concat(substring($s1, 1 div number($cond)), substring($s2, 1 div number(not($cond))))

Note: I found an explicit number() was required to convert the bool to an int otherwise some XPath evaluators threw a type mismatch error. Depending on how strict your XPath processor is type-matching you may not need it.

Remove secure warnings (_CRT_SECURE_NO_WARNINGS) from projects by default in Visual Studio

It may have been because I am still new to VS and definitely new to C, but the only thing that allowed me to build was adding

#pragma warning(disable:4996)

At the top of my file, this suppressed the C4996 error I was getting with sprintf

A bit annoying but perfect for my tiny bit of code and by far the easiest.

I read about it here: https://msdn.microsoft.com/en-us/library/2c8f766e.aspx

How to stop execution after a certain time in Java?

If you can't go over your time limit (it's a hard limit) then a thread is your best bet. You can use a loop to terminate the thread once you get to the time threshold. Whatever is going on in that thread at the time can be interrupted, allowing calculations to stop almost instantly. Here is an example:

Thread t = new Thread(myRunnable); // myRunnable does your calculations

long startTime = System.currentTimeMillis();
long endTime = startTime + 60000L;

t.start(); // Kick off calculations

while (System.currentTimeMillis() < endTime) {
    // Still within time theshold, wait a little longer
    try {
         Thread.sleep(500L);  // Sleep 1/2 second
    } catch (InterruptedException e) {
         // Someone woke us up during sleep, that's OK
    }
}

t.interrupt();  // Tell the thread to stop
t.join();       // Wait for the thread to cleanup and finish

That will give you resolution to about 1/2 second. By polling more often in the while loop, you can get that down.

Your runnable's run would look something like this:

public void run() {
    while (true) {
        try {
            // Long running work
            calculateMassOfUniverse();
        } catch (InterruptedException e) {
            // We were signaled, clean things up
            cleanupStuff();
            break;           // Leave the loop, thread will exit
    }
}

Update based on Dmitri's answer

Dmitri pointed out TimerTask, which would let you avoid the loop. You could just do the join call and the TimerTask you setup would take care of interrupting the thread. This would let you get more exact resolution without having to poll in a loop.

Get the size of the screen, current web page and browser window

In some cases related with responsive layout $(document).height() can return wrong data that displays view port height only. For example when some div#wrapper has height:100%, that #wrapper can be stretched by some block inside it. But it's height still will be like viewport height. In such situation you might use

$('#wrapper').get(0).scrollHeight

That represents actual size of wrapper.

How to deal with "java.lang.OutOfMemoryError: Java heap space" error?

Run Java with the command-line option -Xmx, which sets the maximum size of the heap.

See here for details.

How does Access-Control-Allow-Origin header work?

Whenever I start thinking about CORS, my intuition about which site hosts the headers is incorrect, just as you described in your question. For me, it helps to think about the purpose of the same origin policy.

The purpose of the same origin policy is to protect you from malicious JavaScript on siteA.com accessing private information you've chosen to share only with siteB.com. Without the same origin policy, JavaScript written by the authors of siteA.com could make your browser make requests to siteB.com, using your authentication cookies for siteB.com. In this way, siteA.com could steal the secret information you share with siteB.com.

Sometimes you need to work cross domain, which is where CORS comes in. CORS relaxes the same origin policy for domainB.com, using the Access-Control-Allow-Origin header to list other domains (domainA.com) that are trusted to run JavaScript that can interact with domainA.com.

To understand which domain should serve the CORS headers, consider this. You visit malicious.com, which contains some JavaScript that tries to make a cross domain request to mybank.com. It should be up to mybank.com, not malicious.com, to decide whether or not it sets CORS headers that relax the same origin policy allowing the JavaScript from malicious.com to interact with it. If malicous.com could set its own CORS headers allowing its own JavaScript access to mybank.com, this would completely nullify the same origin policy.

I think the reason for my bad intuition is the point of view I have when developing a site. It's my site, with all my JavaScript, therefore it isn't doing anything malicious and it should be up to me to specify which other sites my JavaScript can interact with. When in fact I should be thinking which other sites JavaScript are trying to interact with my site and should I use CORS to allow them?

jQuery - Detect value change on hidden input field

Although this thread is 3 years old, here is my solution:

$(function ()
{
    keep_fields_uptodate();
});

function keep_fields_uptodate()
{
    // Keep all fields up to date!
    var $inputDate = $("input[type='date']");
    $inputDate.blur(function(event)
    {
        $("input").trigger("change");
    });
}

Shell script to send email

Well, the easiest solution would of course be to pipe the output into mail:

vs@lambda:~$ cat test.sh
sleep 3 && echo test | mail -s test your@address
vs@lambda:~$ nohup sh test.sh
nohup: ignoring input and appending output to `nohup.out'

I guess sh test.sh & will do just as fine normally.

How to change default language for SQL Server?

@John Woo's accepted answer has some caveats which you should be aware of:

  1. Default language setting of a session is controlled from default language setting of the user login instead which you have used to create the session. SQL Server instance level setting doesn't affect the default language of the session.
  2. Changing default language setting at SQL Server instance level doesn't affects the default language setting of the existing SQL Server logins. It is meant to be inherited only by the new user logins that you create after changing the instance level setting.

So, there is an intermediate level between your SQL Server instance and the session which you can use to control the default language setting for session - login level.

SQL Server Instance level setting -> User login level setting -> Query Session level setting

This can help you in case you want to set default language of all new sessions belonging to some specific user only.

Simply change the default language setting of the target user login as per this link and you are all set. You can also do it from SQL Server Management Studio (SSMS) UI. Below you can see the default language setting in properties window of sa user in SQL Server:

enter image description here

Note: Also, it is important to know that changing the setting doesn't affect the default language of already active sessions from that user login. It will affect only the new sessions created after changing the setting.

Unable to capture screenshot. Prevented by security policy. Galaxy S6. Android 6.0

You must have either disabled, froze or uninstalled FaceProvider in settings>applications>all
This will only happen if it's frozen, either uninstall it, or enable it.

Android ClassNotFoundException: Didn't find class on path

1) Create libs folder under project root
2) Copy and paste the jar file into it
3) Configure the build path (Add jar)
4) Clean and run

cheers :-)

Quickest way to compare two generic lists for differences

I think this is a simple and easy way to compare two lists element by element

x=[1,2,3,5,4,8,7,11,12,45,96,25]
y=[2,4,5,6,8,7,88,9,6,55,44,23]

tmp = []


for i in range(len(x)) and range(len(y)):
    if x[i]>y[i]:
        tmp.append(1)
    else:
        tmp.append(0)
print(tmp)

How to install mcrypt extension in xampp

Right from the PHP Docs: PHP 5.3 Windows binaries uses the static version of the MCrypt library, no DLL are needed.

http://php.net/manual/en/mcrypt.requirements.php

But if you really want to download it, just go to the mcrypt sourceforge page

http://sourceforge.net/projects/mcrypt/files/?source=navbar

How to run a command in the background and get no output?

Sorry this is a bit late but found the ideal solution for somple commands where you don't want any standard or error output (credit where it's due: http://felixmilea.com/2014/12/running-bash-commands-background-properly/)

This redirects output to null and keeps screen clear:

command &>/dev/null &

Should I use Python 32bit or Python 64bit

Use the 64 bit version only if you have to work with heavy amounts of data, in that scenario, the 64 bits performs better with the inconvenient that John La Rooy said; if not, stick with the 32 bits.

HttpWebRequest-The remote server returned an error: (400) Bad Request

Are you sure you should be using POST not PUT?

POST is usually used with application/x-www-urlencoded formats. If you are using a REST API, you should maybe be using PUT? If you are uploading a file you probably need to use multipart/form-data. Not always, but usually, that is the right thing to do..

Also you don't seem to be using the credentials to log in - you need to use the Credentials property of the HttpWebRequest object to send the username and password.

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

If error comes for ".settings/language.settings.xml" or any such file you don't need to git.

  1. Team -> Commit -> Staged filelist, check if unwanted file exists, -> Right click on each-> remove from index.
  2. From UnStaged filelist, check if unwanted file exists, -> Right click on each-> Ignore.

Now if Staged file list empty, and Unstaged file list all files are marked as Ignored. You can pull. Otherwise, follow other answers.

How can the size of an input text box be defined in HTML?

The size attribute works, as well

<input size="25" type="text">

How to "wait" a Thread in Android

I just add this line exactly as it appears below (if you need a second delay):

try {
    Thread.sleep(1000);
} catch(InterruptedException e) {
    // Process exception
}

I find the catch IS necessary (Your app can crash due to Android OS as much as your own code).

Android - setOnClickListener vs OnClickListener vs View.OnClickListener

The logic is simple. setOnClickListener belongs to step 2.

  1. You create the button
  2. You create an instance of OnClickListener* like it's done in that example and override the onClick-method.
  3. You assign that OnClickListener to that button using btn.setOnClickListener(myOnClickListener); in your fragments/activities onCreate-method.
  4. When the user clicks the button, the onClick function of the assigned OnClickListener is called.

*If you import android.view.View; you use View.OnClickListener. If you import android.view.View.*; or import android.view.View.OnClickListener; you use OnClickListener as far as I get it.

Another way is to let you activity/fragment inherit from OnClickListener. This way you assign your fragment/activity as the listener for your button and implement onClick as a member-function.

What is the JavaScript equivalent of var_dump or print_r in PHP?

The var_dump equivalent in JavaScript? Simply, there isn't one.

But, that doesn't mean you're left helpless. Like some have suggested, use Firebug (or equivalent in other browsers), but unlike what others suggested, don't use console.log when you have a (slightly) better tool console.dir:

console.dir(object)

Prints an interactive listing of all properties of the object. This looks identical to the view that you would see in the DOM tab.

SCRIPT438: Object doesn't support property or method IE

We were able to solve this problem by adding in the Object.Assign polyfill to the files being imported and throwing the error. We would make it the highest import, that way it would be available to the other code to be called in the stack.

import "mdn-polyfills/Object.assign";

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Polyfill

How do I comment out a block of tags in XML?

Here for commenting we have to write like below:

<!-- Your comment here -->

Shortcuts for IntelliJ Idea and Eclipse

For Windows & Linux:

Shortcut for Commenting a single line:

Ctrl + /

Shortcut for Commenting multiple lines:

Ctrl + Shift + /

For Mac:

Shortcut for Commenting a single line:

cmnd + /

Shortcut for Commenting multiple lines:

cmnd + Shift + /

One thing you have to keep in mind that, you can't comment an attribute of an XML tag. For Example:

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    <!--android:text="Hello.."-->
    android:textStyle="bold" />

Here, TextView is a XML Tag and text is an attribute of that tag. You can't comment attributes of an XML Tag. You have to comment the full XML Tag. For Example:

<!--<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Hello.."
    android:textStyle="bold" />-->

Registering for Push Notifications in Xcode 8/Swift 3.0?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    if #available(iOS 10, *) {

        //Notifications get posted to the function (delegate):  func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: () -> Void)"


        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in

            guard error == nil else {
                //Display Error.. Handle Error.. etc..
                return
            }

            if granted {
                //Do stuff here..

                //Register for RemoteNotifications. Your Remote Notifications can display alerts now :)
                DispatchQueue.main.async {
                    application.registerForRemoteNotifications()
                }
            }
            else {
                //Handle user denying permissions..
            }
        }

        //Register for remote notifications.. If permission above is NOT granted, all notifications are delivered silently to AppDelegate.
        application.registerForRemoteNotifications()
    }
    else {
        let settings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        application.registerUserNotificationSettings(settings)
        application.registerForRemoteNotifications()
    }

    return true
}

How to remove files and directories quickly via terminal (bash shell)

rm -rf some_dir

-r "recursive" -f "force" (suppress confirmation messages)

Be careful!

How can I setup & run PhantomJS on Ubuntu?

Guidouil's answer put me on the right track. I had to add one additional symlink to /usr/bin/, and I did direct symlinks for all 3 - see below.

I'm installing on Ubuntu server Natty Narwhal.

This is exactly what I did.

cd /usr/local/share
sudo wget https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-1.9.7-linux-x86_64.tar.bz2
sudo tar xjf phantomjs-1.9.7-linux-x86_64.tar.bz2
sudo ln -s /usr/local/share/phantomjs-1.9.7-linux-x86_64/bin/phantomjs /usr/local/share/phantomjs
sudo ln -s /usr/local/share/phantomjs-1.9.7-linux-x86_64/bin/phantomjs /usr/local/bin/phantomjs
sudo ln -s /usr/local/share/phantomjs-1.9.7-linux-x86_64/bin/phantomjs /usr/bin/phantomjs

And finally when I do

phantomjs -v

I get 1.9.7

If anyone sees any problems with what I've done, please let me know.

Converting Milliseconds to Minutes and Seconds?

I would suggest using TimeUnit. You can use it like this:

long minutes = TimeUnit.MILLISECONDS.toMinutes(millis);
long seconds = TimeUnit.MILLISECONDS.toSeconds(millis);

Syntax of for-loop in SQL Server

There is no for-loop, only the while-loop:

DECLARE @i int = 0

WHILE @i < 20
BEGIN
    SET @i = @i + 1
    /* do some work */
END

Retrofit and GET using parameters

@QueryMap worked for me instead of FieldMap

If you have a bunch of GET params, another way to pass them into your url is a HashMap.

class YourActivity extends Activity {

private static final String BASEPATH = "http://www.example.com";

private interface API {
    @GET("/thing")
    void getMyThing(@QueryMap Map<String, String> params, new Callback<String> callback);
}

public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.your_layout);

   RestAdapter rest = new RestAdapter.Builder().setEndpoint(BASEPATH).build();
   API service = rest.create(API.class);

   Map<String, String> params = new HashMap<String, String>();
   params.put("key1", "val1");
   params.put("key2", "val2");
   // ... as much as you need.

   service.getMyThing(params, new Callback<String>() {
       // ... do some stuff here.
   });
}
}

The URL called will be http://www.example.com/thing/?key1=val1&key2=val2

YouTube: How to present embed video with sound muted

This is easy. Just add mute=1 to the src parameter of iframe.

Example:

<iframe src="https://www.youtube.com/embed/uNRGWVJ10gQ?controls=0&mute=1&showinfo=0&rel=0&autoplay=1&loop=1&playlist=uNRGWVJ10gQ" frameborder="0" allowfullscreen></iframe>

Is there a way to retrieve the view definition from a SQL Server using plain ADO?

You can get table/view details through below query.

For table :sp_help table_name For View :sp_help view_name