Programs & Examples On #Dd

A low-level command-line tool on Unix-like operating systems to copy and convert files.

dd: How to calculate optimal blocksize?

As others have said, there is no universally correct block size; what is optimal for one situation or one piece of hardware may be terribly inefficient for another. Also, depending on the health of the disks it may be preferable to use a different block size than what is "optimal".

One thing that is pretty reliable on modern hardware is that the default block size of 512 bytes tends to be almost an order of magnitude slower than a more optimal alternative. When in doubt, I've found that 64K is a pretty solid modern default. Though 64K usually isn't THE optimal block size, in my experience it tends to be a lot more efficient than the default. 64K also has a pretty solid history of being reliably performant: You can find a message from the Eug-Lug mailing list, circa 2002, recommending a block size of 64K here: http://www.mail-archive.com/[email protected]/msg12073.html

For determining THE optimal output block size, I've written the following script that tests writing a 128M test file with dd at a range of different block sizes, from the default of 512 bytes to a maximum of 64M. Be warned, this script uses dd internally, so use with caution.

dd_obs_test.sh:

#!/bin/bash

# Since we're dealing with dd, abort if any errors occur
set -e

TEST_FILE=${1:-dd_obs_testfile}
TEST_FILE_EXISTS=0
if [ -e "$TEST_FILE" ]; then TEST_FILE_EXISTS=1; fi
TEST_FILE_SIZE=134217728

if [ $EUID -ne 0 ]; then
  echo "NOTE: Kernel cache will not be cleared between tests without sudo. This will likely cause inaccurate results." 1>&2
fi

# Header
PRINTF_FORMAT="%8s : %s\n"
printf "$PRINTF_FORMAT" 'block size' 'transfer rate'

# Block sizes of 512b 1K 2K 4K 8K 16K 32K 64K 128K 256K 512K 1M 2M 4M 8M 16M 32M 64M
for BLOCK_SIZE in 512 1024 2048 4096 8192 16384 32768 65536 131072 262144 524288 1048576 2097152 4194304 8388608 16777216 33554432 67108864
do
  # Calculate number of segments required to copy
  COUNT=$(($TEST_FILE_SIZE / $BLOCK_SIZE))

  if [ $COUNT -le 0 ]; then
    echo "Block size of $BLOCK_SIZE estimated to require $COUNT blocks, aborting further tests."
    break
  fi

  # Clear kernel cache to ensure more accurate test
  [ $EUID -eq 0 ] && [ -e /proc/sys/vm/drop_caches ] && echo 3 > /proc/sys/vm/drop_caches

  # Create a test file with the specified block size
  DD_RESULT=$(dd if=/dev/zero of=$TEST_FILE bs=$BLOCK_SIZE count=$COUNT conv=fsync 2>&1 1>/dev/null)

  # Extract the transfer rate from dd's STDERR output
  TRANSFER_RATE=$(echo $DD_RESULT | \grep --only-matching -E '[0-9.]+ ([MGk]?B|bytes)/s(ec)?')

  # Clean up the test file if we created one
  if [ $TEST_FILE_EXISTS -ne 0 ]; then rm $TEST_FILE; fi

  # Output the result
  printf "$PRINTF_FORMAT" "$BLOCK_SIZE" "$TRANSFER_RATE"
done

View on GitHub

I've only tested this script on a Debian (Ubuntu) system and on OSX Yosemite, so it will probably take some tweaking to make work on other Unix flavors.

By default the command will create a test file named dd_obs_testfile in the current directory. Alternatively, you can provide a path to a custom test file by providing a path after the script name:

$ ./dd_obs_test.sh /path/to/disk/test_file

The output of the script is a list of the tested block sizes and their respective transfer rates like so:

$ ./dd_obs_test.sh
block size : transfer rate
       512 : 11.3 MB/s
      1024 : 22.1 MB/s
      2048 : 42.3 MB/s
      4096 : 75.2 MB/s
      8192 : 90.7 MB/s
     16384 : 101 MB/s
     32768 : 104 MB/s
     65536 : 108 MB/s
    131072 : 113 MB/s
    262144 : 112 MB/s
    524288 : 133 MB/s
   1048576 : 125 MB/s
   2097152 : 113 MB/s
   4194304 : 106 MB/s
   8388608 : 107 MB/s
  16777216 : 110 MB/s
  33554432 : 119 MB/s
  67108864 : 134 MB/s

(Note: The unit of the transfer rates will vary by OS)

To test optimal read block size, you could use more or less the same process, but instead of reading from /dev/zero and writing to the disk, you'd read from the disk and write to /dev/null. A script to do this might look like so:

dd_ibs_test.sh:

#!/bin/bash

# Since we're dealing with dd, abort if any errors occur
set -e

TEST_FILE=${1:-dd_ibs_testfile}
if [ -e "$TEST_FILE" ]; then TEST_FILE_EXISTS=$?; fi
TEST_FILE_SIZE=134217728

# Exit if file exists
if [ -e $TEST_FILE ]; then
  echo "Test file $TEST_FILE exists, aborting."
  exit 1
fi
TEST_FILE_EXISTS=1

if [ $EUID -ne 0 ]; then
  echo "NOTE: Kernel cache will not be cleared between tests without sudo. This will likely cause inaccurate results." 1>&2
fi

# Create test file
echo 'Generating test file...'
BLOCK_SIZE=65536
COUNT=$(($TEST_FILE_SIZE / $BLOCK_SIZE))
dd if=/dev/urandom of=$TEST_FILE bs=$BLOCK_SIZE count=$COUNT conv=fsync > /dev/null 2>&1

# Header
PRINTF_FORMAT="%8s : %s\n"
printf "$PRINTF_FORMAT" 'block size' 'transfer rate'

# Block sizes of 512b 1K 2K 4K 8K 16K 32K 64K 128K 256K 512K 1M 2M 4M 8M 16M 32M 64M
for BLOCK_SIZE in 512 1024 2048 4096 8192 16384 32768 65536 131072 262144 524288 1048576 2097152 4194304 8388608 16777216 33554432 67108864
do
  # Clear kernel cache to ensure more accurate test
  [ $EUID -eq 0 ] && [ -e /proc/sys/vm/drop_caches ] && echo 3 > /proc/sys/vm/drop_caches

  # Read test file out to /dev/null with specified block size
  DD_RESULT=$(dd if=$TEST_FILE of=/dev/null bs=$BLOCK_SIZE 2>&1 1>/dev/null)

  # Extract transfer rate
  TRANSFER_RATE=$(echo $DD_RESULT | \grep --only-matching -E '[0-9.]+ ([MGk]?B|bytes)/s(ec)?')

  printf "$PRINTF_FORMAT" "$BLOCK_SIZE" "$TRANSFER_RATE"
done

# Clean up the test file if we created one
if [ $TEST_FILE_EXISTS -ne 0 ]; then rm $TEST_FILE; fi

View on GitHub

An important difference in this case is that the test file is a file that is written by the script. Do not point this command at an existing file or the existing file will be overwritten with zeroes!

For my particular hardware I found that 128K was the most optimal input block size on a HDD and 32K was most optimal on a SSD.

Though this answer covers most of my findings, I've run into this situation enough times that I wrote a blog post about it: http://blog.tdg5.com/tuning-dd-block-size/ You can find more specifics on the tests I performed there.

Using grep to search for hex strings in a file

We tried several things before arriving at an acceptable solution:

xxd -u /usr/bin/xxd | grep 'DF'
00017b0: 4010 8D05 0DFF FF0A 0300 53E3 0610 A003  @.........S.....


root# grep -ibH "df" /usr/bin/xxd
Binary file /usr/bin/xxd matches
xxd -u /usr/bin/xxd | grep -H 'DF'
(standard input):00017b0: 4010 8D05 0DFF FF0A 0300 53E3 0610 A003  @.........S.....

Then found we could get usable results with

xxd -u /usr/bin/xxd > /tmp/xxd.hex ; grep -H 'DF' /tmp/xxd

Note that using a simple search target like 'DF' will incorrectly match characters that span across byte boundaries, i.e.

xxd -u /usr/bin/xxd | grep 'DF'
00017b0: 4010 8D05 0DFF FF0A 0300 53E3 0610 A003  @.........S.....
--------------------^^

So we use an ORed regexp to search for ' DF' OR 'DF ' (the searchTarget preceded or followed by a space char).

The final result seems to be

xxd -u -ps -c 10000000000 DumpFile > DumpFile.hex
egrep ' DF|DF ' Dumpfile.hex

0001020: 0089 0424 8D95 D8F5 FFFF 89F0 E8DF F6FF  ...$............
-----------------------------------------^^
0001220: 0C24 E871 0B00 0083 F8FF 89C3 0F84 DF03  .$.q............
--------------------------------------------^^

What are callee and caller saved registers?

Caller-saved registers (AKA volatile registers, or call-clobbered) are used to hold temporary quantities that need not be preserved across calls.

For that reason, it is the caller's responsibility to push these registers onto the stack or copy them somewhere else if it wants to restore this value after a procedure call.

It's normal to let a call destroy temporary values in these registers, though.

Callee-saved registers (AKA non-volatile registers, or call-preserved) are used to hold long-lived values that should be preserved across calls.

When the caller makes a procedure call, it can expect that those registers will hold the same value after the callee returns, making it the responsibility of the callee to save them and restore them before returning to the caller. Or to not touch them.

Accessing a resource via codebehind in WPF

You should use System.Windows.Controls.UserControl's FindResource() or TryFindResource() methods.

Also, a good practice is to create a string constant which maps the name of your key in the resource dictionary (so that you can change it at only one place).

How do I convert struct System.Byte byte[] to a System.IO.Stream object in C#?

The easiest way to convert a byte array to a stream is using the MemoryStream class:

Stream stream = new MemoryStream(byteArray);

"Parameter" vs "Argument"

A parameter is the variable which is part of the method’s signature (method declaration). An argument is an expression used when calling the method.

Consider the following code:

void Foo(int i, float f)
{
    // Do things
}

void Bar()
{
    int anInt = 1;
    Foo(anInt, 2.0);
}

Here i and f are the parameters, and anInt and 2.0 are the arguments.

sql query with multiple where statements

This..

(
        (meta_key = 'lat' AND meta_value >= '60.23457047672217')
    OR
        (meta_key = 'lat' AND meta_value <= '60.23457047672217')
)

is the same as

(
        (meta_key = 'lat')
)

Adding it all together (the same applies to the long filter) you have this impossible WHERE clause which will give no rows because meta_key cannot be 2 values in one row

WHERE
    (meta_key = 'lat' AND meta_key = 'long' )

You need to review your operators to make sure you get the correct logic

Applying .gitignore to committed files

Be sure that your actual repo is the lastest version

  1. Edit .gitignore as you wish
  2. git rm -r --cached . (remove all files)
  3. git add . (re-add all files)

then commit as usual

Android global variable

This global variable works for my project:

public class Global {
    public static int ivar1, ivar2;
    public static String svar1, svar2;
    public static int[] myarray1 = new int[10];
}


//  How to use other or many activity
Global.ivar1 = 10;

int i = Global.ivar1;

How do I use disk caching in Picasso?

For the most updated version 2.71828 These are your answer.

Q1: Does it not have local disk cache?

A1: There is default caching within Picasso and the request flow just like this

App -> Memory -> Disk -> Server

Wherever they met their image first, they'll use that image and then stop the request flow. What about response flow? Don't worry, here it is.

Server -> Disk -> Memory -> App

By default, they will store into a local disk first for the extended keeping cache. Then the memory, for the instance usage of the cache.

You can use the built-in indicator in Picasso to see where images form by enabling this.

Picasso.get().setIndicatorEnabled(true);

It will show up a flag on the top left corner of your pictures.

  • Red flag means the images come from the server. (No caching at first load)
  • Blue flag means the photos come from the local disk. (Caching)
  • Green flag means the images come from the memory. (Instance Caching)

Q2: How do I enable disk caching as I will be using the same image multiple times?

A2: You don't have to enable it. It's the default.

What you'll need to do is DISABLE it when you want your images always fresh. There is 2-way of disabled caching.

  1. Set .memoryPolicy() to NO_CACHE and/or NO_STORE and the flow will look like this.

NO_CACHE will skip looking up images from memory.

App -> Disk -> Server

NO_STORE will skip store images in memory when the first load images.

Server -> Disk -> App
  1. Set .networkPolicy() to NO_CACHE and/or NO_STORE and the flow will look like this.

NO_CACHE will skip looking up images from disk.

App -> Memory -> Server

NO_STORE will skip store images in the disk when the first load images.

Server -> Memory -> App

You can DISABLE neither for fully no caching images. Here is an example.

Picasso.get().load(imageUrl)
             .memoryPolicy(MemoryPolicy.NO_CACHE,MemoryPolicy.NO_STORE)
             .networkPolicy(NetworkPolicy.NO_CACHE, NetworkPolicy.NO_STORE)
             .fit().into(banner);

The flow of fully no caching and no storing will look like this.

App -> Server //Request

Server -> App //Response

So, you may need this to minify your app storage usage also.

Q3: Do I need to add some disk permission to android manifest file?

A3: No, but don't forget to add the INTERNET permission for your HTTP request.

if var == False

Since Python evaluates also the data type NoneType as False during the check, a more precise answer is:

var = False
if var is False:
    print('learnt stuff')

This prevents potentially unwanted behaviour such as:

var = []  # or None
if not var:
    print('learnt stuff') # is printed what may or may not be wanted

But if you want to check all cases where var will be evaluated to False, then doing it by using logical not keyword is the right thing to do.

How to use OUTPUT parameter in Stored Procedure

There are a several things you need to address to get it working

  1. The name is wrong its not @ouput its @code
  2. You need to set the parameter direction to Output.
  3. Don't use AddWithValue since its not supposed to have a value just you Add.
  4. Use ExecuteNonQuery if you're not returning rows

Try

SqlParameter output = new SqlParameter("@code", SqlDbType.Int);
output.Direction = ParameterDirection.Output;
cmd.Parameters.Add(output);
cmd.ExecuteNonQuery();
MessageBox.Show(output.Value.ToString());

How to style the <option> with only CSS?

EDIT 2015 May

Disclaimer: I've taken the snippet from the answer linked below:

Important Update!

In addition to WebKit, as of Firefox 35 we'll be able to use the appearance property:

Using -moz-appearance with the none value on a combobox now remove the dropdown button

So now in order to hide the default styling, it's as easy as adding the following rules on our select element:

select {
   -webkit-appearance: none;
   -moz-appearance: none;
   appearance: none;
}

For IE 11 support, you can use [::-ms-expand][15].

select::-ms-expand { /* for IE 11 */
    display: none;
}

Old Answer

Unfortunately what you ask is not possible by using pure CSS. However, here is something similar that you can choose as a work around. Check the live code below.

_x000D_
_x000D_
div { _x000D_
  margin: 10px;_x000D_
  padding: 10px; _x000D_
  border: 2px solid purple; _x000D_
  width: 200px;_x000D_
  -webkit-border-radius: 5px;_x000D_
  -moz-border-radius: 5px;_x000D_
  border-radius: 5px;_x000D_
}_x000D_
div > ul { display: none; }_x000D_
div:hover > ul {display: block; background: #f9f9f9; border-top: 1px solid purple;}_x000D_
div:hover > ul > li { padding: 5px; border-bottom: 1px solid #4f4f4f;}_x000D_
div:hover > ul > li:hover { background: white;}_x000D_
div:hover > ul > li:hover > a { color: red; }
_x000D_
<div>_x000D_
  Select_x000D_
  <ul>_x000D_
    <li><a href="#">Item 1</a></li>_x000D_
    <li><a href="#">Item 2</a></li>_x000D_
    <li><a href="#">Item 3</a></li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

EDIT

Here is the question that you asked some time ago. How to style a <select> dropdown with CSS only without JavaScript? As it tells there, only in Chrome and to some extent in Firefox you can achieve what you want. Otherwise, unfortunately, there is no cross browser pure CSS solution for styling a select.

Node.js server that accepts POST requests

Receive POST and GET request in nodejs :

1).Server

    var http = require('http');
    var server = http.createServer ( function(request,response){

    response.writeHead(200,{"Content-Type":"text\plain"});
    if(request.method == "GET")
        {
            response.end("received GET request.")
        }
    else if(request.method == "POST")
        {
            response.end("received POST request.");
        }
    else
        {
            response.end("Undefined request .");
        }
});

server.listen(8000);
console.log("Server running on port 8000");

2). Client :

var http = require('http');

var option = {
    hostname : "localhost" ,
    port : 8000 ,
    method : "POST",
    path : "/"
} 

    var request = http.request(option , function(resp){
       resp.on("data",function(chunck){
           console.log(chunck.toString());
       }) 
    })
    request.end();

python variable NameError

This should do it:

#!/usr/local/cpython-2.7/bin/python  # offer users choice for how large of a song list they want to create # in order to determine (roughly) how many songs to copy print "\nHow much space should the random song list occupy?\n" print "1. 100Mb" print "2. 250Mb\n"  tSizeAns = int(raw_input())  if tSizeAns == 1:     tSize = "100Mb" elif tSizeAns == 2:     tSize = "250Mb" else:     tSize = "100Mb"    # in case user fails to enter either a 1 or 2  print "\nYou  want to create a random song list that is {}.".format(tSize) 

BTW, in case you're open to moving to Python 3.x, the differences are slight:

#!/usr/local/cpython-3.3/bin/python  # offer users choice for how large of a song list they want to create # in order to determine (roughly) how many songs to copy print("\nHow much space should the random song list occupy?\n") print("1. 100Mb") print("2. 250Mb\n")  tSizeAns = int(input())  if tSizeAns == 1:     tSize = "100Mb" elif tSizeAns == 2:     tSize = "250Mb" else:     tSize = "100Mb"    # in case user fails to enter either a 1 or 2  print("\nYou want to create a random song list that is {}.".format(tSize)) 

HTH

"Could not find or load main class" Error while running java program using cmd prompt

Execute your Java program using java -d . HelloWorld command.

This command works when you have declared package.

. represent current directory/.

How to change the height of a <br>?

UPDATED Sep. 13, 2019:

I use <br class=big> to make an oversized line break, when I need one. Until today, I styled it like this:

br.big {line-height:190%;vertical-align:top}

(The vertical-align:top was only needed for IE and Edge.)

That worked in all the major browsers that I tried: Chrome, Firefox, Opera, Brave, PaleMoon, Edge, and IE11.

However, it recently stopped working in Chrome-based browsers: my "big" line breaks turned into normal-sized line breaks.

(I don't know exactly when they broke it. As of Sep 12, 2019 it still works in my out-of-date Chromium Portable 55.0.2883.11, but it's broken in Opera 63.0.3368.71 and Chrome 76.0.3809.132 (both Windows and Android).)

After some trial and error, I ended up with the following substitute, which works in the current versions of all those browsers:

br.big {display:block; content:""; margin-top:0.5em; line-height:190%; vertical-align:top;}

Notes:

line-height:190% works in everything except recent versions of Chrome-based browsers.

vertical-align:top is needed for IE and Edge (in combination with line-height:190%), to get the extra space to come after the preceding line, where it belongs, rather than partially before and partially after.

display:block;content:"";margin-top:0.5em works in Chrome, Opera & Firefox, but not Edge & IE.

An alternative (simpler) way of adding a bit of extra vertical space after a <br> tag, if you don't mind editing the HTML, is with something like this. It works fine in all browsers:

<span style="vertical-align:-37%"> </span><br>

(You can, of course, adjust the "-37%" as needed, for a larger or smaller gap.) Here's a demo page which includes some other variations on the theme:

https://burtonsys.com/a_little_extra_vertical_space_for_br_tag.html



May 28, 2020:

I've updated the demo page; it now demonstrates all of the above techniques:

https://burtonsys.com/a_little_extra_vertical_space_for_br_tag.html

What is the difference between declarations, providers, and import in NgModule?

Components are declared, Modules are imported, and Services are provided. An example I'm working with:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';


import { AppComponent } from './app.component';
import {FormsModule} from '@angular/forms';
import { UserComponent } from './components/user/user.component';
import { StateService } from './services/state.service';    

@NgModule({
  declarations: [
    AppComponent,
    UserComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [ StateService ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

Missing Authentication Token while accessing API Gateway?

sometimes this message shown when you are calling a wrong api

check your api endpoint

Run PHP function on html button click

A php file is run whenever you access it via an HTTP request be it GET,POST, PUT.

You can use JQuery/Ajax to send a request on a button click, or even just change the URL of the browser to navigate to the php address.

Depending on the data sent in the POST/GET you can have a switch statement running a different function.

Specifying Function via GET

You can utilize the code here: How to call PHP function from string stored in a Variable along with a switch statement to automatically call the appropriate function depending on data sent.

So on PHP side you can have something like this:

<?php

//see http://php.net/manual/en/function.call-user-func-array.php how to use extensively
if(isset($_GET['runFunction']) && function_exists($_GET['runFunction']))
call_user_func($_GET['runFunction']);
else
echo "Function not found or wrong input";

function test()
{
echo("test");
}

function hello()
{
echo("hello");
}

?>

and you can make the simplest get request using the address bar as testing:

http://127.0.0.1/test.php?runFunction=hellodddddd

results in:

Function not found or wrong input

http://127.0.0.1/test.php?runFunction=hello

results in:

hello

Sending the Data

GET Request via JQuery

See: http://api.jquery.com/jQuery.get/

$.get("test.cgi", { name: "John"})
.done(function(data) {
  alert("Data Loaded: " + data);
});

POST Request via JQuery

See: http://api.jquery.com/jQuery.post/

$.post("test.php", { name: "John"} );

GET Request via Javascript location

See: http://www.javascripter.net/faq/buttonli.htm

<input type=button 
value="insert button text here"
onClick="self.location='Your_URL_here.php?name=hello'">

Reading the Data (PHP)

See PHP Turotial for reading post and get: http://www.tizag.com/phpT/postget.php

Useful Links

http://php.net/manual/en/function.call-user-func.php http://php.net/manual/en/function.function-exists.php

Creating self signed certificate for domain and subdomains - NET::ERR_CERT_COMMON_NAME_INVALID

I think it may be a bug in chrome. There was a similar issue long back: See this.

Try in a different browser. I think it should work fine.

Android ImageButton with a selected state?

Create an XML-file in a res/drawable folder. For instance, "btn_image.xml":

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/bg_state_1"
          android:state_pressed="true"
          android:state_selected="true"/>
    <item android:drawable="@drawable/bg_state_2"
          android:state_pressed="true"
          android:state_selected="false"/>
    <item android:drawable="@drawable/bg_state_selected"
          android:state_selected="true"/>
    <item android:drawable="@drawable/bg_state_deselected"/>
</selector>

You can combine those files you like, for instance, change "bg_state_1" to "bg_state_deselected" and "bg_state_2" to "bg_state_selected".

In any of those files you can write something like:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
    <solid android:color="#ccdd00"/>
    <corners android:radius="5dp"/>
</shape>

Create in a layout file an ImageView or ImageButton with the following attributes:

<ImageView
    android:id="@+id/image"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:adjustViewBounds="true"
    android:background="@drawable/btn_image"
    android:padding="10dp"
    android:scaleType="fitCenter"
    android:src="@drawable/star"/>

Later in code:

image.setSelected(!image.isSelected());

Node.js: How to read a stream into a buffer?

You can convert your readable stream to a buffer and integrate it in your code in an asynchronous way like this.

async streamToBuffer (stream) {
    return new Promise((resolve, reject) => {
      const data = [];

      stream.on('data', (chunk) => {
        data.push(chunk);
      });

      stream.on('end', () => {
        resolve(Buffer.concat(data))
      })

      stream.on('error', (err) => {
        reject(err)
      })
   
    })
  }

the usage would be as simple as:

 // usage
  const myStream // your stream
  const buffer = await streamToBuffer(myStream) // this is a buffer

What is the maximum length of a valid email address?

An email address must not exceed 254 characters.

This was accepted by the IETF following submitted erratum. A full diagnosis of any given address is available online. The original version of RFC 3696 described 320 as the maximum length, but John Klensin subsequently accepted an incorrect value, since a Path is defined as

Path = "<" [ A-d-l ":" ] Mailbox ">"

So the Mailbox element (i.e., the email address) has angle brackets around it to form a Path, which a maximum length of 254 characters to restrict the Path length to 256 characters or fewer.

The maximum length specified in RFC 5321 states:

The maximum total length of a reverse-path or forward-path is 256 characters.

RFC 3696 was corrected here.

People should be aware of the errata against RFC 3696 in particular. Three of the canonical examples are in fact invalid addresses.

I've collated a couple hundred test addresses, which you can find at http://www.dominicsayers.com/isemail

while EOF in JAVA?

nextLine() will throw an exception when there's no line and it will never return null,you can try the Scanner Class instead : http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html

milliseconds to time in javascript

Lots of unnecessary flooring in other answers. If the string is in milliseconds, convert to h:m:s as follows:

function msToTime(s) {
  var ms = s % 1000;
  s = (s - ms) / 1000;
  var secs = s % 60;
  s = (s - secs) / 60;
  var mins = s % 60;
  var hrs = (s - mins) / 60;

  return hrs + ':' + mins + ':' + secs + '.' + ms;
}

If you want it formatted as hh:mm:ss.sss then use:

_x000D_
_x000D_
function msToTime(s) {_x000D_
_x000D_
  // Pad to 2 or 3 digits, default is 2_x000D_
  function pad(n, z) {_x000D_
    z = z || 2;_x000D_
    return ('00' + n).slice(-z);_x000D_
  }_x000D_
_x000D_
  var ms = s % 1000;_x000D_
  s = (s - ms) / 1000;_x000D_
  var secs = s % 60;_x000D_
  s = (s - secs) / 60;_x000D_
  var mins = s % 60;_x000D_
  var hrs = (s - mins) / 60;_x000D_
_x000D_
  return pad(hrs) + ':' + pad(mins) + ':' + pad(secs) + '.' + pad(ms, 3);_x000D_
}_x000D_
_x000D_
console.log(msToTime(55018))
_x000D_
_x000D_
_x000D_

Using some recently added language features, the pad function can be more concise:

_x000D_
_x000D_
function msToTime(s) {_x000D_
    // Pad to 2 or 3 digits, default is 2_x000D_
  var pad = (n, z = 2) => ('00' + n).slice(-z);_x000D_
  return pad(s/3.6e6|0) + ':' + pad((s%3.6e6)/6e4 | 0) + ':' + pad((s%6e4)/1000|0) + '.' + pad(s%1000, 3);_x000D_
}_x000D_
_x000D_
// Current hh:mm:ss.sss UTC_x000D_
console.log(msToTime(new Date() % 8.64e7))
_x000D_
_x000D_
_x000D_

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

You can use querySelectorAll() like this:

var test = document.querySelectorAll('input[value][type="checkbox"]:not([value=""])');

This translates to:

get all inputs with the attribute "value" and has the attribute "value" that is not blank.

In this demo, it disables the checkbox with a non-blank value.

Automatically open Chrome developer tools when new tab/new window is opened

Use --auto-open-devtools-for-tabs flag while running chrome from command line

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --auto-open-devtools-for-tabs

https://developers.google.com/web/tools/chrome-devtools/open#auto

Simple 3x3 matrix inverse code (C++)

//Function for inverse of the input square matrix 'J' of dimension 'dim':

vector<vector<double > > inverseVec33(vector<vector<double > > J, int dim)
{
//Matrix of Minors
 vector<vector<double > > invJ(dim,vector<double > (dim));
for(int i=0; i<dim; i++)
{
    for(int j=0; j<dim; j++)
    {
        invJ[i][j] = (J[(i+1)%dim][(j+1)%dim]*J[(i+2)%dim][(j+2)%dim] -
                      J[(i+2)%dim][(j+1)%dim]*J[(i+1)%dim][(j+2)%dim]);
    }
}

//determinant of the matrix:
double detJ = 0.0;
for(int j=0; j<dim; j++)
{ detJ += J[0][j]*invJ[0][j];}

//Inverse of the given matrix.
 vector<vector<double > > invJT(dim,vector<double > (dim));
 for(int i=0; i<dim; i++)
{
    for(int j=0; j<dim; j++)
    {
        invJT[i][j] = invJ[j][i]/detJ;
    }
}

return invJT;
}

void main()
{
    //given matrix:
vector<vector<double > > Jac(3,vector<double > (3));
Jac[0][0] = 1; Jac[0][1] = 2;  Jac[0][2] = 6;
Jac[1][0] = -3; Jac[1][1] = 4;  Jac[1][2] = 3;
Jac[2][0] = 5; Jac[2][1] = 1;  Jac[2][2] = -4;`

//Inverse of the matrix Jac:
vector<vector<double > > JacI(3,vector<double > (3));
    //call function and store inverse of J as JacI:
JacI = inverseVec33(Jac,3);
}

How to loop an object in React?

You can use it in a more compact way as:

var tifs = {1: 'Joe', 2: 'Jane'};
...

return (
   <select id="tif" name="tif" onChange={this.handleChange}>  
      { Object.entries(tifs).map((t,k) => <option key={k} value={t[0]}>{t[1]}</option>) }          
   </select>
)

And another slightly different flavour:

 Object.entries(tifs).map(([key,value],i) => <option key={i} value={key}>{value}</option>)  

How to force uninstallation of windows service

Refreshing the service list always did it for me. If the services window is open, it will hold some memory of it existing for some reason. F5 and I'm reinstalling again!

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2

Response you are getting is in object form i.e.

{ 
  "dstOffset" : 3600, 
  "rawOffset" : 36000, 
  "status" : "OK", 
  "timeZoneId" : "Australia/Hobart", 
  "timeZoneName" : "Australian Eastern Daylight Time" 
}

Replace below line of code :

List<Post> postsList = Arrays.asList(gson.fromJson(reader,Post.class))

with

Post post = gson.fromJson(reader, Post.class);

What exactly does the Access-Control-Allow-Credentials header do?

By default, CORS does not include cookies on cross-origin requests. This is different from other cross-origin techniques such as JSON-P. JSON-P always includes cookies with the request, and this behavior can lead to a class of vulnerabilities called cross-site request forgery, or CSRF.

In order to reduce the chance of CSRF vulnerabilities in CORS, CORS requires both the server and the client to acknowledge that it is ok to include cookies on requests. Doing this makes cookies an active decision, rather than something that happens passively without any control.

The client code must set the withCredentials property on the XMLHttpRequest to true in order to give permission.

However, this header alone is not enough. The server must respond with the Access-Control-Allow-Credentials header. Responding with this header to true means that the server allows cookies (or other user credentials) to be included on cross-origin requests.

You also need to make sure your browser isn't blocking third-party cookies if you want cross-origin credentialed requests to work.

Note that regardless of whether you are making same-origin or cross-origin requests, you need to protect your site from CSRF (especially if your request includes cookies).

AttributeError: 'numpy.ndarray' object has no attribute 'append'

Use numpy.concatenate(list1 , list2) or numpy.append() Look into the thread at Append a NumPy array to a NumPy array.

Find the differences between 2 Excel worksheets?

ExcelDiff exports a HTML report in a Divided (Side-by-side) or Merged (Overlay) view highlighting the differences as well as the row and column.

Hash and salt passwords in C#

 protected void m_GenerateSHA256_Button1_Click(objectSender, EventArgs e)
{
string salt =createSalt(10);
string hashedPassword=GenerateSHA256Hash(m_UserInput_TextBox.Text,Salt);
m_SaltHash_TextBox.Text=Salt;
 m_SaltSHA256Hash_TextBox.Text=hashedPassword;

}
 public string createSalt(int size)
{
 var rng= new System.Security.Cyptography.RNGCyptoServiceProvider();
 var buff= new byte[size];
rng.GetBytes(buff);
 return Convert.ToBase64String(buff);
}


 public string GenerateSHA256Hash(string input,string salt)
{
 byte[]bytes=System.Text.Encoding.UTF8.GetBytes(input+salt);
 new System.Security.Cyptography.SHA256Managed();
 byte[]hash=sha256hashString.ComputedHash(bytes);
 return bytesArrayToHexString(hash);
  }

Transfer data between databases with PostgreSQL

I just had to do this exact thing so I figured I'd post the recipe here. This assumes that both databases are on the same server.

First, copy the table from the old db to the new db (because apparently you can't move data between databases). At the commandline:

pg_dump -U postgres -t <old_table> <old_database> | psql -U postgres -d <new_database>

# Just adding extra space here so scrollbar doesn't hide the command

Next, grant permissions of the copied table to the user of the new database. Log into psql:

psql -U postgres -d <new_database>

ALTER TABLE <old_table> OWNER TO <new_user>;

\q

Finally, copy data from the old table to the new table. Log in as the new user and then:

INSERT INTO <new_table> (field1, field2, field3) 
SELECT field1, field2, field3 from <old_table>;

Done!

jQuery DataTable overflow and text-wrapping issues

I faced the same problem of text wrapping, solved it by changing the css of table class in DT_bootstrap.css. I introduced last two css lines table-layout and word-break.

   table.table {
    clear: both;
    margin-bottom: 6px !important;
    max-width: none !important;
    table-layout: fixed;
    word-break: break-all;
   } 

DataGridView checkbox column - value and functionality

To test if the column is checked or not:

for (int i = 0; i < dgvName.Rows.Count; i++)
{
    if ((bool)dgvName.Rows[i].Cells[8].Value)
    {
    // Column is checked
    }
}

How to get jSON response into variable from a jquery script

Your PHP array is defined as:

$arr = array ('resonse'=>'error','comment'=>'test comment here');

Notice the mispelling "resonse". Also, as RaYell has mentioned, you have to use data instead of json in your success function because its parameter is currently data.

Try editing your PHP file to change the spelling form resonse to response. It should work then.

SQL Server principal "dbo" does not exist,

USE [<dbname>]
GO
sp_changedbowner '<user>' -- you can use 'sa' as a quick fix in databases with SQL authentication

KB913423 - You cannot run a statement or a module that includes the EXECUTE AS clause after you restore a database in SQL Server 2005

How to read a file into a variable in shell?

this works for me: v=$(cat <file_path>) echo $v

Javascript get the text value of a column from a particular row of an html table

in case if your table has tbody

let tbl = document.getElementById("tbl").getElementsByTagName('tbody')[0];
console.log(tbl.rows[0].cells[0].innerHTML)

Sorting HTML table with JavaScript

Just revisiting an old solution, I thought I'd give it a facelift for it's ~5 year anniversary!

  • Plain Javascript (ES6)
  • Does alpha and numeric sorting - ascending and descending
  • Works in Chrome, Firefox, Safari (and IE11, see below)

Quick explanation

  1. add a click event to all header (th) cells...
    1. for the current table, find all rows (except the first)...
    2. sort the rows, based on the value of the clicked column...
    3. insert the rows back into the table, in the new order.

_x000D_
_x000D_
const getCellValue = (tr, idx) => tr.children[idx].innerText || tr.children[idx].textContent;_x000D_
_x000D_
const comparer = (idx, asc) => (a, b) => ((v1, v2) => _x000D_
    v1 !== '' && v2 !== '' && !isNaN(v1) && !isNaN(v2) ? v1 - v2 : v1.toString().localeCompare(v2)_x000D_
    )(getCellValue(asc ? a : b, idx), getCellValue(asc ? b : a, idx));_x000D_
_x000D_
// do the work..._x000D_
document.querySelectorAll('th').forEach(th => th.addEventListener('click', (() => {_x000D_
    const table = th.closest('table');_x000D_
    Array.from(table.querySelectorAll('tr:nth-child(n+2)'))_x000D_
        .sort(comparer(Array.from(th.parentNode.children).indexOf(th), this.asc = !this.asc))_x000D_
        .forEach(tr => table.appendChild(tr) );_x000D_
})));
_x000D_
table, th, td {_x000D_
    border: 1px solid black;_x000D_
}_x000D_
th {_x000D_
    cursor: pointer;_x000D_
}
_x000D_
<table>_x000D_
    <tr><th>Country</th><th>Date</th><th>Size</th></tr>_x000D_
    <tr><td>France</td><td>2001-01-01</td><td><i>25</i></td></tr>_x000D_
    <tr><td><a href=#>spain</a></td><td><i>2005-05-05</i></td><td></td></tr>_x000D_
    <tr><td><b>Lebanon</b></td><td><a href=#>2002-02-02</a></td><td><b>-17</b></td></tr>_x000D_
    <tr><td><i>Argentina</i></td><td>2005-04-04</td><td><a href=#>100</a></td></tr>_x000D_
    <tr><td>USA</td><td></td><td>-6</td></tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_


IE11 Support (non-ES6)

If you want to support IE11, you'll need to ditch the ES6 syntax and use alternatives to Array.from and Element.closest.

i.e.

var getCellValue = function(tr, idx){ return tr.children[idx].innerText || tr.children[idx].textContent; }

var comparer = function(idx, asc) { return function(a, b) { return function(v1, v2) {
        return v1 !== '' && v2 !== '' && !isNaN(v1) && !isNaN(v2) ? v1 - v2 : v1.toString().localeCompare(v2);
    }(getCellValue(asc ? a : b, idx), getCellValue(asc ? b : a, idx));
}};

// do the work...
Array.prototype.slice.call(document.querySelectorAll('th')).forEach(function(th) { th.addEventListener('click', function() {
        var table = th.parentNode
        while(table.tagName.toUpperCase() != 'TABLE') table = table.parentNode;
        Array.prototype.slice.call(table.querySelectorAll('tr:nth-child(n+2)'))
            .sort(comparer(Array.prototype.slice.call(th.parentNode.children).indexOf(th), this.asc = !this.asc))
            .forEach(function(tr) { table.appendChild(tr) });
    })
});

Difference between window.location.href=window.location.href and window.location.reload()

In our case we just want to reload the page in webview and for some reasons we couldn't find out why! We try almost every solution that has been on the web, but stuck with no reloading using location.reload() or alternative solutions like window.location.reload(), location.reload(true), ...!

Here is our simple solution :

Just use a < a > tag with the empty "href" attribution value like this :

< a href="" ...>Click Me</a>

(in some cases you have to use "return true" on click of the target to trigger reload)

For more information check out this question : Is an empty href valid?

How do I create a foreign key in SQL Server?

And if you just want to create the constraint on its own, you can use ALTER TABLE

alter table MyTable
add constraint MyTable_MyColumn_FK FOREIGN KEY ( MyColumn ) references MyOtherTable(PKColumn)

I wouldn't recommend the syntax mentioned by Sara Chipps for inline creation, just because I would rather name my own constraints.

Extracting specific selected columns to new DataFrame as a copy

If you want to have a new data frame then:

import pandas as pd
old = pd.DataFrame({'A' : [4,5], 'B' : [10,20], 'C' : [100,50], 'D' : [-30,-50]})
new=  old[['A', 'C', 'D']]

Windows Bat file optional argument parsing

Though I tend to agree with @AlekDavis' comment, there are nonetheless several ways to do this in the NT shell.

The approach I would take advantage of the SHIFT command and IF conditional branching, something like this...

@ECHO OFF

SET man1=%1
SET man2=%2
SHIFT & SHIFT

:loop
IF NOT "%1"=="" (
    IF "%1"=="-username" (
        SET user=%2
        SHIFT
    )
    IF "%1"=="-otheroption" (
        SET other=%2
        SHIFT
    )
    SHIFT
    GOTO :loop
)

ECHO Man1 = %man1%
ECHO Man2 = %man2%
ECHO Username = %user%
ECHO Other option = %other%

REM ...do stuff here...

:theend

mysql error 2005 - Unknown MySQL server host 'localhost'(11001)

ERROR 2005 (HY000): Unknown MySQL server host 'localhost' (0)

modify list of host names for your system:

C:\Windows\System32\drivers\etc\hosts

Make sure that you have the following entry:

127.0.0.1 localhost
In my case that entry was 0.0.0.0 localhost which caussed all problem

(you may need to change modify permission to modify this file)

This performs DNS resolution of host “localhost” to the IP address 127.0.0.1.

Using Sockets to send and receive data

I assume you are using TCP sockets for the client-server interaction? One way to send different types of data to the server and have it be able to differentiate between the two is to dedicate the first byte (or more if you have more than 256 types of messages) as some kind of identifier. If the first byte is one, then it is message A, if its 2, then its message B. One easy way to send this over the socket is to use DataOutputStream/DataInputStream:

Client:

Socket socket = ...; // Create and connect the socket
DataOutputStream dOut = new DataOutputStream(socket.getOutputStream());

// Send first message
dOut.writeByte(1);
dOut.writeUTF("This is the first type of message.");
dOut.flush(); // Send off the data

// Send the second message
dOut.writeByte(2);
dOut.writeUTF("This is the second type of message.");
dOut.flush(); // Send off the data

// Send the third message
dOut.writeByte(3);
dOut.writeUTF("This is the third type of message (Part 1).");
dOut.writeUTF("This is the third type of message (Part 2).");
dOut.flush(); // Send off the data

// Send the exit message
dOut.writeByte(-1);
dOut.flush();

dOut.close();

Server:

Socket socket = ... // Set up receive socket
DataInputStream dIn = new DataInputStream(socket.getInputStream());

boolean done = false;
while(!done) {
  byte messageType = dIn.readByte();

  switch(messageType)
  {
  case 1: // Type A
    System.out.println("Message A: " + dIn.readUTF());
    break;
  case 2: // Type B
    System.out.println("Message B: " + dIn.readUTF());
    break;
  case 3: // Type C
    System.out.println("Message C [1]: " + dIn.readUTF());
    System.out.println("Message C [2]: " + dIn.readUTF());
    break;
  default:
    done = true;
  }
}

dIn.close();

Obviously, you can send all kinds of data, not just bytes and strings (UTF).

Note that writeUTF writes a modified UTF-8 format, preceded by a length indicator of an unsigned two byte encoded integer giving you 2^16 - 1 = 65535 bytes to send. This makes it possible for readUTF to find the end of the encoded string. If you decide on your own record structure then you should make sure that the end and type of the record is either known or detectable.

No internet on Android emulator - why and how to fix?

on OSX, Little Snitch was automatically denying any connection to Eclipse (and the emulator). Allow connections in Little Snitch, you have to go into Little Snitch's rules

how to set start value as "0" in chartjs?

For Chart.js 2.*, the option for the scale to begin at zero is listed under the configuration options of the linear scale. This is used for numerical data, which should most probably be the case for your y-axis. So, you need to use this:

options: {
    scales: {
        yAxes: [{
            ticks: {
                beginAtZero: true
            }
        }]
    }
}

A sample line chart is also available here where the option is used for the y-axis. If your numerical data is on the x-axis, use xAxes instead of yAxes. Note that an array (and plural) is used for yAxes (or xAxes), because you may as well have multiple axes.

Normalize numpy array columns in python

You can use sklearn.preprocessing:

from sklearn.preprocessing import normalize
data = np.array([
    [1000, 10, 0.5],
    [765, 5, 0.35],
    [800, 7, 0.09], ])
data = normalize(data, axis=0, norm='max')
print(data)
>>[[ 1.     1.     1.   ]
[ 0.765  0.5    0.7  ]
[ 0.8    0.7    0.18 ]]

How do I create a round cornered UILabel on the iPhone?

Another method is to place a png behind the UILabel. I have views with several labels that overlay a single background png that has all the artwork for the individual labels.

Matplotlib scatter plot with different text at each data point

This might be useful when you need individually annotate in different time (I mean, not in a single for loop)

ax = plt.gca()
ax.annotate('your_lable', (x,y)) 

where x and y are the your target coordinate and type is float/int.

JavaScript: Create and save file

_x000D_
_x000D_
setTimeout("create('Hello world!', 'myfile.txt', 'text/plain')");_x000D_
function create(text, name, type) {_x000D_
  var dlbtn = document.getElementById("dlbtn");_x000D_
  var file = new Blob([text], {type: type});_x000D_
  dlbtn.href = URL.createObjectURL(file);_x000D_
  dlbtn.download = name;_x000D_
}
_x000D_
<a href="javascript:void(0)" id="dlbtn"><button>click here to download your file</button></a>
_x000D_
_x000D_
_x000D_

Assert a function/method was not called using Mock

When you test using class inherits unittest.TestCase you can simply use methods like:

  • assertTrue
  • assertFalse
  • assertEqual

and similar (in python documentation you find the rest).

In your example we can simply assert if mock_method.called property is False, which means that method was not called.

import unittest
from unittest import mock

import my_module

class A(unittest.TestCase):
    def setUp(self):
        self.message = "Method should not be called. Called {times} times!"

    @mock.patch("my_module.method_to_mock")
    def test(self, mock_method):
        my_module.method_to_mock()

        self.assertFalse(mock_method.called,
                         self.message.format(times=mock_method.call_count))

Finding import static statements for Mockito constructs

The problem is that static imports from Hamcrest and Mockito have similar names, but return Matchers and real values, respectively.

One work-around is to simply copy the Hamcrest and/or Mockito classes and delete/rename the static functions so they are easier to remember and less show up in the auto complete. That's what I did.

Also, when using mocks, I try to avoid assertThat in favor other other assertions and verify, e.g.

assertEquals(1, 1);
verify(someMock).someMethod(eq(1));

instead of

assertThat(1, equalTo(1));
verify(someMock).someMethod(eq(1));

If you remove the classes from your Favorites in Eclipse, and type out the long name e.g. org.hamcrest.Matchers.equalTo and do CTRL+SHIFT+M to 'Add Import' then autocomplete will only show you Hamcrest matchers, not any Mockito matchers. And you can do this the other way so long as you don't mix matchers.

How to use parameters with HttpPost

Generally speaking an HTTP POST assumes the content of the body contains a series of key/value pairs that are created (most usually) by a form on the HTML side. You don't set the values using setHeader, as that won't place them in the content body.

So with your second test, the problem that you have here is that your client is not creating multiple key/value pairs, it only created one and that got mapped by default to the first argument in your method.

There are a couple of options you can use. First, you could change your method to accept only one input parameter, and then pass in a JSON string as you do in your second test. Once inside the method, you then parse the JSON string into an object that would allow access to the fields.

Another option is to define a class that represents the fields of the input types and make that the only input parameter. For example

class MyInput
{
    String str1;
    String str2;

    public MyInput() { }
      //  getters, setters
 }

@POST
@Consumes({"application/json"})
@Path("create/")
public void create(MyInput in){
System.out.println("value 1 = " + in.getStr1());
System.out.println("value 2 = " + in.getStr2());
}

Depending on the REST framework you are using it should handle the de-serialization of the JSON for you.

The last option is to construct a POST body that looks like:

str1=value1&str2=value2

then add some additional annotations to your server method:

public void create(@QueryParam("str1") String str1, 
                  @QueryParam("str2") String str2)

@QueryParam doesn't care if the field is in a form post or in the URL (like a GET query).

If you want to continue using individual arguments on the input then the key is generate the client request to provide named query parameters, either in the URL (for a GET) or in the body of the POST.

What characters are valid for JavaScript variable names?

From the ECMAScript specification in section 7.6 Identifier Names and Identifiers, a valid identifier is defined as:

Identifier :: 
    IdentifierName but not ReservedWord

IdentifierName :: 
    IdentifierStart 
    IdentifierName IdentifierPart 

IdentifierStart :: 
    UnicodeLetter 
    $ 
    _ 
    \ UnicodeEscapeSequence 

IdentifierPart :: 
    IdentifierStart 
    UnicodeCombiningMark 
    UnicodeDigit 
    UnicodeConnectorPunctuation 
    \ UnicodeEscapeSequence 

UnicodeLetter 
    any character in the Unicode categories “Uppercase letter (Lu)”, “Lowercase letter (Ll)”, “Titlecase letter (Lt)”, 
    “Modifier letter (Lm)”, “Other letter (Lo)”, or “Letter number (Nl)”. 

UnicodeCombiningMark 
    any character in the Unicode categories “Non-spacing mark (Mn)” or “Combining spacing mark (Mc)” 

UnicodeDigit 
    any character in the Unicode category “Decimal number (Nd)” 

UnicodeConnectorPunctuation 
    any character in the Unicode category “Connector punctuation (Pc)” 

UnicodeEscapeSequence 
    see 7.8.4. 

HexDigit :: one of 
    0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F

which creates a lot of opportunities for naming variables and also in golfing. Let's try some examples.

A valid identifier could start with either a UnicodeLetter, $, _, or \ UnicodeEscapeSequence. A unicode letter is any character from these categories (see all categories):

  • Uppercase letter (Lu)
  • Lowercase letter (Ll)
  • Titlecase letter (Lt)
  • Modifier letter (Lm)
  • Other letter (Lo)
  • Letter number (Nl)

This alone accounts for some crazy possibilities - working examples. If it doesn't work in all browsers, then call it a bug, cause it should.

var ? = "something";
var HELLO = "hello";
var ???? = "less than? wtf";
var ????????????? = "javascript"; // ok that's JavaScript in hindi
var KingGeorge? = "Roman numerals, awesome!";

How do I POST with multipart form data using fetch?

You're setting the Content-Type to be multipart/form-data, but then using JSON.stringify on the body data, which returns application/json. You have a content type mismatch.

You will need to encode your data as multipart/form-data instead of json. Usually multipart/form-data is used when uploading files, and is a bit more complicated than application/x-www-form-urlencoded (which is the default for HTML forms).

The specification for multipart/form-data can be found in RFC 1867.

For a guide on how to submit that kind of data via javascript, see here.

The basic idea is to use the FormData object (not supported in IE < 10):

async function sendData(url, data) {
  const formData  = new FormData();

  for(const name in data) {
    formData.append(name, data[name]);
  }

  const response = await fetch(url, {
    method: 'POST',
    body: formData
  });

  // ...
}

Per this article make sure not to set the Content-Type header. The browser will set it for you, including the boundary parameter.

How to export data to an excel file using PHPExcel

Try the below complete example for the same

<?php
  $objPHPExcel = new PHPExcel();
  $query1 = "SELECT * FROM employee";
  $exec1 = mysql_query($query1) or die ("Error in Query1".mysql_error());
  $serialnumber=0;
  //Set header with temp array
  $tmparray =array("Sr.Number","Employee Login","Employee Name");
  //take new main array and set header array in it.
  $sheet =array($tmparray);

  while ($res1 = mysql_fetch_array($exec1))
  {
    $tmparray =array();
    $serialnumber = $serialnumber + 1;
    array_push($tmparray,$serialnumber);
    $employeelogin = $res1['employeelogin'];
    array_push($tmparray,$employeelogin);
    $employeename = $res1['employeename'];
    array_push($tmparray,$employeename);   
    array_push($sheet,$tmparray);
  }
   header('Content-type: application/vnd.ms-excel');
   header('Content-Disposition: attachment; filename="name.xlsx"');
  $worksheet = $objPHPExcel->getActiveSheet();
  foreach($sheet as $row => $columns) {
    foreach($columns as $column => $data) {
        $worksheet->setCellValueByColumnAndRow($column, $row + 1, $data);
    }
  }

  //make first row bold
  $objPHPExcel->getActiveSheet()->getStyle("A1:I1")->getFont()->setBold(true);
  $objPHPExcel->setActiveSheetIndex(0);
  $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  $objWriter->save(str_replace('.php', '.xlsx', __FILE__));
?>

Spring MVC: how to create a default controller for index page?

I had the same problem, even after following Sinhue's setup, but I solved it.

The problem was that that something (Tomcat?) was forwarding from "/" to "/index.jsp" when I had the file index.jsp in my WebContent directory. When I removed that, the request did not get forwarded anymore.

What I did to diagnose the problem was to make a catch-all request handler and printed the servlet path to the console. This showed me that even though the request I was making was for http://localhost/myapp/, the servlet path was being changed to "/index.html". I was expecting it to be "/".

@RequestMapping("*")
public String hello(HttpServletRequest request) {
    System.out.println(request.getServletPath());
    return "hello";
}

So in summary, the steps you need to follow are:

  1. In your servlet-mapping use <url-pattern>/</url-pattern>
  2. In your controller use RequestMapping("/")
  3. Get rid of welcome-file-list in web.xml
  4. Don't have any files sitting in WebContent that would be considered default pages (index.html, index.jsp, default.html, etc)

Hope this helps.

How to get device make and model on iOS?

EITHER try this library: http://github.com/erica/uidevice-extension/ (by Erica Sadun). (The library is 7-8 years old, and hence is obsolete)

(Sample Code):

    [[UIDevice currentDevice] platformType]   // ex: UIDevice4GiPhone
    [[UIDevice currentDevice] platformString] // ex: @"iPhone 4G"

OR You can use this method:

You can get the device model number using uname from sys/utsname.h. For example:

Objective-C

    #import <sys/utsname.h> // import it in your header or implementation file.

    NSString* deviceName()
    {
        struct utsname systemInfo;
        uname(&systemInfo);
    
        return [NSString stringWithCString:systemInfo.machine
                                  encoding:NSUTF8StringEncoding];
    }

Swift 3

    extension UIDevice {
        var modelName: String {
            var systemInfo = utsname()
            uname(&systemInfo)
            let machineMirror = Mirror(reflecting: systemInfo.machine)
            let identifier = machineMirror.children.reduce("") { identifier, element in
                guard let value = element.value as? Int8, value != 0 else { return identifier }
                return identifier + String(UnicodeScalar(UInt8(value)))
            }
            return identifier
        }
    }

    print(UIDevice.current.modelName)

The result should be:

// Output on a simulator
@"i386"      on 32-bit Simulator
@"x86_64"    on 64-bit Simulator

// Output on an iPhone
@"iPhone1,1" on iPhone
@"iPhone1,2" on iPhone 3G
@"iPhone2,1" on iPhone 3GS
@"iPhone3,1" on iPhone 4 (GSM)
@"iPhone3,2" on iPhone 4 (GSM Rev A)
@"iPhone3,3" on iPhone 4 (CDMA/Verizon/Sprint)
@"iPhone4,1" on iPhone 4S
@"iPhone5,1" on iPhone 5 (model A1428, AT&T/Canada)
@"iPhone5,2" on iPhone 5 (model A1429, everything else)
@"iPhone5,3" on iPhone 5c (model A1456, A1532 | GSM)
@"iPhone5,4" on iPhone 5c (model A1507, A1516, A1526 (China), A1529 | Global)
@"iPhone6,1" on iPhone 5s (model A1433, A1533 | GSM)
@"iPhone6,2" on iPhone 5s (model A1457, A1518, A1528 (China), A1530 | Global)
@"iPhone7,1" on iPhone 6 Plus
@"iPhone7,2" on iPhone 6
@"iPhone8,1" on iPhone 6S
@"iPhone8,2" on iPhone 6S Plus
@"iPhone8,4" on iPhone SE
@"iPhone9,1" on iPhone 7 (CDMA)
@"iPhone9,3" on iPhone 7 (GSM)
@"iPhone9,2" on iPhone 7 Plus (CDMA)
@"iPhone9,4" on iPhone 7 Plus (GSM)
@"iPhone10,1" on iPhone 8 (CDMA)
@"iPhone10,4" on iPhone 8 (GSM)
@"iPhone10,2" on iPhone 8 Plus (CDMA)
@"iPhone10,5" on iPhone 8 Plus (GSM)
@"iPhone10,3" on iPhone X (CDMA)
@"iPhone10,6" on iPhone X (GSM)
@"iPhone11,2" on iPhone XS
@"iPhone11,4" on iPhone XS Max
@"iPhone11,6" on iPhone XS Max China
@"iPhone11,8" on iPhone XR
@"iPhone12,1" on iPhone 11
@"iPhone12,3" on iPhone 11 Pro
@"iPhone12,5" on iPhone 11 Pro Max
@"iPhone12,8" on iPhone SE (2nd Gen)
@"iPhone13,1" on iPhone 12 Mini
@"iPhone13,2" on iPhone 12
@"iPhone13,3" on iPhone 12 Pro
@"iPhone13,4" on iPhone 12 Pro Max

//iPad 1
@"iPad1,1" on iPad - Wifi (model A1219)
@"iPad1,2" on iPad - Wifi + Cellular (model A1337)

//iPad 2
@"iPad2,1" - Wifi (model A1395)
@"iPad2,2" - GSM (model A1396)
@"iPad2,3" - 3G (model A1397)
@"iPad2,4" - Wifi (model A1395)

// iPad Mini
@"iPad2,5" - Wifi (model A1432)
@"iPad2,6" - Wifi + Cellular (model  A1454)
@"iPad2,7" - Wifi + Cellular (model  A1455)

//iPad 3
@"iPad3,1" - Wifi (model A1416)
@"iPad3,2" - Wifi + Cellular (model  A1403)
@"iPad3,3" - Wifi + Cellular (model  A1430)

//iPad 4
@"iPad3,4" - Wifi (model A1458)
@"iPad3,5" - Wifi + Cellular (model  A1459)
@"iPad3,6" - Wifi + Cellular (model  A1460)

//iPad AIR
@"iPad4,1" - Wifi (model A1474)
@"iPad4,2" - Wifi + Cellular (model A1475)
@"iPad4,3" - Wifi + Cellular (model A1476)

// iPad Mini 2
@"iPad4,4" - Wifi (model A1489)
@"iPad4,5" - Wifi + Cellular (model A1490)
@"iPad4,6" - Wifi + Cellular (model A1491)

// iPad Mini 3
@"iPad4,7" - Wifi (model A1599)
@"iPad4,8" - Wifi + Cellular (model A1600)
@"iPad4,9" - Wifi + Cellular (model A1601)

// iPad Mini 4
@"iPad5,1" - Wifi (model A1538)
@"iPad5,2" - Wifi + Cellular (model A1550)

//iPad AIR 2
@"iPad5,3" - Wifi (model A1566)
@"iPad5,4" - Wifi + Cellular (model A1567)

// iPad PRO 9.7"
@"iPad6,3" - Wifi (model A1673)
@"iPad6,4" - Wifi + Cellular (model A1674)
@"iPad6,4" - Wifi + Cellular (model A1675)

//iPad PRO 12.9"
@"iPad6,7" - Wifi (model A1584)
@"iPad6,8" - Wifi + Cellular (model A1652)

//iPad (5th generation)
@"iPad6,11" - Wifi (model A1822)
@"iPad6,12" - Wifi + Cellular (model A1823)
         
//iPad PRO 12.9" (2nd Gen)
@"iPad7,1" - Wifi (model A1670)
@"iPad7,2" - Wifi + Cellular (model A1671)
@"iPad7,2" - Wifi + Cellular (model A1821)
         
//iPad PRO 10.5"
@"iPad7,3" - Wifi (model A1701)
@"iPad7,4" - Wifi + Cellular (model A1709)

// iPad (6th Gen)
@"iPad7,5" - WiFi
@"iPad7,6" - WiFi + Cellular

// iPad (7th Gen)
@"iPad7,11" - WiFi
@"iPad7,12" - WiFi + Cellular

//iPad PRO 11"
@"iPad8,1" - WiFi
@"iPad8,2" - 1TB, WiFi
@"iPad8,3" - WiFi + Cellular
@"iPad8,4" - 1TB, WiFi + Cellular

//iPad PRO 12.9" (3rd Gen)
@"iPad8,5" - WiFi
@"iPad8,6" - 1TB, WiFi
@"iPad8,7" - WiFi + Cellular
@"iPad8,8" - 1TB, WiFi + Cellular

//iPad PRO 11" (2nd Gen)
@"iPad8,9" - WiFi
@"iPad8,10" - 1TB, WiFi

//iPad PRO 12.9" (4th Gen)
@"iPad8,11" - (WiFi)
@"iPad8,12" - (WiFi+Cellular)

// iPad mini 5th Gen
@"iPad11,1" - WiFi
@"iPad11,2" - Wifi  + Cellular

// iPad Air 3rd Gen
@"iPad11,3" - Wifi 
@"iPad11,4" - Wifi  + Cellular

// iPad (8th Gen)
@"iPad11,6" - iPad 8th Gen (WiFi)
@"iPad11,7" - iPad 8th Gen (WiFi+Cellular)

// iPad Air 4th Gen
@"iPad13,1" - iPad air 4th Gen (WiFi)
@"iPad13,2" - iPad air 4th Gen (WiFi+Cellular)

//iPod Touch
@"iPod1,1"   on iPod Touch
@"iPod2,1"   on iPod Touch Second Generation
@"iPod3,1"   on iPod Touch Third Generation
@"iPod4,1"   on iPod Touch Fourth Generation
@"iPod5,1"   on iPod Touch 5th Generation
@"iPod7,1"   on iPod Touch 6th Generation
@"iPod9,1"   on iPod Touch 7th Generation

// Apple Watch
@"Watch1,1" on Apple Watch 38mm case
@"Watch1,2" on Apple Watch 38mm case
@"Watch2,6" on Apple Watch Series 1 38mm case
@"Watch2,7" on Apple Watch Series 1 42mm case
@"Watch2,3" on Apple Watch Series 2 38mm case
@"Watch2,4" on Apple Watch Series 2 42mm case
@"Watch3,1" on Apple Watch Series 3 38mm case (GPS+Cellular)
@"Watch3,2" on Apple Watch Series 3 42mm case (GPS+Cellular)
@"Watch3,3" on Apple Watch Series 3 38mm case (GPS)
@"Watch3,4" on Apple Watch Series 3 42mm case (GPS)
@"Watch4,1" on Apple Watch Series 4 40mm case (GPS)
@"Watch4,2" on Apple Watch Series 4 44mm case (GPS)
@"Watch4,3" on Apple Watch Series 4 40mm case (GPS+Cellular)
@"Watch4,4" on Apple Watch Series 4 44mm case (GPS+Cellular)
@"Watch5,1" on Apple Watch Series 5 40mm case (GPS)
@"Watch5,2" on Apple Watch Series 5 44mm case (GPS)
@"Watch5,3" on Apple Watch Series 5 40mm case (GPS+Cellular)
@"Watch5,4" on Apple Watch Series 5 44mm case (GPS+Cellular)
@"Watch5,9" on Apple Watch SE 40mm case (GPS)
@"Watch5,10" on Apple Watch SE 44mm case (GPS)
@"Watch5,11" on Apple Watch SE 40mm case (GPS+Cellular)
@"Watch5,12" on Apple Watch SE 44mm case (GPS+Cellular)
@"Watch6,1" on Apple Watch Series 6 40mm case (GPS)
@"Watch6,2" on Apple Watch Series 6 44mm case (GPS)
@"Watch6,3" on Apple Watch Series 6 40mm case (GPS+Cellular)
@"Watch6,4" on Apple Watch Series 6 44mm case (GPS+Cellular)

Add external libraries to CMakeList.txt c++

I would start with upgrade of CMAKE version.

You can use INCLUDE_DIRECTORIES for header location and LINK_DIRECTORIES + TARGET_LINK_LIBRARIES for libraries

INCLUDE_DIRECTORIES(your/header/dir)
LINK_DIRECTORIES(your/library/dir)
rosbuild_add_executable(kinectueye src/kinect_ueye.cpp)
TARGET_LINK_LIBRARIES(kinectueye lib1 lib2 lib2 ...)

note that lib1 is expanded to liblib1.so (on Linux), so use ln to create appropriate links in case you do not have them

Are 2 dimensional Lists possible in c#?

Here's a little something that I made a while ago for a game engine I was working on. It was used as a local object variable holder. Basically, you use it as a normal list, but it holds the value at the position of what ever the string name is(or ID). A bit of modification, and you will have your 2D list.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GameEngineInterpreter
{
    public class VariableList<T>
    {
        private List<string> list1;
        private List<T> list2;

        /// <summary>
        /// Initialize a new Variable List
        /// </summary>
        public VariableList()
        {
            list1 = new List<string>();
            list2 = new List<T>();
        }

        /// <summary>
        /// Set the value of a variable. If the variable does not exist, then it is created
        /// </summary>
        /// <param name="variable">Name or ID of the variable</param>
        /// <param name="value">The value of the variable</param>
        public void Set(string variable, T value)
        {
            if (!list1.Contains(variable))
            {
                list1.Add(variable);
                list2.Add(value);
            }
            else
            {
                list2[list1.IndexOf(variable)] = value;
            }
        }

        /// <summary>
        /// Remove the variable if it exists
        /// </summary>
        /// <param name="variable">Name or ID of the variable</param>
        public void Remove(string variable)
        {
            if (list1.Contains(variable))
            {
                list2.RemoveAt(list1.IndexOf(variable));
                list1.RemoveAt(list1.IndexOf(variable));
            }
        }

        /// <summary>
        /// Clears the variable list
        /// </summary>
        public void Clear()
        {
            list1.Clear();
            list2.Clear();
        }

        /// <summary>
        /// Get the value of the variable if it exists
        /// </summary>
        /// <param name="variable">Name or ID of the variable</param>
        /// <returns>Value</returns>
        public T Get(string variable)
        {
            if (list1.Contains(variable))
            {
                return (list2[list1.IndexOf(variable)]);
            }
            else
            {
                return default(T);
            }
        }

        /// <summary>
        /// Get a string list of all the variables 
        /// </summary>
        /// <returns>List string</string></returns>
        public List<string> GetList()
        {
            return (list1);
        }
    }
}

How to reset sequence in postgres and fill id column with new data?

If you don't want to retain the ordering of ids, then you can

ALTER SEQUENCE seq RESTART WITH 1;
UPDATE t SET idcolumn=nextval('seq');

I doubt there's an easy way to do that in the order of your choice without recreating the whole table.

Clear the value of bootstrap-datepicker

I found the best anwser, it work for me. Clear the value of bootstrap-datepicker:

$('#datepicker').datepicker('setDate', null);

Add value for boostrap-datepicker:

$('#datepicker').datepicker('setDate', datePicker);

Attempted to read or write protected memory

Check to make sure you don't have threads within threads. That's what caused this error for me. See this link: Attempted to read or write protected memory. This is often an indication that other memory is corrupt

How should I import data from CSV into a Postgres table using pgAdmin 3?

You may have a table called 'test'

COPY test(gid, "name", the_geom)
FROM '/home/data/sample.csv'
WITH DELIMITER ','
CSV HEADER

When to use extern in C++

This is useful when you want to have a global variable. You define the global variables in some source file, and declare them extern in a header file so that any file that includes that header file will then see the same global variable.

Pandas DataFrame: replace all values in a column, based on condition

We can update the First Season column in df with the following syntax:

df['First Season'] = expression_for_new_values

To map the values in First Season we can use pandas‘ .map() method with the below syntax:

data_frame(['column']).map({'initial_value_1':'updated_value_1','initial_value_2':'updated_value_2'})

Copying a rsa public key to clipboard

Does the file ~/.ssh/id_rsa.pub exist? If not, you need to generate one first:

ssh-keygen -t rsa -C "[email protected]"

Skip first entry in for loop in python?

Here is a more general generator function that skips any number of items from the beginning and end of an iterable:

def skip(iterable, at_start=0, at_end=0):
    it = iter(iterable)
    for x in itertools.islice(it, at_start):
        pass
    queue = collections.deque(itertools.islice(it, at_end))
    for x in it:
        queue.append(x)
        yield queue.popleft()

Example usage:

>>> list(skip(range(10), at_start=2, at_end=2))
[2, 3, 4, 5, 6, 7]

No serializer found for class org.hibernate.proxy.pojo.javassist.Javassist?

This is an issue with Jackson. To prevent this, instruct Jackson not to serialize nested relationship or nested class.

Look at the following example. Address class mapped to City, State, and Country classes and the State itself is pointing to Country and Country pointing to Region. When your get address values through Spring boot REST API you will get the above error. To prevent it, just serialize mapped class ( which reflects level one JSON) and ignore nested relationships with @JsonIgnoreProperties(value = {"state"}),@JsonIgnoreProperties(value = {"country"}) and @JsonIgnoreProperties(value = {"region"})

This will prevent Lazyload exception along with the above error. Use the below code as an example and change your model classes.

Address.java

@Entity
public class Address extends AbstractAuditingEntity
{
    private static final long serialVersionUID = 4203344613880544060L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @Column(name = "street_name")
    private String streetName;

    @Column(name = "apartment")
    private String apartment;

    @ManyToOne
    @JoinColumn(name = "city_id")
    @JsonIgnoreProperties(value = {"state"})
    private City city;

    @ManyToOne
    @JoinColumn(name = "state_id")
    @JsonIgnoreProperties(value = {"country"})
    private State state;

    @ManyToOne
    @JoinColumn(name = "country_id")
    @JsonIgnoreProperties(value = {"region"})
    private Country country;

    @ManyToOne
    @JoinColumn(name = "region_id")
    private Region region;

    @Column(name = "zip_code")
    private String zipCode;

    @ManyToOne
    @JoinColumn(name = "address_type_id", referencedColumnName = "id")
    private AddressType addressType;

}

City.java

@EqualsAndHashCode(callSuper = true)
@Entity
@Table(name = "city")
@Cache(region = "cityCache",usage = CacheConcurrencyStrategy.READ_WRITE)
@Data
public class City extends AbstractAuditingEntity
{
    private static final long serialVersionUID = -8825045541258851493L;

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "name")
    //@Length(max = 100,min = 2)
    private String name;


    @ManyToOne
    @JoinColumn(name = "state_id")
    private State state;
}

State.java

@Entity
@Table(name = "state")
@Data
@EqualsAndHashCode(callSuper = true)
public class State extends AbstractAuditingEntity
{
    private static final long serialVersionUID = 5553856435782266275L;

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "code")
    private String code;

    @Column(name = "name")
    @Length(max = 200, min = 2)
    private String name;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "country_id")
    private Country country;

}

Country.java

@Entity
@Table(name = "country")
@Data
@EqualsAndHashCode(callSuper = true)
public class Country extends AbstractAuditingEntity
{
    private static final long serialVersionUID = 6396100319470393108L;

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "name")
    @Length(max = 200, min = 2)
    private String name;

    @Column(name = "code")
    @Length(max = 3, min = 2)
    private String code;

    @Column(name = "iso_code")
    @Length(max = 3, min = 2)
    private String isoCode;

    @ManyToOne
    @JoinColumn(name = "region_id")
    private Region region;
}

How to pass ArrayList<CustomeObject> from one activity to another?

You can pass an ArrayList<E> the same way, if the E type is Serializable.

You would call the putExtra (String name, Serializable value) of Intent to store, and getSerializableExtra (String name) for retrieval.

Example:

ArrayList<String> myList = new ArrayList<String>();
intent.putExtra("mylist", myList);

In the other Activity:

ArrayList<String> myList = (ArrayList<String>) getIntent().getSerializableExtra("mylist");

How to write inside a DIV box with javascript

HTML:

<div id="log"></div>

JS:

document.getElementById("log").innerHTML="WHATEVER YOU WANT...";

Python Threading String Arguments

from threading import Thread
from time import sleep
def run(name):
    for x in range(10):
        print("helo "+name)
        sleep(1)
def run1():
    for x in range(10):
        print("hi")
        sleep(1)
T=Thread(target=run,args=("Ayla",))
T1=Thread(target=run1)
T.start()
sleep(0.2)
T1.start()
T.join()
T1.join()
print("Bye")

Creating table variable in SQL server 2008 R2

@tableName Table variables are alive for duration of the script running only i.e. they are only session level objects.

To test this, open two query editor windows under sql server management studio, and create table variables with same name but different structures. You will get an idea. The @tableName object is thus temporary and used for our internal processing of data, and it doesn't contribute to the actual database structure.

There is another type of table object which can be created for temporary use. They are #tableName objects declared like similar create statement for physical tables:

Create table #test (Id int, Name varchar(50))

This table object is created and stored in temp database. Unlike the first one, this object is more useful, can store large data and takes part in transactions etc. These tables are alive till the connection is open. You have to drop the created object by following script before re-creating it.

IF OBJECT_ID('tempdb..#test') IS NOT NULL
  DROP TABLE #test 

Hope this makes sense !

Set new id with jQuery

What happens when you set all of the attributes in one attr() command like so

$(this).attr({
               id : this.id + '_' + new_id,
               name: this.name + '_' + new_id,
               value: 'test' 
             });

sql how to cast a select query

I interpreted the question as using cast on a subquery. Yes, you can do that:

select cast((<subquery>) as <newtype>)

If you do so, then you need to be sure that the returns one row and one value. And, since it returns one value, you could put the cast in the subquery instead:

select (select cast(<val> as <newtype>) . . .)

Error: Execution failed for task ':app:clean'. Unable to delete file

try to remove these files manually

In my case I just removed all build directories from project and subprojects

Output single character in C

yes, %c will print a single char:

printf("%c", 'h');

also, putchar/putc will work too. From "man putchar":

#include <stdio.h>

int fputc(int c, FILE *stream);
int putc(int c, FILE *stream);
int putchar(int c);

* fputc() writes the character c, cast to an unsigned char, to stream.
* putc() is equivalent to fputc() except that it may be implemented as a macro which evaluates stream more than once.
* putchar(c); is equivalent to putc(c,stdout).

EDIT:

Also note, that if you have a string, to output a single char, you need get the character in the string that you want to output. For example:

const char *h = "hello world";
printf("%c\n", h[4]); /* outputs an 'o' character */

How to use global variable in node.js?

you can define it with using global or GLOBAL, nodejs supports both.

for e.g

global.underscore = require("underscore");

or

GLOBAL.underscore = require("underscore");

Get the current language in device

here is code to get device country. Compatible with all versions of android even oreo.

Solution: if user does not have sim card than get country he is used during phone setup , or current language selection.

public static String getDeviceCountry(Context context) {
    String deviceCountryCode = null;

    final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

        if(tm != null) {
            deviceCountryCode = tm.getNetworkCountryIso();
        }

    if (deviceCountryCode != null && deviceCountryCode.length() <=3) {
        deviceCountryCode = deviceCountryCode.toUpperCase();
    }
    else {
        deviceCountryCode = ConfigurationCompat.getLocales(Resources.getSystem().getConfiguration()).get(0).getCountry().toUpperCase();
    }

  //  Log.d("countryCode","  : " + deviceCountryCode );
    return deviceCountryCode;
}

Configure Apache .conf for Alias

Sorry not sure what was going on this worked in the end:

<VirtualHost *> 
    ServerName example.com
    DocumentRoot /var/www/html/mjp

    Alias /ncn "/var/www/html/ncn"

    <Directory "/var/www/html/ncn">
        Options None
        AllowOverride None
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

How to start Activity in adapter?

If you want to redirect on url instead of activity from your adapter class then pass context of with startactivity.

btnInstall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(Intent.ACTION_VIEW, Uri.parse(link));
                intent.setData(Uri.parse(link));
                context.startActivity(intent);
            }
        });

Transform hexadecimal information to binary using a Linux command

As @user786653 suggested, use the xxd(1) program:

xxd -r -p input.txt output.bin

In c# is there a method to find the max of 3 numbers?

As generic

public static T Min<T>(params T[] values) {
    return values.Min();
}

public static T Max<T>(params T[] values) {
    return values.Max();
}

How to install a certificate in Xcode (preparing for app store submission)

Under

Provisioning -> Distribution -> Distribution Provisioning Profiles

I downloaded the desired certificate again and installed it. Now I don't see an empty file in Xcode. The build also works now (no code sign error).

What I also did: I downloaded the WWDR and installed it, but I don't know if that was the reason (because I think it's always the same)

How to handle iframe in Selenium WebDriver using java

You have to get back out of the Iframe with the following code:

driver.switchTo().frame(driver.findElement(By.id("frameId")));
//do your stuff
driver.switchTo().defaultContent();

hope that helps

How to code a modulo (%) operator in C/C++/Obj-C that handles negative numbers

The best solution ¹for a mathematician is to use Python.

C++ operator overloading has little to do with it. You can't overload operators for built-in types. What you want is simply a function. Of course you can use C++ templating to implement that function for all relevant types with just 1 piece of code.

The standard C library provides fmod, if I recall the name correctly, for floating point types.

For integers you can define a C++ function template that always returns non-negative remainder (corresponding to Euclidian division) as ...

#include <stdlib.h>  // abs

template< class Integer >
auto mod( Integer a, Integer b )
    -> Integer
{
    Integer const r = a%b;
    return (r < 0? r + abs( b ) : r);
}

... and just write mod(a, b) instead of a%b.

Here the type Integer needs to be a signed integer type.

If you want the common math behavior where the sign of the remainder is the same as the sign of the divisor, then you can do e.g.

template< class Integer >
auto floor_div( Integer const a, Integer const b )
    -> Integer
{
    bool const a_is_negative = (a < 0);
    bool const b_is_negative = (b < 0);
    bool const change_sign  = (a_is_negative != b_is_negative);

    Integer const abs_b         = abs( b );
    Integer const abs_a_plus    = abs( a ) + (change_sign? abs_b - 1 : 0);

    Integer const quot = abs_a_plus / abs_b;
    return (change_sign? -quot : quot);
}

template< class Integer >
auto floor_mod( Integer const a, Integer const b )
    -> Integer
{ return a - b*floor_div( a, b ); }

… with the same constraint on Integer, that it's a signed type.


¹ Because Python's integer division rounds towards negative infinity.

How do ports work with IPv6?

They work almost the same as today. However, be sure you include [] around your IP.

For example : http://[1fff:0:a88:85a3::ac1f]:8001/index.html

Wikipedia has a pretty good article about IPv6: http://en.wikipedia.org/wiki/IPv6#Addressing

Singleton with Arguments in Java

I think this is a common problem. Separating the "initialization" of the singleton from the "get" of the singleton might work (this example uses a variation of double checked locking).

public class MySingleton {

    private static volatile MySingleton INSTANCE;

    @SuppressWarnings("UnusedAssignment")
    public static void initialize(
            final SomeDependency someDependency) {

        MySingleton result = INSTANCE;

        if (result != null) {
            throw new IllegalStateException("The singleton has already "
                    + "been initialized.");
        }

        synchronized (MySingleton.class) {
            result = INSTANCE;

            if (result == null) {
                INSTANCE = result = new MySingleton(someDependency);
            } 
        }
    }

    public static MySingleton get() {
        MySingleton  result = INSTANCE;

        if (result == null) {
            throw new IllegalStateException("The singleton has not been "
                    + "initialized. You must call initialize(...) before "
                    + "calling get()");
        }

       return result;
    }

    ...
}

Pointer-to-pointer dynamic two-dimensional array

this can be done this way

  1. I have used Operator Overloading
  2. Overloaded Assignment
  3. Overloaded Copy Constructor

    /*
     * Soumil Nitin SHah
     * Github: https://github.com/soumilshah1995
     */
    
    #include <iostream>
    using namespace std;
            class Matrix{
    
    public:
        /*
         * Declare the Row and Column
         *
         */
        int r_size;
        int c_size;
        int **arr;
    
    public:
        /*
         * Constructor and Destructor
         */
    
        Matrix(int r_size, int c_size):r_size{r_size},c_size{c_size}
        {
            arr = new int*[r_size];
            // This Creates a 2-D Pointers
            for (int i=0 ;i < r_size; i++)
            {
                arr[i] = new int[c_size];
            }
    
            // Initialize all the Vector to 0 initially
            for (int row=0; row<r_size; row ++)
            {
                for (int column=0; column < c_size; column ++)
                {
                    arr[row][column] = 0;
                }
            }
            std::cout << "Constructor -- creating Array Size ::" << r_size << " " << c_size << endl;
        }
    
        ~Matrix()
        {
            std::cout << "Destructpr  -- Deleting  Array Size ::" << r_size <<" " << c_size << endl;
    
        }
    
        Matrix(const Matrix &source):Matrix(source.r_size, source.c_size)
    
        {
            for (int row=0; row<source.r_size; row ++)
            {
                for (int column=0; column < source.c_size; column ++)
                {
                    arr[row][column] = source.arr[row][column];
                }
            }
    
            cout << "Copy Constructor " << endl;
        }
    
    
    public:
        /*
         * Operator Overloading
         */
    
        friend std::ostream &operator<<(std::ostream &os, Matrix & rhs)
        {
            int rowCounter = 0;
            int columnCOUNTER = 0;
            int globalCounter = 0;
    
            for (int row =0; row < rhs.r_size; row ++)
            {
                for (int column=0; column < rhs.c_size ; column++)
                {
                    globalCounter = globalCounter + 1;
                }
                rowCounter = rowCounter + 1;
            }
    
    
            os << "Total There are " << globalCounter << " Elements" << endl;
            os << "Array Elements are as follow -------" << endl;
            os << "\n";
    
            for (int row =0; row < rhs.r_size; row ++)
            {
                for (int column=0; column < rhs.c_size ; column++)
                {
                    os << rhs.arr[row][column] << " ";
                }
            os <<"\n";
            }
            return os;
        }
    
        void operator()(int row, int column , int Data)
        {
            arr[row][column] = Data;
        }
    
        int &operator()(int row, int column)
        {
            return arr[row][column];
        }
    
        Matrix &operator=(Matrix &rhs)
                {
                    cout << "Assingment Operator called " << endl;cout <<"\n";
                    if(this == &rhs)
                    {
                        return *this;
                    } else
                        {
                        delete [] arr;
    
                            arr = new int*[r_size];
                            // This Creates a 2-D Pointers
                            for (int i=0 ;i < r_size; i++)
                            {
                                arr[i] = new int[c_size];
                            }
    
                            // Initialize all the Vector to 0 initially
                            for (int row=0; row<r_size; row ++)
                            {
                                for (int column=0; column < c_size; column ++)
                                {
                                    arr[row][column] = rhs.arr[row][column];
                                }
                            }
    
                            return *this;
                        }
    
                }
    
    };
    
                int main()
    {
    
        Matrix m1(3,3);         // Initialize Matrix 3x3
    
        cout << m1;cout << "\n";
    
        m1(0,0,1);
        m1(0,1,2);
        m1(0,2,3);
    
        m1(1,0,4);
        m1(1,1,5);
        m1(1,2,6);
    
        m1(2,0,7);
        m1(2,1,8);
        m1(2,2,9);
    
        cout << m1;cout <<"\n";             // print Matrix
        cout << "Element at Position (1,2) : " << m1(1,2) << endl;
    
        Matrix m2(3,3);
        m2 = m1;
        cout << m2;cout <<"\n";
    
        print(m2);
    
        return 0;
    }
    

Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path

In this case that you know that you have all items in the first place on array you can parse the string to JArray and then parse the first item using JObject.Parse

var  jsonArrayString = @"
[
  {
    ""country"": ""India"",
    ""city"": ""Mall Road, Gurgaon"",
  },
  {
    ""country"": ""India"",
    ""city"": ""Mall Road, Kanpur"",
  }
]";
JArray jsonArray = JArray.Parse(jsonArrayString);
dynamic data = JObject.Parse(jsonArray[0].ToString());

C++ Get name of type in template

typeid(uint8_t).name() is nice, but it returns "unsigned char" while you may expect "uint8_t".

This piece of code will return you the appropriate type

#define DECLARE_SET_FORMAT_FOR(type) \
    if ( typeid(type) == typeid(T) ) \
        formatStr = #type;

template<typename T>
static std::string GetFormatName()
{
    std::string formatStr;

    DECLARE_SET_FORMAT_FOR( uint8_t ) 
    DECLARE_SET_FORMAT_FOR( int8_t ) 

    DECLARE_SET_FORMAT_FOR( uint16_t )
    DECLARE_SET_FORMAT_FOR( int16_t )

    DECLARE_SET_FORMAT_FOR( uint32_t )
    DECLARE_SET_FORMAT_FOR( int32_t )

    DECLARE_SET_FORMAT_FOR( float )

    // .. to be exptended with other standard types you want to be displayed smartly

    if ( formatStr.empty() )
    {
        assert( false );
        formatStr = typeid(T).name();
    }

    return formatStr;
}

Select All Rows Using Entity Framework

How about:

using (ModelName context = new ModelName())
{
    var ptx = (from r in context.TableName select r);
}

ModelName is the class auto-generated by the designer, which inherits from ObjectContext.

Java integer list

So it would become:

List<Integer> myCoords = new ArrayList<Integer>();
myCoords.add(10);
myCoords.add(20);
myCoords.add(30);
myCoords.add(40);
myCoords.add(50);
while(true)
    Iterator<Integer> myListIterator = myCoords.iterator(); 
    while (myListIterator.hasNext()) {
        Integer coord = myListIterator.next();    
        System.out.print("\r" + coord);
        try{
    Thread.sleep(2000);
  }catch(Exception e){
   // handle the exception...
  }
    }
}

Python: how can I check whether an object is of type datetime.date?

If your existing code is already relying on from datetime import datetime, you can also simply also import date

from datetime import datetime, timedelta, date
print isinstance(datetime.today().date(), date)

Show git diff on file in staging area

In order to see the changes that have been staged already, you can pass the -–staged option to git diff (in pre-1.6 versions of Git, use –-cached).

git diff --staged
git diff --cached

Why do multiple-table joins produce duplicate rows?

If one of the tables M, S, D, or H has more than one row for a given Id (if just the Id column is not the Primary Key), then the query would result in "duplicate" rows. If you have more than one row for an Id in a table, then the other columns, which would uniquely identify a row, also must be included in the JOIN condition(s).

References:

Related Question on MSDN Forum

Array of char* should end at '\0' or "\0"?

Null termination is a bad design pattern best left in the history books. There's still plenty of inertia behind c-strings, so it can't be avoided there. But there's no reason to use it in the OP's example.

Don't use any terminator, and use sizeof(array) / sizeof(array[0]) to get the number of elements.

Support for "border-radius" in IE

Use -ms-border-radius: 15px, any element that uses css -ms- is compatible with IE.

How do I do logging in C# without using 3rd party libraries?

If you want to stay close to .NET check out Enterprise Library Logging Application Block. Look here. Or for a quickstart tutorial check this. I have used the Validation application Block from the Enterprise Library and it really suits my needs and is very easy to "inherit" (install it and refrence it!) in your project.

Can you use @Autowired with static fields?

In short, no. You cannot autowire or manually wire static fields in Spring. You'll have to write your own logic to do this.

MySQL: can't access root account

I got the same problem when accessing mysql with root. The problem I found is that some database files does not have permission by the mysql user, which is the user that started the mysql server daemon.

We can check this with ls -l /var/lib/mysql command, if the mysql user does not have permission of reading or writing on some files or directories, that might cause problem. We can change the owner or mode of those files or directories with chown/chmod commands.

After these changes, restart the mysqld daemon and login with root with command:

mysql -u root

Then change passwords or create other users for logging into mysql.

HTH

Using ResourceManager

According to the MSDN documentation here, The basename argument specifies "The root name of the resource file without its extension but including any fully qualified namespace name. For example, the root name for the resource file named "MyApplication.MyResource.en-US.resources" is "MyApplication.MyResource"."

The ResourceManager will automatically try to retrieve the values for the current UI culture. If you want to use a specific language, you'll need to set the current UI culture to the language you wish to use.

How to use the TextWatcher class in Android?

A little bigger perspective of the solution:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.yourlayout, container, false);
        View tv = v.findViewById(R.id.et1);
        ((TextView) tv).addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                 SpannableString contentText = new SpannableString(((TextView) tv).getText());
                 String contents = Html.toHtml(contentText).toString();
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                // TODO Auto-generated method stub
            }

            @Override
            public void afterTextChanged(Editable s) {

                // TODO Auto-generated method stub
            }
        });
        return v;
    }

This works for me, doing it my first time.

Simplest/cleanest way to implement a singleton in JavaScript

I think the easiest way is to declare a simple object literal:

var myInstance = {
  method1: function () {
    // ...
  },
  method2: function () {
    // ...
  }
};

If you want private members on your singleton instance, you can do something like this:

var myInstance = (function() {
  var privateVar = '';

  function privateMethod () {
    // ...
  }

  return { // public interface
    publicMethod1: function () {
      // All private members are accessible here
    },
    publicMethod2: function () {
    }
  };
})();

This has been called the module pattern, and it basically allows you to encapsulate private members on an object, by taking advantage of the use of closures.

If you want to prevent the modification of the singleton object, you can freeze it, using the ES5 Object.freeze method.

That will make the object immutable, preventing any modification to the its structure and values.

If you are using ES6, you can represent a singleton using ES Modules very easily, and you can even hold private state by declaring variables at the module scope:

// my-singleton.js
const somePrivateState = []

function privateFn () {
  // ...
}

export default {
  method1() {
    // ...
  },
  method2() {
    // ...
  }
}

Then you can simply import the singleton object to use it:

import myInstance from './my-singleton.js'
// ...

Match whitespace but not newlines

Use a double-negative:

/[^\S\r\n]/

That is, not-not-whitespace (the capital S complements) or not-carriage-return or not-newline. Distributing the outer not (i.e., the complementing ^ in the character class) with De Morgan's law, this is equivalent to “whitespace but not carriage return or newline.” Including both \r and \n in the pattern correctly handles all of Unix (LF), classic Mac OS (CR), and DOS-ish (CR LF) newline conventions.

No need to take my word for it:

#! /usr/bin/env perl

use strict;
use warnings;

use 5.005;  # for qr//

my $ws_not_crlf = qr/[^\S\r\n]/;

for (' ', '\f', '\t', '\r', '\n') {
  my $qq = qq["$_"];
  printf "%-4s => %s\n", $qq,
    (eval $qq) =~ $ws_not_crlf ? "match" : "no match";
}

Output:

" "  => match
"\f" => match
"\t" => match
"\r" => no match
"\n" => no match

Note the exclusion of vertical tab, but this is addressed in v5.18.

Before objecting too harshly, the Perl documentation uses the same technique. A footnote in the “Whitespace” section of perlrecharclass reads

Prior to Perl v5.18, \s did not match the vertical tab. [^\S\cK] (obscurely) matches what \s traditionally did.

The same section of perlrecharclass also suggests other approaches that won’t offend language teachers’ opposition to double-negatives.

Outside locale and Unicode rules or when the /a switch is in effect, “\s matches [\t\n\f\r ] and, starting in Perl v5.18, the vertical tab, \cK.” Discard \r and \n to leave /[\t\f\cK ]/ for matching whitespace but not newline.

If your text is Unicode, use code similar to the sub below to construct a pattern from the table in the aforementioned documentation section.

sub ws_not_nl {
  local($_) = <<'EOTable';
0x0009        CHARACTER TABULATION   h s
0x000a              LINE FEED (LF)    vs
0x000b             LINE TABULATION    vs  [1]
0x000c              FORM FEED (FF)    vs
0x000d        CARRIAGE RETURN (CR)    vs
0x0020                       SPACE   h s
0x0085             NEXT LINE (NEL)    vs  [2]
0x00a0              NO-BREAK SPACE   h s  [2]
0x1680            OGHAM SPACE MARK   h s
0x2000                     EN QUAD   h s
0x2001                     EM QUAD   h s
0x2002                    EN SPACE   h s
0x2003                    EM SPACE   h s
0x2004          THREE-PER-EM SPACE   h s
0x2005           FOUR-PER-EM SPACE   h s
0x2006            SIX-PER-EM SPACE   h s
0x2007                FIGURE SPACE   h s
0x2008           PUNCTUATION SPACE   h s
0x2009                  THIN SPACE   h s
0x200a                  HAIR SPACE   h s
0x2028              LINE SEPARATOR    vs
0x2029         PARAGRAPH SEPARATOR    vs
0x202f       NARROW NO-BREAK SPACE   h s
0x205f   MEDIUM MATHEMATICAL SPACE   h s
0x3000           IDEOGRAPHIC SPACE   h s
EOTable

  my $class;
  while (/^0x([0-9a-f]{4})\s+([A-Z\s]+)/mg) {
    my($hex,$name) = ($1,$2);
    next if $name =~ /\b(?:CR|NL|NEL|SEPARATOR)\b/;
    $class .= "\\N{U+$hex}";
  }

  qr/[$class]/u;
}

Other Applications

The double-negative trick is also handy for matching alphabetic characters too. Remember that \w matches “word characters,” alphabetic characters and digits and underscore. We ugly-Americans sometimes want to write it as, say,

if (/[A-Za-z]+/) { ... }

but a double-negative character-class can respect the locale:

if (/[^\W\d_]+/) { ... }

Expressing “a word character but not digit or underscore” this way is a bit opaque. A POSIX character-class communicates the intent more directly

if (/[[:alpha:]]+/) { ... }

or with a Unicode property as szbalint suggested

if (/\p{Letter}+/) { ... }

Write values in app.config file

//if you want change
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
config.AppSettings.Settings[key].Value = value;

//if you want add
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
config.AppSettings.Settings.Add("key", value);

Python Request Post with param data

params is for GET-style URL parameters, data is for POST-style body information. It is perfectly legal to provide both types of information in a request, and your request does so too, but you encoded the URL parameters into the URL already.

Your raw post contains JSON data though. requests can handle JSON encoding for you, and it'll set the correct Content-Type header too; all you need to do is pass in the Python object to be encoded as JSON into the json keyword argument.

You could split out the URL parameters as well:

params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}

then post your data with:

import requests

url = 'http://192.168.3.45:8080/api/v2/event/log'

data = {"eventType": "AAS_PORTAL_START", "data": {"uid": "hfe3hf45huf33545", "aid": "1", "vid": "1"}}
params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}

requests.post(url, params=params, json=data)

The json keyword is new in requests version 2.4.2; if you still have to use an older version, encode the JSON manually using the json module and post the encoded result as the data key; you will have to explicitly set the Content-Type header in that case:

import requests
import json

headers = {'content-type': 'application/json'}
url = 'http://192.168.3.45:8080/api/v2/event/log'

data = {"eventType": "AAS_PORTAL_START", "data": {"uid": "hfe3hf45huf33545", "aid": "1", "vid": "1"}}
params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}

requests.post(url, params=params, data=json.dumps(data), headers=headers)

How do I make a Windows batch script completely silent?

You can redirect stdout to nul to hide it.

COPY %scriptDirectory%test.bat %scriptDirectory%test2.bat >nul

Just add >nul to the commands you want to hide the output from.

Here you can see all the different ways of redirecting the std streams.

C# Macro definitions in Preprocessor

No, C# does not support preprocessor macros like C. Visual Studio on the other hand has snippets. Visual Studio's snippets are a feature of the IDE and are expanded in the editor rather than replaced in the code on compilation by a preprocessor.

Clear and refresh jQuery Chosen dropdown list

MVC 4:

    function Cargar_BS(bs) {
        $.getJSON('@Url.Action("GetBienServicio", "MonitoreoAdministracion")',
                        {
                            id: bs
                        },
                        function (d) {
                            $("#txtIdItem").empty().append('<option value="">-Seleccione-</option>');
                            $.each(d, function (idx, item) {
                                jQuery("<option/>").text(item.C_DescBs).attr("value", item.C_CodBs).appendTo("#txtIdItem");
                            })
                            $('#txtIdItem').trigger("chosen:updated");
                        });
    }

How to run test methods in specific order in JUnit4?

Please check out this one: https://github.com/TransparentMarket/junit. It runs the test in the order they are specified (defined within the compiled class file). Also it features a AllTests suite to run tests defined by sub package first. Using the AllTests implementation one can extend the solution in also filtering for properties (we used to use @Fast annotations but those were not published yet).

Install specific branch from github using Npm

Tried suggested answers, but got it working only with this prefix approach:

npm i github:user/repo.git#version --save -D

The database cannot be opened because it is version 782. This server supports version 706 and earlier. A downgrade path is not supported

I use VS 2017. By default SQL Server Instance name is (LocalDB)\MSSQLLocalDB. However, downgrading the compatibility level of the database to 110 as in @user3390927's answer, I could attach the database file in VS, choosing Server Name as "localhost\SQLExpress".

In Jenkins, how to checkout a project into a specific directory (using GIT)

The default git plugin for Jenkins does the job quite nicely.

After adding a new git repository (project configuration > Source Code Management > check the GIT option) to the project navigate to the bottom of the plugin settings, just above Repository browser region. There should be an Advanced button. After clicking it a new form should appear, with a value described as Local subdirectory for repo (optional). Setting this to folder will make the plugin to check out the repository into the folder relative to your workspace. This way you can have as many repositories in your project as you need, all in separate locations.

Alternatively, if the project you're using will allow that, you can use GIT sub modules, which are similar to external paths in SVN. In the GIT Book there is a section on that very topic. If that will not be against some policy, submodules are fairly simple to use, giving you powerful way to control the locations, versions/tags/branches that will be imported AND it will be available on your local repository as well giving you better portability.

Obviously the GIT plugin supports checking out submodules, so Jenkins can work with them quite effectively.

Iterating over Numpy matrix rows to apply a function each?

While you should certainly provide more information, if you are trying to go through each row, you can just iterate with a for loop:

import numpy
m = numpy.ones((3,5),dtype='int')
for row in m:
  print str(row)

How to add manifest permission to an application?

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.photoeffect"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="18" />

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="com.example.towntour.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@android:style/Theme.Black.NoTitleBar" >
    <activity
        android:name="com.photoeffect.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

</manifest>

How to show and update echo on same line

I use printf, is shorter as it doesn't need flags to do the work:

printf "\rMy static $myvars composed text"

How to print the full NumPy array, without truncation?

import numpy as np
np.set_printoptions(threshold=np.inf)

I suggest using np.inf instead of np.nan which is suggested by others. They both work for your purpose, but by setting the threshold to "infinity" it is obvious to everybody reading your code what you mean. Having a threshold of "not a number" seems a little vague to me.

How do you find what version of libstdc++ library is installed on your linux machine?

To find which library is being used you could run

 $ /sbin/ldconfig -p | grep stdc++
    libstdc++.so.6 (libc6) => /usr/lib/libstdc++.so.6

The list of compatible versions for libstdc++ version 3.4.0 and above is provided by

 $ strings /usr/lib/libstdc++.so.6 | grep LIBCXX
 GLIBCXX_3.4
 GLIBCXX_3.4.1
 GLIBCXX_3.4.2
 ...

For earlier versions the symbol GLIBCPP is defined.

The date stamp of the library is defined in a macro __GLIBCXX__ or __GLIBCPP__ depending on the version:

// libdatestamp.cxx
#include <cstdio>

int main(int argc, char* argv[]){
#ifdef __GLIBCPP__
    std::printf("GLIBCPP: %d\n",__GLIBCPP__);
#endif
#ifdef __GLIBCXX__
    std::printf("GLIBCXX: %d\n",__GLIBCXX__);
#endif
   return 0;
}

$ g++ libdatestamp.cxx -o libdatestamp
$ ./libdatestamp
GLIBCXX: 20101208

The table of datestamps of libstdc++ versions is listed in the documentation:

Setting values on a copy of a slice from a DataFrame

This warning comes because your dataframe x is a copy of a slice. This is not easy to know why, but it has something to do with how you have come to the current state of it.

You can either create a proper dataframe out of x by doing

x = x.copy()

This will remove the warning, but it is not the proper way

You should be using the DataFrame.loc method, as the warning suggests, like this:

x.loc[:,'Mass32s'] = pandas.rolling_mean(x.Mass32, 5).shift(-2)

Android and setting alpha for (image) view alpha

Use this form to ancient version of android.

ImageView myImageView;
myImageView = (ImageView) findViewById(R.id.img);

AlphaAnimation alpha = new AlphaAnimation(0.5F, 0.5F);
alpha.setDuration(0); 
alpha.setFillAfter(true); 
myImageView.startAnimation(alpha);

Editable 'Select' element

Thanks to @Arraxas's anwser, I customized the arrow and make the input element auto-adaptive to the select element, and it looks good on Chrome, Firefox of my Android mobile phone (set color:transparent for select and some color for option to hide text display of the select because the input and .combobox div:after cannot completely cover select).

_x000D_
_x000D_
/* https://stackoverflow.com/questions/13694271/modify-select-so-only-the-first-one-is-gray/41941056#41941056
select option:first-child, */
.combobox select, .combobox select option { color: #000000; }
.combobox select:invalid, .combobox select option[value=""] { color:grey; }

.combobox {position:absolute; left:80px; top:6px;}
.combobox>div { position:relative; font-size:1em; }
.combobox select {
    font-size:inherit; color:transparent;
    padding:0; -moz-appearance:none; -webkit-appearance:none; appearance:none;
    border:1px solid blueviolet;
}
.combobox input {
    position:absolute;top:1px;left:0px; text-overflow:ellipsis;
    box-sizing:border-box; padding:0px; margin:0px; height:calc(100% - 1px); width:calc(100% - 20px);
    border:1px solid blueviolet; border-right:none; border-top:none;
}
.combobox>div:after{
    position:absolute; top:0px; right:0px; height:100%; width:20px;
    box-sizing:border-box; content:"?"; border:1px solid blueviolet; pointer-events:none;
    display:flex; flex-direction:row; align-items:center; justify-content:center;
}
.combobox select:focus, .combobox input:focus {outline:none;}
_x000D_
<!-- mandatory benefits/social security/welfare -->
<div class="combobox"><div>
    <select id=MandatoryBenefits onchange="this.nextElementSibling.value=this.value" required>
        <option value="" selected>Select ...</option>
        <option value="Pension">Pension %</option>
        <option value="Medical">Medical %</option>
        <option value="Unemployment">Unemployment %</option>
        <option value="Injury">Injury %</option>
        <option value="Maternity">Maternity %</option>
        <option value="Serious Illness">Serious Illness %</option>
        <option value="Housing Fund">Housing Fund %</option>
    </select>
    <input type="text" value="" onchange="this.previousElementSibling.selectedIndex=0"
        oninput="this.previousElementSibling.options[0].value=this.value; this.previousElementSibling.options[0].innerHTML=this.value" />
</div></div>
_x000D_
_x000D_
_x000D_

online demo (@jsbin)

How to add trendline in python matplotlib dot (scatter) graphs?

as explained here

With help from numpy one can calculate for example a linear fitting.

# plot the data itself
pylab.plot(x,y,'o')

# calc the trendline
z = numpy.polyfit(x, y, 1)
p = numpy.poly1d(z)
pylab.plot(x,p(x),"r--")
# the line equation:
print "y=%.6fx+(%.6f)"%(z[0],z[1])

How to get Python requests to trust a self signed SSL certificate?

Setting export SSL_CERT_FILE=/path/file.crt should do the job.

How do you extract IP addresses from files using a regex in a linux shell?

I usually start with grep, to get the regexp right.

# [multiple failed attempts here]
grep    '[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*'                 file  # good?
grep -E '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' file  # good enough

Then I'd try and convert it to sed to filter out the rest of the line. (After reading this thread, you and I aren't going to do that anymore: we're going to use grep -o instead)

sed -ne 's/.*\([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\).*/\1/p  # FAIL

That's when I usually get annoyed with sed for not using the same regexes as anyone else. So I move to perl.

$ perl -nle '/[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/ and print $&'

Perl's good to know in any case. If you've got a teeny bit of CPAN installed, you can even make it more reliable at little cost:

$ perl -MRegexp::Common=net -nE '/$RE{net}{IPV4}/ and say $&' file(s)

How to generate a HTML page dynamically using PHP?

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

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

Enjoy!

iPhone UILabel text soft shadow

_nameLabel = [[UILabel alloc] initWithFrame:CGRectZero];
_nameLabel.font = [UIFont boldSystemFontOfSize:19.0f];
_nameLabel.textColor = [UIColor whiteColor];
_nameLabel.backgroundColor = [UIColor clearColor];
_nameLabel.shadowColor = [UIColor colorWithWhite:0 alpha:0.2];
_nameLabel.shadowOffset = CGSizeMake(0, 1);

i think you should use the [UIColor colorWithWhite:0 alpha:0.2] to set the alpha value.

Nested classes' scope?

All explanations can be found in Python Documentation The Python Tutorial

For your first error <type 'exceptions.NameError'>: name 'outer_var' is not defined. The explanation is:

There is no shorthand for referencing data attributes (or other methods!) from within methods. I find that this actually increases the readability of methods: there is no chance of confusing local variables and instance variables when glancing through a method.

quoted from The Python Tutorial 9.4

For your second error <type 'exceptions.NameError'>: name 'OuterClass' is not defined

When a class definition is left normally (via the end), a class object is created.

quoted from The Python Tutorial 9.3.1

So when you try inner_var = Outerclass.outer_var, the Quterclass hasn't been created yet, that's why name 'OuterClass' is not defined

A more detailed but tedious explanation for your first error:

Although classes have access to enclosing functions’ scopes, though, they do not act as enclosing scopes to code nested within the class: Python searches enclosing functions for referenced names, but never any enclosing classes. That is, a class is a local scope and has access to enclosing local scopes, but it does not serve as an enclosing local scope to further nested code.

quoted from Learning.Python(5th).Mark.Lutz

INSERT with SELECT

Yes, it is. You can write :

INSERT INTO courses (name, location, gid) 
SELECT name, location, 'whatever you want' 
FROM courses 
WHERE cid = $ci

or you can get values from another join of the select ...

Recursive file search using PowerShell

Get-ChildItem V:\MyFolder -name -recurse *.CopyForbuild.bat

Will also work

How do I make CMake output into a 'bin' dir?

English is not my native language; please excuse typing errors.

use this line config :
set(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/build/)
place your any CMakeLists.txt project.
this ${PROJECT_SOURCE_DIR} is your current source directory where project place .
and if wander why is ${EXECUTABLE_OUTPUT_PATH}
check this file CMakeCache.txt then search the key word output path,
all the variables define here , it would give a full explanation of the project all setting·

How to return only 1 row if multiple duplicate rows and still return rows that are not duplicates?

If you have a one to many relationship in your query, duplicate rows may occurs on one side.

Suppose the following

TABLE TEAM
ID       TEAM_NAME
0        BULLS
1        LAKERS


TABLE PLAYER
ID       TEAM_ID     PLAYER_NAME
0        0           JORDAN
1        0           PIPPEN

And you execute a query like

SELECT 
    TEAM.TEAM_NAME, 
    PLAYER.PLAYER_NAME 
FROM TEAM
INNER JOIN PLAYER

You will get

TEAM_NAME   PLAYER_NAME
BULLS       JORDAN
BULLS       PIPPEN

So you will have duplicate TEAM NAME. Even using DISTINCT clause, your result set will contain duplicate TEAM NAME

So if you do not want duplicate TEAM_NAME in your query, do the following

SELECT ID, TEAM_NAME FROM TEAM

And for each team ID encountered executes

SELECT PLAYER_NAME FROM PLAYER WHERE TEAM_ID = <PUT_TEAM_ID_RIGHT_HERE>

So this way you will not get duplicates references on one side

regards,

How to check if JavaScript object is JSON

Peter's answer with an additional check! Of course, not 100% guaranteed!

var isJson = false;
outPutValue = ""
var objectConstructor = {}.constructor;
if(jsonToCheck.constructor === objectConstructor){
    outPutValue = JSON.stringify(jsonToCheck);
    try{
            JSON.parse(outPutValue);
            isJson = true;
    }catch(err){
            isJson = false;
    }
}

if(isJson){
    alert("Is json |" + JSON.stringify(jsonToCheck) + "|");
}else{
    alert("Is other!");
}

db.collection is not a function when using MongoClient v3.0

It used to work with the older versions of MongoDb client ~ 2.2.33

Option 1: So you can either use the older version

npm uninstall mongodb --save

npm install [email protected] --save

Option 2: Keep using the newer version (3.0 and above) and modify the code a little bit.

let MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017', function(err, client){
  if(err) throw err;
  let db = client.db('myTestingDb');
  db.collection('customers').find().toArray(function(err, result){
    if(err) throw err;
    console.log(result);
    client.close();
    });
 });

Could not find module FindOpenCV.cmake ( Error in configuration process)

I had the same error, I use windows. I add "C:\opencv\build" (opencv folder) to path at the control pannel. So, That's Ok!!

What is the naming convention in Python for variable and function names?

Most python people prefer underscores, but even I am using python since more than 5 years right now, I still do not like them. They just look ugly to me, but maybe that's all the Java in my head.

I simply like CamelCase better since it fits better with the way classes are named, It feels more logical to have SomeClass.doSomething() than SomeClass.do_something(). If you look around in the global module index in python, you will find both, which is due to the fact that it's a collection of libraries from various sources that grew overtime and not something that was developed by one company like Sun with strict coding rules. I would say the bottom line is: Use whatever you like better, it's just a question of personal taste.

Chart.js v2 hide dataset labels

It's just as simple as adding this: legend: { display: false, }

// Or if you want you could use this other option which should also work:

Chart.defaults.global.legend.display = false;

What is the use of WPFFontCache Service in WPF? WPFFontCache_v0400.exe taking 100 % CPU all the time this exe is running, why?

After installing Free BitDefender AntiVirus the services related to the AntiVirus used about 80 MB of my computer's Memory. I also noticed that after installing BitDefender the service related to windows Presentation Font Cache was also installed: "WPFFontCache_v0300.exe". I disabled the service from stating automatically and now BitDefender Free AntiVirus use only 15-20 MB (!!!) of my computer's Memory! As far as I concern, this service affected negatively the memory usage of my PC inother services. I recommend you to disable it.

Bootstrap 3 - disable navbar collapse

The nabvar will collapse on small devices. The point of collapsing is defined by @grid-float-breakpoint in variables. By default this will by before 768px. For screens below the 768 pixels screen width, the navbar will look like:

enter image description here

It's possible to change the @grid-float-breakpoint in variables.less and recompile Bootstrap. When doing this you also will have to change @screen-xs-max in navbar.less. You will have to set this value to your new @grid-float-breakpoint -1. See also: https://github.com/twbs/bootstrap/pull/10465. This is needed to change navbar forms and dropdowns at the @grid-float-breakpoint to their mobile version too.

Easiest way is to customize bootstrap

find variable:

 @grid-float-breakpoint

which is set to @screen-sm, you can change it according to your needs. Hope it helps!


For SAAS Users

add your custom variables like $grid-float-breakpoint: 0px; before the @import "bootstrap.scss";

SQLDataReader Row Count

SQLDataReaders are forward-only. You're essentially doing this:

count++;  // initially 1
.DataBind(); //consuming all the records

//next iteration on
.Read()
//we've now come to end of resultset, thanks to the DataBind()
//count is still 1 

You could do this instead:

if (reader.HasRows)
{
    rep.DataSource = reader;
    rep.DataBind();
}
int count = rep.Items.Count; //somehow count the num rows/items `rep` has.

git cherry-pick says "...38c74d is a merge but no -m option was given"

The way a cherry-pick works is by taking the diff a changeset represents (the difference between the working tree at that point and the working tree of its parent), and applying it to your current branch.

So, if a commit has two or more parents, it also represents two or more diffs - which one should be applied?

You're trying to cherry pick fd9f578, which was a merge with two parents. So you need to tell the cherry-pick command which one against which the diff should be calculated, by using the -m option. For example, git cherry-pick -m 1 fd9f578 to use parent 1 as the base.

I can't say for sure for your particular situation, but using git merge instead of git cherry-pick is generally advisable. When you cherry-pick a merge commit, it collapses all the changes made in the parent you didn't specify to -m into that one commit. You lose all their history, and glom together all their diffs. Your call.

Partial Dependency (Databases)

Partial dependence is solved for arriving to a relation in 2NF but 2NF is a "stepping stone" (C. Date) for solving any transitive dependency and arriving to a relation in 3NF (which is the operational target). However, the most interested thing on partial dependence is that it is a particular case of the own transitive dependency. This was demostrated by P. A. Berstein in 1976: IF {(x•y)?z but y?z} THEN {(x•y)?y & y?z}. The 3NF synthesizer algorithm of Berstein does not need doing distintions among these two type of relational defects.

How to integrate SAP Crystal Reports in Visual Studio 2017

To integrate SAP Crystal Reports with Visual Studio 2017 below steps needs to be followed right:

  • Uninstall all installed components from system related to Crystal Report. [If any]
  • Install compatible Crystal Report Developer Edition (as per target VS) with administrator priviledge. [As of writing, latest compatible service pack is 23]
    • Install appropriate Crystal Report Runtime (x86/ x64) for Visual Studio. [Not mandatory]
  • Open solution in VS and remove all assembly references from project related to Crystal Report. [If any]
  • Include following assembly references in project:
    • CrystalDecisions.CrystalReports.Engine
    • CrystalDecisions.ReportSource
    • CrystalDecisions.Shared
    • CrystalDecisions.CrystalReports.Design
    • CrystalDecisions.VSDesigner
  • Make sure "Copy Local" property is set to "True" in reference properties.
  • Build/ Rebuild project.

Use the XmlInclude or SoapInclude attribute to specify types that are not known statically

I agree with bizl

[XmlInclude(typeof(ParentOfTheItem))]
[Serializable]
public abstract class WarningsType{ }

also if you need to apply this included class to an object item you can do like that

[System.Xml.Serialization.XmlElementAttribute("Warnings", typeof(WarningsType))]
public object[] Items
{
    get
    {
        return this.itemsField;
    }
    set
    {
        this.itemsField = value;
    }
}

How to restore a SQL Server 2012 database to SQL Server 2008 R2?

If you are in same network then add the destination server to the MS Server management studio using connect option and then try exporting from source to destination. The most easiest way :)

How to deep copy a list?

Regarding the list as a tree, the deep_copy in python can be most compactly written as

def deep_copy(x):
    if not isinstance(x, list): return x
    else: return map(deep_copy, x)

Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel

I got this error after I accidentally published one website into the directory of another website. The two websites had different versions of .net. What fixed it for me was changing the application pool. To do that, in the IIS manager:

click the website => Advanced Settings... (on the right) => click to the right of Application Pool => a button with "..." should appear => select ".NET v4.5 Classic"

If that application pool doesn't work, try some of the others.

MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

In Mysql Latest docker container

ALTER USER root IDENTIFIED WITH mysql_native_password BY 'password';

Difference between VARCHAR and TEXT in MySQL

There is an important detail that has been omitted in the answer above.

MySQL imposes a limit of 65,535 bytes for the max size of each row. The size of a VARCHAR column is counted towards the maximum row size, while TEXT columns are assumed to be storing their data by reference so they only need 9-12 bytes. That means even if the "theoretical" max size of your VARCHAR field is 65,535 characters you won't be able to achieve that if you have more than one column in your table.

Also note that the actual number of bytes required by a VARCHAR field is dependent on the encoding of the column (and the content). MySQL counts the maximum possible bytes used toward the max row size, so if you use a multibyte encoding like utf8mb4 (which you almost certainly should) it will use up even more of your maximum row size.

Correction: Regardless of how MySQL computes the max row size, whether or not the VARCHAR/TEXT field data is ACTUALLY stored in the row or stored by reference depends on your underlying storage engine. For InnoDB the row format affects this behavior. (Thanks Bill-Karwin)

Reasons to use TEXT:

  • If you want to store a paragraph or more of text
  • If you don't need to index the column
  • If you have reached the row size limit for your table

Reasons to use VARCHAR:

  • If you want to store a few words or a sentence
  • If you want to index the (entire) column
  • If you want to use the column with foreign-key constraints

Get selected option text with JavaScript

All these functions and random things, I think it is best to use this, and do it like this:

this.options[this.selectedIndex].text

How to reload or re-render the entire page using AngularJS

If you are using angular ui-router this will be the best solution.

$scope.myLoadingFunction = function() {
    $state.reload();
};

Javascript Uncaught TypeError: Cannot read property '0' of undefined

The error is here:

hasLetter("a",words[]);

You are passing the first item of words, instead of the array.

Instead, pass the array to the function:

hasLetter("a",words);

Problem solved!


Here's a breakdown of what the problem was:

I'm guessing in your browser (chrome throws a different error), words[] == words[0], so when you call hasLetter("a",words[]);, you are actually calling hasLetter("a",words[0]);. So, in essence, you are passing the first item of words to your function, not the array as a whole.

Of course, because words is just an empty array, words[0] is undefined. Therefore, your function call is actually:

hasLetter("a", undefined);

which means that, when you try to access d[ascii], you are actually trying to access undefined[0], hence the error.

Python: SyntaxError: keyword can't be an expression

sum.up is not a valid keyword argument name. Keyword arguments must be valid identifiers. You should look in the documentation of the library you are using how this argument really is called – maybe sum_up?

What exactly does Double mean in java?

Double is a wrapper class,

The Double class wraps a value of the primitive type double in an object. An object of type Double contains a single field whose type is double.

In addition, this class provides several methods for converting a double to a String and a String to a double, as well as other constants and methods useful when dealing with a double.

The double data type,

The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is 4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative). For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.

Check each datatype with their ranges : Java's Primitive Data Types.


Important Note : If you'r thinking to use double for precise values, you need to re-think before using it. Java Traps: double

Sys is undefined

Try setting your ScriptManager to this.

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" /> 

What does DIM stand for in Visual Basic and BASIC?

Back in the day DIM reserved memory for the array and when memory was limited you had to be careful how you used it. I once wrote (in 1981) a BASIC program on TRS-80 Model III with 48Kb RAM. It wouldn't run on a similar machine with 16Kb RAM until I decreased the array size by changing the DIM statement

How do I get a range's address including the worksheet name, but not the workbook name, in Excel VBA?

[edit on 2009-04-21]

    As Micah pointed out, this only works when you have named that
    particular range (hence .Name anyone?) Yeah, oops!

[/edit]

A little late to the party, I know, but in case anyone else catches this in a google search (as I just did), you could also try the following:

Dim cell as Range
Dim address as String
Set cell = Sheet1.Range("A1")
address = cell.Name

This should return the full address, something like "=Sheet1!$A$1".

Assuming you don't want the equal sign, you can strip it off with a Replace function:

address = Replace(address, "=", "")

From io.Reader to string in Go

var b bytes.Buffer
b.ReadFrom(r)

// b.String()

How to bind WPF button to a command in ViewModelBase?

 <Grid >
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Button Command="{Binding ClickCommand}" Width="100" Height="100" Content="wefwfwef"/>
</Grid>

the code behind for the window:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModelBase();
    }
}

The ViewModel:

public class ViewModelBase
{
    private ICommand _clickCommand;
    public ICommand ClickCommand
    {
        get
        {
            return _clickCommand ?? (_clickCommand = new CommandHandler(() => MyAction(), ()=> CanExecute));
        }
    }
     public bool CanExecute
     {
        get
        {
            // check if executing is allowed, i.e., validate, check if a process is running, etc. 
            return true/false;
        }
     }

    public void MyAction()
    {

    }
}

Command Handler:

 public class CommandHandler : ICommand
{
    private Action _action;
    private Func<bool> _canExecute;

    /// <summary>
    /// Creates instance of the command handler
    /// </summary>
    /// <param name="action">Action to be executed by the command</param>
    /// <param name="canExecute">A bolean property to containing current permissions to execute the command</param>
    public CommandHandler(Action action, Func<bool> canExecute)
    {
        _action = action;
        _canExecute = canExecute;
    }

    /// <summary>
    /// Wires CanExecuteChanged event 
    /// </summary>
    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    /// <summary>
    /// Forcess checking if execute is allowed
    /// </summary>
    /// <param name="parameter"></param>
    /// <returns></returns>
    public bool CanExecute(object parameter)
    {
        return _canExecute.Invoke();
    }

    public void Execute(object parameter)
    {
        _action();
    }
}

I hope this will give you the idea.

In Swift how to call method with parameters on GCD main thread?

//Perform some task and update UI immediately.
DispatchQueue.global(qos: .userInitiated).async {  
    // Call your function here
    DispatchQueue.main.async {  
        // Update UI
        self.tableView.reloadData()  
    }
}

//To call or execute function after some time
DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
    //Here call your function
}

//If you want to do changes in UI use this
DispatchQueue.main.async(execute: {
    //Update UI
    self.tableView.reloadData()
})

How to Determine the Screen Height and Width in Flutter

Getting width is easy but height can be tricky, following are the ways to deal with height

// Full screen width and height
double width = MediaQuery.of(context).size.width;
double height = MediaQuery.of(context).size.height;

// Height (without SafeArea)
var padding = MediaQuery.of(context).padding;
double height1 = height - padding.top - padding.bottom;

// Height (without status bar)
double height2 = height - padding.top;

// Height (without status and toolbar)
double height3 = height - padding.top - kToolbarHeight;

How to: Add/Remove Class on mouseOver/mouseOut - JQuery .hover?

You could just use: {in and out function callback}

$(".result").hover(function () {
    $(this).toggleClass("result_hover");
 });

For your example, better will be to use CSS pseudo class :hover: {no js/jquery needed}

.result {
    height: 72px;
    width: 100%;
    border: 1px solid #000;
  }
  .result:hover {
    background-color: #000;
  }

How to access parameters in a Parameterized Build?

Please note, the way that build parameters are accessed inside pipeline scripts (pipeline plugin) has changed. This approach:

getBinding().hasVariable("MY_PARAM")

Is not working anymore. Please try this instead:

def myBool = env.getEnvironment().containsKey("MY_BOOL") ? Boolean.parseBoolean("$env.MY_BOOL") : false

Set a variable if undefined in JavaScript

Works even if the default value is a boolean value:

var setVariable = ( (b = 0) => b )( localStorage.getItem('value') );

Java replace issues with ' (apostrophe/single quote) and \ (backslash) together

Remember that stringToEdit.replaceAll(String, String) returns the result string. It doesn't modify stringToEdit because Strings are immutable in Java. To get any change to stick, you should use

stringToEdit = stringToEdit.replaceAll("'", "\\'");

error: command 'gcc' failed with exit status 1 while installing eventlet

For openSUSE 42.1 Leap Linux use this

sudo zypper install python3-devel

Git Pull While Ignoring Local Changes?

This will fetch the current branch and attempt to do a fast forward to master:

git fetch && git merge --ff-only origin/master

HTML5 Video // Completely Hide Controls

You could hide controls using CSS Pseudo Selectors like Demo: https://jsfiddle.net/g1rsasa3

_x000D_
_x000D_
//For Firefox we have to handle it in JavaScript _x000D_
var vids = $("video"); _x000D_
$.each(vids, function(){_x000D_
       this.controls = false; _x000D_
}); _x000D_
//Loop though all Video tags and set Controls as false_x000D_
_x000D_
$("video").click(function() {_x000D_
  //console.log(this); _x000D_
  if (this.paused) {_x000D_
    this.play();_x000D_
  } else {_x000D_
    this.pause();_x000D_
  }_x000D_
});
_x000D_
video::-webkit-media-controls {_x000D_
  display: none;_x000D_
}_x000D_
_x000D_
/* Could Use thise as well for Individual Controls */_x000D_
video::-webkit-media-controls-play-button {}_x000D_
_x000D_
video::-webkit-media-controls-volume-slider {}_x000D_
_x000D_
video::-webkit-media-controls-mute-button {}_x000D_
_x000D_
video::-webkit-media-controls-timeline {}_x000D_
_x000D_
video::-webkit-media-controls-current-time-display {}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>_x000D_
<!-- Hiding HTML5 Video Controls using CSS Pseudo selectors -->_x000D_
_x000D_
<video width="800" autoplay controls="false">_x000D_
  <source src="http://clips.vorwaerts-gmbh.de/VfE_html5.mp4" type="video/mp4">_x000D_
</video>
_x000D_
_x000D_
_x000D_

maven compilation failure

I had the same issue (even though the project was compiling/working fine in Eclipse), it was not when using the command line build. The reason was that I wasn't using the correct folder structure for mvn: "src/main/java/com" etc. It is looking at these folders by default (I was using "/scr/main/com" etc. which caused issues).

How to convert a number to string and vice versa in C++

I stole this convienent class from somewhere here at StackOverflow to convert anything streamable to a string:

// make_string
class make_string {
public:
  template <typename T>
  make_string& operator<<( T const & val ) {
    buffer_ << val;
    return *this;
  }
  operator std::string() const {
    return buffer_.str();
  }
private:
  std::ostringstream buffer_;
};

And then you use it as;

string str = make_string() << 6 << 8 << "hello";

Quite nifty!

Also I use this function to convert strings to anything streamable, althrough its not very safe if you try to parse a string not containing a number; (and its not as clever as the last one either)

// parse_string
template <typename RETURN_TYPE, typename STRING_TYPE>
RETURN_TYPE parse_string(const STRING_TYPE& str) {
  std::stringstream buf;
  buf << str;
  RETURN_TYPE val;
  buf >> val;
  return val;
}

Use as:

int x = parse_string<int>("78");

You might also want versions for wstrings.

How does the data-toggle attribute work? (What's its API?)

The data-toggle attribute simple tell Bootstrap what exactly to do by giving it the name of the toggle action it is about to perform on a target element. If you specify collapse. It means bootstrap will collapse or uncollapse the element pointed by data-target of the action you clicked

Note: the target element must have the appropriate class for bootstrap to carry out the action

Source action:
data-toggle = collapse //type of toggle
data-target = #myDiv

Target:
class=collapse //I can collapse
id=myDiv

This is same for other type of toggle actions like tab, modal, dropdown

Determining complexity for recursive functions (Big O notation)

We can prove it mathematically which is something I was missing in the above answers.

It can dramatically help you understand how to calculate any method. I recommend reading it from top to bottom to fully understand how to do it:

  1. T(n) = T(n-1) + 1 It means that the time it takes for the method to finish is equal to the same method but with n-1 which is T(n-1) and we now add + 1 because it's the time it takes for the general operations to be completed (except T(n-1)). Now, we are going to find T(n-1) as follow: T(n-1) = T(n-1-1) + 1. It looks like we can now form a function that can give us some sort of repetition so we can fully understand. We will place the right side of T(n-1) = ... instead of T(n-1) inside the method T(n) = ... which will give us: T(n) = T(n-1-1) + 1 + 1 which is T(n) = T(n-2) + 2 or in other words we need to find our missing k: T(n) = T(n-k) + k. The next step is to take n-k and claim that n-k = 1 because at the end of the recursion it will take exactly O(1) when n<=0. From this simple equation we now know that k = n - 1. Let's place k in our final method: T(n) = T(n-k) + k which will give us: T(n) = 1 + n - 1 which is exactly n or O(n).
  2. Is the same as 1. You can test it your self and see that you get O(n).
  3. T(n) = T(n/5) + 1 as before, the time for this method to finish equals to the time the same method but with n/5 which is why it is bounded to T(n/5). Let's find T(n/5) like in 1: T(n/5) = T(n/5/5) + 1 which is T(n/5) = T(n/5^2) + 1. Let's place T(n/5) inside T(n) for the final calculation: T(n) = T(n/5^k) + k. Again as before, n/5^k = 1 which is n = 5^k which is exactly as asking what in power of 5, will give us n, the answer is log5n = k (log of base 5). Let's place our findings in T(n) = T(n/5^k) + k as follow: T(n) = 1 + logn which is O(logn)
  4. T(n) = 2T(n-1) + 1 what we have here is basically the same as before but this time we are invoking the method recursively 2 times thus we multiple it by 2. Let's find T(n-1) = 2T(n-1-1) + 1 which is T(n-1) = 2T(n-2) + 1. Our next place as before, let's place our finding: T(n) = 2(2T(n-2)) + 1 + 1 which is T(n) = 2^2T(n-2) + 2 that gives us T(n) = 2^kT(n-k) + k. Let's find k by claiming that n-k = 1 which is k = n - 1. Let's place k as follow: T(n) = 2^(n-1) + n - 1 which is roughly O(2^n)
  5. T(n) = T(n-5) + n + 1 It's almost the same as 4 but now we add n because we have one for loop. Let's find T(n-5) = T(n-5-5) + n + 1 which is T(n-5) = T(n - 2*5) + n + 1. Let's place it: T(n) = T(n-2*5) + n + n + 1 + 1) which is T(n) = T(n-2*5) + 2n + 2) and for the k: T(n) = T(n-k*5) + kn + k) again: n-5k = 1 which is n = 5k + 1 that is roughly n = k. This will give us: T(n) = T(0) + n^2 + n which is roughly O(n^2).

I now recommend reading the rest of the answers which now, will give you a better perspective. Good luck winning those big O's :)

Basic text editor in command prompt?

There is one built into windows 7 in which you can open by clicking the windows and r keys at the same time and then typing edit.com.

I hope this helped

OR is not supported with CASE Statement in SQL Server

UPDATE table_name 
  SET column_name=CASE 
WHEN column_name in ('value1', 'value2',.....) 
  THEN 'update_value' 
WHEN column_name in ('value1', 'value2',.....) 
  THEN 'update_value' 
END

table_name = The name of table on which you want to perform operation.

column_name = The name of Column/Field of which value you want to set.

update_value = The value you want to set of column_name

Python "string_escape" vs "unicode_escape"

According to my interpretation of the implementation of unicode-escape and the unicode repr in the CPython 2.6.5 source, yes; the only difference between repr(unicode_string) and unicode_string.encode('unicode-escape') is the inclusion of wrapping quotes and escaping whichever quote was used.

They are both driven by the same function, unicodeescape_string. This function takes a parameter whose sole function is to toggle the addition of the wrapping quotes and escaping of that quote.

How remove border around image in css?

What class do you have on the image tag?

Try this

<img src="/images/myimage.jpg" style="border:none;" alt="my image" />

What's the difference between '$(this)' and 'this'?

this is the element, $(this) is the jQuery object constructed with that element

$(".class").each(function(){
 //the iterations current html element 
 //the classic JavaScript API is exposed here (such as .innerHTML and .appendChild)
 var HTMLElement = this;

 //the current HTML element is passed to the jQuery constructor
 //the jQuery API is exposed here (such as .html() and .append())
 var jQueryObject = $(this);
});

A deeper look

thisMDN is contained in an execution context

The scope refers to the current Execution ContextECMA. In order to understand this, it is important to understand the way execution contexts operate in JavaScript.

execution contexts bind this

When control enters an execution context (code is being executed in that scope) the environment for variables are setup (Lexical and Variable Environments - essentially this sets up an area for variables to enter which were already accessible, and an area for local variables to be stored), and the binding of this occurs.

jQuery binds this

Execution contexts form a logical stack. The result is that contexts deeper in the stack have access to previous variables, but their bindings may have been altered. Every time jQuery calls a callback function, it alters the this binding by using applyMDN.

callback.apply( obj[ i ] )//where obj[i] is the current element

The result of calling apply is that inside of jQuery callback functions, this refers to the current element being used by the callback function.

For example, in .each, the callback function commonly used allows for .each(function(index,element){/*scope*/}). In that scope, this == element is true.

jQuery callbacks use the apply function to bind the function being called with the current element. This element comes from the jQuery object's element array. Each jQuery object constructed contains an array of elements which match the selectorjQuery API that was used to instantiate the jQuery object.

$(selector) calls the jQuery function (remember that $ is a reference to jQuery, code: window.jQuery = window.$ = jQuery;). Internally, the jQuery function instantiates a function object. So while it may not be immediately obvious, using $() internally uses new jQuery(). Part of the construction of this jQuery object is to find all matches of the selector. The constructor will also accept html strings and elements. When you pass this to the jQuery constructor, you are passing the current element for a jQuery object to be constructed with. The jQuery object then contains an array-like structure of the DOM elements matching the selector (or just the single element in the case of this).

Once the jQuery object is constructed, the jQuery API is now exposed. When a jQuery api function is called, it will internally iterate over this array-like structure. For each item in the array, it calls the callback function for the api, binding the callback's this to the current element. This call can be seen in the code snippet above where obj is the array-like structure, and i is the iterator used for the position in the array of the current element.

SQL: IF clause within WHERE clause

To clarify some of the logical equivalence solutions.

An if statement

if (a) then b

is logically equivalent to

(!a || b)

It's the first line on the Logical equivalences involving conditional statements section of the Logical equivalence wikipedia article.

To include the else, all you would do is add another conditional

if(a) then b; 
if(!a) then c;

which is logically equivalent to (!a || b) && (a || c)

So using the OP as an example:

IF IsNumeric(@OrderNumber) = 1
    OrderNumber = @OrderNumber
ELSE
    OrderNumber LIKE '%' + @OrderNumber + '%'

the logical equivalent would be:

(IsNumeric(@OrderNumber) <> 1 OR OrderNumber = @OrderNumber)
AND (IsNumeric(@OrderNumber) = 1 OR OrderNumber LIKE '%' + @OrderNumber + '%' )

Performing SQL queries on an Excel Table within a Workbook with VBA Macro

Just answering the second part of your question about getting the name of the sheet where a table is:

Dim name as String

name = Range("Table1").Worksheet.Name

Edit:

To make things more clear: someone suggested that to use Range on a Sheet object. In this case, you need not; the Range where the table lives can be obtained using the table's name; this name is available throughout the book. So, calling Range alone works well.

How to get a view table query (code) in SQL Server 2008 Management Studio

right-click the view in the object-explorer, select "script view as...", then "create to" and then "new query editor window"

Change Select List Option background colour on hover in html

No, it's not possible.

It's really, if not use native selects, if you create custom select widget from html elements, t.e. "li".

git still shows files as modified after adding to .gitignore

  1. Git add .

  2. Git status //Check file that being modified

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

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

  4. git commit -m ''

  5. git push

How to find the last day of the month from date?

I have wrapped it in my date time helper class here https://github.com/normandqq/Date-Time-Helper using $dateLastDay = Model_DTHpr::getLastDayOfTheMonth();

And it is done

final keyword in method parameters

The final keyword on a method parameter means absolutely nothing to the caller. It also means absolutely nothing to the running program, since its presence or absence doesn't change the bytecode. It only ensures that the compiler will complain if the parameter variable is reassigned within the method. That's all. But that's enough.

Some programmers (like me) think that's a very good thing and use final on almost every parameter. It makes it easier to understand a long or complex method (though one could argue that long and complex methods should be refactored.) It also shines a spotlight on method parameters that aren't marked with final.

How to get value by class name in JavaScript or jquery?

If you get the the text inside the element use

Text()

$(".element-classname").text();

In your code:

$('.HOEnZb').text();

if you want get all the data including html Tags use:

html()

 $(".element-classname").html();

In your code:

$('.HOEnZb').html();

Hope it helps:)

Convert Uppercase Letter to Lowercase and First Uppercase in Sentence using CSS

can simply use style inside element

<p style="text-transform: lowercase;">HI I AM NEW HERE</p>

How to prevent buttons from submitting forms

I agree with Shog9, though I might instead use:

<input type = "button" onClick="addItem(); return false;" value="Add Item" />

According to w3schools, the <button> tag has different behavior on different browsers.

Unknown version of Tomcat was specified in Eclipse

Having installed tomcat with brew the solution for me was:

sudo chmod -R 777 /usr/local/Cellar/tomcat/<your_version>

Updating to latest version of CocoaPods?

Execute the following on your terminal to get the latest stable version:

sudo gem install cocoapods

Add --pre to get the latest pre release:

sudo gem install cocoapods --pre

If you originally installed the cocoapods gem using sudo, you should use that command again.

Later on, when you're actively using CocoaPods by installing pods, you will be notified when new versions become available with a CocoaPods X.X.X is now available, please update message.

MySql Error: 1364 Field 'display_name' doesn't have default value

Also, I had this issue using Laravel, but fixed by changing my database schema to allow "null" inputs on a table where I plan to collect the information from separate forms:

public function up()
{

    Schema::create('trip_table', function (Blueprint $table) {
        $table->increments('trip_id')->unsigned();
        $table->time('est_start');
        $table->time('est_end');
        $table->time('act_start')->nullable();
        $table->time('act_end')->nullable();
        $table->date('Trip_Date');
        $table->integer('Starting_Miles')->nullable();
        $table->integer('Ending_Miles')->nullable();
        $table->string('Bus_id')->nullable();
        $table->string('Event');
        $table->string('Desc')->nullable();
        $table->string('Destination');
        $table->string('Departure_location');
        $table->text('Drivers_Comment')->nullable();
        $table->string('Requester')->nullable();
        $table->integer('driver_id')->nullable();
        $table->timestamps();
    });

}

The ->nullable(); Added to the end. This is using Laravel. Hope this helps someone, thanks!

std::string length() and size() member functions

length of string ==how many bits that string having, size==size of those bits, In strings both are same if the editor allocates size of character is 1 byte

How do I make a self extract and running installer

I have created step by step instructions on how to do this as I also was very confused about how to get this working.

How to make a self extracting archive that runs your setup.exe with 7zip -sfx switch

Here are the steps.

Step 1 - Setup your installation folder

To make this easy create a folder c:\Install. This is where we will copy all the required files.

Step 2 - 7Zip your installers

  1. Go to the folder that has your .msi and your setup.exe
  2. Select both the .msi and the setup.exe
  3. Right-Click and choose 7Zip --> "Add to Archive"
  4. Name your archive "Installer.7z" (or a name of your choice)
  5. Click Ok
  6. You should now have "Installer.7z".
  7. Copy this .7z file to your c:\Install directory

Step 3 - Get the 7z-Extra sfx extension module

You need to download 7zSD.sfx

  1. Download one of the LZMA packages from here
  2. Extract the package and find 7zSD.sfx in the bin folder.
  3. Copy the file "7zSD.sfx" to c:\Install

Step 4 - Setup your config.txt

I would recommend using NotePad++ to edit this text file as you will need to encode in UTF-8, the following instructions are using notepad++.

  1. Using windows explorer go to c:\Install
  2. right-click and choose "New Text File" and name it config.txt
  3. right-click and choose "Edit with NotePad++
  4. Click the "Encoding Menu" and choose "Encode in UTF-8"
  5. Enter something like this:

    ;!@Install@!UTF-8!
    Title="SOFTWARE v1.0.0.0"
    BeginPrompt="Do you want to install SOFTWARE v1.0.0.0?"
    RunProgram="setup.exe"
    ;!@InstallEnd@!
    

Edit this replacing [SOFTWARE v1.0.0.0] with your product name. Notes on the parameters and options for the setup file are here.

CheckPoint

You should now have a folder "c:\Install" with the following 3 files:

  1. Installer.7z
  2. 7zSD.sfx
  3. config.txt

Step 5 - Create the archive

These instructions I found on the web but nowhere did it explain any of the 4 steps above.

  1. Open a cmd window, Window + R --> cmd --> press enter
  2. In the command window type the following

    cd \
    cd Install
    copy /b 7zSD.sfx + config.txt + Installer.7z MyInstaller.exe
    
  3. Look in c:\Install and you will now see you have a MyInstaller.exe

  4. You are finished

Run the installer

Double click on MyInstaller.exe and it will prompt with your message. Click OK and the setup.exe will run.

P.S. Note on Automation

Now that you have this working in your c:\Install directory I would create an "Install.bat" file and put the copy script in it.

copy /b 7zSD.sfx + config.txt + Installer.7z MyInstaller.exe

Now you can just edit and run the Install.bat every time you need to rebuild a new version of you deployment package.

Git: How to remove remote origin from Git repo

perhaps I am late you can use git remote remove origin it will do the job.

What is the JavaScript version of sleep()?

Since Node 7.6, you can combine the promisify function from the utils module with setTimeout.

const sleep = require('util').promisify(setTimeout)

General Usage

async function main() {
    console.time("Slept for")
    await sleep(3000)
    console.timeEnd("Slept for")
}

main()

Question Usage

async function asyncGenerator() {
    while (goOn) {
      var fileList = await listFiles(nextPageToken);
      await sleep(3000)
      var parents = await requestParents(fileList);
    }
  }

?: ?? Operators Instead Of IF|ELSE

For [1], you can't: these operators are made to return a value, not perform operations.

The expression

a ? b : c

evaluates to b if a is true and evaluates to c if a is false.

The expression

b ?? c

evaluates to b if b is not null and evaluates to c if b is null.

If you write

return a ? b : c;

or

return b ?? c;

they will always return something.

For [2], you can write a function that returns the right value that performs your "multiple operations", but that's probably worse than just using if/else.

How to use a findBy method with comparative criteria

The class Doctrine\ORM\EntityRepository implements Doctrine\Common\Collections\Selectable API.

The Selectable interface is very flexible and quite new, but it will allow you to handle comparisons and more complex criteria easily on both repositories and single collections of items, regardless if in ORM or ODM or completely separate problems.

This would be a comparison criteria as you just requested as in Doctrine ORM 2.3.2:

$criteria = new \Doctrine\Common\Collections\Criteria();
$criteria->where($criteria->expr()->gt('prize', 200));

$result = $entityRepository->matching($criteria);

The major advantage in this API is that you are implementing some sort of strategy pattern here, and it works with repositories, collections, lazy collections and everywhere the Selectable API is implemented.

This allows you to get rid of dozens of special methods you wrote for your repositories (like findOneBySomethingWithParticularRule), and instead focus on writing your own criteria classes, each representing one of these particular filters.