Programs & Examples On #Cycle plugin

Android - Best and safe way to stop thread

I used this method.


you can try.

How to increase buffer size in Oracle SQL Developer to view all records?

after you retrieve the first 50 rows in the query windows, simply click a column to get focus on the query window, then once selected do ctrl + pagedown

This will load the full result set (all rows)

How to save all files from source code of a web site?

In Chrome, go to options (Customize and Control, the 3 dots/bars at top right) ---> More Tools ---> save page as

save page as  
filename     : any_name.html 
save as type : webpage complete.

Then you will get any_name.html and any_name folder.

Format bytes to kilobytes, megabytes, gigabytes

It's a little late but a slightly faster version of the accepted answer is below:

function formatBytes($bytes, $precision)
    $unit_list = array

    $bytes = max($bytes, 0);
    $index = floor(log($bytes, 2) / 10);
    $index = min($index, count($unit_list) - 1);
    $bytes /= pow(1024, $index);

    return round($bytes, $precision) . ' ' . $unit_list[$index];

It's more efficient, due to performing a single log-2 operation instead of two log-e operations.

It's actually faster to do the more obvious solution below, however:

function formatBytes($bytes, $precision)
    $unit_list = array

    $index_max = count($unit_list) - 1;
    $bytes = max($bytes, 0);

    for ($index = 0; $bytes >= 1024 && $index < $index_max; $index++)
        $bytes /= 1024;

    return round($bytes, $precision) . ' ' . $unit_list[$index];

This is because as the index is calculated at the same time as the value of the number of bytes in the appropriate unit. This cut the execution time by about 35% (a 55% speed increase).

What's "tools:context" in Android layout files?

This is best solution :

This is design attributes we can set activty context in xml like




enter image description here

You can navigate to java class when clicking on the marked icon and tools have more features like

tools:listItems=""//for recycler view 


PHP: How to get current time in hour:minute:second?

You can have both formats as an argument to the function date():

date("d-m-Y H:i:s")

Check the manual for more info :

As pointed out by @ThomasVdBerge to display minutes you need the 'i' character

how to convert .java file to a .class file

To get a .class file you have to compile the .java file.

The command for this is javac. The manual for this is found here (Windows)

In short:


Correct Semantic tag for copyright info - html5

The <footer> tag seems like a good candidate:

<footer>&copy; 2011 Some copyright message</footer>

MySQL show current connection info

If you want to know the port number of your local host on which Mysql is running you can use this query on MySQL Command line client --

SHOW VARIABLES WHERE Variable_name = 'port';

mysql> SHOW VARIABLES WHERE Variable_name = 'port';
| Variable_name | Value |
| port          | 3306  |
1 row in set (0.00 sec)

It will give you the port number on which MySQL is running.

If you want to know the hostname of your Mysql you can use this query on MySQL Command line client --

SHOW VARIABLES WHERE Variable_name = 'hostname';

mysql> SHOW VARIABLES WHERE Variable_name = 'hostname';
| Variable_name     | Value |
| hostname          | Dell  |
1 row in set (0.00 sec)

It will give you the hostname for mysql.

If you want to know the username of your Mysql you can use this query on MySQL Command line client --

select user();   

mysql> select user();
| user()         |
| root@localhost |
1 row in set (0.00 sec)

It will give you the username for mysql.

exception in initializer error in java when using Netbeans

@Christian Ullenboom' explanation is correct.

I'm surmising that the OBD2nerForm code you posted is a static initializer block and that it is all generated. Based on that and on the stack trace, it seems likely that generated code is tripping up because it has found some component of your form that doesn't have the type that it is expecting.

I'd do the following to try and diagnose this:

  • Google for reports of similar problems with NetBeans generated forms.
  • If you are running an old version of NetBeans, scan through the "bugs fixed" pages for more recent releases. Or just upgrade try a newer release anyway to see if that fixes the problem.
  • Try cutting bits out of the form design until the problem "goes away" ... and try to figure out what the real cause is that way.
  • Run the application under a debugger to figure out what is being (incorrectly) type cast as what. Just knowing the class names may help. And looking at the instance variables of the objects may reveal more; e.g. which specific form component is causing the problem.

My suspicion is that the root cause is a combination of something a bit unusual (or incorrect) with your form design, and bugs in the NetBeans form generator that is not coping with your form. If you can figure it out, a workaround may reveal itself.

How can I delete Docker's images?

You have to stop/delete all unnecessary containers created on that images first.

Have a look: How to remove old Docker containers.

After that use @marcell solution.

How to pretty print nested dictionaries?

pout can pretty print anything you throw at it, for example (borrowing data from another answer):

data = {'a':2, 'b':{'x':3, 'y':{'t1': 4, 't2':5}}}

would result in output printed to the screen like:

    'a': 2,
            't2': 5,
            't1': 4
        'x': 3

or you can return the formatted string output of your object:

v = pout.s(data)

Its primary use case is for debugging so it doesn't choke on object instances or anything and it handles unicode output as you would expect, works in python 2.7 and 3.

disclosure: I'm the author and maintainer of pout.

AngularJS POST Fails: Response for preflight has invalid HTTP status code 404

For a Node.js app, in the server.js file before registering all of my own routes, I put the code below. It sets the headers for all responses. It also ends the response gracefully if it is a pre-flight "OPTIONS" call and immediately sends the pre-flight response back to the client without "nexting" (is that a word?) down through the actual business logic routes. Here is my server.js file. Relevant sections highlighted for Stackoverflow use.

// server.js

// ==================

// import the packages we need
var express    = require('express');
var app        = express();
var bodyParser = require('body-parser');
var morgan     = require('morgan');
var jwt        = require('jsonwebtoken'); // used to create, sign, and verify tokens

// ====================================================
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));

// Logger

// -------------------------------------------------------------
// -------------------------------------------------------------

//Set CORS header and intercept "OPTIONS" preflight call from AngularJS
var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    if (req.method === "OPTIONS") 

// -------------------------------------------------------------
// -------------------------------------------------------------

// =================================================

var route1 = require("./routes/route1");
var route2 = require("./routes/route2");
var error404 = require("./routes/error404");

// ======================================================

// -------------------------------------------------------------
// -------------------------------------------------------------


// -------------------------------------------------------------
// -------------------------------------------------------------

app.use("/api/v1/route1/", route1);
app.use("/api/v1/route2/", route2);
app.use('/', error404);

// =================

var port = process.env.PORT || 8080;        // set our port
console.log('API Active on port ' + port);

IF... OR IF... in a windows batch file

Never got exist to work.

I use if not exist g:xyz/what goto h: Else xcopy c:current/files g:bu/current There are modifiers /a etc. Not sure which ones. Laptop in shop. And computer in office. I am not there.

Never got batch files to work above Windows XP

Call async/await functions in parallel

I create a helper function waitAll, may be it can make it sweeter. It only works in nodejs for now, not in browser chrome.

    //const parallel = async (...items) => {
    const waitAll = async (...items) => {
        //this function does start execution the functions
        //the execution has been started before running this code here
        //instead it collects of the result of execution of the functions

        const temp = [];
        for (const item of items) {
            //this is not
            //temp.push(await item())
            //it does wait for the result in series (not in parallel), but
            //it doesn't affect the parallel execution of those functions
            //because they haven started earlier
            temp.push(await item);
        return temp;

    //the async functions are executed in parallel before passed
    //in the waitAll function

    //const finalResult = await waitAll(someResult(), anotherResult());
    //const finalResult = await parallel(someResult(), anotherResult());
    const [result1, result2] = await waitAll(someResult(), anotherResult());
    //const [result1, result2] = await parallel(someResult(), anotherResult());

Composer - the requested PHP extension mbstring is missing from your system

sudo apt-get install php-mbstring

# if your are using php 7.1
sudo apt-get install php7.1-mbstring

# if your are using php 7.2
sudo apt-get install php7.2-mbstring

How do I get next month date from today's date and insert it in my database?

You can use PHP's strtotime() function:

// One month from today
$date = date('Y-m-d', strtotime('+1 month'));

// One month from a specific date
$date = date('Y-m-d', strtotime('+1 month', strtotime('2015-01-01')));

Just note that +1 month is not always calculated intuitively. It appears to always add the number of days that exist in the current month.

Current Date  | +1 month
2015-01-01    | 2015-02-01   (+31 days)
2015-01-15    | 2015-02-15   (+31 days)
2015-01-30    | 2015-03-02   (+31 days, skips Feb)
2015-01-31    | 2015-03-03   (+31 days, skips Feb)
2015-02-15    | 2015-03-15   (+28 days)
2015-03-31    | 2015-05-01   (+31 days, skips April)
2015-12-31    | 2016-01-31   (+31 days)

Some other date/time intervals that you can use:

$date = date('Y-m-d'); // Initial date string to use in calculation

$date = date('Y-m-d', strtotime('+1 day', strtotime($date)));
$date = date('Y-m-d', strtotime('+1 week', strtotime($date)));
$date = date('Y-m-d', strtotime('+2 week', strtotime($date)));
$date = date('Y-m-d', strtotime('+1 month', strtotime($date)));
$date = date('Y-m-d', strtotime('+30 days', strtotime($date)));

Git: How to remove proxy

Check if you have environment variable that could still define a proxy (picked up by curl, even if the git config does not include any proxy setting anymore):


YAML: Do I need quotes for strings in YAML?

After a brief review of the YAML cookbook cited in the question and some testing, here's my interpretation:

  • In general, you don't need quotes.
  • Use quotes to force a string, e.g. if your key or value is 10 but you want it to return a String and not a Fixnum, write '10' or "10".
  • Use quotes if your value includes special characters, (e.g. :, {, }, [, ], ,, &, *, #, ?, |, -, <, >, =, !, %, @, \).
  • Single quotes let you put almost any character in your string, and won't try to parse escape codes. '\n' would be returned as the string \n.
  • Double quotes parse escape codes. "\n" would be returned as a line feed character.
  • The exclamation mark introduces a method, e.g. !ruby/sym to return a Ruby symbol.

Seems to me that the best approach would be to not use quotes unless you have to, and then to use single quotes unless you specifically want to process escape codes.


"Yes" and "No" should be enclosed in quotes (single or double) or else they will be interpreted as TrueClass and FalseClass values:

    'yes': 'Yes'
    'no': 'No'

How to pick just one item from a generator?

You can pick specific items using destructuring, e.g.:

>>> [first, *middle, last] = range(10)
>>> first
>>> middle
[1, 2, 3, 4, 5, 6, 7, 8]
>>> last

Note that this is going to consume your generator, so while highly readable, it is less efficient than something like next(), and ruinous on infinite generators:

>>> [first, *rest] = itertools.count()

How to set Toolbar text and back arrow color









app:popupTheme="@style/Theme.AppCompat.NoActionBar" />

That toolbar theme specifies a textColorPrimary and textColorSecondary to change the color of the title text and of the menu overflow button. You could just specify the standard Theme.AppCompat.Light.NoActionBar theme for the toolbar, to get the dark text and overflow icon, but I wanted to derive from my own theme and make only small changes, because I have no idea what else might be affected.

<style name="GalaxyZooThemeToolbarDarkOverflow" parent="Theme.AppCompat.NoActionBar">

<!-- android:textColorPrimary is the  color of the title text
   in the Toolbar, in the Theme.AppCompat theme:  -->

<item name="android:textColorPrimary">@color/abc_primary_text_material_light</item>

<!-- android:textColorPrimaryInverse is the  color of the title
   text in the Toolbar, in the Theme.AppCompat.Light theme:  -->

<!-- <item name="android:textColorPrimaryInverse">@color/abc_primary_text_material_light</item> -->

This is how you can change the color of text and icons on toolbar.

For more Ref:

C++ String Concatenation operator<<

First of all it is unclear what type name has. If it has the type std::string then instead of

string nametext;
nametext = "Your name is" << name;

you should write

std::string nametext = "Your name is " + name;

where operator + serves to concatenate strings.

If name is a character array then you may not use operator + for two character arrays (the string literal is also a character array), because character arrays in expressions are implicitly converted to pointers by the compiler. In this case you could write

std::string nametext( "Your name is " );
nametext.append( name );


std::string nametext( "Your name is " );
nametext += name;

Loop through childNodes

const results = Array.from(myNodeList.values()).map(parser_item);

NodeList is not Array but NodeList.values() return a Array Iterator, so can convert it to Array.

What is this property in Spring Boot?

This property will register an OpenEntityManagerInViewInterceptor, which registers an EntityManager to the current thread, so you will have the same EntityManager until the web request is finished. It has nothing to do with a Hibernate SessionFactory etc.

How to center-justify the last line of text in CSS?

You can use the text-align-last property

.center-justified {
    text-align: justify;
    text-align-last: center;

Here is a compatibility table :

Works in all browsers except for Safari (both Mac and iOS), including Internet Explorer.

Also in Internet Explorer, only works with text-align: justify (no other values of text-align) and start and end are not supported.

c++ boost split string

The problem is somewhere else in your code, because this works:

string line("test\ttest2\ttest3");
vector<string> strs;

cout << "* size of the vector: " << strs.size() << endl;    
for (size_t i = 0; i < strs.size(); i++)
    cout << strs[i] << endl;

and testing your approach, which uses a vector iterator also works:

string line("test\ttest2\ttest3");
vector<string> strs;

cout << "* size of the vector: " << strs.size() << endl;
for (vector<string>::iterator it = strs.begin(); it != strs.end(); ++it)
    cout << *it << endl;

Again, your problem is somewhere else. Maybe what you think is a \t character on the string, isn't. I would fill the code with debugs, starting by monitoring the insertions on the vector to make sure everything is being inserted the way its supposed to be.


* size of the vector: 3

Position: absolute and parent height?

You can do that with a grid:

article {
    display: grid;

.one {
    grid-area: 1 / 1 / 2 / 2;

.two {
    grid-area: 1 / 1 / 2 / 2;

Django auto_now and auto_now_add

Talking about a side question: if you want to see this fields in admin (though, you won't be able to edit it), you can add readonly_fields to your admin class.

class SomeAdmin(ModelAdmin):
    readonly_fields = ("created","modified",)

Well, this applies only to latest Django versions (I believe, 1.3 and above)

Get Memory Usage in Android

An easy way to check the CPU usage is to use the adb tool w/ top. I.e.:

adb shell top -m 10

How to convert seconds to HH:mm:ss in moment.js

How to correctly use moment.js durations? | Use moment.duration() in codes

First, you need to import moment and moment-duration-format.

import moment from 'moment';
import 'moment-duration-format';

Then, use duration function. Let us apply the above example: 28800 = 8 am.

moment.duration(28800, "seconds").format("h:mm a");

Well, you do not have above type error. Do you get a right value 8:00 am ? No…, the value you get is 8:00 a. Moment.js format is not working as it is supposed to.

The solution is to transform seconds to milliseconds and use UTC time.

moment.utc(moment.duration(value, 'seconds').asMilliseconds()).format('h:mm a')

All right we get 8:00 am now. If you want 8 am instead of 8:00 am for integral time, we need to do RegExp

const time = moment.utc(moment.duration(value, 'seconds').asMilliseconds()).format('h:mm a');
time.replace(/:00/g, '')

Nginx subdomain configuration

Another type of solution would be to autogenerate the nginx conf files via Jinja2 templates from ansible. The advantage of this is easy deployment to a cloud environment, and easy to replicate on multiple dev machines

XOR operation with two strings in java

This solution is compatible with Android (I've tested and used it myself). Thanks to @user467257 whose solution I adapted this from.

import android.util.Base64;

public class StringXORer {

public String encode(String s, String key) {
    return new String(Base64.encode(xorWithKey(s.getBytes(), key.getBytes()), Base64.DEFAULT));

public String decode(String s, String key) {
    return new String(xorWithKey(base64Decode(s), key.getBytes()));

private byte[] xorWithKey(byte[] a, byte[] key) {
    byte[] out = new byte[a.length];
    for (int i = 0; i < a.length; i++) {
        out[i] = (byte) (a[i] ^ key[i%key.length]);
    return out;

private byte[] base64Decode(String s) {
    return Base64.decode(s,Base64.DEFAULT);

private String base64Encode(byte[] bytes) {
    return new String(Base64.encode(bytes,Base64.DEFAULT));


Can I run multiple versions of Google Chrome on the same machine? (Mac or Windows)

As professional testers, my friends use browsers section to test compatibility of site in various browsers. Hope this should help you.

Python Pandas Error tokenizing data

You can try;

data = pd.read_csv('file1.csv', sep='\t')

How to get the client IP address in PHP

The following function determine all possibilities and return the values in a comma separated format (ip, ip, etc.).

It has also an optional validation function as (first parameter that disabled by default) to validate the IP address against (private range and reserved range).

echo GetClientIP(true);

function GetClientIP($validate = False) {
  $ipkeys = array(

  Now we check each key against $_SERVER if containing such value
  $ip = array();
  foreach ($ipkeys as $keyword) {
    if (isset($_SERVER[$keyword])) {
      if ($validate) {
        if (ValidatePublicIP($_SERVER[$keyword])) {
          $ip[] = $_SERVER[$keyword];
        $ip[] = $_SERVER[$keyword];

  $ip = ( empty($ip) ? 'Unknown' : implode(", ", $ip) );
  return $ip;

function ValidatePublicIP($ip){
    return true;
  else {
    return false;

CSS: Position text in the middle of the page

Try this CSS:

h1 {
    left: 0;
    line-height: 200px;
    margin-top: -100px;
    position: absolute;
    text-align: center;
    top: 50%;
    width: 100%;


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

There are lots of differences between ISO 8601 and RFC 3339. Here is some examples to give you an idea:

2020-12-09T16:09:53+00:00 is a date time value that is compliant both both standards.

2020-12-09 16:09:53+00:00 uses a space to separate the date and time. This is allowed by RFC 3339 but not allowed by ISO 8601.

2020-12-09T16:09:53-00:00 has a negative sign in the time offset. This is allowed by RFC 3339 but not allowed by ISO 8601.

20201209T160953Z omits the hyphens. This is allowed by ISO 8601 but not allowed by RFC 3339.

ISO 8601 allows for things like ordinal dates such as 2020-344 which represents the 344th day of year 2020. RFC 3339 doesn't allow for that.

For your questions:

Is one just an extension?

No. As shown above each standard supports syntax variations not supported by the the other standard. So one syntax is not a superset or an extension of the other.

Should I use one over the other?

Of course this depends on your scenario. A safe general strategy is to generate date time strings that are valid by both standards.

Another good general strategy is to use an existing standard library for parsing/formatting date time strings and not write custom implementations unless you are addressing a genuinely custom scenario.

Do I really need to care that bad?

Well, that's up to you. Most regular developers who deal with date time strings should have a high level understanding but don't need to dive into the details.

String replace a Backslash

To Replace backslash at particular location:

if ((stringValue.contains("\\"))&&(stringValue.indexOf("\\", location-1)==(location-1))) {

Shall we always use [unowned self] inside closure in Swift

I thought I would add some concrete examples specifically for a view controller. Many of the explanations, not just here on Stack Overflow, are really good, but I work better with real world examples (@drewag had a good start on this):

  • If you have a closure to handle a response from a network requests use weak, because they are long lived. The view controller could close before the request completes so self no longer points to a valid object when the closure is called.
  • If you have closure that handles an event on a button. This can be unowned because as soon as the view controller goes away, the button and any other items it may be referencing from self goes away at the same time. The closure block will also go away at the same time.

    class MyViewController: UIViewController {
          @IBOutlet weak var myButton: UIButton!
          let networkManager = NetworkManager()
          let buttonPressClosure: () -> Void // closure must be held in this class. 
          override func viewDidLoad() {
              // use unowned here
              buttonPressClosure = { [unowned self] in
                  self.changeDisplayViewMode() // won't happen after vc closes. 
              // use weak here
              networkManager.fetch(query: query) { [weak self] (results, error) in
                  self?.updateUI() // could be called any time after vc closes
          @IBAction func buttonPress(self: Any) {
          // rest of class below.

CSS3 equivalent to jQuery slideUp and slideDown?

I changed your solution, so that it works in all modern browsers:

css snippet:

-webkit-transition: height 1s ease-in-out;
-moz-transition: height 1s ease-in-out;
-ms-transition: height 1s ease-in-out;
-o-transition: height 1s ease-in-out;
transition: height 1s ease-in-out;

js snippet:

    var clone = $('#this').clone()

    var newHeight = $(".slideClone").height();
    $('#this').css('height',newHeight + 'px');

here's the full example

'setInterval' vs 'setTimeout'


It is a function that execute a JavaScript statement AFTER x interval.

setTimeout(function () {
}, 1000); // Execute something() 1 second later.


It is a function that execute a JavaScript statement EVERY x interval.

setInterval(function () {
}, 2000); // Execute somethingElse() every 2 seconds.

The interval unit is in millisecond for both functions.

JS: Failed to execute 'getComputedStyle' on 'Window': parameter is not of type 'Element'

The error message says that getComputedStyle requires the parameter to be Element type. You receive it because the parameter has an incorrect type.

The most common case is that you try to pass an element that doesn't exist as an argument:

my_element = document.querySelector(#non_existing_id);

Now that element is null, this will result in mentioned error:

my_style = window.getComputedStyle(my_element);

If it's not possible to always get element correctly, you can, for example, use the following to end function if querySelector didn't find any match:

if (my_element === null) return;

HTTPS and SSL3_GET_SERVER_CERTIFICATE:certificate verify failed, CA is OK

I have the same error on amazon AMI linux.

I Solved by setting curl.cainfo on /etc/php.d/curl.ini

Addition October 2018

On Amazon Linux v1 edit this file

vi /etc/php.d/20-curl.ini

To add this line


What is the difference between, and localhost?

In current version of Jekyll, it defaults to
This is good, if you are connected to a network but do not want anyone else to access your application.

However it may happen that you want to see how your application runs on a mobile or from some other laptop/computer.

In that case, you can use

jekyll serve --host

This binds your application to the host & next use following to connect to it from some other host

http://host's IP adress/4000 

How does one represent the empty char?

There are two ways to do the same instruction, that is, an empty string. The first way is to allocate an empty string on static memory:

char* my_variable = "";

or, if you want to be explicit:

char my_variable = '\0';

The way posted above is only for a character. And, the second way:

#include <string.h>
char* my_variable = strdup("");

Don't forget to use free() with this one because strdup() use malloc inside.

Display / print all rows of a tibble (tbl_df)

You could also use

print(tbl_df(df), n=40)

or with the help of the pipe operator

df %>% tbl_df %>% print(n=40)

To print all rows specify tbl_df %>% print(n = Inf)

How to force link from iframe to be opened in the parent window

Yah I found

<base target="_parent" />

This useful for open all iframe links open in iframe.


        return true;

This we can use for whole page or specific part of page.

Thanks all for your help.

unique object identifier in javascript

Typescript version of @justin answer, ES6 compatible, using Symbols to prevent any key collision and added into the global for convenience. Just copy paste the code below, or put it into an ObjecId.ts file you will import.


declare global {
    interface ObjectConstructor {
        id: (object: any) => number;

const uniqueId: symbol = Symbol('The unique id of an object');

export function enableObjectID(): void {
    if (typeof Object['id'] !== 'undefined') {

    let id: number = 0;

    Object['id'] = (object: any) => {
        const hasUniqueId: boolean = !!object[uniqueId];
        if (!hasUniqueId) {
            object[uniqueId] = ++id;

        return object[uniqueId];

Example of usage:


Accessing attributes from an AngularJS directive

See section Attributes from documentation on directives.

observing interpolated attributes: Use $observe to observe the value changes of attributes that contain interpolation (e.g. src="{{bar}}"). Not only is this very efficient but it's also the only way to easily get the actual value because during the linking phase the interpolation hasn't been evaluated yet and so the value is at this time set to undefined.

Check if a string is a valid date using DateTime.TryParse

So this question has been answered but to me the code used is not simple enough or complete. To me this bit here is what I was looking for and possibly some other people will like this as well.

string dateString = "198101";

if (DateTime.TryParse(dateString, out DateTime Temp) == true)
     //do stuff

The output is stored in Temp and not needed afterwards, datestring is the input string to be tested.

How to update specific key's value in an associative array in PHP?

Use array_walk_recursive function for multi-denominational array.

array_walk_recursive($data, function (&$v, $k) { 
    if($k == 'transaction_date'){ 
        $v = date('d/m/Y',$v); 

How do you view ALL text from an ntext or nvarchar(max) in SSMS?

Return data as XML

FROM [dbo].[FormData]
WHERE [UID] LIKE '{my-uid}'

Make sure you set a reasonable limit in the SSMS options window, depending on the result you're expecting. enter image description here

This will work if the text you're returning doesn't contain unencoded characters like & instead of &amp; that will cause the XML conversion to fail.

Returning data using PowerShell

For this you will need the PowerShell SQL Server module installed on the machine on which you'll be running the command.

If you're all set up, configure and run the following script:

Invoke-Sqlcmd -Query "SELECT [Data] FROM [dbo].[FormData] WHERE [UID] LIKE '{my-uid}'" -ServerInstance "database-server-name" -Database "database-name" -Username "user" -Password "password" -MaxCharLength 10000000 | Out-File -filePath "C:\db_data.txt"

Make sure you set the -MaxCharLength parameter to a value that suits your needs.

Accessing session from TWIG template

I found that the cleanest way to do this is to create a custom TwigExtension and override its getGlobals() method. Rather than using $_SESSION, it's also better to use Symfony's Session class since it handles automatically starting/stopping the session.

I've got the following extension in /src/AppBundle/Twig/AppExtension.php:

namespace AppBundle\Twig;

use Symfony\Component\HttpFoundation\Session\Session;

class AppExtension extends \Twig_Extension {

    public function getGlobals() {
        $session = new Session();
        return array(
            'session' => $session->all(),

    public function getName() {
        return 'app_extension';

Then add this in /app/config/services.yml:

        class: AppBundle\Twig\AppExtension
        public: false
            - { name: twig.extension }

Then the session can be accessed from any view using:

{{ session.my_variable }}

How do I do multiple CASE WHEN conditions using SQL Server 2008?

There are two formats of case expression. You can do CASE with many WHEN as;

CASE  WHEN Col1 = 1 OR Col3 = 1  THEN 1 
      WHEN Col1 = 2 THEN 2
      ELSE 0 END as Qty

Or a Simple CASE expression


Or CASE within CASE as;

CASE  WHEN Col1 < 2 THEN  
                    CASE Col2 WHEN 'X' THEN 10 ELSE 11 END
      WHEN Col1 = 2 THEN 2
      ELSE 0 END as Qty

How do I remove an array item in TypeScript?

Same way as you would in JavaScript.

delete myArray[key];

Note that this sets the element to undefined.

Better to use the Array.prototype.splice function:

const index = myArray.indexOf(key, 0);
if (index > -1) {
   myArray.splice(index, 1);

how to toggle attr() in jquery

For readonly/disabled and other attributes with true/false values

$(':submit').attr('disabled', function(_, attr){ return !attr});

how does Request.QueryString work?

A query string is an array of parameters sent to a web page.

This url: http://page.asp?x=1&y=hello

Request.QueryString[0] is the same as 
Request.QueryString["x"] and holds a string value "1"

Request.QueryString[1] is the same as 
Request.QueryString["y"] and holds a string value "hello"

setOnItemClickListener on custom ListView

Sorry for coding with Kotlin. But I faced the same problem. I solved with the code below.

list.setOnItemClickListener{ _, view, _, _ ->
        val text1 = view.find<TextView>(


You can put an id which shows a TextView that you want in "~~".

Hope it'll help someone!

How to append text to an existing file in Java?

Using java.nio.Files along with java.nio.file.StandardOpenOption

    PrintWriter out = null;
    BufferedWriter bufWriter;

        bufWriter =
        out = new PrintWriter(bufWriter, true);
    }catch(IOException e){
        //Oh, no! Failed to create PrintWriter

    //After successful creation of PrintWriter
    out.println("Text to be appended");

    //After done writing, remember to close!

This creates a BufferedWriter using Files, which accepts StandardOpenOption parameters, and an auto-flushing PrintWriter from the resultant BufferedWriter. PrintWriter's println() method, can then be called to write to the file.

The StandardOpenOption parameters used in this code: opens the file for writing, only appends to the file, and creates the file if it does not exist.

Paths.get("path here") can be replaced with new File("path here").toPath(). And Charset.forName("charset name") can be modified to accommodate the desired Charset.

How to create web service (server & Client) in Visual Studio 2012?

WCF is a newer technology that is a viable alternative in many instances. ASP is great and works well, but I personally prefer WCF. And you can do it in .Net 4.5.

WCF Project

enter image description here

Create a new project. enter image description here Right-Click on the project in solution explorer, select "Add Service Reference" enter image description here

Create a textbox and button in the new application. Below is my click event for the button:

private void btnGo_Click(object sender, EventArgs e)
        ServiceReference1.Service1Client testClient = new ServiceReference1.Service1Client();
        //Add error handling, null checks, etc...
        int iValue = int.Parse(txtInput.Text);
        string sResult = testClient.GetData(iValue).ToString();

And you're done. enter image description here

Are all Spring Framework Java Configuration injection examples buggy?

In your test, you are comparing the two TestParent beans, not the single TestedChild bean.

Also, Spring proxies your @Configuration class so that when you call one of the @Bean annotated methods, it caches the result and always returns the same object on future calls.

See here:

How to check the Angular version?

ng --version command returns the details of the version of Angular CLI installed

How to tell if homebrew is installed on Mac OS X

Another one possible way:

# Check if Ninja is installed
if ! which ninja > /dev/null
echo 'Ninja installation...'
brew install ninja

Laravel redirect back to original destination after login

return Redirect::intended('/');

this will redirect you to default page of your project i.e. start page.

How to replace text of a cell based on condition in excel

You can use the IF statement in a new cell to replace text, such as:

=IF(A4="C", "Other", A4)

This will check and see if cell value A4 is "C", and if it is, it replaces it with the text "Other"; otherwise, it uses the contents of cell A4.


Assuming that the Employee_Count values are in B1-B10, you can use this:

=IF(B1=LARGE($B$1:$B$10, 10), "Other", B1)

This function doesn't even require the data to be sorted; the LARGE function will find the 10th largest number in the series, and then the rest of the formula will compare against that.

Visual Studio Code pylint: Unable to import 'protorpc'

First I will check the python3 path where it lives

enter image description here

And then in the VS Code settings just add that path, for example:

"python.pythonPath": "/usr/local/bin/python3"

How to enable Logger.debug() in Log4j

You need to set the logger level to the lowest you want to display. For example, if you want to display DEBUG messages, you need to set the logger level to DEBUG.

The Apache log4j manual has a section on Configuration.

jQuery - find child with a specific class




Do sessions really violate RESTfulness?

  1. Sessions are not RESTless
  2. Do you mean that REST service for http-use only or I got smth wrong? Cookie-based session must be used only for own(!) http-based services! (It could be a problem to work with cookie, e.g. from Mobile/Console/Desktop/etc.)
  3. if you provide RESTful service for 3d party developers, never use cookie-based session, use tokens instead to avoid the problems with security.

How can I change CSS display none or block property using jQuery?

In javascript:

document.getElementById("myDIV").style.display = "none";

and in jquery:

$("#myDIV").css({display: "none"});
$("#myDIV").css({display: "block"});

and you can use:


How to recursively find the latest modified file in a directory?

find . -type f -printf '%T@ %p\n' \
| sort -n | tail -1 | cut -f2- -d" "

For a huge tree, it might be hard for sort to keep everything in memory.

%T@ gives you the modification time like a unix timestamp, sort -n sorts numerically, tail -1 takes the last line (highest timestamp), cut -f2 -d" " cuts away the first field (the timestamp) from the output.

Edit: Just as -printf is probably GNU-only, ajreals usage of stat -c is too. Although it is possible to do the same on BSD, the options for formatting is different (-f "%m %N" it would seem)

And I missed the part of plural; if you want more then the latest file, just bump up the tail argument.

Integrating Dropzone.js into existing HTML form with other fields

You can modify the formData by catching the 'sending' event from your dropzone.

dropZone.on('sending', function(data, xhr, formData){
        formData.append('fieldname', 'value');

Python how to plot graph sine wave

This is another option

#!/usr/bin/env python

import numpy as np
import matplotlib
matplotlib.use('TKAgg') #use matplotlib backend TkAgg (optional)
import matplotlib.pyplot as plt

sample_rate = 200 # sampling frequency in Hz (atleast 2 times f)
t = np.linspace(0,5,sample_rate)    #time axis
f = 100 #Signal frequency in Hz
sig = np.sin(2*np.pi*f*(t/sample_rate))

Pandas: create two new columns in a dataframe with values calculated from a pre-existing column

I'd just use zip:

In [1]: from pandas import *

In [2]: def calculate(x):
   ...:     return x*2, x*3

In [3]: df = DataFrame({'a': [1,2,3], 'b': [2,3,4]})

In [4]: df
   a  b
0  1  2
1  2  3
2  3  4

In [5]: df["A1"], df["A2"] = zip(*df["a"].map(calculate))

In [6]: df
   a  b  A1  A2
0  1  2   2   3
1  2  3   4   6
2  3  4   6   9

CORS Access-Control-Allow-Headers wildcard being ignored?

I found that Access-Control-Allow-Headers: * should be set ONLY for OPTIONS request. If you return it for POST request then browser cancel the request (at least for chrome)

The following PHP code works for me

// Allow CORS
if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');    
    header("Access-Control-Allow-Methods: GET, POST, OPTIONS"); 
// Access-Control headers are received during OPTIONS requests
    header("Access-Control-Allow-Headers: *");

I found similar questions with some misleading response:

  • Server thread says that this is 2 years bug of chrome: Access-Control-Allow-Headers does not match with localhost. It's wrong: I can use CORS to my local server with Post normally
  • Access-Control-Allow-Headers does accept wildcards. It's also wrong, wildcard works for me (I tested only with Chrome)

This take me half day to figure out the issue.

Happy coding

What does %s mean in a python format string?

In answer to your second question: What does this code do?...

This is fairly standard error-checking code for a Python script that accepts command-line arguments.

So the first if statement translates to: if you haven't passed me an argument, I'm going to tell you how you should pass me an argument in the future, e.g. you'll see this on-screen:

Usage: database-name

The next if statement checks to see if the 'database-name' you passed to the script actually exists on the filesystem. If not, you'll get a message like this:

ERROR: Database database-name was not found!

From the documentation:

argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string '-c'. If no script name was passed to the Python interpreter, argv[0] is the empty string.

matplotlib colorbar for scatter

Here is the OOP way of adding a colorbar:

fig, ax = plt.subplots()
im = ax.scatter(x, y, c=c)
fig.colorbar(im, ax=ax)

Finding the median of an unsorted array

Quickselect works in O(n), this is also used in the partition step of Quicksort.

Mysql command not found in OS X 10.7

If you installed MySQL Server and you still get

mysql -u root -p command not found

You're most likely experiencing this because you have an older mac version.

Try this:

in the home directory in terminal open -t .bash_profile

paste export PATH=${PATH}:/usr/local/mysql/bin/ inside and save it

instead of writing mysql -u root -p paste the following in your terminal:

/usr/local/mysql/bin/mysql -u root -p 

Enter your password. Now you're in.

How to set the title of UIButton as left alignment?

For Swift 2.0:

emailBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left  

This can help if any one needed.

setAttribute('display','none') not working

It works for me

setAttribute('style', 'display:none');

Gradle version 2.2 is required. Current version is 2.10

I Had similar issue. Every project has his own gradle folder, check if in your project root there's another gradle folder:


If so, in every folder you'll find /gradle/wrapper/

Check if in /my_projects_root_folder/gradle/ gradle version at least match /my_projects_root_folder/ project/ gradle/ gradle version

Or just delete/rename your /my_projects_root_folder/gradle and restart android studio and let Gradle sync work and download required gradle.

Select every Nth element in CSS

You need the correct argument for the nth-child pseudo class.

  • The argument should be in the form of an + b to match every ath child starting from b.

  • Both a and b are optional integers and both can be zero or negative.

    • If a is zero then there is no "every ath child" clause.
    • If a is negative then matching is done backwards starting from b.
    • If b is zero or negative then it is possible to write equivalent expression using positive b e.g. 4n+0 is same as 4n+4. Likewise 4n-1 is same as 4n+3.


Select every 4th child (4, 8, 12, ...)

li:nth-child(4n) {_x000D_
  background: yellow;_x000D_

Select every 4th child starting from 1 (1, 5, 9, ...)

li:nth-child(4n+1) {_x000D_
  background: yellow;_x000D_

Select every 3rd and 4th child from groups of 4 (3 and 4, 7 and 8, 11 and 12, ...)

/* two selectors are required */_x000D_
li:nth-child(4n+4) {_x000D_
  background: yellow;_x000D_

Select first 4 items (4, 3, 2, 1)

/* when a is negative then matching is done backwards  */_x000D_
li:nth-child(-n+4) {_x000D_
  background: yellow;_x000D_

Professional jQuery based Combobox control?

Sexy-Combo has been deprecated. Further development exists in the Unobtrusive Fast-Filter Dropdown project. Looks promising, as i have similar requirements.

How do I show a console output/window in a forms application?

Building on Chaz's answer, in .NET 5 there is a breaking change, so two modifications are required in the project file, i.e. changing OutputType and adding DisableWinExeOutputInference. Example:


What is causing ERROR: there is no unique constraint matching given keys for referenced table?

In postgresql all foreign keys must reference a unique key in the parent table, so in your bar table you must have a unique (name) index.

See also and specifically:

Finally, we should mention that a foreign key must reference columns that either are a primary key or form a unique constraint.

Emphasis mine.

How to declare string constants in JavaScript?

You can use freeze method of Object to create a constant. For example:

var configObj ={timeOut :36000};

In this way you can not alter the configObj.

Altering a column to be nullable

Assuming SQL Server (based on your previous questions):

ALTER TABLE Merchant_Pending_Functions ALTER COLUMN NumberOfLocations INT NULL

Replace INT with your actual datatype.

Rails 3 check if attribute changed

Above answers are better but yet for knowledge we have another approch as well, Lets 'catagory' column value changed for an object (@design),


The .changes will return a hash with key as column's name and values as a array with two values [old_value, new_value] for each columns. For example catagory for above is changed from 'ABC' to 'XYZ' of @design,

@design.changes   # => {} 
@design.catagory = 'XYZ'
@design.changes # => { 'catagory' => ['ABC', 'XYZ'] }

For references change in ROR

Replace part of a string with another string

I'm just now learning C++, but editing some of the code previously posted, I'd probably use something like this. This gives you the flexibility to replace 1 or multiple instances, and also lets you specify the start point.

using namespace std;

// returns number of replacements made in string
long strReplace(string& str, const string& from, const string& to, size_t start = 0, long count = -1) {
    if (from.empty()) return 0;

    size_t startpos = str.find(from, start);
    long replaceCount = 0;

    while (startpos != string::npos){
        str.replace(startpos, from.length(), to);
        startpos += to.length();

        if (count > 0 && replaceCount >= count) break;
        startpos = str.find(from, startpos);

    return replaceCount;

Adding a new SQL column with a default value

Like this?

ALTER TABLE `tablename` ADD `new_col_name` INT NOT NULL DEFAULT 0;

Microsoft.ReportViewer.Common Version=

I worked on this issue for a few days. Installed all packages, modified web.config and still had the same problem. I finally removed

<add assembly="Microsoft.ReportViewer.Common, Version=, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />

from the web.config and it worked. No exactly sure why it didn't work with the tags in the web.config file. My guess there is a conflict with the GAC and the BIN folder.

Here is my web.config file:

<?xml version="1.0"?>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
      <add verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />     
    <validation validateIntegratedModeConfiguration="false" />
      <add name="ReportViewerWebControlHandler" preCondition="integratedMode" verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />      

Generating random numbers with Swift

I'm late to the party

Using a function that allows you to change the size of the array and the range selection on the fly is the most versatile method. You can also use map so it's very concise. I use it in all of my performance testing/bench marking.

elements is the number of items in the array
only including numbers from 0...max

func randArr(_ elements: Int, _ max: Int) -> [Int] {
        return (0..<elements).map{ _ in Int.random(in: 0...max) }

Code Sense / Placeholders look like this. randArr(elements: Int, max: Int)

10 elements in my array ranging from 0 to 1000.

randArr(10, 1000) // [554, 8, 54, 87, 10, 33, 349, 888, 2, 77]

Atom menu is missing. How do I re-enable

Get cursor on top, where white header with file name, then press Alt. To set top menu by default always visible. You needed in top menu selected: FILE -> Config... -> autoHideMenuBar: true (change it to autoHideMenuBar: false) Save it.

Invoking a static method using reflection

Fromthe Javadoc of Method.invoke():

If the underlying method is static, then the specified obj argument is ignored. It may be null.

What happens when you

Class klass = ...;
Method m = klass.getDeclaredMethod(methodName, paramtypes);
m.invoke(null, args)

Vertical align in bootstrap table

vetrical-align: middle did not work for me for some reason (and it was being applied). I used this:

table.vertical-align > tbody > tr > td {
  display: flex;
  align-items: center;

Is it correct to use alt tag for an anchor link?

For anchors, you should use title instead. alt is not valid atribute of a. See

How do you change library location in R?

I'm late to the party but I encountered the same thing when I tried to get fancy and move my library and then had files being saved to a folder that was outdated:

.libloc <<- "C:/Program Files/rest_of_your_Library_FileName"

One other point to mention is that for Windows Computers, if you copy the address from Windows Explorer, you have to manually change the '\' to a '/' for the directory to be recognized.

How to increase font size in NeatBeans IDE?

1st Way:

press down Alt+z and scroll up or down (mouse wheel)

2nd way:

press down mouse scroll(wheel) button and scroll up or down

How to stop text from taking up more than 1 line?

Using ellipsis will add the ... at the last.

   <style type="text/css">
    div {
      white-space: nowrap;
      overflow: hidden;
text-overflow: ellipsis;

Difference between InvariantCulture and Ordinal string comparison

Always try to use InvariantCulture in those string methods that accept it as overload. By using InvariantCulture you are on a safe side. Many .NET programmers may not use this functionality but if your software will be used by different cultures, InvariantCulture is an extremely handy feature.

What is the main purpose of setTag() getTag() methods of View?

We can use setTag() and getTag() to set and get custom objects as per our requirement. The setTag() method takes an argument of type Object, and getTag() returns an Object.

For example,

Person p = new Person();

How to include js and CSS in JSP with spring MVC

In a situation where you are using just spring and not spring mvc, take the following approach.

Place the following in servlet dispatcher

<mvc:annotation-driven />               
<mvc:resources mapping="/css/**" location="/WEB-INF/assets/css/"/>
<mvc:resources mapping="/js/**" location="/WEB-INF/assets/js/"/>

As you will notice /css for stylesheet location, doesn't have to be in /resources folder if you don't have the folder structure required for spring mvc as is the case with a spring application.Same applies to javascript files, fonts if you need them etc.

You can then access the resources as you need them like so

<link rel="stylesheet" href="css/vendor/swiper.min.css" type="text/css" />
<link rel="stylesheet" href="css/styles.css" type="text/css" />

I am sure someone will find this useful as most examples are with spring mvc

Why can't Visual Studio find my DLL?

Specifying the path to the DLL file in your project's settings does not ensure that your application will find the DLL at run-time. You only told Visual Studio how to find the files it needs. That has nothing to do with how the program finds what it needs, once built.

Placing the DLL file into the same folder as the executable is by far the simplest solution. That's the default search path for dependencies, so you won't need to do anything special if you go that route.
To avoid having to do this manually each time, you can create a Post-Build Event for your project that will automatically copy the DLL into the appropriate directory after a build completes.

Alternatively, you could deploy the DLL to the Windows side-by-side cache, and add a manifest to your application that specifies the location.

Is there a way to create and run javascript in Chrome?

You should write in file:

     //write your JavaScript code here

save it with .html extension and open with browser.

For example:

// this is test.html
   var a = 5;
   function incr(arg){
       return arg;

How to automatically reload a page after a given period of inactivity

<script type="text/javascript">
  var timeout = setTimeout("location.reload(true);",600000);
  function resetTimeout() {
    timeout = setTimeout("location.reload(true);",600000);

Above will refresh the page every 10 minutes unless resetTimeout() is called. For example:

<a href="javascript:;" onclick="resetTimeout();">clicky</a>

Days between two dates?

Referencing my comments on other answers. This is how I would work out the difference in days based on 24 hours and calender days. the days attribute works well for 24 hours and the function works best for calendar checks.

from datetime import timedelta, datetime

def cal_days_diff(a,b):

    A = a.replace(hour = 0, minute = 0, second = 0, microsecond = 0)
    B = b.replace(hour = 0, minute = 0, second = 0, microsecond = 0)
    return (A - B).days

if __name__ == '__main__':

    x = datetime(2013, 06, 18, 16, 00)
    y = datetime(2013, 06, 19, 2, 00)

    print (y - x).days          # 0
    print cal_days_diff(y, x)   # 1 

    z = datetime(2013, 06, 20, 2, 00)

    print (z - x).days          # 1
    print cal_days_diff(z, x)   # 2 

How to pop an alert message box using PHP?

You need some JS to achieve this by simply adding alert('Your message') within your PHP code.

See example below


//my other php code here
        function function_alert() { 
            // Display the alert box; note the Js tags within echo, it performs the magic
            echo "<script>alert('Your message Here');</script>"; 

when you visit your browser using the route supposed to triger your function_alert, you will see the alert box with your message displayed on your screen.


How do you follow an HTTP Redirect in Node.js?

Is there a wrapper module on top of the http to more easily handle processing http responses from a node application?


Redirection logic in request

C# Validating input for textbox on winforms

With WinForms you can use the ErrorProvider in conjunction with the Validating event to handle the validation of user input. The Validating event provides the hook to perform the validation and ErrorProvider gives a nice consistent approach to providing the user with feedback on any error conditions.

What exactly is a Maven Snapshot and why do we need it?

A Maven SNAPSHOT is an artifact created by a Maven build and pretends to help developers in the software development cycle. A SNAPSHOT is an artifact (or project build result ) that is not pretended to be used anywhere, it's only a temporarily .jar, ear, ... created to test the build process or to test new requirements that are not yet ready to go to a production environment. After you are happy with the SNAPSHOT artifact quality, you can create a RELEASE artifact that can be used by other projects or can be deployed itself.

In your project, you can define a SNAPSHOT using the version element in the pom.xml file of Maven:

<description>Maven pom example</description>

If you want to understand better Maven you can look into these articles too:

get dictionary value by key

          private void button2_Click(object sender, EventArgs e)
                Dictionary<string, string> Data_Array = new Dictionary<string, string>();
                Data_Array.Add("XML_File", "Settings.xml");

          static void XML_Array(Dictionary<string, string> Data_Array)
                String xmlfile = Data_Array["XML_File"];

The cause of "bad magic number" error when loading a workspace and how to avoid it?

If you are working with devtools try to save the files with:

devtools::use_data(x, internal = TRUE)

Then, delete all files saved previously.

From doc:

internal If FALSE, saves each object in individual .rda files in the data directory. These are available whenever the package is loaded. If TRUE, stores all objects in a single R/sysdata.rda file. These objects are only available within the package.

Can't load AMD 64-bit .dll on a IA 32-bit platform

If you are still getting that error after installing the 64 bit JRE, it means that the JVM running Gurobi package is still using the 32 bit JRE.

Check that you have updated the PATH and JAVA_HOME globally and in the command shell that you are using. (Maybe you just need to exit and restart it.)

Check that your command shell runs the right version of Java by running "java -version" and checking that it says it is a 64bit JRE.

If you are launching the example via a wrapper script / batch file, make sure that the script is using the right JRE. Modify as required ...

CSS text-align: center; is not centering things

I don't Know you use any Bootstrap version but the useful helper class for centering and block an element in center it is .center-block because this class contain margin and display CSS properties but the .text-center class only contain the text-align property

Bootstrap Helper Class center-block

How to Make A Chevron Arrow Using CSS?

An other approach using borders and no CSS3 properties :

div, div:after{_x000D_
    border-width: 80px 0 80px 80px;_x000D_
    border-color: transparent transparent transparent #000;_x000D_
    left:-115px; top:-80px;_x000D_

How do I comment on the Windows command line?

Lines starting with "rem" (from the word remarks) are comments:

rem comment here
echo "hello"

Handling warning for possible multiple enumeration of IEnumerable

First off, that warning does not always mean so much. I usually disabled it after making sure it's not a performance bottle neck. It just means the IEnumerable is evaluated twice, wich is usually not a problem unless the evaluation itself takes a long time. Even if it does take a long time, in this case your only using one element the first time around.

In this scenario you could also exploit the powerful linq extension methods even more.

var firstObject = objects.First();
return DoSomeThing(firstObject).Concat(DoSomeThingElse(objects).ToList();

It is possible to only evaluate the IEnumerable once in this case with some hassle, but profile first and see if it's really a problem.

C#/Linq: Apply a mapping function to each element in an IEnumerable?

You're looking for Select which can be used to transform\project the input sequence:

IEnumerable<string> strings = integers.Select(i => i.ToString());

Change navbar color in Twitter Bootstrap

In this navbar CSS, set to own color:

/* Navbar */_x000D_
.navbar-default {_x000D_
    background-color: #F8F8F8;_x000D_
    border-color: #E7E7E7;_x000D_
/* Title */_x000D_
.navbar-default .navbar-brand {_x000D_
    color: #777;_x000D_
.navbar-default .navbar-brand:hover,_x000D_
.navbar-default .navbar-brand:focus {_x000D_
    color: #5E5E5E;_x000D_
/* Link */_x000D_
.navbar-default .navbar-nav > li > a {_x000D_
    color: #777;_x000D_
.navbar-default .navbar-nav > li > a:hover,_x000D_
.navbar-default .navbar-nav > li > a:focus {_x000D_
    color: #333;_x000D_
.navbar-default .navbar-nav > .active > a, _x000D_
.navbar-default .navbar-nav > .active > a:hover, _x000D_
.navbar-default .navbar-nav > .active > a:focus {_x000D_
    color: #555;_x000D_
    background-color: #E7E7E7;_x000D_
.navbar-default .navbar-nav > .open > a, _x000D_
.navbar-default .navbar-nav > .open > a:hover, _x000D_
.navbar-default .navbar-nav > .open > a:focus {_x000D_
    color: #555;_x000D_
    background-color: #D5D5D5;_x000D_
/* Caret */_x000D_
.navbar-default .navbar-nav > .dropdown > a .caret {_x000D_
    border-top-color: #777;_x000D_
    border-bottom-color: #777;_x000D_
.navbar-default .navbar-nav > .dropdown > a:hover .caret,_x000D_
.navbar-default .navbar-nav > .dropdown > a:focus .caret {_x000D_
    border-top-color: #333;_x000D_
    border-bottom-color: #333;_x000D_
.navbar-default .navbar-nav > .open > a .caret, _x000D_
.navbar-default .navbar-nav > .open > a:hover .caret, _x000D_
.navbar-default .navbar-nav > .open > a:focus .caret {_x000D_
    border-top-color: #555;_x000D_
    border-bottom-color: #555;_x000D_

How to truncate float values?

Most answers are way too complicated in my opinion, how about this?

digits = 2  # Specify how many digits you want

fnum = '122.485221'
truncated_float = float(fnum[:fnum.find('.') + digits + 1])

>>> 122.48

Simply scanning for the index of '.' and truncate as desired (no rounding). Convert string to float as final step.

Or in your case if you get a float as input and want a string as output:

fnum = str(122.485221)  # convert float to string first
truncated_float = fnum[:fnum.find('.') + digits + 1]  # string output

How to check command line parameter in ".bat" file?

I've been struggling recently with the implementation of complex parameter switches in a batch file so here is the result of my research. None of the provided answers are fully safe, examples:

"%1"=="-?" will not match if the parameter is enclosed in quotes (needed for file names etc.) or will crash if the parameter is in quotes and has spaces (again often seen in file names)

echo starting parameter test...
rem echo First parameter is %1
if "%1"=="-?" (echo Condition is true, param=%1) else (echo Condition is false, param=%1)
C:\>test.bat -?

starting parameter test...

Condition is true, param=-?

C:\>test.bat "-?"

starting parameter test...

Condition is false, param="-?"

Any combination with square brackets [%1]==[-?] or [%~1]==[-?] will fail in case the parameter has spaces within quotes:

echo starting parameter test...
echo First parameter is %1
if [%~1]==[-?] (echo Condition is true, param=%1) else (echo Condition is false, param=%1)

C:\>test.bat "long file name"

starting parameter test...

First parameter is "long file name"
file was unexpected at this time.

The proposed safest solution "%~1"=="-?" will crash with a complex parameter that includes text outside the quotes and text with spaces within the quotes:

echo starting parameter test...
echo First parameter is %1
if "%~1"=="-?" (echo Condition is true, param=%1) else (echo Condition is false, param=%1)

C:\>test.bat -source:"long file name"

starting parameter test...

First parameter is -source:"long file name"
file was unexpected at this time.

The only way to ensure all above scenarios are covered is to use EnableDelayedExpansion and to pass the parameters by reference (not by value) using variables. Then even the most complex scenario will work fine:

SETLOCAL EnableDelayedExpansion
echo starting parameter test...
echo First parameter is %1
:: we assign the parameter to a variable to pass by reference with delayed expansion
set "var1=%~1"
echo var1 is !var1!
:: we assign the value to compare with to a second variable to pass by reference with delayed expansion
set "var2=-source:"c:\app images"\image.png"
echo var2 is !var2!
if "!var1!"=="!var2!" (echo Condition is true, param=!var1!) else (echo Condition is false, param=!var1!)
C:\>test.bat -source:"c:\app images"\image.png

starting parameter test...

First parameter is -source:"c:\app images"\image.png
var1 is -source:"c:\app images"\image.png
var2 is -source:"c:\app images"\image.png
Condition is true, param=-source:"c:\app images"\image.png

C:\>test.bat -source:"c:\app images"\image1.png

starting parameter test...

First parameter is -source:"c:\app images"\image1.png
var1 is -source:"c:\app images"\image1.png
var2 is -source:"c:\app images"\image.png
Condition is false, param=-source:"c:\app images"\image1.png

C:\>test.bat -source:"c:\app images\image.png"

starting parameter test...

First parameter is -source:"c:\app images\image.png"
var1 is -source:"c:\app images\image.png"
var2 is -source:"c:\app images"\image.png
Condition is false, param=-source:"c:\app images\image.png"

How can you detect the version of a browser?

Adding my own implementation of Hermann's answer. I needed OS detection so that's been added. Also includes some ES6 code (because we have a transpiler) that you might need to ES5-ify.

detectClient() {
    let nav = navigator.appVersion,
        os = 'unknown',
        client = (() => {
            let agent = navigator.userAgent,
                engine = agent.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [],

                build = /\brv[ :]+(\d+)/g.exec(agent) || [];
                return {browser:'IE', version:(build[1] || '')};

            if(engine[1] === 'Chrome'){
                build = agent.match(/\bOPR\/(\d+)/);

                if(build !== null) {
                    return {browser: 'Opera', version: build[1]};

            engine = engine[2] ? [engine[1], engine[2]] : [navigator.appName, nav, '-?'];

            if((build = agent.match(/version\/(\d+)/i)) !== null) {
                engine.splice(1, 1, build[1]);

            return {
              browser: engine[0],
              version: engine[1]

    switch (true) {
        case nav.indexOf('Win') > -1:
            os = 'Windows';
        case nav.indexOf('Mac') > -1:
            os = 'MacOS';
        case nav.indexOf('X11') > -1:
            os = 'UNIX';
        case nav.indexOf('Linux') > -1:
            os = 'Linux';

    client.os = os;
    return client;

Returns: Object {browser: "Chrome", version: "50", os: "UNIX"}

Using IF..ELSE in UPDATE (SQL server 2005 and/or ACCESS 2007)

Yes you can use CASE

UPDATE table 
SET columnB = CASE fieldA 
        WHEN columnA=1 THEN 'x' 
        WHEN columnA=2 THEN 'y' 
        ELSE 'z' 
WHERE columnC = 1

How to Set JPanel's Width and Height?

Board.setPreferredSize(new Dimension(x, y));
//Main.add(Board, BorderLayout.CENTER);
Main.add(Board, BorderLayout.CENTER);
Main.setLocations(x, y);

Why I am Getting Error 'Channel is unrecoverably broken and will be disposed!'

I got same logcat message, just realize that string.xml value of array cannot be number/digit, but only text/alphabet is allowed.

IIS7 Settings File Locations

Also check this answer from here: Cannot manually edit applicationhost.config

The answer is simple, if not that obvious: win2008 is 64bit, notepad++ is 32bit. When you navigate to Windows\System32\inetsrv\config using explorer you are using a 64bit program to find the file. When you open the file using using notepad++ you are trying to open it using a 32bit program. The confusion occurs because, rather than telling you that this is what you are doing, windows allows you to open the file but when you save it the file's path is transparently mapped to Windows\SysWOW64\inetsrv\Config.

So in practice what happens is you open applicationhost.config using notepad++, make a change, save the file; but rather than overwriting the original you are saving a 32bit copy of it in Windows\SysWOW64\inetsrv\Config, therefore you are not making changes to the version that is actually used by IIS. If you navigate to the Windows\SysWOW64\inetsrv\Config you will find the file you just saved.

How to get around this? Simple - use a 64bit text editor, such as the normal notepad that ships with windows.

What's the difference between Visual Studio Community and other, paid versions?

There are 2 major differences.

  1. Technical
  2. Licensing

Technical, there are 3 major differences:

First and foremost, Community doesn't have TFS support.
You'll just have to use git (arguable whether this constitutes a disadvantage or whether this actually is a good thing).
Note: This is what MS wrote. Actually, you can check-in&out with TFS as normal, if you have a TFS server in the network. You just cannot use Visual Studio as TFS SERVER.

Second, VS Community is severely limited in its testing capability.
Only unit tests. No Performance tests, no load tests, no performance profiling.

Third, VS Community's ability to create Virtual Environments has been severely cut.

On the other hand, syntax highlighting, IntelliSense, Step-Through debugging, GoTo-Definition, Git-Integration and Build/Publish are really all the features I need, and I guess that applies to a lot of developers.

For all other things, there are tools that do the same job faster, better and cheaper.

If you, like me, anyway use git, do unit testing with NUnit, and use Java-Tools to do Load-Testing on Linux plus TeamCity for CI, VS Community is more than sufficient, technically speaking.


A) If you're an individual developer (no enterprise, no organization), no difference (AFAIK), you can use CommunityEdition like you'd use the paid edition (as long as you don't do subcontracting)
B) You can use CommunityEdition freely for OpenSource (OSI) projects
C) If you're an educational insitution, you can use CommunityEdition freely (for education/classroom use)
D) If you're an enterprise with 250 PCs or users or more than one million US dollars in revenue (including subsidiaries), you are NOT ALLOWED to use CommunityEdition.
E) If you're not an enterprise as defined above, and don't do OSI or education, but are an "enterprise"/organization, with 5 or less concurrent (VS) developers, you can use VS Community freely (but only if you're the owner of the software and sell it, not if you're a subcontractor creating software for a larger enterprise, software which in the end the enterprise will own), otherwise you need a paid edition.

The above does not consitute legal advise.
See also:

VBA copy cells value and format

Found this on OzGrid courtesy of Mr. Aaron Blood - simple direct and works.

Cells(1, 3).Copy Cells(1, 1)
Cells(1, 1).Value = Cells(1, 3).Value

However, I kinda suspect you were just providing us with an oversimplified example to ask the question. If you just want to copy formats from one range to another it looks like this...

Cells(1, 3).Copy
    Cells(1, 1).PasteSpecial (xlPasteFormats)
    Application.CutCopyMode = False

No @XmlRootElement generated by JAXB

As you know the answer is to use the ObjectFactory(). Here is a sample of the code that worked for me :)

ObjectFactory myRootFactory = new ObjectFactory();

MyRootType myRootType = myRootFactory.createMyRootType();

try {

        File file = new File("./file.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(MyRoot.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        //output pretty printed
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        JABXElement<MyRootType> myRootElement = myRootFactory.createMyRoot(myRootType);

        jaxbMarshaller.marshal(myRootElement, file);
        jaxbMarshaller.marshal(myRootElement, System.out);

    } catch (JAXBException e) {

How to get all possible combinations of a list’s elements?

I'm late to the party but would like to share the solution I found to the same issue: Specifically, I was looking to do sequential combinations, so for "STAR" I wanted "STAR", "TA", "AR", but not "SR".

lst = [S, T, A, R]
lstCombos = []
for Length in range(0,len(lst)+1):
    for i in lst:

Duplicates can be filtered with adding in an additional if before the last line:

lst = [S, T, A, R]
lstCombos = []
for Length in range(0,len(lst)+1):
    for i in lst:
         if not lst[lst.index(i):lst.index(i)+Length]) in lstCombos:

If for some reason this returns blank lists in the output, which happened to me, I added:

for subList in lstCombos:
    if subList = '':

Select all from table with Laravel and Eloquent

If your table is very big, you can also process rows by "small packages" (not all at oce) (laravel doc: Eloquent> Chunking Results )

Post::chunk(200, function($posts)
    foreach ($posts as $post)
        // process post here.

ReferenceError: event is not defined error in Firefox

You're declaring (some of) your event handlers incorrectly:

$('.menuOption').click(function( event ){ // <---- "event" parameter here

    var categories = $(this).attr('rel');


You need "event" to be a parameter to the handlers. WebKit follows IE's old behavior of using a global symbol for "event", but Firefox doesn't. When you're using jQuery, that library normalizes the behavior and ensures that your event handlers are passed the event parameter.

edit — to clarify: you have to provide some parameter name; using event makes it clear what you intend, but you can call it e or cupcake or anything else.

Note also that the reason you probably should use the parameter passed in from jQuery instead of the "native" one (in Chrome and IE and Safari) is that that one (the parameter) is a jQuery wrapper around the native event object. The wrapper is what normalizes the event behavior across browsers. If you use the global version, you don't get that.

How to resolve TypeError: Cannot convert undefined or null to object

In my case, I added Lucid extension to Chrome and didn't notice the problem at that moment. After about a day of working on the problem and turning the program upside down, in a post someone had mentioned Lucid. I remembered what I had done and removed the extension from Chrome and ran the program again. The problem was gone. I am working with React. I thought this might help.

SQL - Create view from multiple tables

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

    SELECT *

Change IPython/Jupyter notebook working directory

Usually $ ipython notebook will launch the notebooks and kernels at he current working directory of the terminal.

But if you want to specify the launch directory, you can use --notebook-dir option as follows:

$ ipython notebook --notebook-dir=/path/to/specific/directory

Binary Data in JSON String. Something better than Base64

There are 94 Unicode characters which can be represented as one byte according to the JSON spec (if your JSON is transmitted as UTF-8). With that in mind, I think the best you can do space-wise is base85 which represents four bytes as five characters. However, this is only a 7% improvement over base64, it's more expensive to compute, and implementations are less common than for base64 so it's probably not a win.

You could also simply map every input byte to the corresponding character in U+0000-U+00FF, then do the minimum encoding required by the JSON standard to pass those characters; the advantage here is that the required decoding is nil beyond builtin functions, but the space efficiency is bad -- a 105% expansion (if all input bytes are equally likely) vs. 25% for base85 or 33% for base64.

Final verdict: base64 wins, in my opinion, on the grounds that it's common, easy, and not bad enough to warrant replacement.

See also: Base91 and Base122

How do you beta test an iphone app?

Diawi Alternatives

Since have added some limitations for free accounds.

Next best available and easy to use alternative is




Happy build sharing!

What does the error "JSX element type '...' does not have any construct or call signatures" mean?

In my case, I was using React.ReactNode as a type for a functional component instead of React.FC type.

In this component to be exact:

export const PropertiesList: React.FC = (props: any) => {_x000D_
  const list:string[] = [_x000D_
    ' Consequat Phasellus sollicitudin.',_x000D_
    ' Consequat Phasellus sollicitudin.',_x000D_
  return (_x000D_
      header={<ListHeader heading="Properties List" />}_x000D_
        renderItem={(listItem, index) =>_x000D_
          <List.Item key={index}> {listItem } </List.Item>_x000D_

Best way to serialize/unserialize objects in JavaScript?

JSON has no functions as data types. You can only serialize strings, numbers, objects, arrays, and booleans (and null)

You could create your own toJson method, only passing the data that really has to be serialized:

Person.prototype.toJson = function() {
    return JSON.stringify({age: this.age});

Similar for deserializing:

Person.fromJson = function(json) {
    var data = JSON.parse(json); // Parsing the json string.
    return new Person(data.age);

The usage would be:

var serialize = p1.toJson();
var _p1 = Person.fromJson(serialize);
alert("Is old: " + _p1.isOld());

To reduce the amount of work, you could consider to store all the data that needs to be serialized in a special "data" property for each Person instance. For example:

function Person(age) { = {
        age: age
    this.isOld = function (){
        return > 60 ? true : false;

then serializing and deserializing is merely calling JSON.stringify( and setting the data of an instance would be = JSON.parse(json).

This would keep the toJson and fromJson methods simple but you'd have to adjust your other functions.

Side note:

You should add the isOld method to the prototype of the function:

Person.prototype.isOld = function() {}

Otherwise, every instance has it's own instance of that function which also increases memory.

In-place edits with sed on OS X

You can use -i'' (--in-place) for sed as already suggested. See: The -i in-place argument, however note that -i option is non-standard FreeBSD extensions and may not be available on other operating systems. Secondly sed is a Stream EDitor, not a file editor.

Alternative way is to use built-in substitution in Vim Ex mode, like:

$ ex +%s/foo/bar/g -scwq file.txt

and for multiple-files:

$ ex +'bufdo!%s/foo/bar/g' -scxa *.*

To edit all files recursively you can use **/*.* if shell supports that (enable by shopt -s globstar).

Another way is to use gawk and its new "inplace" extension such as:

$ gawk -i inplace '{ gsub(/foo/, "bar") }; { print }' file1

How to get JSON data from the URL (REST API) to UI using jQuery or plain JavaScript?

            url: `//your api url`
            type: "GET",
            dataType: "json",
            success: function(data) {
                jQuery.each(data, function(index, value) {
                        `All you API data is here`

Checking if a key exists in a JS object

map.has(key) is the latest ECMAScript 2015 way of checking the existance of a key in a map. Refer to this for complete details.

Python coding standards/best practices

To add to bhadra's list of idiomatic guides:

Checkout Anthony Baxter's presentation on Effective Python Programming (from OSON 2005).

An excerpt:

# dict's setdefault method turns this:
if key in dictobj:
    dictobj[key] = [val]
# into this:

navigator.geolocation.getCurrentPosition sometimes works sometimes doesn't

I found, that this way doesn't work

navigator.geolocation.getCurrentPosition(function() {...}, function(err) {...}, {});


this way works perfect

function storeCoordinates(position) {
    console.log(position.coords.latitude, position.coords.longitude);

function errorHandler() {...}

navigator.geolocation.getCurrentPosition(storeCoordinates, errorHandler, { enableHighAccuracy: true, timeout: 20000, maximumAge: 0 });

dll missing in JDBC

You have to make sure your DLL is in the classpath.

One such way to do so is to put the path to the DLL in PATH environment variable.

Other option is to add it to the VM arguments in the variable LD_LIBRARY_PATH, like this:

java -Djava.library.path=/path/to/my/dll -cp /my/classpath/goes/here MainClass

'mvn' is not recognized as an internal or external command,

Make sure you have your maven bin directory in the path and the JAVA_HOME property set

Send form data using ajax

I have written myself a function that converts most of the stuff one may want to send via AJAX to GET of POST query.
Following part of the function might be of interest:

  if(data.tagName!=null&&data.tagName.toUpperCase()=="FORM") {
    //Get all the input elements in form
    var elem = data.elements;
    //Loop through the element array
    for(var i = 0; i < elem.length; i++) {
      //Ignore elements that are not supposed to be sent
      //Add & to any subsequent entries (that means every iteration except the first one) 
      //Get data for selectbox
      if (elem[i].tagName.toUpperCase() == "SELECT")
        data_string += elem[i].name + "=" + encodeURIComponent(elem[i].options[elem[i].selectedIndex].value) ;
      //Get data from checkbox
      else if(elem[i].type=="checkbox")
        data_string += elem[i].name + "="+(elem[i].value==null?"on":elem[i].value);
      //Get data from textfield
        data_string += elem[i].name + (elem[i].value!=""?"=" + encodeURIComponent(elem[i].value):"=");
    return data_string; 

It does not need jQuery since I don't use it. But I'm sure jquery's $.post accepts string as seconf argument.

Here is the whole function, other parts are not commented though. I can't promise there are no bugs in it:

function ajax_create_request_string(data, recursion) {
  var data_string = '';
  //Zpracovani formulare
  if(data.tagName!=null&&data.tagName.toUpperCase()=="FORM") {
    //Get all the input elements in form
    var elem = data.elements;
    //Loop through the element array
    for(var i = 0; i < elem.length; i++) {
      //Ignore elements that are not supposed to be sent
      //Add & to any subsequent entries (that means every iteration except the first one) 
      //Get data for selectbox
      if (elem[i].tagName.toUpperCase() == "SELECT")
        data_string += elem[i].name + "=" + encodeURIComponent(elem[i].options[elem[i].selectedIndex].value) ;
      //Get data from checkbox
      else if(elem[i].type=="checkbox")
        data_string += elem[i].name + "="+(elem[i].value==null?"on":elem[i].value);
      //Get data from textfield
        if(elem[i].className.indexOf("autoempty")!=-1) {
          data_string += elem[i].name+"=";
          data_string += elem[i].name + (elem[i].value!=""?"=" + encodeURIComponent(elem[i].value):"=");
    return data_string; 
  //Loop through array
  if(data instanceof Array) {
    for(var i=0; i<data.length; i++) {
    return data_string;
  //Loop through object (like foreach)
  for(var i in data) {
    if(typeof data[i]=="object") {
        data_string+= ajax_create_request_string(data[i], i);
        data_string+= ajax_create_request_string(data[i], recursion+"["+i+"]");
    else if(recursion==null)
  return data_string;

How do I tell Gradle to use specific JDK version?

If you are using linux and gradle wrapper you can use following solution.

Add path to file:

javaHome=<path to JDK>

Add to your gradlew script file:

DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
source $DIR/ 2>/dev/null

if ! [ -z "$javaHome" ]

In this solution, each developer can set his own JDK path. File shouldn't be included in version control system.

Finding the length of a Character Array in C

You can use strlen


You can code it yourself so you understand how it works

size_t my_strlen(const char *str)
  size_t i;

  for (i = 0; str[i]; i++);
  return i;

if you want the size of the array then you use sizeof

char urarray[255];
printf("%zu", sizeof(urarray));

"ImportError: No module named" when trying to run Python script

This kind of errors occurs most probably due to python version conflicts. For example, if your application runs only on python 3 and you got python 2 as well, then it's better to specify which version to use. For example use

python3 .....

instead of


Spring Boot - Loading Initial Data

You can create a data.sql file in your src/main/resources folder and it will be automatically executed on startup. In this file you can add some insert statements, eg.:

INSERT INTO users (username, firstname, lastname) VALUES
  ('lala', 'lala', 'lala'),
  ('lolo', 'lolo', 'lolo');

Similarly, you can create a schema.sql file (or schema-h2.sql) as well to create your schema:

  id          INTEGER PRIMARY KEY,
  description VARCHAR(64) NOT NULL,
  completed   BIT NOT NULL);

Though normally you shouldn't have to do this since Spring boot already configures Hibernate to create your schema based on your entities for an in memory database. If you really want to use schema.sql you'll have to disable this feature by adding this to your


More information can be found at the documentation about Database initialization.

If you're using Spring boot 2, database initialization only works for embedded databases (H2, HSQLDB, ...). If you want to use it for other databases as well, you need to change the spring.datasource.initialization-mode property:


If you're using multiple database vendors, you can name your file data-h2.sql or data-mysql.sql depending on which database platform you want to use.

To make that work, you'll have to configure the spring.datasource.platform property though:


Why does using an Underscore character in a LIKE filter give me all the results?

The underscore is the wildcard in a LIKE query for one arbitrary character.

Hence LIKE %_% means "give me all records with at least one arbitrary character in this column".

You have to escape the wildcard character, in sql-server with [] around:

FROM Manager m 
WHERE m.managerid    LIKE  '[_]%'
AND   m.managername  LIKE '%[_]%'

See: LIKE (Transact-SQL)


Print commit message of a given commit in git

It's not "plumbing", but it'll do exactly what you want:

$ git log --format=%B -n 1 <commit>

If you absolutely need a "plumbing" command (not sure why that's a requirement), you can use rev-list:

$ git rev-list --format=%B --max-count=1 <commit>

Although rev-list will also print out the commit sha (on the first line) in addition to the commit message.

Constructor overload in TypeScript

Note that you can also work around the lack of overloading at the implementation level through default parameters in TypeScript, e.g.:

interface IBox {    
    x : number;
    y : number;
    height : number;
    width : number;

class Box {
    public x: number;
    public y: number;
    public height: number;
    public width: number;

    constructor(obj : IBox = {x:0,y:0, height:0, width:0}) {    
        this.x = obj.x;
        this.y = obj.y;
        this.height = obj.height;
        this.width = obj.width;

Edit: As of Dec 5 '16, see Benson's answer for a more elaborate solution that allows more flexibility.

How to use jquery $.post() method to submit form values

Yor $.post has no data. You need to pass the form data. You can use serialize() to post the form data. Try this

    $.post("process.php", $('#reg-form').serialize() ,function(data){

Multiple files upload (Array) with CodeIgniter 2.0

All Posted files will be come in $_FILES variable, for use codeigniter upload library we need to give field_name that we are using in for upload (by default it will be 'userfile'), so we get all posted file and create another files array that create our own name for each files, and give this name to codeigniter library do_upload function.

    $j = 1;                 
    foreach($_FILES as $filekey=>$fileattachments){
        foreach($fileattachments as $key=>$val){
                $i = 1;
                foreach($val as $v){
                    $field_name = "multiple_".$filekey."_".$i;
                    $_FILES[$field_name][$key] = $v;
                $field_name = "single_".$filekey."_".$j;
                $_FILES[$field_name] = $fileattachments;
        // Unset the useless one 
    foreach($_FILES as $field_name => $file){
        if(isset($file['error']) && $file['error']==0){
            $config['upload_path'] = [upload_path];
            $config['allowed_types'] = [allowed_types];
            $config['max_size'] = 100;
            $config['max_width'] = 1024;
            $config['max_height'] = 768;
            $this->load->library('upload', $config);

            if ( ! $this->upload->do_upload($field_name)){
                $error = array('error' => $this->upload->display_errors());
                echo "Error Message : ". $error['error'];
                $data = $this->upload->data();
                echo "Uploaded FileName : ".$data['file_name'];
                // Code for insert into database

How to check Grants Permissions at Run-Time?

You can also query by following code snippet as backward compatible;

int hasPermission = ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_CONTACTS);
if (hasPermission == PackageManager.PERMISSION_GRANTED) {
    //Do smthng

Python circular importing?

I was able to import the module within the function (only) that would require the objects from this module:

def my_func():
    import Foo
    foo_instance = Foo()

Error "package does not exist"

After Rebuild the project issue resolved..

What's the better (cleaner) way to ignore output in PowerShell?

There is also the Out-Null cmdlet, which you can use in a pipeline, for example, Add-Item | Out-Null.

Manual page for Out-Null


    Deletes output instead of sending it to the console.

    Out-Null [-inputObject <psobject>] [<CommonParameters>]

    The Out-Null cmdlet sends output to NULL, in effect, deleting it.


     For more information, type: "get-help Out-Null -detailed".
     For technical information, type: "get-help Out-Null -full".

Import/Index a JSON file into Elasticsearch

Per the current docs,

If you’re providing text file input to curl, you must use the --data-binary flag instead of plain -d. The latter doesn’t preserve newlines.


$ curl -s -XPOST localhost:9200/_bulk --data-binary @requests

Div side by side without float

A div is a block level element, meaning that will behave as a block, and blocks can't stay side by side without being floated. You can however set them to inline elements with:


Give it a try...

Another way is to place them using:




Note: For this to work as expected, the wrapper element must have a position:relative; so that the elements with absolute positioning stay relative to their wrapper element.

How do I change the font color in an html table?

if you need to change specific option from the select menu you can do it like this

option[value="Basic"] {

or you can change them all

select {

Authentication failed because remote party has closed the transport stream

I would advise against restricting the SecurityProtocol to TLS 1.1.

The recommended solution is to use

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls

Another option is add the following Registry key:

Key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319 
Value: SchUseStrongCrypto 

It is worth noting that .NET 4.6 will use the correct protocol by default and does not require either solution.

How to read a file in other directory in python

In case you're not in the specified directory (i.e. direct), you should use (in linux):

x_file = open('path/to/direct/filename.txt')

Note the quotes and the relative path to the directory.

This may be your problem, but you also don't have permission to access that file. Maybe you're trying to open it as another user.

How do I check for a network connection?

The marked answer is 100% fine, however, there are certain cases when the standard method is fooled by virtual cards (virtual box, ...). It's also often desirable to discard some network interfaces based on their speed (serial ports, modems, ...).

Here is a piece of code that checks for these cases:

    /// <summary>
    /// Indicates whether any network connection is available
    /// Filter connections below a specified speed, as well as virtual network cards.
    /// </summary>
    /// <returns>
    ///     <c>true</c> if a network connection is available; otherwise, <c>false</c>.
    /// </returns>
    public static bool IsNetworkAvailable()
        return IsNetworkAvailable(0);

    /// <summary>
    /// Indicates whether any network connection is available.
    /// Filter connections below a specified speed, as well as virtual network cards.
    /// </summary>
    /// <param name="minimumSpeed">The minimum speed required. Passing 0 will not filter connection using speed.</param>
    /// <returns>
    ///     <c>true</c> if a network connection is available; otherwise, <c>false</c>.
    /// </returns>
    public static bool IsNetworkAvailable(long minimumSpeed)
        if (!NetworkInterface.GetIsNetworkAvailable())
            return false;

        foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
            // discard because of standard reasons
            if ((ni.OperationalStatus != OperationalStatus.Up) ||
                (ni.NetworkInterfaceType == NetworkInterfaceType.Loopback) ||
                (ni.NetworkInterfaceType == NetworkInterfaceType.Tunnel))

            // this allow to filter modems, serial, etc.
            // I use 10000000 as a minimum speed for most cases
            if (ni.Speed < minimumSpeed)

            // discard virtual cards (virtual box, virtual pc, etc.)
            if ((ni.Description.IndexOf("virtual", StringComparison.OrdinalIgnoreCase) >= 0) ||
                (ni.Name.IndexOf("virtual", StringComparison.OrdinalIgnoreCase) >= 0))

            // discard "Microsoft Loopback Adapter", it will not show as NetworkInterfaceType.Loopback but as Ethernet Card.
            if (ni.Description.Equals("Microsoft Loopback Adapter", StringComparison.OrdinalIgnoreCase))

            return true;
        return false;

unsigned APK can not be installed

I did not know that even with the "Allow Installation of non-Marked application", I still needed to sign the application.

I self-signed my application, following this link self-sign and release application, It only took 5 minutes, then I emailed the signed-APK file to myself and downloaded it to SD-card and then installed it without any problem.

Creating multiple log files of different content with log4j

Perhaps something like this?

<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="">
 <!-- general application log -->
 <appender name="MainLogFile" class="org.apache.log4j.FileAppender">
  <param name="File" value="server.log" />
  <param name="Threshold" value="INFO" />
  <layout class="org.apache.log4j.PatternLayout">
   <param name="ConversionPattern" value="%-5p %t [%-40.40c] %x - %m%n"/>
 <!-- additional fooSystem logging -->
 <appender name="FooLogFile" class="org.apache.log4j.FileAppender">
  <param name="File" value="foo.log" />
  <layout class="org.apache.log4j.PatternLayout">
   <param name="ConversionPattern" value="%-5p %t [%-40.40c] %x - %m%n"/>
 <!-- foo logging -->
 <logger name="">
  <level value="DEBUG"/>
  <appender-ref ref="FooLogFile"/>
 <!-- default logging -->
  <level value="INFO"/>
  <appender-ref ref="MainLogFile"/>

Thus, all info messages are written to server.log; by contrast, foo.log contains only messages, including debug-level messages.

Table overflowing outside of div

I tried all the solutions mentioned above, then did not work. I have 3 tables one below the other. The last one over flowed. I fixed it using:

/* Grid Definition */
table {
    word-break: break-word;

For IE11 in edge mode, you need to set this to word-break:break-all

How can I add (simple) tracing in C#?

I followed around five different answers as well as all the blog posts in the previous answers and still had problems. I was trying to add a listener to some existing code that was tracing using the TraceSource.TraceEvent(TraceEventType, Int32, String) method where the TraceSource object was initialised with a string making it a 'named source'.

For me the issue was not creating a valid combination of source and switch elements to target this source. Here is an example that will log to a file called tracelog.txt. For the following code:

TraceSource source = new TraceSource("sourceName");
source.TraceEvent(TraceEventType.Verbose, 1, "Trace message");

I successfully managed to log with the following diagnostics configuration:

        <source name="sourceName" switchName="switchName">
                    initializeData="tracelog.txt" />

        <add name="switchName" value="Verbose" />

error 1265. Data truncated for column when trying to load data from txt file

The reason is that mysql expecting end of the row symbol in the text file after last specified column, and this symbol is char(10) or '\n'. Depends on operation system where text file created or if you created your text file yourself, it can be other combination (Windows uses '\r\n' (chr(13)+chr(10)) as rows separator). Thus, if you use Windows generated text file, add following suffix to your LOAD command: “ LINES TERMINATED BY '\r\n' ”. Otherwise, check how rows are separated in your text file. On default mysql expecting char(10) as rows separator.

Vim 80 column layout concerns

I'm afraid that you've put constraints on the set of solutions that, well, leave you with the null set.

Using :set textwidth=80 will fix all of the problems you mentioned except that you can't easily see the line limit coming up. If you :set ruler, you'll enable the x,y position display on the status bar, which you can use to see which column you're in.

Aside from that, I'm not sure what to tell you. It's a shame to lose the number column, fold column and splits just because you have to :set columns=80.

Why is division in Ruby returning an integer instead of decimal value?

Fixnum#to_r is not mentioned here, it was introduced since ruby 1.9. It converts Fixnum into rational form. Below are examples of its uses. This also can give exact division as long as all the numbers used are Fixnum.

 a = 1.to_r  #=> (1/1) 
 a = 10.to_r #=> (10/1) 
 a = a / 3   #=> (10/3) 
 a = a * 3   #=> (10/1) 
 a.to_f      #=> 10.0

Example where a float operated on a rational number coverts the result to float.

a = 5.to_r   #=> (5/1) 
a = a * 5.0  #=> 25.0 

Parsing arguments to a Java command line program

You could just do it manually.

NB: might be better to use a HashMap instead of an inner class for the opts.

/** convenient "-flag opt" combination */
private class Option {
     String flag, opt;
     public Option(String flag, String opt) { this.flag = flag; this.opt = opt; }

static public void main(String[] args) {
    List<String> argsList = new ArrayList<String>();  
    List<Option> optsList = new ArrayList<Option>();
    List<String> doubleOptsList = new ArrayList<String>();

    for (int i = 0; i < args.length; i++) {
        switch (args[i].charAt(0)) {
        case '-':
            if (args[i].length < 2)
                throw new IllegalArgumentException("Not a valid argument: "+args[i]);
            if (args[i].charAt(1) == '-') {
                if (args[i].length < 3)
                    throw new IllegalArgumentException("Not a valid argument: "+args[i]);
                // --opt
                doubleOptsList.add(args[i].substring(2, args[i].length));
            } else {
                if (args.length-1 == i)
                    throw new IllegalArgumentException("Expected arg after: "+args[i]);
                // -opt
                optsList.add(new Option(args[i], args[i+1]));
            // arg
    // etc

Replace \n with actual new line in Sublime Text

For Windows line endings:

(Turn on regex - Alt+R)

Find: \\r\\n

Replace: \r\n


Version vs build in Xcode

Apple sort of rearranged/repurposed the fields.

Going forward, if you look on the Info tab for your Application Target, you should use the "Bundle versions string, short" as your Version (e.g., 3.4.0) and "Bundle version" as your Build (e.g., 500 or 1A500). If you don't see them both, you can add them. Those will map to the proper Version and Build textboxes on the Summary tab; they are the same values.

When viewing the Info tab, if you right-click and select Show Raw Keys/Values, you'll see the actual names are CFBundleShortVersionString (Version) and CFBundleVersion (Build).

The Version is usually used how you appear to have been using it with Xcode 3. I'm not sure on what level you're asking about the Version/Build difference, so I'll answer it philosophically.

There are all sorts of schemes, but a popular one is:


  • Major version - Major changes, redesigns, and functionality changes
  • Minor version - Minor improvements, additions to functionality
  • Revision - A patch number for bug-fixes

Then the Build is used separately to indicate the total number of builds for a release or for the entire product lifetime.

Many developers start the Build number at 0, and every time they build they increase the number by one, increasing forever. In my projects, I have a script that automatically increases the build number every time I build. See instructions for that below.

  • Release 1.0.0 might be build 542. It took 542 builds to get to a 1.0.0 release.
  • Release 1.0.1 might be build 578.
  • Release 1.1.0 might be build 694.
  • Release 2.0.0 might be build 949.

Other developers, including Apple, have a Build number comprised of a major version + minor version + number of builds for the release. These are the actual software version numbers, as opposed to the values used for marketing.

If you go to Xcode menu > About Xcode, you'll see the Version and Build numbers. If you hit the More Info... button you'll see a bunch of different versions. Since the More Info... button was removed in Xcode 5, this information is also available from the Software > Developer section of the System Information app, available by opening Apple menu > About This Mac > System Report....

For example, Xcode 4.2 (4C139). Marketing version 4.2 is Build major version 4, Build minor version C, and Build number 139. The next release (presumably 4.3) will likely be Build release 4D, and the Build number will start over at 0 and increment from there.

The iPhone Simulator Version/Build numbers are the same way, as are iPhones, Macs, etc.

  • 3.2: (7W367a)
  • 4.0: (8A400)
  • 4.1: (8B117)
  • 4.2: (8C134)
  • 4.3: (8H7)

Update: By request, here are the steps to create a script that runs each time you build your app in Xcode to read the Build number, increment it, and write it back to the app's {App}-Info.plist file. There are optional, additional steps if you want to write your version/build numbers to your Settings.bundle/Root*.plist file(s).

This is extended from the how-to article here.

In Xcode 4.2 - 5.0:

  1. Load your Xcode project.
  2. In the left hand pane, click on your project at the very top of the hierarchy. This will load the project settings editor.
  3. On the left-hand side of the center window pane, click on your app under the TARGETS heading. You will need to configure this setup for each project target.
  4. Select the Build Phases tab.
    • In Xcode 4, at the bottom right, click the Add Build Phase button and select Add Run Script.
    • In Xcode 5, select Editor menu > Add Build Phase > Add Run Script Build Phase.
  5. Drag-and-drop the new Run Script phase to move it to just before the Copy Bundle Resources phase (when the app-info.plist file will be bundled with your app).
  6. In the new Run Script phase, set Shell: /bin/bash.
  7. Copy and paste the following into the script area for integer build numbers:

    buildNumber=$(/usr/libexec/PlistBuddy -c "Print CFBundleVersion" "$INFOPLIST_FILE")
    buildNumber=$(($buildNumber + 1))
    /usr/libexec/PlistBuddy -c "Set :CFBundleVersion $buildNumber" "$INFOPLIST_FILE"

    As @Bdebeez pointed out, the Apple Generic Versioning Tool (agvtool) is also available. If you prefer to use it instead, then there are a couple things to change first:

    • Select the Build Settings tab.
    • Under the Versioning section, set the Current Project Version to the initial build number you want to use, e.g., 1.
    • Back on the Build Phases tab, drag-and-drop your Run Script phase after the Copy Bundle Resources phase to avoid a race condition when trying to both build and update the source file that includes your build number.

    Note that with the agvtool method you may still periodically get failed/canceled builds with no errors. For this reason, I don't recommend using agvtool with this script.

    Nevertheless, in your Run Script phase, you can use the following script:

    "${DEVELOPER_BIN_DIR}/agvtool" next-version -all

    The next-version argument increments the build number (bump is also an alias for the same thing), and -all updates Info.plist with the new build number.

  8. And if you have a Settings bundle where you show the Version and Build, you can add the following to the end of the script to update the version and build. Note: Change the PreferenceSpecifiers values to match your settings. PreferenceSpecifiers:2 means look at the item at index 2 under the PreferenceSpecifiers array in your plist file, so for a 0-based index, that's the 3rd preference setting in the array.

    productVersion=$(/usr/libexec/PlistBuddy -c "Print CFBundleShortVersionString" "$INFOPLIST_FILE")
    /usr/libexec/PlistBuddy -c "Set PreferenceSpecifiers:2:DefaultValue $buildNumber" Settings.bundle/Root.plist
    /usr/libexec/PlistBuddy -c "Set PreferenceSpecifiers:1:DefaultValue $productVersion" Settings.bundle/Root.plist

    If you're using agvtool instead of reading the Info.plist directly, you can add the following to your script instead:

    buildNumber=$("${DEVELOPER_BIN_DIR}/agvtool" what-version -terse)
    productVersion=$("${DEVELOPER_BIN_DIR}/agvtool" what-marketing-version -terse1)
    /usr/libexec/PlistBuddy -c "Set PreferenceSpecifiers:2:DefaultValue $buildNumber" Settings.bundle/Root.plist
    /usr/libexec/PlistBuddy -c "Set PreferenceSpecifiers:1:DefaultValue $productVersion" Settings.bundle/Root.plist
  9. And if you have a universal app for iPad & iPhone, then you can also set the settings for the iPhone file:

    /usr/libexec/PlistBuddy -c "Set PreferenceSpecifiers:2:DefaultValue $buildNumber" Settings.bundle/Root~iphone.plist    
    /usr/libexec/PlistBuddy -c "Set PreferenceSpecifiers:1:DefaultValue $productVersion" Settings.bundle/Root~iphone.plist

Windows batch script launch program and exit console

Use start notepad.exe.

More info with start /?.

How to cast from List<Double> to double[] in Java?

As per your question,

List<Double> frameList =  new ArrayList<Double>();
  1. First you have to convert List<Double> to Double[] by using

    Double[] array = frameList.toArray(new Double[frameList.size()]);
  2. Next you can convert Double[] to double[] using

    double[] doubleArray = ArrayUtils.toPrimitive(array);

You can directly use it in one line:

double[] array = ArrayUtils.toPrimitive(frameList.toArray(new Double[frameList.size()]));

How to set the maxAllowedContentLength to 500MB while running on IIS7?

The limit of requests in .Net can be configured from two properties together:


  • Web.Config/system.web/httpRuntime/maxRequestLength
  • Unit of measurement: kilobytes
  • Default value 4096 KB (4 MB)
  • Max. value 2147483647 KB (2 TB)


  • Web.Config/system.webServer/security/requestFiltering/requestLimits/maxAllowedContentLength (in bytes)
  • Unit of measurement: bytes
  • Default value 30000000 bytes (28.6 MB)
  • Max. value 4294967295 bytes (4 GB)



<location path="upl">
     <!--The default size is 4096 kilobytes (4 MB). MaxValue is 2147483647 KB (2 TB)-->
     <!-- 100 MB in kilobytes -->
     <httpRuntime maxRequestLength="102400" />
         <!--The default size is 30000000 bytes (28.6 MB). MaxValue is 4294967295 bytes (4 GB)-->
         <!-- 100 MB in bytes -->
         <requestLimits maxAllowedContentLength="104857600" />

Python TypeError: cannot convert the series to <class 'int'> when trying to do math on dataframe

Seems your initial data contains strings and not numbers. It would probably be best to ensure that the data is already of the required type up front.

However, you can convert strings to numbers like this:

pd.Series(['123', '42']).astype(float)

instead of float(series)

Calling the base class constructor from the derived class constructor

The base-class constructor is already automatically called by your derived-class constructor. In C++, if the base class has a default constructor (takes no arguments, can be auto-generated by the compiler!), and the derived-class constructor does not invoke another base-class constructor in its initialisation list, the default constructor will be called. I.e. your code is equivalent to:

class PetStore: public Farm
public :
    : Farm()     // <---- Call base-class constructor in initialision list
    int idF;
    string nameF;

java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient

starting the hive metastore service worked for me. First, set up the database for hive metastore:

 $ hive --service metastore 


Second, run the following commands:

 $ schematool -dbType mysql -initSchema  
 $ schematool -dbType mysql -info

Adding whitespace in Java

I think you are talking about padding strings with spaces.

One way to do this is with string format codes.

For example, if you want to pad a string to a certain length with spaces, use something like this:

String padded = String.format("%-20s", str);

In a formatter, % introduces a format sequence. The - means that the string will be left-justified (spaces will be added on the right of the string). The 20 means the resulting string will be 20 characters long. The s is the character string format code, and ends the format sequence.

How to check file MIME type with javascript before upload?

You can easily determine the file MIME type with JavaScript's FileReader before uploading it to a server. I agree that we should prefer server-side checking over client-side, but client-side checking is still possible. I'll show you how and provide a working demo at the bottom.

Check that your browser supports both File and Blob. All major ones should.

if (window.FileReader && window.Blob) {
    // All the File APIs are supported.
} else {
    // File and Blob are not supported

Step 1:

You can retrieve the File information from an <input> element like this (ref):

<input type="file" id="your-files" multiple>
var control = document.getElementById("your-files");
control.addEventListener("change", function(event) {
    // When the control has changed, there are new files
    var files = control.files,
    for (var i = 0; i < files.length; i++) {
        console.log("Filename: " + files[i].name);
        console.log("Type: " + files[i].type);
        console.log("Size: " + files[i].size + " bytes");
}, false);

Here is a drag-and-drop version of the above (ref):

<div id="your-files"></div>
var target = document.getElementById("your-files");
target.addEventListener("dragover", function(event) {
}, false);

target.addEventListener("drop", function(event) {
    // Cancel default actions
    var files = event.dataTransfer.files,
    for (var i = 0; i < files.length; i++) {
        console.log("Filename: " + files[i].name);
        console.log("Type: " + files[i].type);
        console.log("Size: " + files[i].size + " bytes");
}, false);

Step 2:

We can now inspect the files and tease out headers and MIME types.

✘ Quick method

You can naïvely ask Blob for the MIME type of whatever file it represents using this pattern:

var blob = files[i]; // See step 1 above

For images, MIME types come back like the following:


Caveat: The MIME type is detected from the file extension and can be fooled or spoofed. One can rename a .jpg to a .png and the MIME type will be be reported as image/png.

✓ Proper header-inspecting method

To get the bonafide MIME type of a client-side file we can go a step further and inspect the first few bytes of the given file to compare against so-called magic numbers. Be warned that it's not entirely straightforward because, for instance, JPEG has a few "magic numbers". This is because the format has evolved since 1991. You might get away with checking only the first two bytes, but I prefer checking at least 4 bytes to reduce false positives.

Example file signatures of JPEG (first 4 bytes):

FF D8 FF E0 (SOI + ADD0)
FF D8 FF E1 (SOI + ADD1)
FF D8 FF E2 (SOI + ADD2)

Here is the essential code to retrieve the file header:

var blob = files[i]; // See step 1 above
var fileReader = new FileReader();
fileReader.onloadend = function(e) {
  var arr = (new Uint8Array(, 4);
  var header = "";
  for(var i = 0; i < arr.length; i++) {
     header += arr[i].toString(16);

  // Check the file signature against known types


You can then determine the real MIME type like so (more file signatures here and here):

switch (header) {
    case "89504e47":
        type = "image/png";
    case "47494638":
        type = "image/gif";
    case "ffd8ffe0":
    case "ffd8ffe1":
    case "ffd8ffe2":
    case "ffd8ffe3":
    case "ffd8ffe8":
        type = "image/jpeg";
        type = "unknown"; // Or you can use the blob.type as fallback

Accept or reject file uploads as you like based on the MIME types expected.


Here is a working demo for local files and remote files (I had to bypass CORS just for this demo). Open the snippet, run it, and you should see three remote images of different types displayed. At the top you can select a local image or data file, and the file signature and/or MIME type will be displayed.

Notice that even if an image is renamed, its true MIME type can be determined. See below.


Expected output of demo

// Return the first few bytes of the file as a hex string_x000D_
function getBLOBFileHeader(url, blob, callback) {_x000D_
  var fileReader = new FileReader();_x000D_
  fileReader.onloadend = function(e) {_x000D_
    var arr = (new Uint8Array(, 4);_x000D_
    var header = "";_x000D_
    for (var i = 0; i < arr.length; i++) {_x000D_
      header += arr[i].toString(16);_x000D_
    callback(url, header);_x000D_
function getRemoteFileHeader(url, callback) {_x000D_
  var xhr = new XMLHttpRequest();_x000D_
  // Bypass CORS for this demo - naughty, Drakes_x000D_'GET', '//' + url);_x000D_
  xhr.responseType = "blob";_x000D_
  xhr.onload = function() {_x000D_
    callback(url, xhr.response);_x000D_
  xhr.onerror = function() {_x000D_
    alert('A network error occurred!');_x000D_
function headerCallback(url, headerString) {_x000D_
  printHeaderInfo(url, headerString);_x000D_
function remoteCallback(url, blob) {_x000D_
  getBLOBFileHeader(url, blob, headerCallback);_x000D_
function printImage(blob) {_x000D_
  // Add this image to the document body for proof of GET success_x000D_
  var fr = new FileReader();_x000D_
  fr.onloadend = function() {_x000D_
    $("hr").after($("<img>").attr("src", fr.result))_x000D_
      .after($("<div>").text("Blob MIME type: " + blob.type));_x000D_
// Add more from
function mimeType(headerString) {_x000D_
  switch (headerString) {_x000D_
    case "89504e47":_x000D_
      type = "image/png";_x000D_
    case "47494638":_x000D_
      type = "image/gif";_x000D_
    case "ffd8ffe0":_x000D_
    case "ffd8ffe1":_x000D_
    case "ffd8ffe2":_x000D_
      type = "image/jpeg";_x000D_
      type = "unknown";_x000D_
  return type;_x000D_
function printHeaderInfo(url, headerString) {_x000D_
  $("hr").after($("<div>").text("Real MIME type: " + mimeType(headerString)))_x000D_
    .after($("<div>").text("File header: 0x" + headerString))_x000D_
/* Demo driver code */_x000D_
var imageURLsArray = ["", "", ""];_x000D_
// Check for FileReader support_x000D_
if (window.FileReader && window.Blob) {_x000D_
  // Load all the remote images from the urls array_x000D_
  for (var i = 0; i < imageURLsArray.length; i++) {_x000D_
    getRemoteFileHeader(imageURLsArray[i], remoteCallback);_x000D_
  /* Handle local files */_x000D_
  $("input").on('change', function(event) {_x000D_
    var file =[0];_x000D_
    if (file.size >= 2 * 1024 * 1024) {_x000D_
      alert("File size must be at most 2MB");_x000D_
    remoteCallback(escape(, file);_x000D_
} else {_x000D_
  // File and Blob are not supported_x000D_
  $("hr").after( $("<div>").text("It seems your browser doesn't support FileReader") );_x000D_
} /* Drakes, 2015 */
img {_x000D_
  max-height: 200px_x000D_
div {_x000D_
  height: 26px;_x000D_
  font: Arial;_x000D_
  font-size: 12pt_x000D_
form {_x000D_
  height: 40px;_x000D_
<script src=""></script>_x000D_
  <input type="file" />_x000D_
  <div>Choose an image to see its file signature.</div>_x000D_

Eclipse java debugging: source not found

None of the mentioned answer worked for me.

To resolve this issue i have to follow bellow steps:

  • Right click on Java HotSpot(TM) 64 Bit server.
  • Select "Edit Source Lookup".
  • Click on "Add".
  • Select "File System Directory" instead of Java project.
  • Select Root directory of your project.
  • Check "Search Subfolders".
  • Click Ok ok ok.


AngularJS view not updating on model change

As Ajay beniwal mentioned above you need to use Apply to start digestion.

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

app.controller('TestCtrl', function ($scope) {
   $scope.testValue = 0;

    setInterval(function() {
    }, 500);

How do I give ASP.NET permission to write to a folder in Windows 7?

My immediate solution (since I couldn't find the ASP.NET worker process) was to give write (that is, Modify) permission to IIS_IUSRS. This worked. I seem to recall that in WinXP I had to specifically given the ASP.NET worker process write permission to accomplish this. Maybe my memory is faulty, but anyway...

@DraganRadivojevic wrote that he thought this was dangerous from a security viewpoint. I do not disagree, but since this was my workstation and not a network server, it seemed relatively safe. In any case, his answer is better and is what I finally settled on after chasing down a fail-path due to not specifying the correct domain for the AppPool user.

How to Convert UTC Date To Local time Zone in MySql Select Query

SELECT CONVERT_TZ() will work for that.but its not working for me.

Why, what error do you get?

SELECT CONVERT_TZ(displaytime,'GMT','MET');

should work if your column type is timestamp, or date

Test how this works:

SELECT CONVERT_TZ(a_ad_display.displaytime,'+00:00','+04:00');

Check your timezone-table

SELECT * FROM mysql.time_zone;
SELECT * FROM mysql.time_zone_name;

If those tables are empty, you have not initialized your timezone tables. According to link above you can use mysql_tzinfo_to_sql program to load the Time Zone Tables. Please try this

shell> mysql_tzinfo_to_sql /usr/share/zoneinfo

or if not working read more:

Session timeout in ASP.NET

In my situation, it was Application Pool. It is set to restart when idle for xx mins. When I set it to not restart, it seems to use value from Web Config.

How to pass parameters to maven build using pom.xml?

mvn install "-Dsomeproperty=propety value"

In pom.xml:

    <someproperty> ${someproperty} </someproperty>

Referred from this question

How to count occurrences of a column value efficiently in SQL?

Here's another solution. this one uses very simple syntax. The first example of the accepted solution did not work on older versions of Microsoft SQL (i.e 2000)

SELECT age, count(*)
FROM Students 
GROUP by age

Send File Attachment from Form Using phpMailer and PHP

This will work perfectly

    <form method='post' enctype="multipart/form-data">
    <input type='file' name='uploaded_file' id='uploaded_file' multiple='multiple' />
    <input type='submit' name='upload'/> 

             if (isset($_FILES['uploaded_file']) && $_FILES['uploaded_file']['error'] == UPLOAD_ERR_OK)
                     if (array_key_exists('uploaded_file', $_FILES))
                            $mail->Subject = "My Subject";
                            $mail->Body = 'This is the body';
                            $uploadfile = tempnam(sys_get_temp_dir(), sha1($_FILES['uploaded_file']['name']));
                        if (move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $uploadfile))
                            echo 'Message has been sent';
                    echo "The file is not uploaded. please try again.";
                    echo "The file is not uploaded. please try again";

Android LinearLayout Gradient Background

My problem was the .xml extension was not added to the filename of the newly created XML file. Adding the .xml extension fixed my problem.

What are carriage return, linefeed, and form feed?

\f is used for page break. You cannot see any effect in the console. But when you use this character constant in your file then you can see the difference.

Other example is that if you can redirect your output to a file then you don't have to write a file or use file handling.

For ex:

Write this code in c++

void main()    
    cout<<"helloooooo" ;

    cout<<"hiiiii" ;


and when you compile this it generate an exe(for ex. abc.exe)

then you can redirect your output to a file using this:

abc > xyz.doc

then open the file xyz.doc you can see the actual page break between hellooo and hiiii....

Replace CRLF using powershell

Below is my script for converting all files recursively. You can specify folders or files to exclude.

$excludeFolders = "node_modules|dist|.vs";
$excludeFiles = ".*\.map.*|.*\.zip|.*\.png|.*\.ps1"

Function Dos2Unix {
    Param([Parameter(ValueFromPipeline)] $fileName)

    Write-Host -Nonewline "."

    $fileContents = Get-Content -raw $fileName
    $containsCrLf = $fileContents | %{$_ -match "\r\n"}
    If($containsCrLf -contains $true)
        Write-Host "`r`nCleaing file: $fileName"
        set-content -Nonewline -Encoding utf8 $fileName ($fileContents -replace "`r`n","`n")

Get-Childitem -File "." -Recurse |
Where-Object {$_.PSParentPath -notmatch $excludeFolders} |
Where-Object {$_.PSPath -notmatch $excludeFiles} |
foreach { $_.PSPath | Dos2Unix }