Programs & Examples On #Navigateuri

Example using Hyperlink in WPF

If you want to localize string later, then those answers aren't enough, I would suggest something like:

<TextBlock>
    <Hyperlink NavigateUri="http://labsii.com/">
       <Hyperlink.Inlines>
            <Run Text="Click here"/>
       </Hyperlink.Inlines>
   </Hyperlink>
</TextBlock>

SQL Server equivalent to Oracle's CREATE OR REPLACE VIEW

You can use 'IF EXISTS' to check if the view exists and drop if it does.

IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS
        WHERE TABLE_NAME = 'MyView')
    DROP VIEW MyView
GO

CREATE VIEW MyView
AS 
     ....
GO

Checking to see if one array's elements are in another array in PHP

Here's a way I am doing it after researching it for a while. I wanted to make a Laravel API endpoint that checks if a field is "in use", so the important information is: 1) which DB table? 2) what DB column? and 3) is there a value in that column that matches the search terms?

Knowing this, we can construct our associative array:

$SEARCHABLE_TABLE_COLUMNS = [
    'users' => [ 'email' ],
];

Then, we can set our values that we will check:

$table = 'users';
$column = 'email';
$value = '[email protected]';

Then, we can use array_key_exists() and in_array() with eachother to execute a one, two step combo and then act upon the truthy condition:

// step 1: check if 'users' exists as a key in `$SEARCHABLE_TABLE_COLUMNS`
if (array_key_exists($table, $SEARCHABLE_TABLE_COLUMNS)) {

    // step 2: check if 'email' is in the array: $SEARCHABLE_TABLE_COLUMNS[$table]
    if (in_array($column, $SEARCHABLE_TABLE_COLUMNS[$table])) {

        // if table and column are allowed, return Boolean if value already exists
        // this will either return the first matching record or null
        $exists = DB::table($table)->where($column, '=', $value)->first();

        if ($exists) return response()->json([ 'in_use' => true ], 200);
        return response()->json([ 'in_use' => false ], 200);
    }

    // if $column isn't in $SEARCHABLE_TABLE_COLUMNS[$table],
    // then we need to tell the user we can't proceed with their request
    return response()->json([ 'error' => 'Illegal column name: '.$column ], 400);
}

// if $table isn't a key in $SEARCHABLE_TABLE_COLUMNS,
// then we need to tell the user we can't proceed with their request
return response()->json([ 'error' => 'Illegal table name: '.$table ], 400);

I apologize for the Laravel-specific PHP code, but I will leave it because I think you can read it as pseudo-code. The important part is the two if statements that are executed synchronously.

array_key_exists() and in_array() are PHP functions.

source:

The nice thing about the algorithm that I showed above is that you can make a REST endpoint such as GET /in-use/{table}/{column}/{value} (where table, column, and value are variables).

You could have:

$SEARCHABLE_TABLE_COLUMNS = [
    'accounts' => [ 'account_name', 'phone', 'business_email' ],
    'users' => [ 'email' ],
];

and then you could make GET requests such as:

GET /in-use/accounts/account_name/Bob's Drywall (you may need to uri encode the last part, but usually not)

GET /in-use/accounts/phone/888-555-1337

GET /in-use/users/email/[email protected]

Notice also that no one can do:

GET /in-use/users/password/dogmeat1337 because password is not listed in your list of allowed columns for user.

Good luck on your journey.

Java code To convert byte to Hexadecimal

The Best solution is this badass one-liner:

String hex=DatatypeConverter.printHexBinary(byte[] b);

as mentioned here

javascript date + 7 days

In One line:

new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)

How to Decrease Image Brightness in CSS

You could use:

filter: brightness(50%);
-webkit-filter: brightness(50%);
-moz-filter: brightness(50%);
-o-filter: brightness(50%);
-ms-filter: brightness(50%);

Regex to extract URLs from href attribute in HTML with Python

import re

url = '<p>Hello World</p><a href="http://example.com">More Examples</a><a href="http://example2.com">Even More Examples</a>'

urls = re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', url)

>>> print urls
['http://example.com', 'http://example2.com']

What is console.log?

Apart from the usages mentioned above, console.log can also print to the terminal in node.js. A server created with express (for eg.) can use console.log to write to the output logger file.

MySQL Alter Table Add Field Before or After a field already present

$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark` 
          ADD COLUMN `ping_status` INT(1) NOT NULL 
          AFTER `<TABLE COLUMN BEFORE THIS COLUMN>`";

I believe you need to have ADD COLUMN and use AFTER, not BEFORE.

In case you want to place column at the beginning of a table, use the FIRST statement:

$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark`
          ADD COLUMN `ping_status` INT(1) NOT NULL 
          FIRST";

http://dev.mysql.com/doc/refman/5.1/en/alter-table.html

Uninstalling an MSI file from the command line without using msiexec

The msi file extension is mapped to msiexec (same way typing a .txt filename on a command prompt launches Notepad/default .txt file handler to display the file).

Thus typing in a filename with an .msi extension really runs msiexec with the MSI file as argument and takes the default action, install. For that reason, uninstalling requires you to invoke msiexec with uninstall switch to unstall it.

How to force garbage collector to run?

System.GC.Collect() forces garbage collector to run. This is not recommended but can be used if situations arise.

C char* to int conversion

Use atoi() from <stdlib.h>

http://linux.die.net/man/3/atoi

Or, write your own atoi() function which will convert char* to int

int a2i(const char *s)
{
  int sign=1;
  if(*s == '-'){
    sign = -1;
    s++;
  }
  int num=0;
  while(*s){
    num=((*s)-'0')+num*10;
    s++;   
  }
  return num*sign;
}

How to deal with ModalDialog using selenium webdriver?

Nope, Model window needs to be handle by javaScriptExecutor,Because majorly model window made up of window model, This will works once model appeared then control take a place into model and click the expected element.

have to import javascriptexector

like below,

Javascriptexecutor js =(Javascriptexecutor).driver;
js.executescript(**<element to be clicked>**);

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

Since I found that the above approved answer lacks some clarity and the op provides an incorrect solution that he/she will use. I therefore hope that the below example will help others. The solution is more or less portable as well.

/******************************************************************************
 * Checks to see if a directory exists. Note: This method only checks the
 * existence of the full path AND if path leaf is a dir.
 *
 * @return  >0 if dir exists AND is a dir,
 *           0 if dir does not exist OR exists but not a dir,
 *          <0 if an error occurred (errno is also set)
 *****************************************************************************/
int dirExists(const char* const path)
{
    struct stat info;

    int statRC = stat( path, &info );
    if( statRC != 0 )
    {
        if (errno == ENOENT)  { return 0; } // something along the path does not exist
        if (errno == ENOTDIR) { return 0; } // something in path prefix is not a dir
        return -1;
    }

    return ( info.st_mode & S_IFDIR ) ? 1 : 0;
}

How to use a filter in a controller?

There is another way to evaluate filters that mirrors the syntax from the views. The invocation is hairy but you could build a shortcut to it. I like that the syntax of the string is identical to what you'd have in a view. Looks like this:

function myCtrl($scope, $interpolate) { 
  $scope.$eval($interpolate( "{{ myvar * 10 | currency }} dollars." ))
}

Script to get the HTTP status code of a list of urls?

Extending the answer already provided by Phil. Adding parallelism to it is a no brainer in bash if you use xargs for the call.

Here the code:

xargs -n1 -P 10 curl -o /dev/null --silent --head --write-out '%{url_effective}: %{http_code}\n' < url.lst

-n1: use just one value (from the list) as argument to the curl call

-P10: Keep 10 curl processes alive at any time (i.e. 10 parallel connections)

Check the write_out parameter in the manual of curl for more data you can extract using it (times, etc).

In case it helps someone this is the call I'm currently using:

xargs -n1 -P 10 curl -o /dev/null --silent --head --write-out '%{url_effective};%{http_code};%{time_total};%{time_namelookup};%{time_connect};%{size_download};%{speed_download}\n' < url.lst | tee results.csv

It just outputs a bunch of data into a csv file that can be imported into any office tool.

get one item from an array of name,value JSON

The easiest approach which I have used is

var found = arr.find(function(element) {
         return element.name === "k1";
 });

//If you print the found :
console.log(found);
=> Object { name: "k1", value: "abc" }

//If you need the value
console.log(found.value)
=> "abc"

The similar approach can be used to find the values from the JSON Array based on any input data from the JSON.

Python 3.4.0 with MySQL database

MySQLdb does not support Python 3 but it is not the only MySQL driver for Python.

mysqlclient is essentially just a fork of MySQLdb with Python 3 support merged in (and a few other improvements).

PyMySQL is a pure python MySQL driver, which means it is slower, but it does not require a compiled C component or MySQL libraries and header files to be installed on client machines. It has Python 3 support.

Another option is simply to use another database system like PostgreSQL.

How to achieve pagination/table layout with Angular.js?

The best simple plug and play solution for pagination.

https://ciphertrick.com/2015/06/01/search-sort-and-pagination-ngrepeat-angularjs/#comment-1002

you would jus need to replace ng-repeat with custom directive.

<tr dir-paginate="user in userList|filter:search |itemsPerPage:7">
<td>{{user.name}}</td></tr>

Within the page u just need to add

<div align="center">
       <dir-pagination-controls
            max-size="100"
            direction-links="true"
            boundary-links="true" >
       </dir-pagination-controls>
</div>

In your index.html load

<script src="./js/dirPagination.js"></script>

In your module just add dependencies

angular.module('userApp',['angularUtils.directives.dirPagination']);

and thats all needed for pagination.

Might be helpful for someone.

how do I give a div a responsive height

I don't think this is the BEST solution, but it does appear to work. Instead of using the background color, I'm going to just embed an image of the background, position it relatively and then wrap the text in a child element and position it absolute - in the centre.

iOS Remote Debugging

I recommend Vorlon, works like weinre. I like the UI of Vorlon, and it support SSL, my application is in HTTPS, I tried weinre with ngrok, ghostlab and vorlon, only vorlon works fine.

MySQL - SELECT all columns WHERE one column is DISTINCT

In MySQL you can simply use "group by". Below will select ALL, with a DISTINCT "col"

SELECT *
FROM tbl
GROUP BY col

How to set up file permissions for Laravel?

Most folders should be normal "755" and files, "644"

Laravel requires some folders to be writable for the web server user. You can use this command on unix based OSs.

sudo chgrp -R www-data storage bootstrap/cache
sudo chmod -R ug+rwx storage bootstrap/cache

Combine two integer arrays

NOTE: didn't test it

int[] concatArray(int[] a, int[] b) {
  int[] c = new int[a.length + b.length];
  int i = 0;
  for (int x : a) { c[i] = x; i ++; }
  for (int x : b) { c[i] = x; i ++; }
  return c;
}

How to display two digits after decimal point in SQL Server

You can also Make use of the Following if you want to Cast and Round as well. That may help you or someone else.

SELECT CAST(ROUND(Column_Name, 2) AS DECIMAL(10,2), Name FROM Table_Name

Create a txt file using batch file in a specific folder

You have it almost done. Just explicitly say where to create the file

@echo off
  echo.>"d:\testing\dblank.txt"

This creates a file containing a blank line (CR + LF = 2 bytes).

If you want the file empty (0 bytes)

@echo off
  break>"d:\testing\dblank.txt"

Hash function for a string

Hash functions for algorithmic use have usually 2 goals, first they have to be fast, second they have to evenly distibute the values across the possible numbers. The hash function also required to give the all same number for the same input value.

if your values are strings, here are some examples for bad hash functions:

  1. string[0] - the ASCII characters a-Z are way more often then others
  2. string.lengh() - the most probable value is 1

Good hash functions tries to use every bit of the input while keeping the calculation time minimal. If you only need some hash code, try to multiply the bytes with prime numbers, and sum them.

How to generate entire DDL of an Oracle schema (scriptable)?

There is a problem with objects such as PACKAGE_BODY:

SELECT DBMS_METADATA.get_ddl(object_Type, object_name, owner) FROM ALL_OBJECTS WHERE OWNER = 'WEBSERVICE';


ORA-31600 invalid input value PACKAGE BODY parameter OBJECT_TYPE in function GET_DDL
ORA-06512: ??  "SYS.DBMS_METADATA", line 4018
ORA-06512: ??  "SYS.DBMS_METADATA", line 5843
ORA-06512: ??  line 1
31600. 00000 -  "invalid input value %s for parameter %s in function %s"
*Cause:    A NULL or invalid value was supplied for the parameter.
*Action:   Correct the input value and try the call again.



SELECT DBMS_METADATA.GET_DDL(REPLACE(object_type,' ','_'), object_name, owner)
  FROM all_OBJECTS 
  WHERE (OWNER = 'OWNER1');

How to get Enum Value from index in Java?

I recently had the same problem and used the solution provided by Harry Joy. That solution only works with with zero-based enumaration though. I also wouldn't consider it save as it doesn't deal with indexes that are out of range.

The solution I ended up using might not be as simple but it's completely save and won't hurt the performance of your code even with big enums:

public enum Example {

    UNKNOWN(0, "unknown"), ENUM1(1, "enum1"), ENUM2(2, "enum2"), ENUM3(3, "enum3");

    private static HashMap<Integer, Example> enumById = new HashMap<>();
    static {
        Arrays.stream(values()).forEach(e -> enumById.put(e.getId(), e));
    }

    public static Example getById(int id) {
        return enumById.getOrDefault(id, UNKNOWN);
    }

    private int id;
    private String description;

    private Example(int id, String description) {
        this.id = id;
        this.description= description;
    }

    public String getDescription() {
        return description;
    }

    public int getId() {
        return id;
    }
}

If you are sure that you will never be out of range with your index and you don't want to use UNKNOWN like I did above you can of course also do:

public static Example getById(int id) {
        return enumById.get(id);
}

How to get JSON response from http.Get

You need upper case property names in your structs in order to be used by the json packages.

Upper case property names are exported properties. Lower case property names are not exported.

You also need to pass the your data object by reference (&data).

package main

import "os"
import "fmt"
import "net/http"
import "io/ioutil"
import "encoding/json"

type tracks struct {
    Toptracks []toptracks_info
}

type toptracks_info struct {
    Track []track_info
    Attr  []attr_info
}

type track_info struct {
    Name       string
    Duration   string
    Listeners  string
    Mbid       string
    Url        string
    Streamable []streamable_info
    Artist     []artist_info
    Attr       []track_attr_info
}

type attr_info struct {
    Country    string
    Page       string
    PerPage    string
    TotalPages string
    Total      string
}

type streamable_info struct {
    Text      string
    Fulltrack string
}

type artist_info struct {
    Name string
    Mbid string
    Url  string
}

type track_attr_info struct {
    Rank string
}

func get_content() {
    // json data
    url := "http://ws.audioscrobbler.com/2.0/?method=geo.gettoptracks&api_key=c1572082105bd40d247836b5c1819623&format=json&country=Netherlands"

    res, err := http.Get(url)

    if err != nil {
        panic(err.Error())
    }

    body, err := ioutil.ReadAll(res.Body)

    if err != nil {
        panic(err.Error())
    }

    var data tracks
    json.Unmarshal(body, &data)
    fmt.Printf("Results: %v\n", data)
    os.Exit(0)
}

func main() {
    get_content()
}

Why does this AttributeError in python occur?

This happens because the scipy module doesn't have any attribute named sparse. That attribute only gets defined when you import scipy.sparse.

Submodules don't automatically get imported when you just import scipy; you need to import them explicitly. The same holds for most packages, although a package can choose to import its own submodules if it wants to. (For example, if scipy/__init__.py included a statement import scipy.sparse, then the sparse submodule would be imported whenever you import scipy.)

How to use delimiter for csv in python

Your code is blanking out your file:

import csv
workingdir = "C:\Mer\Ven\sample"
csvfile = workingdir+"\test3.csv"
f=open(csvfile,'wb') # opens file for writing (erases contents)
csv.writer(f, delimiter =' ',quotechar =',',quoting=csv.QUOTE_MINIMAL)

if you want to read the file in, you will need to use csv.reader and open the file for reading.

import csv
workingdir = "C:\Mer\Ven\sample"
csvfile = workingdir+"\test3.csv"
f=open(csvfile,'rb') # opens file for reading
reader = csv.reader(f)
for line in reader:
    print line

If you want to write that back out to a new file with different delimiters, you can create a new file and specify those delimiters and write out each line (instead of printing the tuple).

After submitting a POST form open a new window showing the result

Add

<form target="_blank" ...></form>

or

form.setAttribute("target", "_blank");

to your form's definition.

SelectSingleNode returning null for known good xml node path using XPath

This should work in your case without removing namespaces:

XmlNode idNode = myXmlDoc.GetElementsByTagName("id")[0];

Bootstrap 4 dropdown with search

dropdown with search using bootstrap 4.4.0 version

_x000D_
_x000D_
function myFunction() {
  document.getElementById("myDropdown").classList.toggle("show");
}

function filterFunction() {
  var input, filter, ul, li, a, i;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  div
    = document.getElementById("myDropdown");
  a = div.getElementsByTagName("a");
  for (i = 0; i <
    a.length; i++) {
    txtValue = a[i].textContent || a[i].innerText;
    if (txtValue.toUpperCase().indexOf(filter) > -1) {
      a[i].style.display = "";
    } else {
      a[i].style.display = "none";
    }
  }
}
_x000D_
#myInput {
  box-sizing: border-box;
  background-image: url('searchicon.png');
  background-position: 14px 12px;
  background-repeat: no-repeat;
  font-size: 16px;
  padding: 14px 20px 12px 45px;
  border: none;
  border-bottom: 1px solid #ddd;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f6f6f6;
  min-width: 230px;
  overflow: auto;
  border: 1px solid #ddd;
  z-index: 1;
}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

.dropdown a:hover {
  background-color: #ddd;
}

.show {
  display: block;
}
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>

<div class="dropdown">
  <button onclick="myFunction()" class="dropbtn">Dropdown</button>
  <div id="myDropdown" class="dropdown-content">
    <input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()">
    <a href="#about">home</a>
    <a href="#base">contact</a>

  </div>
</div>
_x000D_
_x000D_
_x000D_

I can't access http://localhost/phpmyadmin/

http://localhost:80/phpmyadmin/ 

or if you changed port from httpd.conf write port number instead of 80.

How to create file object from URL object (image)

You can convert the URL to a String and use it to create a new File. e.g.

URL url = new URL("http://google.com/pathtoaimage.jpg");
File f = new File(url.getFile());

Checking if sys.argv[x] is defined

In the end, the difference between try, except and testing len(sys.argv) isn't all that significant. They're both a bit hackish compared to argparse.

This occurs to me, though -- as a sort of low-budget argparse:

arg_names = ['command', 'x', 'y', 'operation', 'option']
args = dict(zip(arg_names, sys.argv))

You could even use it to generate a namedtuple with values that default to None -- all in four lines!

Arg_list = collections.namedtuple('Arg_list', arg_names)
args = Arg_list(*(args.get(arg, None) for arg in arg_names))

In case you're not familiar with namedtuple, it's just a tuple that acts like an object, allowing you to access its values using tup.attribute syntax instead of tup[0] syntax.

So the first line creates a new namedtuple type with values for each of the values in arg_names. The second line passes the values from the args dictionary, using get to return a default value when the given argument name doesn't have an associated value in the dictionary.

Bootstrap 3.0 - Fluid Grid that includes Fixed Column Sizes

or use display property with table-cell;

css

.table-layout {
    display:table;
    width:100%;
}
.table-layout .table-cell {
    display:table-cell;
    border:solid 1px #ccc;
}

.fixed-width-200 {
    width:200px;
}

html

<div class="table-layout">
    <div class="table-cell fixed-width-200">
        <p>fixed width div</p>
    </div>
    <div class="table-cell">
        <p>fluid width div</p>    
    </div>
</div>

http://jsfiddle.net/DnGDz/

How do you append to a file?

Python has many variations off of the main three modes, these three modes are:

'w'   write text
'r'   read text
'a'   append text

So to append to a file it's as easy as:

f = open('filename.txt', 'a') 
f.write('whatever you want to write here (in append mode) here.')

Then there are the modes that just make your code fewer lines:

'r+'  read + write text
'w+'  read + write text
'a+'  append + read text

Finally, there are the modes of reading/writing in binary format:

'rb'  read binary
'wb'  write binary
'ab'  append binary
'rb+' read + write binary
'wb+' read + write binary
'ab+' append + read binary

Why is <deny users="?" /> included in the following example?

Example 1 is for asp.net applications using forms authenication. This is common practice for internet applications because user is unauthenticated until it is authentcation against some security module.

Example 2 is for asp.net application using windows authenication. Windows Authentication uses Active Directory to authenticate users. The will prevent access to your application. I use this feature on intranet applications.

Getting the last revision number in SVN?

The following should work:

svnlook youngest <repo-path>

It returns a single revision number.

how to convert from int to char*?

You also can use casting.

example:

string s;
int value = 3;
s.push_back((char)('0' + value));

Cannot resolve symbol AppCompatActivity - Support v7 libraries aren't recognized?

I changed from "... extends ActionBarActivity" to "... extends AppCompatActivity" and tried cleaning, restarting, Invalidate Caches / Restart and wasn't getting anywhere. All my versions were up to the latest.

What finally solved it was making sure my import was correct:

import android.support.v7.app.AppCompatActivity;

For some reason it didn't get set up automatically like I was used to and I had to add it manually.

Hope that helps someone!

Excel Formula which places date/time in cell when data is entered in another cell in the same row

Not sure if this works for cells with functions but I found this code elsewhere for single cell entries and modified it for my use. If done properly, you do not need to worry about entering a function in a cell or the file changing the dates to that day's date every time it is opened.

  • open Excel
  • press "Alt+F11"
  • Double-click on the worksheet that you want to apply the change to (listed on the left)
  • copy/paste the code below
  • adjust the Range(:) input to correspond to the column you will update
  • adjust the Offset(0,_) input to correspond to the column where you would like the date displayed (in the version below I am making updates to column D and I want the date displayed in column F, hence the input entry of "2" for 2 columns over from column D)
  • hit save
  • repeat steps above if there are other worksheets in your workbook that need the same code
  • you may have to change the number format of the column displaying the date to "General" and increase the column's width if it is displaying "####" after you make an updated entry

Copy/Paste Code below:


Private Sub Worksheet_Change(ByVal Target As Range)

If Intersect(Target, Range("D:D")) Is Nothing Then Exit Sub
Target.Offset(0, 2) = Date

End Sub


Good luck...

Eclipse doesn't stop at breakpoints

I suddenly experienced the skipping of breakpoints as well in Eclipse Juno CDT. For me the issue was that I had set optimization levels up. Once I set it back to none it was working fine. To set optimization levels go to Project Properties -> C/C++ Build -> Settings -> Tool Settings pan depending on which compiler you are using go to -> Optimization and set Optimization Level to: None (-O0). Hope this helps! Best

How do I use Wget to download all images into a single folder, from a URL?

According to the man page the -P flag is:

-P prefix --directory-prefix=prefix Set directory prefix to prefix. The directory prefix is the directory where all other files and subdirectories will be saved to, i.e. the top of the retrieval tree. The default is . (the current directory).

This mean that it only specifies the destination but where to save the directory tree. It does not flatten the tree into just one directory. As mentioned before the -nd flag actually does that.

@Jon in the future it would be beneficial to describe what the flag does so we understand how something works.

How to display multiple images in one figure correctly?

You could try the following:

import matplotlib.pyplot as plt
import numpy as np

def plot_figures(figures, nrows = 1, ncols=1):
    """Plot a dictionary of figures.

    Parameters
    ----------
    figures : <title, figure> dictionary
    ncols : number of columns of subplots wanted in the display
    nrows : number of rows of subplots wanted in the figure
    """

    fig, axeslist = plt.subplots(ncols=ncols, nrows=nrows)
    for ind,title in zip(range(len(figures)), figures):
        axeslist.ravel()[ind].imshow(figures[title], cmap=plt.jet())
        axeslist.ravel()[ind].set_title(title)
        axeslist.ravel()[ind].set_axis_off()
    plt.tight_layout() # optional



# generation of a dictionary of (title, images)
number_of_im = 20
w=10
h=10
figures = {'im'+str(i): np.random.randint(10, size=(h,w)) for i in range(number_of_im)}

# plot of the images in a figure, with 5 rows and 4 columns
plot_figures(figures, 5, 4)

plt.show()

However, this is basically just copy and paste from here: Multiple figures in a single window for which reason this post should be considered to be a duplicate.

I hope this helps.

mysqli::query(): Couldn't fetch mysqli

Probably somewhere you have DBconnection->close(); and then some queries try to execute .


Hint: It's sometimes mistake to insert ...->close(); in __destruct() (because __destruct is event, after which there will be a need for execution of queries)

Change the name of a key in dictionary

d = {1:2,3:4}

suppose that we want to change the keys to the list elements p=['a' , 'b']. the following code will do:

d=dict(zip(p,list(d.values()))) 

and we get

{'a': 2, 'b': 4}

IP to Location using Javascript

Either one of the following links should take care of this:

http://ipinfodb.com/ip_location_api_json.php

http://www.adam-mcfarland.net/2009/11/19/simple-ip-geolocation-using-javascript-and-the-google-ajax-search-api/

Those links have tutorials for getting a users location through Javascript. However, they do so through an API to an external data service. If you have an extremely high traffic site, you might want to hosting the data yourself (or getting a premium api service). To host everything yourself, you will have to host a database with IP Geolocation and use ajax to feed the users location into Javascript. If this is the approach you want to take, you can get a free database of IP information below:

http://www.ipinfodb.com/ip_database.php

Please note that this method entails having to periodically update the database to stay accurate in tracing ips to locations.

How do I get a Cron like scheduler in Python?

I know there are a lot of answers, but another solution could be to go with decorators. This is an example to repeat a function everyday at a specific time. The cool think about using this way is that you only need to add the Syntactic Sugar to the function you want to schedule:

@repeatEveryDay(hour=6, minutes=30)
def sayHello(name):
    print(f"Hello {name}")

sayHello("Bob") # Now this function will be invoked every day at 6.30 a.m

And the decorator will look like:

def repeatEveryDay(hour, minutes=0, seconds=0):
    """
    Decorator that will run the decorated function everyday at that hour, minutes and seconds.
    :param hour: 0-24
    :param minutes: 0-60 (Optional)
    :param seconds: 0-60 (Optional)
    """
    def decoratorRepeat(func):

        @functools.wraps(func)
        def wrapperRepeat(*args, **kwargs):

            def getLocalTime():
                return datetime.datetime.fromtimestamp(time.mktime(time.localtime()))

            # Get the datetime of the first function call
            td = datetime.timedelta(seconds=15)
            if wrapperRepeat.nextSent == None:
                now = getLocalTime()
                wrapperRepeat.nextSent = datetime.datetime(now.year, now.month, now.day, hour, minutes, seconds)
                if wrapperRepeat.nextSent < now:
                    wrapperRepeat.nextSent += td

            # Waiting till next day
            while getLocalTime() < wrapperRepeat.nextSent:
                time.sleep(1)

            # Call the function
            func(*args, **kwargs)

            # Get the datetime of the next function call
            wrapperRepeat.nextSent += td
            wrapperRepeat(*args, **kwargs)

        wrapperRepeat.nextSent = None
        return wrapperRepeat

    return decoratorRepeat

Using ZXing to create an Android barcode scanning app

Using Zxing this way requires a user to also install the barcode scanner app, which isn't ideal. What you probably want is to bundle Zxing into your app directly.

I highly recommend using this library: https://github.com/dm77/barcodescanner

It takes all the crazy build issues you're going to run into trying to integrate Xzing or Zbar directly. It uses those libraries under the covers, but wraps them in a very simple to use API.

What is the purpose of the HTML "no-js" class?

Modernizr.js will remove the no-js class.

This allows you to make CSS rules for .no-js something to apply them only if Javascript is disabled.

SQL count rows in a table

Use This Query :

Select
    S.name + '.' + T.name As TableName ,
    SUM( P.rows ) As RowCont 

From sys.tables As T
    Inner Join sys.partitions As P On ( P.OBJECT_ID = T.OBJECT_ID )
    Inner Join sys.schemas As S On ( T.schema_id = S.schema_id )
Where
    ( T.is_ms_shipped = 0 )
    AND 
    ( P.index_id IN (1,0) )
    And
    ( T.type = 'U' )

Group By S.name , T.name 

Order By SUM( P.rows ) Desc

Passing parameter via url to sql server reporting service

http://desktop-qr277sp/Reports01/report/Reports/reportName?Log%In%Name=serverUsername&paramName=value

Pass parameter to the report with server authentication

Python: Get relative path from comparing two absolute paths

A write-up of jme's suggestion, using pathlib, in Python 3.

from pathlib import Path
parent = Path(r'/a/b')
son = Path(r'/a/b/c/d')            
?
if parent in son.parents or parent==son:
    print(son.relative_to(parent)) # returns Path object equivalent to 'c/d'

Forward declaration of a typedef in C++

Using forward declarations instead of a full #includes is possible only when you are not intending on using the type itself (in this file's scope) but a pointer or reference to it.

To use the type itself, the compiler must know its size - hence its full declaration must be seen - hence a full #include is needed.

However, the size of a pointer or reference is known to the compiler, regardless of the size of the pointee, so a forward declaration is sufficient - it declares a type identifier name.

Interestingly, when using pointer or reference to class or struct types, the compiler can handle incomplete types saving you the need to forward declare the pointee types as well:

// header.h

// Look Ma! No forward declarations!
typedef class A* APtr; // class A is an incomplete type - no fwd. decl. anywhere
typedef class A& ARef;

typedef struct B* BPtr; // struct B is an incomplete type - no fwd. decl. anywhere
typedef struct B& BRef;

// Using the name without the class/struct specifier requires fwd. decl. the type itself.    
class C;         // fwd. decl. type
typedef C* CPtr; // no class/struct specifier 
typedef C& CRef; // no class/struct specifier 

struct D;        // fwd. decl. type
typedef D* DPtr; // no class/struct specifier 
typedef D& DRef; // no class/struct specifier 

No matching bean of type ... found for dependency

I have similar trouble in test config, because of using AOP. I added this line of code in spring-config.xml

<aop:config proxy-target-class="true"/>

And it works !

Remove last commit from remote git repository

If nobody has pulled it, you can probably do something like

git push remote +branch^1:remotebranch

which will forcibly update the remote branch to the last but one commit of your branch.

How to get maximum value from the Collection (for example ArrayList)?

Java 8

As integers are comparable we can use the following one liner in:

List<Integer> ints = Stream.of(22,44,11,66,33,55).collect(Collectors.toList());
Integer max = ints.stream().mapToInt(i->i).max().orElseThrow(NoSuchElementException::new); //66
Integer min = ints.stream().mapToInt(i->i).min().orElseThrow(NoSuchElementException::new); //11

Another point to note is we cannot use Funtion.identity() in place of i->i as mapToInt expects ToIntFunction which is a completely different interface and is not related to Function. Moreover this interface has only one method applyAsInt and no identity() method.

How to deselect a selected UITableView cell?

Swift 4:

func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
    let cell = tableView.cellForRow(at: indexPath)
    if cell?.isSelected == true { // check if cell has been previously selected
        tableView.deselectRow(at: indexPath, animated: true)
        return nil
    } else {
        return indexPath
    }
}

Change IPython/Jupyter notebook working directory

If you are using ipython in linux, then follow the steps:
!cd /directory_name/
You can try all the commands which work in you linux terminal.
!vi file_name.py

Just specify the exclamation(!) symbol before your linux commands.

replacing text in a file with Python

This is a short and simple example I just used:

If:

fp = open("file.txt", "w")

Then:

fp.write(line.replace('is', 'now'))
// "This is me" becomes "This now me"

Not:

line.replace('is', 'now')
fp.write(line)
// "This is me" not changed while writing

Why is the parent div height zero when it has floated children

Content that is floating does not influence the height of its container. The element contains no content that isn't floating (so nothing stops the height of the container being 0, as if it were empty).

Setting overflow: hidden on the container will avoid that by establishing a new block formatting context. See methods for containing floats for other techniques and containing floats for an explanation about why CSS was designed this way.

pythonic way to do something N times without an index variable?

Assume that you've defined do_something as a function, and you'd like to perform it N times. Maybe you can try the following:

todos = [do_something] * N  
for doit in todos:  
    doit()

How to run DOS/CMD/Command Prompt commands from VB.NET?

You Can try This To Run Command Then cmd Exits

Process.Start("cmd", "/c YourCode")

You Can try This To Run The Command And Let cmd Wait For More Commands

Process.Start("cmd", "/k YourCode")

SQL Server default character encoding

If you need to know the default collation for a newly created database use:

SELECT SERVERPROPERTY('Collation')

This is the server collation for the SQL Server instance that you are running.

Changing git commit message after push (given that no one pulled from remote)

Use these two step in console :

git commit --amend -m "new commit message"

and then

git push -f

Done :)

matplotlib.pyplot will not forget previous plots - how can I flush/refresh?

I discovered that this behaviour only occurs after running a particular script, similar to the one in the question. I have no idea why it occurs.

It works (refreshes the graphs) if I put

plt.clf()
plt.cla()
plt.close()

after every plt.show()

What is difference between MVC, MVP & MVVM design pattern in terms of coding c#

Great Explanation from the link : http://geekswithblogs.net/dlussier/archive/2009/11/21/136454.aspx

Let's First look at MVC

The input is directed at the Controller first, not the view. That input might be coming from a user interacting with a page, but it could also be from simply entering a specific url into a browser. In either case, its a Controller that is interfaced with to kick off some functionality.

There is a many-to-one relationship between the Controller and the View. That’s because a single controller may select different views to be rendered based on the operation being executed.

There is one way arrow from Controller to View. This is because the View doesn’t have any knowledge of or reference to the controller.

The Controller does pass back the Model, so there is knowledge between the View and the expected Model being passed into it, but not the Controller serving it up.

MVP – Model View Presenter

Now let’s look at the MVP pattern. It looks very similar to MVC, except for some key distinctions:

The input begins with the View, not the Presenter.

There is a one-to-one mapping between the View and the associated Presenter.

The View holds a reference to the Presenter. The Presenter is also reacting to events being triggered from the View, so its aware of the View its associated with.

The Presenter updates the View based on the requested actions it performs on the Model, but the View is not Model aware.

MVVM – Model View View Model

So with the MVC and MVP patterns in front of us, let’s look at the MVVM pattern and see what differences it holds:

The input begins with the View, not the View Model.

While the View holds a reference to the View Model, the View Model has no information about the View. This is why its possible to have a one-to-many mapping between various Views and one View Model…even across technologies. For example, a WPF View and a Silverlight View could share the same View Model.

border-radius not working

Try add !important to your css. Its working for me.

.panel {
  float: right;
  width: 120px;
  height: auto;
  background: #fff;
  border-radius: 7px!important;
}

Read pdf files with php

You might want to also try this application http://pdfbox.apache.org/. A working example can be found at https://www.jinises.com

How do I get time of a Python program's execution?

In Linux or Unix:

$ time python yourprogram.py

In Windows, see this StackOverflow question: How do I measure execution time of a command on the Windows command line?

For more verbose output,

$ time -v python yourprogram.py
    Command being timed: "python3 yourprogram.py"
    User time (seconds): 0.08
    System time (seconds): 0.02
    Percent of CPU this job got: 98%
    Elapsed (wall clock) time (h:mm:ss or m:ss): 0:00.10
    Average shared text size (kbytes): 0
    Average unshared data size (kbytes): 0
    Average stack size (kbytes): 0
    Average total size (kbytes): 0
    Maximum resident set size (kbytes): 9480
    Average resident set size (kbytes): 0
    Major (requiring I/O) page faults: 0
    Minor (reclaiming a frame) page faults: 1114
    Voluntary context switches: 0
    Involuntary context switches: 22
    Swaps: 0
    File system inputs: 0
    File system outputs: 0
    Socket messages sent: 0
    Socket messages received: 0
    Signals delivered: 0
    Page size (bytes): 4096
    Exit status: 0

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).

Simple CSS: Text won't center in a button

Usualy, your code should work...

But here is a way to center text in css:

.text
{
    margin-left: auto;
    margin-right: auto;
}

This has proved to be bulletproof to me whenever I want to center text with css.

Print execution time of a shell command

In zsh you can use

=time ...

In bash or zsh you can use

command time ...

These (by different mechanisms) force an external command to be used.

How can I create a dropdown menu from a List in Tkinter?

To create a "drop down menu" you can use OptionMenu in tkinter

Example of a basic OptionMenu:

from Tkinter import *

master = Tk()

variable = StringVar(master)
variable.set("one") # default value

w = OptionMenu(master, variable, "one", "two", "three")
w.pack()

mainloop()

More information (including the script above) can be found here.


Creating an OptionMenu of the months from a list would be as simple as:

from tkinter import *

OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc

master = Tk()

variable = StringVar(master)
variable.set(OPTIONS[0]) # default value

w = OptionMenu(master, variable, *OPTIONS)
w.pack()

mainloop()

In order to retrieve the value the user has selected you can simply use a .get() on the variable that we assigned to the widget, in the below case this is variable:

from tkinter import *

OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc

master = Tk()

variable = StringVar(master)
variable.set(OPTIONS[0]) # default value

w = OptionMenu(master, variable, *OPTIONS)
w.pack()

def ok():
    print ("value is:" + variable.get())

button = Button(master, text="OK", command=ok)
button.pack()

mainloop()

I would highly recommend reading through this site for further basic tkinter information as the above examples are modified from that site.

How do you handle a "cannot instantiate abstract class" error in C++?

The error means there are some methods of the class that aren't implemented. You cannot instantiate such a class, so there isn't anything you can do, other than implement all of the methods of the class.

On the other hand, a common pattern is to instantiate a concrete class and assign it to a pointer of an abstrate base class:

class Abstract { /* stuff */ 4};
class Derived : virtual public Abstract { /* implement Abstract's methods */ };

Abstract* pAbs = new Derived; // OK

Just an aside, to avoid memory management issues with the above line, you could consider using a smart pointer, such as an `std::unique_ptr:

std::unique_ptr<Abstract> pAbs(new Derived);

How to test abstract class in Java with JUnit?

If you need a solution anyway (e.g. because you have too many implementations of the abstract class and the testing would always repeat the same procedures) then you could create an abstract test class with an abstract factory method which will be excuted by the implementation of that test class. This examples works or me with TestNG:

The abstract test class of Car:

abstract class CarTest {

// the factory method
abstract Car createCar(int speed, int fuel);

// all test methods need to make use of the factory method to create the instance of a car
@Test
public void testGetSpeed() {
    Car car = createCar(33, 44);
    assertEquals(car.getSpeed(), 33);
    ...

Implementation of Car

class ElectricCar extends Car {

    private final int batteryCapacity;

    public ElectricCar(int speed, int fuel, int batteryCapacity) {
        super(speed, fuel);
        this.batteryCapacity = batteryCapacity;
    }

    ...

Unit test class ElectricCarTest of the Class ElectricCar:

class ElectricCarTest extends CarTest {

    // implementation of the abstract factory method
    Car createCar(int speed, int fuel) {
        return new ElectricCar(speed, fuel, 0);
    }

    // here you cann add specific test methods
    ...

Oracle 12c Installation failed to access the temporary location

This problem arises due to the administrative share.

Here is the solution :

  1. Set HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System DWORD value: LocalAccountTokenFilterPolicy to 1

  2. Go to this link: http://www.snehashish.com/install-oracle-database-12c-software/ Follow 8th point.
    It helped me a lot.
    After creating the hidden share (c$) it should look like this (you can ignore the description tab)

And for remaining you can follow the above link.

And let me know if it worked or not.

Write to rails console

As other have said, you want to use either puts or p. Why? Is that magic?

Actually not. A rails console is, under the hood, an IRB, so all you can do in IRB you will be able to do in a rails console. Since for printing in an IRB we use puts, we use the same command for printing in a rails console.

You can actually take a look at the console code in the rails source code. See the require of irb? :)

How can I use Html.Action?

Another case is http redirection. If your page redirects http requests to https, then may be your partial view tries to redirect by itself.

It causes same problem again. For this problem, you can reorganize your .net error pages or iis error pages configuration.

Just make sure you are redirecting requests to right error or not found page and make sure this error page contains non problematic partial. If your page supports only https, do not forward requests to error page without using https, if error page contains partial, this partials tries to redirect seperately from requested url, it causes problem.

Setting the value of checkbox to true or false with jQuery

You can do (jQuery 1.6 onwards):

$('#idCheckbox').prop('checked', true);
$('#idCheckbox').prop('checked', false);

to remove you can also use:

$('#idCheckbox').removeProp('checked');

with jQuery < 1.6 you must do

$('#idCheckbox').attr('checked', true);
$('#idCheckbox').removeAttr('checked');

PHP date add 5 year to current date

       $date = strtotime($row['timestamp']);
       $newdate = date('d-m-Y',strtotime("+1 year",$date));

Email address validation using ASP.NET MVC data type attributes

if you aren't yet using .net 4.5:

/// <summary>
/// TODO: AFTER WE UPGRADE TO .NET 4.5 THIS WILL NO LONGER BE NECESSARY.
/// </summary>
public class EmailAnnotation : RegularExpressionAttribute
{
    static EmailAnnotation()
    {
        DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(EmailAnnotation), typeof(RegularExpressionAttributeAdapter));
    }

    /// <summary>
    /// from: http://stackoverflow.com/a/6893571/984463
    /// </summary>
    public EmailAnnotation()
        : base(@"^[\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?\^_`{|}~]+)*"
            + "@"
            + @"((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3}))$") { }

    public override string FormatErrorMessage(string name)
    {
        return "E-mail is not valid";
    }
}

Then you can do this:

    public class ContactEmailAddressDto
    {
        public int ContactId { get; set; }
        [Required]
        [Display(Name = "New Email Address")]
        [EmailAnnotation] //**<----- Nifty.**
        public string EmailAddressToAdd { get; set; }
    }

How to resolve ambiguous column names when retrieving results?

I had this same issue with dynamic tables. (Tables that are assumed to have an id to be able to join but without any assumption for the rest of the fields.) In this case you don't know the aliases before hand.

In such cases you can first get the table column names for all dynamic tables:

$tblFields = array_keys($zendDbInstance->describeTable($tableName));

Where $zendDbInstance is an instance of Zend_Db or you can use one of the functions here to not rely on Zend php pdo: get the columns name of a table

Then for all dynamic tables you can get the aliases and use $tableName.* for the ones you don't need aliases:

$aliases = "";
foreach($tblKeys as $field)
    $aliases .= $tableName . '.' . $field . ' AS ' . $tableName . '_' . $field . ',' ;
$aliases = trim($aliases, ',');

You can wrap this whole process up into one generic function and just have cleaner code or get more lazy if you wish :)

Difference between <context:annotation-config> and <context:component-scan>

As a complementary, you can use @ComponentScan to use <context:component-scan> in annotation way.

It's also described at spring.io

Configures component scanning directives for use with @Configuration classes. Provides support parallel with Spring XML's element.

One thing to note, if you're using Spring Boot, the @Configuration and @ComponentScan can be implied by using @SpringBootApplication annotation.

jQuery 'each' loop with JSON array

Try (untested):

$.getJSON("data.php", function(data){
    $.each(data.justIn, function() {
        $.each(this, function(k, v) {
            alert(k + ' ' + v);
        });
    });
    $.each(data.recent, function() {
        $.each(this, function(k, v) {
            alert(k + ' ' + v);
        });
    });
    $.each(data.old, function() {
        $.each(this, function(k, v) {
            alert(k + ' ' + v);
        });
    });    
});

I figured, three separate loops since you'll probably want to treat each dataset differently (justIn, recent, old). If not, you can do:

$.getJSON("data.php", function(data){
    $.each(data, function(k, v) {
        alert(k + ' ' + v);
        $.each(v, function(k1, v1) {
            alert(k1 + ' ' + v1);
        });
    });
}); 

ParseError: not well-formed (invalid token) using cElementTree

I was having the same error (with ElementTree). In my case it was because of encodings, and I was able to solve it without having to use an external library. Hope this helps other people finding this question based on the title. (reference)

import xml.etree.ElementTree as ET
parser = ET.XMLParser(encoding="utf-8")
tree = ET.fromstring(xmlstring, parser=parser)

EDIT: Based on comments, this answer might be outdated. But this did work back when it was answered...

Replace deprecated preg_replace /e with preg_replace_callback

You can use an anonymous function to pass the matches to your function:

$result = preg_replace_callback(
    "/\{([<>])([a-zA-Z0-9_]*)(\?{0,1})([a-zA-Z0-9_]*)\}(.*)\{\\1\/\\2\}/isU",
    function($m) { return CallFunction($m[1], $m[2], $m[3], $m[4], $m[5]); },
    $result
);

Apart from being faster, this will also properly handle double quotes in your string. Your current code using /e would convert a double quote " into \".

How do I use CREATE OR REPLACE?

One of the nice things about the syntax is that you can be sure that a CREATE OR REPLACE will never cause you to lose data (the most you will lose is code, which hopefully you'll have stored in source control somewhere).

The equivalent syntax for tables is ALTER, which means you have to explicitly enumerate the exact changes that are required.

EDIT: By the way, if you need to do a DROP + CREATE in a script, and you don't care for the spurious "object does not exist" errors (when the DROP doesn't find the table), you can do this:

BEGIN
  EXECUTE IMMEDIATE 'DROP TABLE owner.mytable';
EXCEPTION
  WHEN OTHERS THEN
    IF sqlcode != -0942 THEN RAISE; END IF;
END;
/

Decoding and verifying JWT token using System.IdentityModel.Tokens.Jwt

I am just wondering why to use some libraries for JWT token decoding and verification at all.

Encoded JWT token can be created using following pseudocode

var headers = base64URLencode(myHeaders);
var claims = base64URLencode(myClaims);
var payload = header + "." + claims;

var signature = base64URLencode(HMACSHA256(payload, secret));

var encodedJWT = payload + "." + signature;

It is very easy to do without any specific library. Using following code:

using System;
using System.Text;
using System.Security.Cryptography;

public class Program
{   
    // More info: https://stormpath.com/blog/jwt-the-right-way/
    public static void Main()
    {           
        var header = "{\"typ\":\"JWT\",\"alg\":\"HS256\"}";
        var claims = "{\"sub\":\"1047986\",\"email\":\"[email protected]\",\"given_name\":\"John\",\"family_name\":\"Doe\",\"primarysid\":\"b521a2af99bfdc65e04010ac1d046ff5\",\"iss\":\"http://example.com\",\"aud\":\"myapp\",\"exp\":1460555281,\"nbf\":1457963281}";

        var b64header = Convert.ToBase64String(Encoding.UTF8.GetBytes(header))
            .Replace('+', '-')
            .Replace('/', '_')
            .Replace("=", "");
        var b64claims = Convert.ToBase64String(Encoding.UTF8.GetBytes(claims))
            .Replace('+', '-')
            .Replace('/', '_')
            .Replace("=", "");

        var payload = b64header + "." + b64claims;
        Console.WriteLine("JWT without sig:    " + payload);

        byte[] key = Convert.FromBase64String("mPorwQB8kMDNQeeYO35KOrMMFn6rFVmbIohBphJPnp4=");
        byte[] message = Encoding.UTF8.GetBytes(payload);

        string sig = Convert.ToBase64String(HashHMAC(key, message))
            .Replace('+', '-')
            .Replace('/', '_')
            .Replace("=", "");

        Console.WriteLine("JWT with signature: " + payload + "." + sig);        
    }

    private static byte[] HashHMAC(byte[] key, byte[] message)
    {
        var hash = new HMACSHA256(key);
        return hash.ComputeHash(message);
    }
}

The token decoding is reversed version of the code above.To verify the signature you will need to the same and compare signature part with calculated signature.

UPDATE: For those how are struggling how to do base64 urlsafe encoding/decoding please see another SO question, and also wiki and RFCs

Javascript add leading zeroes to date

As @John Henckel suggests, starting using the toISOString() method makes things easier

_x000D_
_x000D_
const dateString = new Date().toISOString().split('-');_x000D_
const year = dateString[0];_x000D_
const month = dateString[1];_x000D_
const day = dateString[2].split('T')[0];_x000D_
_x000D_
console.log(`${year}-${month}-${day}`);
_x000D_
_x000D_
_x000D_

Spring MVC: difference between <context:component-scan> and <annotation-driven /> tags?

Annotation-driven indicates to Spring that it should scan for annotated beans, and to not just rely on XML bean configuration. Component-scan indicates where to look for those beans.

Here's some doc: http://static.springsource.org/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-config-enable

Restore DB — Error RESTORE HEADERONLY is terminating abnormally.

I ran into this issue and my problem was a bit more involved... Originally I was trying to restore a SQL Server 2000 backup to SQL Server 2012. Of course this didn't work cause SQL server 2012 only supports backups from 2005 and upwards .

So, I restored the database on a SQL Server 2008 machine. Once this was done - I copied the database over to restore on SQL Server 2012 - and it failed with the following error

The media family on device 'C:\XXXXXXXXXXX.bak' is incorrectly formed. SQL Server cannot process this media family. RESTORE HEADERONLY is terminating abnormally. (Microsoft SQL Server, Error: 3241)

After a lot of research I found that I had skipped a step - I had to go back to the SQL Server 2008 machine and Right Click On the database(that I wanted to backup)> Properties > Options > Make sure compatibility level is set to SQL Server 2008. > Save

And then re-create the backup - After this I was able to restore to SQL Server 2012.

Using Mockito to test abstract classes

The following suggestion let's you test abstract classes without creating a "real" subclass - the Mock is the subclass.

use Mockito.mock(My.class, Mockito.CALLS_REAL_METHODS), then mock any abstract methods that are invoked.

Example:

public abstract class My {
  public Result methodUnderTest() { ... }
  protected abstract void methodIDontCareAbout();
}

public class MyTest {
    @Test
    public void shouldFailOnNullIdentifiers() {
        My my = Mockito.mock(My.class, Mockito.CALLS_REAL_METHODS);
        Assert.assertSomething(my.methodUnderTest());
    }
}

Note: The beauty of this solution is that you do not have to implement the abstract methods, as long as they are never invoked.

In my honest opinion, this is neater than using a spy, since a spy requires an instance, which means you have to create an instantiatable subclass of your abstract class.

Setting different color for each series in scatter plot on matplotlib

I don't know what you mean by 'manually'. You can choose a colourmap and make a colour array easily enough:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm

x = np.arange(10)
ys = [i+x+(i*x)**2 for i in range(10)]

colors = cm.rainbow(np.linspace(0, 1, len(ys)))
for y, c in zip(ys, colors):
    plt.scatter(x, y, color=c)

Matplotlib graph with different colors

Or you can make your own colour cycler using itertools.cycle and specifying the colours you want to loop over, using next to get the one you want. For example, with 3 colours:

import itertools

colors = itertools.cycle(["r", "b", "g"])
for y in ys:
    plt.scatter(x, y, color=next(colors))

Matplotlib graph with only 3 colors

Come to think of it, maybe it's cleaner not to use zip with the first one neither:

colors = iter(cm.rainbow(np.linspace(0, 1, len(ys))))
for y in ys:
    plt.scatter(x, y, color=next(colors))

What is the reason for java.lang.IllegalArgumentException: No enum const class even though iterating through values() works just fine?

I had parsing enum problem when i was trying to pass Nullable Enum that we get from Backend. Of course it was working when we get value, but it was problem when the null comes up.

java.lang.IllegalArgumentException: No enum constant

Also the problem was when we at Parcelize read moment write some short if.

My solution for this was

1.Create companion object with parsing method.

enum class CarsType {
    @Json(name = "SMALL")
    SMALL,
    @Json(name = "BIG")
    BIG;

    companion object {
        fun nullableValueOf(name: String?) = when (name) {
            null -> null
            else -> valueOf(name)
        }
    }
}

2. In Parcerable read place use it like this

data class CarData(
    val carId: String? = null,
    val carType: CarsType?,
    val data: String?
) : Parcelable {
    constructor(parcel: Parcel) : this(
        parcel.readString(),
        CarsType.nullableValueOf(parcel.readString()),
        parcel.readString())

Is there a limit to the length of a GET request?

Not in the RFC, no, but there are practical limits.

The HTTP protocol does not place any a priori limit on the length of a URI. Servers MUST be able to handle the URI of any resource they serve, and SHOULD be able to handle URIs of unbounded length if they provide GET-based forms that could generate such URIs. A server SHOULD return 414 (Request-URI Too Long) status if a URI is longer than the server can handle (see section 10.4.15).

Note: Servers should be cautious about depending on URI lengths above 255 bytes, because some older client or proxy implementations may not properly support these lengths.

How to pass parameters to ThreadStart method in Thread?

In Additional

    Thread thread = new Thread(delegate() { download(i); });
    thread.Start();

Pandas df.to_csv("file.csv" encode="utf-8") still gives trash characters for minus sign

Your "bad" output is UTF-8 displayed as CP1252.

On Windows, many editors assume the default ANSI encoding (CP1252 on US Windows) instead of UTF-8 if there is no byte order mark (BOM) character at the start of the file. While a BOM is meaningless to the UTF-8 encoding, its UTF-8-encoded presence serves as a signature for some programs. For example, Microsoft Office's Excel requires it even on non-Windows OSes. Try:

df.to_csv('file.csv',encoding='utf-8-sig')

That encoder will add the BOM.

Find unused code

The truth is that the tool can never give you a 100% certain answer, but coverage tool can give you a pretty good run for the money.

If you count with comprehensive unit test suite, than you can use test coverage tool to see exactly what lines of code were not executed during the test run. You will still need to analyze the code manually: either eliminate what you consider dead code or write test to improve test coverage.

One such tool is NCover, with open source precursor on Sourceforge. Another alternative is PartCover.

Check out this answer on stackoverflow.

How can one print a size_t variable portably using the printf family?

Use the z modifier:

size_t x = ...;
ssize_t y = ...;
printf("%zu\n", x);  // prints as unsigned decimal
printf("%zx\n", x);  // prints as hex
printf("%zd\n", y);  // prints as signed decimal

How to add 'libs' folder in Android Studio?

also you should click right button on mouse at your projectname and choose "open module settings" or press F4 button. Then on "dependencies" tab add your lib.jar to declare needed lib

Material UI and Grid system

Material UI have implemented their own Flexbox layout via the Grid component.

It appears they initially wanted to keep themselves as purely a 'components' library. But one of the core developers decided it was too important not to have their own. It has now been merged into the core code and was released with v1.0.0.

You can install it via:

npm install @material-ui/core

It is now in the official documentation with code examples.

WPF Application that only has a tray icon

I recently had this same problem. Unfortunately, NotifyIcon is only a Windows.Forms control at the moment, if you want to use it you are going to have to include that part of the framework. I guess that depends how much of a WPF purist you are.

If you want a quick and easy way of getting started check out this WPF NotifyIcon control on the Code Project which does not rely on the WinForms NotifyIcon at all. A more recent version seems to be available on the author's website and as a NuGet package. This seems like the best and cleanest way to me so far.

  • Rich ToolTips rather than text
  • WPF context menus and popups
  • Command support and routed events
  • Flexible data binding
  • Rich balloon messages rather than the default messages provides by the OS

Check it out. It comes with an amazing sample app too, very easy to use, and you can have great looking Windows Live Messenger style WPF popups, tooltips, and context menus. Perfect for displaying an RSS feed, I am using it for a similar purpose.

How to get a value of an element by name instead of ID

This works fine .. here btnAddCat is button id

$('#btnAddCat').click(function(){
        var eventCategory=$("input[name=txtCategory]").val();
        alert(eventCategory);
    });

:not(:empty) CSS selector is not working?

Another pure CSS solution

_x000D_
_x000D_
.form{_x000D_
  position:relative;_x000D_
  display:inline-block;_x000D_
}_x000D_
.form input{_x000D_
  margin-top:10px;_x000D_
}_x000D_
.form label{_x000D_
    position:absolute;_x000D_
    left:0;_x000D_
    top:0;_x000D_
    opacity:0;_x000D_
    transition:all 1s ease;_x000D_
}_x000D_
input:not(:placeholder-shown) + label{_x000D_
    top:-10px;_x000D_
    opacity:1;_x000D_
}
_x000D_
<div class="form">_x000D_
    <input type="text" id="inputFName" placeholder="Firstname">_x000D_
    <label class="label" for="inputFName">Firstname</label>_x000D_
</div>_x000D_
<div class="form">_x000D_
    <input type="text" id="inputLName" placeholder="Lastname">_x000D_
    <label class="label" for="inputLName">Lastname</label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Concatenate text files with Windows command line, dropping leading lines

In powershell:

Get-Content file1.txt | Out-File out.txt
Get-Content file2.txt | Select-Object -Skip 1 | Out-File -Append out.txt

c# dictionary How to add multiple values for single key?

Though nearly the same as most of the other responses, I think this is the most efficient and concise way to implement it. Using TryGetValue is faster than using ContainsKey and reindexing into the dictionary as some other solutions have shown.

void Add(string key, string val)
{
    List<string> list;

    if (!dictionary.TryGetValue(someKey, out list))
    {
       values = new List<string>();
       dictionary.Add(key, list);
    }

    list.Add(val);
}

Oracle SQL Developer - tables cannot be seen

You need select privileges on All_users view

What's the difference between dependencies, devDependencies and peerDependencies in npm package.json file?

To save a package to package.json as dev dependencies:

npm install "$package" --save-dev

When you run npm install it will install both devDependencies and dependencies. To avoid install devDependencies run:

npm install --production

Read input from a JOptionPane.showInputDialog box

Your problem is that, if the user clicks cancel, operationType is null and thus throws a NullPointerException. I would suggest that you move

if (operationType.equalsIgnoreCase("Q")) 

to the beginning of the group of if statements, and then change it to

if(operationType==null||operationType.equalsIgnoreCase("Q")). 

This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.

Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.

How to get height of <div> in px dimension

Use height():

var result = $("#myDiv").height();
alert(result);

This will give you the unit-less computed height in pixels. "px" will be stripped from the result. I.e. if the height is 400px, the result will be 400, but the result will be in pixels.

If you want to do it without jQuery, you can use plain JavaScript:

var result = document.getElementById("myDiv").offsetHeight;

Connect to sqlplus in a shell script and run SQL scripts

For example:

sqlplus -s admin/password << EOF
whenever sqlerror exit sql.sqlcode;
set echo off 
set heading off

@pl_script_1.sql
@pl_script_2.sql

exit;
EOF

How does BitLocker affect performance?

Some practical tests...

  • Dell Latitude E7440
  • Intel Core i7-4600U
  • 16.0 GB
  • Windows 8.1 Professional
  • LiteOn IT LMT-256M6M MSATA 256GB

This test is using a system partition. Results for a non-system partition are a bit better.

Score decrease:
Read: 5%
Write: 16%

Without BitLocker:

Without BitLocker

With BitLocker:

With BitLocker

So you can see that with a very strong configuration and a modern SSD disk you can see a small performance degradation with tests. I don't know what about a typical work, especially with the Visual Studio.

How to easily consume a web service from PHP

Well, those features are specific to a tool that you are using for development in those languages.

You wouldn't have those tools if (for example) you were using notepad to write code. So, maybe you should ask the question for the tool you are using.

For PHP: http://webservices.xml.com/pub/a/ws/2004/03/24/phpws.html

Resizing a button

If you want to call a different size for the button inline, you would probably do it like this:

<div class="button" style="width:60px;height:100px;">This is a button</div>

Or, a better way to have different sizes (say there will be 3 standard sizes for the button) would be to have classes just for size.

For example, you would call your button like this:

<div class="button small">This is a button</div>

And in your CSS

.button.small { width: 60px; height: 100px; }

and just create classes for each size you wish to have. That way you still have the perks of using a stylesheet in case say, you want to change the size of all the small buttons at once.

java.lang.NoClassDefFoundError: org/apache/juli/logging/LogFactory

I ran into this problem when using tomcat-embed-core::7.0.47, from Maven. I'm not sure why they didn't add tomcat-util as a runtime dependency, so I added my own runtime dependency to my own project.

<dependency>
  <groupId>org.apache.tomcat</groupId>
  <artifactId>tomcat-util</artifactId>
  <version><!-- version from tomcat-embed-core --></version>
  <scope>runtime</scope>
</dependency>

Change a column type from Date to DateTime during ROR migration

First in your terminal:

rails g migration change_date_format_in_my_table

Then in your migration file:

For Rails >= 3.2:

class ChangeDateFormatInMyTable < ActiveRecord::Migration
  def up
    change_column :my_table, :my_column, :datetime
  end

  def down
    change_column :my_table, :my_column, :date
  end
end

How can I check if char* variable points to empty string?

My preferred method:

if (*ptr == 0) // empty string

Probably more common:

if (strlen(ptr) == 0) // empty string

Detecting an "invalid date" Date instance in JavaScript

date.parse(valueToBeTested) > 0 is all that's needed. A valid date will return the epoch value and an invalid value will return NaN which will fail > 0 test by virtue of not even being a number.

This is so simple that a helper function won't save code though it might be a bit more readable. If you wanted one:

String.prototype.isDate = function() {
  return !Number.isNaN(Date.parse(this));
}

OR

To use:

"StringToTest".isDate();

How can I trigger a Bootstrap modal programmatically?

The same thing happened to me. I wanted to open the Bootstrap modal by clicking on the table rows and get more details about each row. I used a trick to do this, Which I call the virtual button! Compatible with the latest version of Bootstrap (v5.0.0-alpha2). It might be useful for others as well.

See this code snippet with preview: https://gist.github.com/alireza-rezaee/c60da1429c36351ef4f071dec0ea9aba

Summary:

let exampleButton = document.createElement("button");
exampleButton.classList.add("d-none");
document.body.appendChild(exampleButton);
exampleButton.dataset.toggle = "modal";
exampleButton.dataset.target = "#exampleModal";

//AddEventListener to all rows
document.querySelectorAll('#exampleTable tr').forEach(row => {
    row.addEventListener('click', e => {
        //Set parameteres (clone row dataset)
        exampleButton.dataset.whatever = e.target.closest('tr').dataset.whatever;
        //Button click simulation
        //Now we can use relatedTarget
        exampleButton.click();
    })
});

All this is to use the relatedTarget property. (See Bootstrap docs)

How to compare two object variables in EL expression language?

Not sure if I get you right, but the simplest way would be something like:

<c:if test="${languageBean.locale == 'en'">
  <f:selectItems value="#{customerBean.selectableCommands_limited_en}" />
</c:if>

Just a quick copy and paste from an app of mine...

HTH

WinError 2 The system cannot find the file specified (Python)

Popen expect a list of strings for non-shell calls and a string for shell calls.

Call subprocess.Popen with shell=True:

process = subprocess.Popen(command, stdout=tempFile, shell=True)

Hopefully this solves your issue.

This issue is listed here: https://bugs.python.org/issue17023

getting error while updating Composer

for php7 you can do that:

sudo apt-get install php-gd php-xml php7.0-mbstring

How to pass multiple parameters in json format to a web service using jquery?

Found the solution:

It should be:

"{'Id1':'2','Id2':'2'}"

and not

"{'Id1':'2'},{'Id2':'2'}"

Clear input fields on form submit

You can access the form over the event:

e.target.reset();

Docker remove <none> TAG images

try this to see list docker images ID with tag <none>

docker images -a | awk '/^<none>/ {print $3}'

and then you can delete all image with tag <none>. this worked for me.

docker rmi $(docker images -a | awk '/^<none>/ {print $3}')

Manually highlight selected text in Notepad++

"Select your text, right click, then choose Style Token and then using 1st style (2nd style, etc …). At the moment is not possible to save the style tokens but there is an idea pending on Idea torrent you may vote for if your are interested in that."

It should be default, but it might be hidden.

"It might be that something happened to your contextMenu.xml so that you only get the basic standard. Have a look in NPPs config folder (%appdata%\Notepad++\) if the contextMenu.xml is there. If no: that would be the answer; if yes: it might be defect. Anyway you can grab the original standart contextMenu.xml from here and place it into the config folder (or replace the existing xml). Start NPP and you should have quite a long context menu. Tip: have a look at the contextmenu.xml itself - because you're allowed to change it to your own needs."

See this for more information

C++ compiling on Windows and Linux: ifdef switch

use:

#ifdef __linux__ 
    //linux code goes here
#elif _WIN32
    // windows code goes here
#else

#endif

What is the difference between README and README.md in GitHub projects?

.md stands for markdown and is generated at the bottom of your github page as html.

Typical syntax includes:

Will become a heading
==============

Will become a sub heading
--------------

*This will be Italic*

**This will be Bold**

- This will be a list item
- This will be a list item

    Add a indent and this will end up as code

For more details: http://daringfireball.net/projects/markdown/

Caching a jquery ajax response in javascript/browser

All the modern browsers provides you storage apis. You can use them (localStorage or sessionStorage) to save your data.

All you have to do is after receiving the response store it to browser storage. Then next time you find the same call, search if the response is saved already. If yes, return the response from there; if not make a fresh call.

Smartjax plugin also does similar things; but as your requirement is just saving the call response, you can write your code inside your jQuery ajax success function to save the response. And before making call just check if the response is already saved.

How to get Month Name from Calendar?

DateFormat date =  new SimpleDateFormat("dd/MMM/yyyy");
Date date1 = new Date();
System.out.println(date.format(date1));

generating variable names on fly in python

Though I don't see much point, here it is:

for i in xrange(0, len(prices)):
    exec("price%d = %s" % (i + 1, repr(prices[i])));

Parallel.ForEach vs Task.Factory.StartNew

I did a small experiment of running a method "1,000,000,000 (one billion)" times with "Parallel.For" and one with "Task" objects.

I measured the processor time and found Parallel more efficient. Parallel.For divides your task in to small work items and executes them on all the cores parallely in a optimal way. While creating lot of task objects ( FYI TPL will use thread pooling internally) will move every execution on each task creating more stress in the box which is evident from the experiment below.

I have also created a small video which explains basic TPL and also demonstrated how Parallel.For utilizes your core more efficiently http://www.youtube.com/watch?v=No7QqSc5cl8 as compared to normal tasks and threads.

Experiment 1

Parallel.For(0, 1000000000, x => Method1());

Experiment 2

for (int i = 0; i < 1000000000; i++)
{
    Task o = new Task(Method1);
    o.Start();
}

Processor time comparison

php check if array contains all array values from another array

How about this:

function array_keys_exist($searchForKeys = array(), $searchableArray) {
    $searchableArrayKeys = array_keys($searchableArray);

    return count(array_intersect($searchForKeys, $searchableArrayKeys)) == count($searchForKeys); 
}

css 100% width div not taking up full width of parent

The problem is caused by your #grid having a width:1140px.

You need to set a min-width:1140px on the body.

This will stop the body from getting smaller than the #grid. Remove width:100% as block level elements take up the available width by default. Live example: http://jsfiddle.net/tw16/LX8R3/

html, body{
    margin:0;
    padding:0;
    min-width: 1140px; /* this is the important part*/
}
#grid-container{
    background:#f8f8f8 url(../images/grid-container-bg.gif) repeat-x top left;
}
#grid{
    width:1140px;
    margin:0px auto;
}

Disable developer mode extensions pop up in Chrome

I am working on Windows And I have tried lots of things provided here as answer but Pop up was disabling the extension continually then i have tried following steps and it works now:

  1. Go to chrome://extensions page and click Pack extension button and select your root Directory of extension by clicking on red rectangled browse button displayed in below image.

browse root directory of extension

  1. after selecting root directory Click on Pack extension button displayed in red circle in below image.

enter image description here

  1. Now in check parent directory of your selected root directory of extension, 2 file would have created [extension name].crx and [extension name].pem.

  2. Now just drag and drop the [extension name].crx file onto the chrome://extensions page and it will ask using add app dialog box click on Add app and refresh the page it is installed now.

Note: Before doing anything as above make sure to enable Developer mode for extensions. If this was not enabled, refresh the chrome://extensions page after enabling it.

Maven won't run my Project : Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec

Netbeans needs to be able to index the maven repository. Allow it to do that and try again. It was giving me the same error and after it indexed the repository it ran like a charm

Refer to a cell in another worksheet by referencing the current worksheet's name?

Unless you want to go the VBA route to work out the Tab name, the Excel formula is fairly ugly based upon Mid functions, etc. But both these methods can be found here if you want to go that way.

Rather, the way I would do it is:

1) Make one cell on your sheet named, for example, Reference_Sheet and put in that cell the value "Jan Item" for example.

2) Now, use the Indirect function like:

=INDIRECT(Reference_Sheet&"!J3") 

3) Now, for each month's sheet, you just have to change that one Reference_Sheet cell.

Hope this gives you what you're looking for!

Java heap terminology: young, old and permanent generations?

This seems like a common misunderstanding. In Oracle's JVM, the permanent generation is not part of the heap. It's a separate space for class definitions and related data. In Java 6 and earlier, interned strings were also stored in the permanent generation. In Java 7, interned strings are stored in the main object heap.

Here is a good post on permanent generation.

I like the descriptions given for each space in Oracle's guide on JConsole:

For the HotSpot Java VM, the memory pools for serial garbage collection are the following.

  • Eden Space (heap): The pool from which memory is initially allocated for most objects.
  • Survivor Space (heap): The pool containing objects that have survived the garbage collection of the Eden space.
  • Tenured Generation (heap): The pool containing objects that have existed for some time in the survivor space.
  • Permanent Generation (non-heap): The pool containing all the reflective data of the virtual machine itself, such as class and method objects. With Java VMs that use class data sharing, this generation is divided into read-only and read-write areas.
  • Code Cache (non-heap): The HotSpot Java VM also includes a code cache, containing memory that is used for compilation and storage of native code.

Java uses generational garbage collection. This means that if you have an object foo (which is an instance of some class), the more garbage collection events it survives (if there are still references to it), the further it gets promoted. It starts in the young generation (which itself is divided into multiple spaces - Eden and Survivor) and would eventually end up in the tenured generation if it survived long enough.

Bootstrap: Collapse other sections when one is expanded

If you are using Bootstrap 4, and you don't want to change your markup:

var $myGroup = $('#myGroup');
$myGroup.on('show.bs.collapse','.collapse', function() {
$myGroup.find('.collapse.show').collapse('hide');
});

Syntax for creating a two-dimensional array in Java

Try:

int[][] multD = new int[5][10];

Note that in your code only the first line of the 2D array is initialized to 0. Line 2 to 5 don't even exist. If you try to print them you'll get null for everyone of them.

Excel VBA Password via Hex Editor

If you deal with .xlsm file instead of .xls you can use the old method. I was trying to modify vbaProject.bin in .xlsm several times using DBP->DBx method by it didn't work, also changing value of DBP didn't. So I was very suprised that following worked :
1. Save .xlsm as .xls.
2. Use DBP->DBx method on .xls.
3. Unfortunately some erros may occur when using modified .xls file, I had to save .xls as .xlsx and add modules, then save as .xlsm.

How can I get the last character in a string?

Since in Javascript a string is a char array, you can access the last character by the length of the string.

var lastChar = myString[myString.length -1];

Why am I getting Unknown error in line 1 of pom.xml?

For me I changed in the parent tag of the pom.xml and it solved it change 2.1.5 to 2.1.4 then Maven-> Update Project

Run on server option not appearing in Eclipse

Right click on the project, go to "Run as", select "Run configurations" and create a run configuration.

Asynchronous method call in Python?

You can implement a decorator to make your functions asynchronous, though that's a bit tricky. The multiprocessing module is full of little quirks and seemingly arbitrary restrictions – all the more reason to encapsulate it behind a friendly interface, though.

from inspect import getmodule
from multiprocessing import Pool


def async(decorated):
    r'''Wraps a top-level function around an asynchronous dispatcher.

        when the decorated function is called, a task is submitted to a
        process pool, and a future object is returned, providing access to an
        eventual return value.

        The future object has a blocking get() method to access the task
        result: it will return immediately if the job is already done, or block
        until it completes.

        This decorator won't work on methods, due to limitations in Python's
        pickling machinery (in principle methods could be made pickleable, but
        good luck on that).
    '''
    # Keeps the original function visible from the module global namespace,
    # under a name consistent to its __name__ attribute. This is necessary for
    # the multiprocessing pickling machinery to work properly.
    module = getmodule(decorated)
    decorated.__name__ += '_original'
    setattr(module, decorated.__name__, decorated)

    def send(*args, **opts):
        return async.pool.apply_async(decorated, args, opts)

    return send

The code below illustrates usage of the decorator:

@async
def printsum(uid, values):
    summed = 0
    for value in values:
        summed += value

    print("Worker %i: sum value is %i" % (uid, summed))

    return (uid, summed)


if __name__ == '__main__':
    from random import sample

    # The process pool must be created inside __main__.
    async.pool = Pool(4)

    p = range(0, 1000)
    results = []
    for i in range(4):
        result = printsum(i, sample(p, 100))
        results.append(result)

    for result in results:
        print("Worker %i: sum value is %i" % result.get())

In a real-world case I would ellaborate a bit more on the decorator, providing some way to turn it off for debugging (while keeping the future interface in place), or maybe a facility for dealing with exceptions; but I think this demonstrates the principle well enough.

Use string value from a cell to access worksheet of same name

Here is a solution using INDIRECT, which if you drag the formula, it will pick up different cells from the target sheet accordingly. It uses R1C1 notation and is not limited to working only on columns A-Z.

=INDIRECT("'"&$A$5&"'!R"&ROW()&"C"&COLUMN(),FALSE)

This version picks up the value from the target cell corresponding to the cell where the formula is placed. For example, if you place the formula in 'Summary'!B5 then it will pick up the value from 'SERVER-ONE'!B5, not 'SERVER-ONE'!G7 as specified in the original question. But you could easily add in offsets to the row and column to achieve the desired mapping in any case.

Get environment value in controller

It Doesn't work in Laravel 5.3+ if you want to try to access the value from the controller like below. It always returns null

<?php

    $value = env('MY_VALUE', 'default_value');

SOLUTION: Rather, you need to create a file in the configuration folder, say values.php and then write the code like below

File values.php

<?php

    return [

        'myvalue' => env('MY_VALUE',null),

        // Add other values as you wish

Then access the value in your controller with the following code

<?php

    $value = \Config::get('values.myvalue')

Where "values" is the filename followed by the key "myvalue".

Round a double to 2 decimal places

If you really want the same double, but rounded in the way you want you can use BigDecimal, for example

new BigDecimal(myValue).setScale(2, RoundingMode.HALF_UP).doubleValue();

Using gradle to find dependency tree

For Android, use this line

 gradle app:dependencies

or if you have a gradle wrapper:

./gradlew app:dependencies

where app is your project module.

Additionally, if you want to check if something is compile vs. testCompile vs androidTestCompile dependency as well as what is pulling it in:

./gradlew :app:dependencyInsight --configuration compile --dependency <name>
./gradlew :app:dependencyInsight --configuration testCompile --dependency <name>
./gradlew :app:dependencyInsight --configuration androidTestCompile --dependency <name>

If the application doesn't use modules, try:

gradle dependencies

CSS transition with visibility not working

Visibility is animatable. Check this blog post about it: http://www.greywyvern.com/?post=337

You can see it here too: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties

Let's say you have a menu that you want to fade-in and fade-out on mouse hover. If you use opacity:0 only, your transparent menu will still be there and it will animate when you hover the invisible area. But if you add visibility:hidden, you can eliminate this problem:

_x000D_
_x000D_
div {_x000D_
    width:100px;_x000D_
    height:20px;_x000D_
}_x000D_
.menu {_x000D_
    visibility:hidden;_x000D_
    opacity:0;_x000D_
    transition:visibility 0.3s linear,opacity 0.3s linear;_x000D_
    _x000D_
    background:#eee;_x000D_
    width:100px;_x000D_
    margin:0;_x000D_
    padding:5px;_x000D_
    list-style:none;_x000D_
}_x000D_
div:hover > .menu {_x000D_
    visibility:visible;_x000D_
    opacity:1;_x000D_
}
_x000D_
<div>_x000D_
  <a href="#">Open Menu</a>_x000D_
  <ul class="menu">_x000D_
    <li><a href="#">Item</a></li>_x000D_
    <li><a href="#">Item</a></li>_x000D_
    <li><a href="#">Item</a></li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to add text to a WPF Label in code?

In normal winForms, value of Label object is changed by,

myLabel.Text= "Your desired string";

But in WPF Label control, you have to use .content property of Label control for example,

myLabel.Content= "Your desired string";

How to sort in mongoose?

UPDATE:

Post.find().sort({'updatedAt': -1}).all((posts) => {
  // do something with the array of posts
});

Try:

Post.find().sort([['updatedAt', 'descending']]).all((posts) => {
  // do something with the array of posts
});

JSONException: Value of type java.lang.String cannot be converted to JSONObject

In my case the problem occured from php file. It gave unwanted characters.That is why a json parsing problem occured.

Then I paste my php code in Notepad++ and select Encode in utf-8 without BOM from Encoding tab and running this code-

My problem gone away.

Sass Nesting for :hover does not work

You can easily debug such things when you go through the generated CSS. In this case the pseudo-selector after conversion has to be attached to the class. Which is not the case. Use "&".

http://sass-lang.com/documentation/file.SASS_REFERENCE.html#parent-selector

.class {
    margin:20px;
    &:hover {
        color:yellow;
    }
}

modal View controllers - how to display and dismiss

Radu Simionescu - awesome work! and below Your solution for Swift lovers:

@IBAction func showSecondControlerAndCloseCurrentOne(sender: UIButton) {
    let secondViewController = storyboard?.instantiateViewControllerWithIdentifier("ConrollerStoryboardID") as UIViewControllerClass // change it as You need it
    var presentingVC = self.presentingViewController
    self.dismissViewControllerAnimated(false, completion: { () -> Void   in
        presentingVC!.presentViewController(secondViewController, animated: true, completion: nil)
    })
}

What is the strict aliasing rule?

Note

This is excerpted from my "What is the Strict Aliasing Rule and Why do we care?" write-up.

What is strict aliasing?

In C and C++ aliasing has to do with what expression types we are allowed to access stored values through. In both C and C++ the standard specifies which expression types are allowed to alias which types. The compiler and optimizer are allowed to assume we follow the aliasing rules strictly, hence the term strict aliasing rule. If we attempt to access a value using a type not allowed it is classified as undefined behavior(UB). Once we have undefined behavior all bets are off, the results of our program are no longer reliable.

Unfortunately with strict aliasing violations, we will often obtain the results we expect, leaving the possibility the a future version of a compiler with a new optimization will break code we thought was valid. This is undesirable and it is a worthwhile goal to understand the strict aliasing rules and how to avoid violating them.

To understand more about why we care, we will discuss issues that come up when violating strict aliasing rules, type punning since common techniques used in type punning often violate strict aliasing rules and how to type pun correctly.

Preliminary examples

Let's look at some examples, then we can talk about exactly what the standard(s) say, examine some further examples and then see how to avoid strict aliasing and catch violations we missed. Here is an example that should not be surprising (live example):

int x = 10;
int *ip = &x;

std::cout << *ip << "\n";
*ip = 12;
std::cout << x << "\n";

We have a int* pointing to memory occupied by an int and this is a valid aliasing. The optimizer must assume that assignments through ip could update the value occupied by x.

The next example shows aliasing that leads to undefined behavior (live example):

int foo( float *f, int *i ) { 
    *i = 1;               
    *f = 0.f;            

   return *i;
}

int main() {
    int x = 0;

    std::cout << x << "\n";   // Expect 0
    x = foo(reinterpret_cast<float*>(&x), &x);
    std::cout << x << "\n";   // Expect 0?
}

In the function foo we take an int* and a float*, in this example we call foo and set both parameters to point to the same memory location which in this example contains an int. Note, the reinterpret_cast is telling the compiler to treat the the expression as if it had the type specificed by its template parameter. In this case we are telling it to treat the expression &x as if it had type float*. We may naively expect the result of the second cout to be 0 but with optimization enabled using -O2 both gcc and clang produce the following result:

0
1

Which may not be expected but is perfectly valid since we have invoked undefined behavior. A float can not validly alias an int object. Therefore the optimizer can assume the constant 1 stored when dereferencing i will be the return value since a store through f could not validly affect an int object. Plugging the code in Compiler Explorer shows this is exactly what is happening(live example):

foo(float*, int*): # @foo(float*, int*)
mov dword ptr [rsi], 1  
mov dword ptr [rdi], 0
mov eax, 1                       
ret

The optimizer using Type-Based Alias Analysis (TBAA) assumes 1 will be returned and directly moves the constant value into register eax which carries the return value. TBAA uses the languages rules about what types are allowed to alias to optimize loads and stores. In this case TBAA knows that a float can not alias and int and optimizes away the load of i.

Now, to the Rule-Book

What exactly does the standard say we are allowed and not allowed to do? The standard language is not straightforward, so for each item I will try to provide code examples that demonstrates the meaning.

What does the C11 standard say?

The C11 standard says the following in section 6.5 Expressions paragraph 7:

An object shall have its stored value accessed only by an lvalue expression that has one of the following types:88) — a type compatible with the effective type of the object,

int x = 1;
int *p = &x;   
printf("%d\n", *p); // *p gives us an lvalue expression of type int which is compatible with int

— a qualified version of a type compatible with the effective type of the object,

int x = 1;
const int *p = &x;
printf("%d\n", *p); // *p gives us an lvalue expression of type const int which is compatible with int

— a type that is the signed or unsigned type corresponding to the effective type of the object,

int x = 1;
unsigned int *p = (unsigned int*)&x;
printf("%u\n", *p ); // *p gives us an lvalue expression of type unsigned int which corresponds to 
                     // the effective type of the object

gcc/clang has an extension and also that allows assigning unsigned int* to int* even though they are not compatible types.

— a type that is the signed or unsigned type corresponding to a qualified version of the effective type of the object,

int x = 1;
const unsigned int *p = (const unsigned int*)&x;
printf("%u\n", *p ); // *p gives us an lvalue expression of type const unsigned int which is a unsigned type 
                     // that corresponds with to a qualified verison of the effective type of the object

— an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union), or

struct foo {
  int x;
};

void foobar( struct foo *fp, int *ip );  // struct foo is an aggregate that includes int among its members so it can
                                         // can alias with *ip

foo f;
foobar( &f, &f.x );

— a character type.

int x = 65;
char *p = (char *)&x;
printf("%c\n", *p );  // *p gives us an lvalue expression of type char which is a character type.
                      // The results are not portable due to endianness issues.

What the C++17 Draft Standard say

The C++17 draft standard in section [basic.lval] paragraph 11 says:

If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined:63 (11.1) — the dynamic type of the object,

void *p = malloc( sizeof(int) ); // We have allocated storage but not started the lifetime of an object
int *ip = new (p) int{0};        // Placement new changes the dynamic type of the object to int
std::cout << *ip << "\n";        // *ip gives us a glvalue expression of type int which matches the dynamic type 
                                  // of the allocated object

(11.2) — a cv-qualified version of the dynamic type of the object,

int x = 1;
const int *cip = &x;
std::cout << *cip << "\n";  // *cip gives us a glvalue expression of type const int which is a cv-qualified 
                            // version of the dynamic type of x

(11.3) — a type similar (as defined in 7.5) to the dynamic type of the object,

(11.4) — a type that is the signed or unsigned type corresponding to the dynamic type of the object,

// Both si and ui are signed or unsigned types corresponding to each others dynamic types
// We can see from this godbolt(https://godbolt.org/g/KowGXB) the optimizer assumes aliasing.
signed int foo( signed int &si, unsigned int &ui ) {
  si = 1;
  ui = 2;

  return si;
}

(11.5) — a type that is the signed or unsigned type corresponding to a cv-qualified version of the dynamic type of the object,

signed int foo( const signed int &si1, int &si2); // Hard to show this one assumes aliasing

(11.6) — an aggregate or union type that includes one of the aforementioned types among its elements or nonstatic data members (including, recursively, an element or non-static data member of a subaggregate or contained union),

struct foo {
 int x;
};

// Compiler Explorer example(https://godbolt.org/g/z2wJTC) shows aliasing assumption
int foobar( foo &fp, int &ip ) {
 fp.x = 1;
 ip = 2;

 return fp.x;
}

foo f; 
foobar( f, f.x ); 

(11.7) — a type that is a (possibly cv-qualified) base class type of the dynamic type of the object,

struct foo { int x ; };

struct bar : public foo {};

int foobar( foo &f, bar &b ) {
  f.x = 1;
  b.x = 2;

  return f.x;
}

(11.8) — a char, unsigned char, or std::byte type.

int foo( std::byte &b, uint32_t &ui ) {
  b = static_cast<std::byte>('a');
  ui = 0xFFFFFFFF;                   

  return std::to_integer<int>( b );  // b gives us a glvalue expression of type std::byte which can alias
                                     // an object of type uint32_t
}

Worth noting signed char is not included in the list above, this is a notable difference from C which says a character type.

What is Type Punning

We have gotten to this point and we may be wondering, why would we want to alias for? The answer typically is to type pun, often the methods used violate strict aliasing rules.

Sometimes we want to circumvent the type system and interpret an object as a different type. This is called type punning, to reinterpret a segment of memory as another type. Type punning is useful for tasks that want access to the underlying representation of an object to view, transport or manipulate. Typical areas we find type punning being used are compilers, serialization, networking code, etc…

Traditionally this has been accomplished by taking the address of the object, casting it to a pointer of the type we want to reinterpret it as and then accessing the value, or in other words by aliasing. For example:

int x =  1 ;

// In C
float *fp = (float*)&x ;  // Not a valid aliasing

// In C++
float *fp = reinterpret_cast<float*>(&x) ;  // Not a valid aliasing

printf( "%f\n", *fp ) ;

As we have seen earlier this is not a valid aliasing, so we are invoking undefined behavior. But traditionally compilers did not take advantage of strict aliasing rules and this type of code usually just worked, developers have unfortunately gotten used to doing things this way. A common alternate method for type punning is through unions, which is valid in C but undefined behavior in C++ (see live example):

union u1
{
  int n;
  float f;
} ;

union u1 u;
u.f = 1.0f;

printf( "%d\n”, u.n );  // UB in C++ n is not the active member

This is not valid in C++ and some consider the purpose of unions to be solely for implementing variant types and feel using unions for type punning is an abuse.

How do we Type Pun correctly?

The standard method for type punning in both C and C++ is memcpy. This may seem a little heavy handed but the optimizer should recognize the use of memcpy for type punning and optimize it away and generate a register to register move. For example if we know int64_t is the same size as double:

static_assert( sizeof( double ) == sizeof( int64_t ) );  // C++17 does not require a message

we can use memcpy:

void func1( double d ) {
  std::int64_t n;
  std::memcpy(&n, &d, sizeof d); 
  //...

At a sufficient optimization level any decent modern compiler generates identical code to the previously mentioned reinterpret_cast method or union method for type punning. Examining the generated code we see it uses just register mov (live Compiler Explorer Example).

C++20 and bit_cast

In C++20 we may gain bit_cast (implementation available in link from proposal) which gives a simple and safe way to type-pun as well as being usable in a constexpr context.

The following is an example of how to use bit_cast to type pun a unsigned int to float, (see it live):

std::cout << bit_cast<float>(0x447a0000) << "\n" ; //assuming sizeof(float) == sizeof(unsigned int)

In the case where To and From types don't have the same size, it requires us to use an intermediate struct15. We will use a struct containing a sizeof( unsigned int ) character array (assumes 4 byte unsigned int) to be the From type and unsigned int as the To type.:

struct uint_chars {
 unsigned char arr[sizeof( unsigned int )] = {} ;  // Assume sizeof( unsigned int ) == 4
};

// Assume len is a multiple of 4 
int bar( unsigned char *p, size_t len ) {
 int result = 0;

 for( size_t index = 0; index < len; index += sizeof(unsigned int) ) {
   uint_chars f;
   std::memcpy( f.arr, &p[index], sizeof(unsigned int));
   unsigned int result = bit_cast<unsigned int>(f);

   result += foo( result );
 }

 return result ;
}

It is unfortunate that we need this intermediate type but that is the current constraint of bit_cast.

Catching Strict Aliasing Violations

We don't have a lot of good tools for catching strict aliasing in C++, the tools we have will catch some cases of strict aliasing violations and some cases of misaligned loads and stores.

gcc using the flag -fstrict-aliasing and -Wstrict-aliasing can catch some cases although not without false positives/negatives. For example the following cases will generate a warning in gcc (see it live):

int a = 1;
short j;
float f = 1.f; // Originally not initialized but tis-kernel caught 
               // it was being accessed w/ an indeterminate value below

printf("%i\n", j = *(reinterpret_cast<short*>(&a)));
printf("%i\n", j = *(reinterpret_cast<int*>(&f)));

although it will not catch this additional case (see it live):

int *p;

p=&a;
printf("%i\n", j = *(reinterpret_cast<short*>(p)));

Although clang allows these flags it apparently does not actually implement the warnings.

Another tool we have available to us is ASan which can catch misaligned loads and stores. Although these are not directly strict aliasing violations they are a common result of strict aliasing violations. For example the following cases will generate runtime errors when built with clang using -fsanitize=address

int *x = new int[2];               // 8 bytes: [0,7].
int *u = (int*)((char*)x + 6);     // regardless of alignment of x this will not be an aligned address
*u = 1;                            // Access to range [6-9]
printf( "%d\n", *u );              // Access to range [6-9]

The last tool I will recommend is C++ specific and not strictly a tool but a coding practice, don't allow C-style casts. Both gcc and clang will produce a diagnostic for C-style casts using -Wold-style-cast. This will force any undefined type puns to use reinterpret_cast, in general reinterpret_cast should be a flag for closer code review. It is also easier to search your code base for reinterpret_cast to perform an audit.

For C we have all the tools already covered and we also have tis-interpreter, a static analyzer that exhaustively analyzes a program for a large subset of the C language. Given a C verions of the earlier example where using -fstrict-aliasing misses one case (see it live)

int a = 1;
short j;
float f = 1.0 ;

printf("%i\n", j = *((short*)&a));
printf("%i\n", j = *((int*)&f));

int *p; 

p=&a;
printf("%i\n", j = *((short*)p));

tis-interpeter is able to catch all three, the following example invokes tis-kernal as tis-interpreter (output is edited for brevity):

./bin/tis-kernel -sa example1.c 
...
example1.c:9:[sa] warning: The pointer (short *)(& a) has type short *. It violates strict aliasing
              rules by accessing a cell with effective type int.
...

example1.c:10:[sa] warning: The pointer (int *)(& f) has type int *. It violates strict aliasing rules by
              accessing a cell with effective type float.
              Callstack: main
...

example1.c:15:[sa] warning: The pointer (short *)p has type short *. It violates strict aliasing rules by
              accessing a cell with effective type int.

Finally there is TySan which is currently in development. This sanitizer adds type checking information in a shadow memory segment and checks accesses to see if they violate aliasing rules. The tool potentially should be able to catch all aliasing violations but may have a large run-time overhead.

Does a foreign key automatically create an index?

It depends. On MySQL an index is created if you don't create it on your own:

MySQL requires that foreign key columns be indexed; if you create a table with a foreign key constraint but no index on a given column, an index is created.

Source: https://dev.mysql.com/doc/refman/8.0/en/constraint-foreign-key.html

The same for MySQL 5.6 eh.

Insert at first position of a list in Python

From the documentation:

list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a),x) is equivalent to a.append(x)

http://docs.python.org/2/tutorial/datastructures.html#more-on-lists

Display Back Arrow on Toolbar

You can always add a Relative layout or a Linear Layout in your Toolbar and place a Image view for back icon or close icon anywhere in toolbar as you like

For example I have used Relative layout in my toolbar

 <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar_top"
                android:layout_width="match_parent"
                android:layout_height="35dp"
                android:minHeight="?attr/actionBarSize"
                android:nextFocusDown="@id/netflixVideoGridView"
                app:layout_collapseMode="pin">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">


                    <TextView

                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Myflix"
                        android:textAllCaps="true"
                        android:textSize="19sp"
                        android:textColor="@color/red"
                        android:textStyle="bold" />


                    <ImageView
                        android:id="@+id/closeMyFlix"
                        android:layout_alignParentRight="true"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_vertical"
                        app:srcCompat="@drawable/vector_close" />


                </RelativeLayout>

            </android.support.v7.widget.Toolbar>

And it looks like this:

enter image description here

You can add click listener on that image view from Activity or fragment like this.

  closeMyFlix.setOnClickListener({
            Navigator.instance.showFireTV(  activity!!.supportFragmentManager)
        })

Remove blank lines with grep

Using Perl:

perl -ne 'print if /\S/'

\S means match non-blank characters.

Get a file name from a path

Dont use _splitpath() and _wsplitpath(). They are not safe, and they are obsolete!

Instead, use their safe versions, namely _splitpath_s() and _wsplitpath_s()

No Exception while type casting with a null in java

This is by design. You can cast null to any reference type. Otherwise you wouldn't be able to assign it to reference variables.

How to launch PowerShell (not a script) from the command line

The color and window sizing are defined by the shortcut LNK file. I think I found a way that will do what you need, try this:

explorer.exe "Windows PowerShell.lnk"

The LNK file is in the all user start menu which is located in different places depending whether your on XP or Windows 7. In 7 the LNK file is here:

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Accessories\Windows PowerShell

Changing Background Image with CSS3 Animations

Updated for 2020: Yes, it can be done! Here's how.

Snippet demo:

_x000D_
_x000D_
#mydiv{ animation: changeBg 1s infinite; width:143px; height:100px; }
@keyframes changeBg{
   0%,100%  {background-image: url("https://i.stack.imgur.com/YdrqG.png");}
   25% {background-image: url("https://i.stack.imgur.com/2wKWi.png");}
   50% {background-image: url("https://i.stack.imgur.com/HobHO.png");}
   75% {background-image: url("https://i.stack.imgur.com/3hiHO.png");}
}
_x000D_
<div id='mydiv'></div>
_x000D_
_x000D_
_x000D_


Background image [isn't a property that can be animated][1] - you can't tween the property.

Original Answer: (still a good alternative) Instead, try laying out all the images on top of each other using position:absolute, then animate the opacity of all of them to 0 except the one you want repeatedly.

Symfony - generate url with parameter in controller

If you want absolute urls, you have the third parameter.

$product_url = $this->generateUrl('product_detail', 
    array(
        'slug' => 'slug'
    ),
    UrlGeneratorInterface::ABSOLUTE_URL
);

Remember to include UrlGeneratorInterface.

use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

How do I render a Word document (.doc, .docx) in the browser using JavaScript?

There seem to be some js libraries that can handle .docx (not .doc) to html conversion client-side (in no particular order):

Note: If you are looking for the best way to convert a doc/docx file on the client side, then probably the answer is don't do it. If you really need to do it then do it server-side, i.e. with libreoffice in headless mode, apache-poi (java), pandoc or whatever other library works best for you.

Specifying content of an iframe instead of the src attribute to a page

You can .write() the content into the iframe document. Example:

<iframe id="FileFrame" src="about:blank"></iframe>

<script type="text/javascript">
   var doc = document.getElementById('FileFrame').contentWindow.document;
   doc.open();
   doc.write('<html><head><title></title></head><body>Hello world.</body></html>');
   doc.close();
</script>

How to easily import multiple sql files into a MySQL database?

Just type below command on your command prompt & it will bind all sql file into single sql file,

c:/xampp/mysql/bin/sql/ type *.sql > OneFile.sql;

how do you pass images (bitmaps) between android activities using bundles?

You can pass image in short without using bundle like this This is the code of sender .class file

Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher;
Intent intent = new Intent();
Intent.setClass(<Sender_Activity>.this, <Receiver_Activity.class);
Intent.putExtra("Bitmap", bitmap);
startActivity(intent);

and this is receiver class file code.

Bitmap bitmap = (Bitmap)this.getIntent().getParcelableExtra("Bitmap");
ImageView viewBitmap = (ImageView)findViewById(R.id.bitmapview);
viewBitmap.setImageBitmap(bitmap);

No need to compress. that's it

Insert multiple lines into a file after specified pattern using shell script

Here is a more generic solution based on @rindeal solution which does not work on MacOS/BSD (/r expects a file):

cat << DOC > input.txt
abc
cdef
line
DOC
$ cat << EOF | sed '/^cdef$/ r /dev/stdin' input.txt
line 1
line 2
EOF

# outputs:
abc
cdef
line 1
line 2
line

This can be used to pipe anything into the file at the given position:

$ date | sed '/^cdef$/ r /dev/stdin' input.txt

# outputs
abc
cdef
Tue Mar 17 10:50:15 CET 2020
line

Also, you could add multiple commands which allows deleting the marker line cdef:

$ date | sed '/^cdef$/ {
  r /dev/stdin
  d
}' input.txt

# outputs
abc
Tue Mar 17 10:53:53 CET 2020
line

How to control the line spacing in UILabel

I thought about adding something new to this answer, so I don't feel as bad... Here is a Swift answer:

import Cocoa

let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 40

let attrString = NSMutableAttributedString(string: "Swift Answer")
attrString.addAttribute(.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attrString.length))

var tableViewCell = NSTableCellView()
tableViewCell.textField.attributedStringValue = attrString

"Short answer: you can't. To change the spacing between lines of text, you will have to subclass UILabel and roll your own drawTextInRect, or create multiple labels."

See: Set UILabel line spacing


This is a really old answer, and other have already addded the new and better way to handle this.. Please see the up to date answers provided below.

Java error: Implicit super constructor is undefined for default constructor

You could also get this error when JRE is not set. If so, try adding JRE System Library to your project.

Under Eclipse IDE:

  1. open menu Project --> Properties, or right-click on your project in Package Explorer and choose Properties (Alt+Enter on Windows, Command+I on Mac)
  2. click on Java Build Path then Libraries tab
  3. choose Modulepath or Classpath and press Add Library... button
  4. select JRE System Library then click Next
  5. keep Workspace default JRE selected (you can also take another option) and click Finish
  6. finally press Apply and Close.

Adding POST parameters before submit

To add that using Jquery:

$('#commentForm').submit(function(){ //listen for submit event
    $.each(params, function(i,param){
        $('<input />').attr('type', 'hidden')
            .attr('name', param.name)
            .attr('value', param.value)
            .appendTo('#commentForm');
    });

    return true;
}); 

How can I get the number of days between 2 dates in Oracle 11g?

I figured it out myself. I need

select extract(day from sysdate - to_date('2009-10-01', 'yyyy-mm-dd')) from dual

password-check directive in angularjs

I've used this directive with success before:

 .directive('sameAs', function() {
  return {
    require: 'ngModel',
    link: function(scope, elm, attrs, ctrl) {
      ctrl.$parsers.unshift(function(viewValue) {
        if (viewValue === scope[attrs.sameAs]) {
          ctrl.$setValidity('sameAs', true);
          return viewValue;
        } else {
          ctrl.$setValidity('sameAs', false);
          return undefined;
        }
      });
    }
  };
});

Usage

     <input ... name="password" />
    <input type="password" placeholder="Confirm Password" 
name="password2" ng-model="password2" ng-minlength="9" same-as='password' required>

Excel compare two columns and highlight duplicates

There may be a simpler option, but you can use VLOOKUP to check if a value appears in a list (and VLOOKUP is a powerful formula to get to grips with anyway).

So for A1, you can set a conditional format using the following formula:

=NOT(ISNA(VLOOKUP(A1,$B:$B,1,FALSE)))

Copy and Paste Special > Formats to copy that conditional format to the other cells in column A.

What the above formula is doing:

  • VLOOKUP is looking up the value of Cell A1 (first parameter) against the whole of column B ($B:$B), in the first column (that's the 3rd parameter, redundant here, but typically VLOOKUP looks up a table rather than a column). The last parameter, FALSE, specifies that the match must be exact rather than just the closest match.
  • VLOOKUP will return #ISNA if no match is found, so the NOT(ISNA(...)) returns true for all cells which have a match in column B.

Javascript, Time and Date: Getting the current minute, hour, day, week, month, year of a given millisecond time

The variable names should be descriptive:

var date = new Date;
date.setTime(result_from_Date_getTime);

var seconds = date.getSeconds();
var minutes = date.getMinutes();
var hour = date.getHours();

var year = date.getFullYear();
var month = date.getMonth(); // beware: January = 0; February = 1, etc.
var day = date.getDate();

var dayOfWeek = date.getDay(); // Sunday = 0, Monday = 1, etc.
var milliSeconds = date.getMilliseconds();

The days of a given month do not change. In a leap year, February has 29 days. Inspired by http://www.javascriptkata.com/2007/05/24/how-to-know-if-its-a-leap-year/ (thanks Peter Bailey!)

Continued from the previous code:

var days_in_months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
// for leap years, February has 29 days. Check whether
// February, the 29th exists for the given year
if( (new Date(year, 1, 29)).getDate() == 29 ) days_in_month[1] = 29;

There is no straightforward way to get the week of a year. For the answer on that question, see Is there a way in javascript to create a date object using year & ISO week number?

Has been blocked by CORS policy: Response to preflight request doesn’t pass access control check

This answer explains what's going on behind the scenes, and the basics of how to solve this problem in any language. For reference, see the MDN docs on this topic.

You are making a request for a URL from JavaScript running on one domain (say domain-a.com) to an API running on another domain (domain-b.com). When you do that, the browser has to ask domain-b.com if it's okay to allow requests from domain-a.com. It does that with an HTTP OPTIONS request. Then, in the response, the server on domain-b.com has to give (at least) the following HTTP headers that say "Yeah, that's okay":

HTTP/1.1 204 No Content                            // or 200 OK
Access-Control-Allow-Origin: https://domain-a.com  // or * for allowing anybody
Access-Control-Allow-Methods: POST, GET, OPTIONS   // What kind of methods are allowed
...                                                // other headers

If you're in Chrome, you can see what the response looks like by pressing F12 and going to the "Network" tab to see the response the server on domain-b.com is giving.

So, back to the bare minimum from @threeve's original answer:

header := w.Header()
header.Add("Access-Control-Allow-Origin", "*")

if r.Method == "OPTIONS" {
    w.WriteHeader(http.StatusOK)
    return
}

This will allow anybody from anywhere to access this data. The other headers he's included are necessary for other reasons, but these headers are the bare minimum to get past the CORS (Cross Origin Resource Sharing) requirements.

Calculating the SUM of (Quantity*Price) from 2 different tables

I had the same problem as Marko and come across a solution like this:

/*Create a Table*/
CREATE TABLE tableGrandTotal
(
columnGrandtotal int
)

/*Create a Stored Procedure*/
CREATE PROCEDURE GetGrandTotal
AS

/*Delete the 'tableGrandTotal' table for another usage of the stored procedure*/
DROP TABLE tableGrandTotal

/*Create a new Table which will include just one column*/
CREATE TABLE tableGrandTotal
(
columnGrandtotal int
)

/*Insert the query which returns subtotal for each orderitem row into tableGrandTotal*/
INSERT INTO tableGrandTotal
    SELECT oi.Quantity * p.Price AS columnGrandTotal
        FROM OrderItem oi
        JOIN Product p ON oi.Id = p.Id

/*And return the sum of columnGrandTotal from the newly created table*/    
SELECT SUM(columnGrandTotal) as [Grand Total]
    FROM tableGrandTotal

And just simply use the GetGrandTotal Stored Procedure to retrieve the Grand Total :)

EXEC GetGrandTotal

How to get the current user in ASP.NET MVC

I realize this is really old, but I'm just getting started with ASP.NET MVC, so I thought I'd stick my two cents in:

  • Request.IsAuthenticated tells you if the user is authenticated.
  • Page.User.Identity gives you the identity of the logged-in user.

How to remove old and unused Docker images

There is sparrow plugin docker-remove-dangling-images you can use to clean up stopped containers and unused (dangling) images:

$ sparrow plg run docker-remove-dangling-images

It works both for Linux and Windows OS.

Creating a custom JButton in Java

I'm probably going a million miles in the wrong direct (but i'm only young :P ). but couldn't you add the graphic to a panel and then a mouselistener to the graphic object so that when the user on the graphic your action is preformed.

Execute script after specific delay using JavaScript

why can't you put the code behind a promise? (typed in off the top of my head)

_x000D_
_x000D_
new Promise(function(resolve, reject) {_x000D_
  setTimeout(resolve, 2000);_x000D_
}).then(function() {_x000D_
  console.log('do whatever you wanted to hold off on');_x000D_
});
_x000D_
_x000D_
_x000D_

how to permit an array with strong parameters

It should be like

params.permit(:id => [])

Also since rails version 4+ you can use:

params.permit(id: [])

How can I create a blank/hardcoded column in a sql query?

Thank you, in PostgreSQL this works for boolean

SELECT
hat,
shoe,
boat,
false as placeholder
FROM
objects

Create a custom callback in JavaScript

If you want to execute a function when something is done. One of a good solution is to listen to events. For example, I'll implement a Dispatcher, a DispatcherEvent class with ES6,then:

let Notification = new Dispatcher()
Notification.on('Load data success', loadSuccessCallback)

const loadSuccessCallback = (data) =>{
   ...
}
//trigger a event whenever you got data by
Notification.dispatch('Load data success')

Dispatcher:

class Dispatcher{
  constructor(){
    this.events = {}
  }

  dispatch(eventName, data){
    const event = this.events[eventName]
    if(event){
      event.fire(data)
    }
  }

  //start listen event
  on(eventName, callback){
    let event = this.events[eventName]
    if(!event){
      event = new DispatcherEvent(eventName)
      this.events[eventName] = event
    }
    event.registerCallback(callback)
  }

  //stop listen event
  off(eventName, callback){
    const event = this.events[eventName]
    if(event){
      delete this.events[eventName]
    }
  }
}

DispatcherEvent:

class DispatcherEvent{
  constructor(eventName){
    this.eventName = eventName
    this.callbacks = []
  }

  registerCallback(callback){
    this.callbacks.push(callback)
  }

  fire(data){
    this.callbacks.forEach((callback=>{
      callback(data)
    }))
  }
}

Happy coding!

p/s: My code is missing handle some error exceptions

Failed to load the JNI shared Library (JDK)

I had the same issue after upgrading from Java 6 to Java 7. After I removed Java 6 (64 bit) and reinstalled Java 7 (64 bit), Eclipse worked. :)

How to fix getImageData() error The canvas has been tainted by cross-origin data?

You are "tainting" the canvas by loading from a cross origins domain. Check out this MDN article:

https://developer.mozilla.org/en-US/docs/HTML/CORS_Enabled_Image

Java/ JUnit - AssertTrue vs AssertFalse

The course contains a logical error:

    assertTrue("Book check in failed", ml.checkIn(b1));

    assertFalse("Book was aleready checked in", ml.checkIn(b1));

In the first assert we expect the checkIn to return True (because checkin is succesful). If this would fail we would print a message like "book check in failed. Now in the second assert we expect the checkIn to fail, because the book was checked in already in the first line. So we expect a checkIn to return a False. If for some reason checkin returns a True (which we don't expect) than the message should never be "Book was already checked in", because the checkin was succesful.

How do I put variables inside javascript strings?

Here is a Multi-line String Literal example in Node.js.

> let name = 'Fred'
> tm = `Dear ${name},
... This is to inform you, ${name}, that you are
... IN VIOLATION of Penal Code 64.302-4.
... Surrender yourself IMMEDIATELY!
... THIS MEANS YOU, ${name}!!!
...
... `
'Dear Fred,\nThis is to inform you, Fred, that you are\nIN VIOLATION of Penal Code 64.302-4.\nSurrender yourself IMMEDIATELY!\nTHIS MEANS YOU, Fred!!!\n\n'
console.log(tm)
Dear Fred,
This is to inform you, Fred, that you are
IN VIOLATION of Penal Code 64.302-4.
Surrender yourself IMMEDIATELY!
THIS MEANS YOU, Fred!!!


undefined
>

How to export a MySQL database to JSON?

Another possibility is using the MySQL Workbench.

There is a JSON export option at the object browser context menu and at the result grid menu.

More information on MySQL documentation: Data export and import.