Programs & Examples On #Biometrics

Biometrics is a set of methods related to unique identification of people based on physiological or behavioural traits

PHP: How to remove all non printable characters in a string?

For anyone that is still looking how to do this without removing the non-printable characters, but rather escaping them, I made this to help out. Feel free to improve it! Characters are escaped to \\x[A-F0-9][A-F0-9].

Call like so:

$escaped = EscapeNonASCII($string);

$unescaped = UnescapeNonASCII($string);

<?php 
  function EscapeNonASCII($string) //Convert string to hex, replace non-printable chars with escaped hex
    {
        $hexbytes = strtoupper(bin2hex($string));
        $i = 0;
        while ($i < strlen($hexbytes))
        {
            $hexpair = substr($hexbytes, $i, 2);
            $decimal = hexdec($hexpair);
            if ($decimal < 32 || $decimal > 126)
            {
                $top = substr($hexbytes, 0, $i);
                $escaped = EscapeHex($hexpair);
                $bottom = substr($hexbytes, $i + 2);
                $hexbytes = $top . $escaped . $bottom;
                $i += 8;
            }
            $i += 2;
        }
        $string = hex2bin($hexbytes);
        return $string;
    }
    function EscapeHex($string) //Helper function for EscapeNonASCII()
    {
        $x = "5C5C78"; //\x
        $topnibble = bin2hex($string[0]); //Convert top nibble to hex
        $bottomnibble = bin2hex($string[1]); //Convert bottom nibble to hex
        $escaped = $x . $topnibble . $bottomnibble; //Concatenate escape sequence "\x" with top and bottom nibble
        return $escaped;
    }

    function UnescapeNonASCII($string) //Convert string to hex, replace escaped hex with actual hex.
    {
        $stringtohex = bin2hex($string);
        $stringtohex = preg_replace_callback('/5c5c78([a-fA-F0-9]{4})/', function ($m) { 
            return hex2bin($m[1]);
        }, $stringtohex);
        return hex2bin(strtoupper($stringtohex));
    }
?>

Bootstrap 3: how to make head of dropdown link clickable in navbar

Here this the code which slides down the sub menu on hover, and let you redirect to a page if you click on it.

How: strip out class="dropdown-toggle" data-toggle="dropdown" from a tag, and add css.

Here is the demo at jsfiddle. For demo, please adjust jsfiddle's splitter to see the dropdown due to Bootstrap CSS. jsfiddle won't let you redirect to a new page.

enter image description here

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" type="text/css" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css">
    <script type='text/javascript' src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type='text/javascript' src="http://netdna.bootstrapcdn.com/bootstrap/3.0.2/js/bootstrap.min.js"></script>
    <style type='text/css'>
        ul.nav li.dropdown:hover ul.dropdown-menu {
            display: block;
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-fixed-top admin-menu" role="navigation">
        <div class="navbar-header">...</div>
        <!-- Collect the nav links, forms, and other content for toggling -->
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav navbar-right">
                <li class="dropdown"><a href="http://stackoverflow.com/">Stack Overflow <b class="caret"></b></a>

                    <ul class="dropdown-menu">
                        <li><a href="/page2">Page2</a>
                        </li>
                    </ul>
                </li>
                <li><a href="#">I DO WORK</a>
                </li>
            </ul>
        </div>
        <!-- /.navbar-collapse -->
    </nav>
</body>
</html>

Checkout another branch when there are uncommitted changes on the current branch

The correct answer is

git checkout -m origin/master

It merges changes from the origin master branch with your local even uncommitted changes.

Best Practice: Software Versioning

As Mahesh says: I would use x.y.z kind of versioning

x - major release y - minor release z - build number

you may want to add a datetime, maybe instead of z.

You increment the minor release when you have another release. The major release will probably stay 0 or 1, you change that when you really make major changes (often when your software is at a point where its not backwards compatible with previous releases, or you changed your entire framework)

Detect if Android device has Internet connection

You are right. The code you've provided only checks if there is a network connection. The best way to check if there is an active Internet connection is to try and connect to a known server via http.

public static boolean hasActiveInternetConnection(Context context) {
    if (isNetworkAvailable(context)) {
        try {
            HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
            urlc.setRequestProperty("User-Agent", "Test");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(1500); 
            urlc.connect();
            return (urlc.getResponseCode() == 200);
        } catch (IOException e) {
            Log.e(LOG_TAG, "Error checking internet connection", e);
        }
    } else {
        Log.d(LOG_TAG, "No network available!");
    }
    return false;
}

Of course you can substitute the http://www.google.com URL for any other server you want to connect to, or a server you know has a good uptime.

As Tony Cho also pointed out in this comment below, make sure you don't run this code on the main thread, otherwise you'll get a NetworkOnMainThread exception (in Android 3.0 or later). Use an AsyncTask or Runnable instead.

If you want to use google.com you should look at Jeshurun's modification. In his answer he modified my code and made it a bit more efficient. If you connect to

HttpURLConnection urlc = (HttpURLConnection) 
            (new URL("http://clients3.google.com/generate_204")
            .openConnection());

and then check the responsecode for 204

return (urlc.getResponseCode() == 204 && urlc.getContentLength() == 0);

then you don't have to fetch the entire google home page first.

SQL Insert into table only if record doesn't exist

Although the answer I originally marked as chosen is correct and achieves what I asked there is a better way of doing this (which others acknowledged but didn't go into). A composite unique index should be created on the table consisting of fund_id and date.

ALTER TABLE funds ADD UNIQUE KEY `fund_date` (`fund_id`, `date`);

Then when inserting a record add the condition when a conflict is encountered:

INSERT INTO funds (`fund_id`, `date`, `price`)
    VALUES (23, DATE('2013-02-12'), 22.5)
        ON DUPLICATE KEY UPDATE `price` = `price`; --this keeps the price what it was (no change to the table) or:

INSERT INTO funds (`fund_id`, `date`, `price`)
    VALUES (23, DATE('2013-02-12'), 22.5)
        ON DUPLICATE KEY UPDATE `price` = 22.5; --this updates the price to the new value

This will provide much better performance to a sub-query and the structure of the table is superior. It comes with the caveat that you can't have NULL values in your unique key columns as they are still treated as values by MySQL.

C++ unordered_map using a custom class type as the key

To be able to use std::unordered_map (or one of the other unordered associative containers) with a user-defined key-type, you need to define two things:

  1. A hash function; this must be a class that overrides operator() and calculates the hash value given an object of the key-type. One particularly straight-forward way of doing this is to specialize the std::hash template for your key-type.

  2. A comparison function for equality; this is required because the hash cannot rely on the fact that the hash function will always provide a unique hash value for every distinct key (i.e., it needs to be able to deal with collisions), so it needs a way to compare two given keys for an exact match. You can implement this either as a class that overrides operator(), or as a specialization of std::equal, or – easiest of all – by overloading operator==() for your key type (as you did already).

The difficulty with the hash function is that if your key type consists of several members, you will usually have the hash function calculate hash values for the individual members, and then somehow combine them into one hash value for the entire object. For good performance (i.e., few collisions) you should think carefully about how to combine the individual hash values to ensure you avoid getting the same output for different objects too often.

A fairly good starting point for a hash function is one that uses bit shifting and bitwise XOR to combine the individual hash values. For example, assuming a key-type like this:

struct Key
{
  std::string first;
  std::string second;
  int         third;

  bool operator==(const Key &other) const
  { return (first == other.first
            && second == other.second
            && third == other.third);
  }
};

Here is a simple hash function (adapted from the one used in the cppreference example for user-defined hash functions):

namespace std {

  template <>
  struct hash<Key>
  {
    std::size_t operator()(const Key& k) const
    {
      using std::size_t;
      using std::hash;
      using std::string;

      // Compute individual hash values for first,
      // second and third and combine them using XOR
      // and bit shifting:

      return ((hash<string>()(k.first)
               ^ (hash<string>()(k.second) << 1)) >> 1)
               ^ (hash<int>()(k.third) << 1);
    }
  };

}

With this in place, you can instantiate a std::unordered_map for the key-type:

int main()
{
  std::unordered_map<Key,std::string> m6 = {
    { {"John", "Doe", 12}, "example"},
    { {"Mary", "Sue", 21}, "another"}
  };
}

It will automatically use std::hash<Key> as defined above for the hash value calculations, and the operator== defined as member function of Key for equality checks.

If you don't want to specialize template inside the std namespace (although it's perfectly legal in this case), you can define the hash function as a separate class and add it to the template argument list for the map:

struct KeyHasher
{
  std::size_t operator()(const Key& k) const
  {
    using std::size_t;
    using std::hash;
    using std::string;

    return ((hash<string>()(k.first)
             ^ (hash<string>()(k.second) << 1)) >> 1)
             ^ (hash<int>()(k.third) << 1);
  }
};

int main()
{
  std::unordered_map<Key,std::string,KeyHasher> m6 = {
    { {"John", "Doe", 12}, "example"},
    { {"Mary", "Sue", 21}, "another"}
  };
}

How to define a better hash function? As said above, defining a good hash function is important to avoid collisions and get good performance. For a real good one you need to take into account the distribution of possible values of all fields and define a hash function that projects that distribution to a space of possible results as wide and evenly distributed as possible.

This can be difficult; the XOR/bit-shifting method above is probably not a bad start. For a slightly better start, you may use the hash_value and hash_combine function template from the Boost library. The former acts in a similar way as std::hash for standard types (recently also including tuples and other useful standard types); the latter helps you combine individual hash values into one. Here is a rewrite of the hash function that uses the Boost helper functions:

#include <boost/functional/hash.hpp>

struct KeyHasher
{
  std::size_t operator()(const Key& k) const
  {
      using boost::hash_value;
      using boost::hash_combine;

      // Start with a hash value of 0    .
      std::size_t seed = 0;

      // Modify 'seed' by XORing and bit-shifting in
      // one member of 'Key' after the other:
      hash_combine(seed,hash_value(k.first));
      hash_combine(seed,hash_value(k.second));
      hash_combine(seed,hash_value(k.third));

      // Return the result.
      return seed;
  }
};

And here’s a rewrite that doesn’t use boost, yet uses good method of combining the hashes:

namespace std
{
    template <>
    struct hash<Key>
    {
        size_t operator()( const Key& k ) const
        {
            // Compute individual hash values for first, second and third
            // http://stackoverflow.com/a/1646913/126995
            size_t res = 17;
            res = res * 31 + hash<string>()( k.first );
            res = res * 31 + hash<string>()( k.second );
            res = res * 31 + hash<int>()( k.third );
            return res;
        }
    };
}

How to overcome "'aclocal-1.15' is missing on your system" warning?

The problem is not automake package, is the repository

sudo apt-get install automake

Installs version aclocal-1.4, that's why you can't find 1.5 (In Ubuntu 14,15)

Use this script to install latest https://github.com/gp187/nginx-builder/blob/master/fix/aclocal.sh

How to convert an IPv4 address into a integer in C#?

I have encountered some problems with the described solutions, when facing IP Adresses with a very large value. The result would be, that the byte[0] * 16777216 thingy would overflow and become a negative int value. what fixed it for me, is the a simple type casting operation.

public static long ConvertIPToLong(string ipAddress)
{
    System.Net.IPAddress ip;

    if (System.Net.IPAddress.TryParse(ipAddress, out ip))
    {
        byte[] bytes = ip.GetAddressBytes();

        return
            16777216L * bytes[0] +
            65536 * bytes[1] +
            256 * bytes[2] +
            bytes[3]
            ;
    }
    else
        return 0;
}

How to Exit a Method without Exiting the Program?

The basic problem here is that you are mistaking System.Environment.Exit for return.

How do I extract part of a string in t-sql

declare @data as varchar(50)
set @data='ciao335'


--get text
Select Left(@Data, PatIndex('%[0-9]%', @Data + '1') - 1)    ---->>ciao

--get numeric
Select right(@Data, len(@data) - (PatIndex('%[0-9]%', @Data )-1) )   ---->>335

Unable to ping vmware guest from another vmware guest

I have been able to ping from VMs and the host by setting the VM's network settings to "Bridged" mode. This, in short, places them all on the same physical network. This coupled with your static IP addresses should do the trick.

Calculating Time Difference

The datetime module will do all the work for you:

>>> import datetime
>>> a = datetime.datetime.now()
>>> # ...wait a while...
>>> b = datetime.datetime.now()
>>> print(b-a)
0:03:43.984000

If you don't want to display the microseconds, just use (as gnibbler suggested):

>>> a = datetime.datetime.now().replace(microsecond=0)
>>> b = datetime.datetime.now().replace(microsecond=0)
>>> print(b-a)
0:03:43

Sort tuples based on second parameter

    def findMaxSales(listoftuples):
        newlist = []
        tuple = ()
        for item in listoftuples:
             movie = item[0]
             value = (item[1])
             tuple = value, movie

             newlist += [tuple]
             newlist.sort()
             highest = newlist[-1]
             result = highest[1]
       return result

             movieList = [("Finding Dory", 486), ("Captain America: Civil                      

             War", 408), ("Deadpool", 363), ("Zootopia", 341), ("Rogue One", 529), ("The  Secret Life of Pets", 368), ("Batman v Superman", 330), ("Sing", 268), ("Suicide Squad", 325), ("The Jungle Book", 364)]
             print(findMaxSales(movieList))

output --> Rogue One

PHP - how to create a newline character?

Actually \r\n is for the html side of the output. With those chars you can just create a newline in the html code to make it more readable:

echo "<html>First line \r\n Second line</html>";

will output:

<html>First line
Second line</html>

that viewing the page will be:

First line Second line

If you really meant this you have just to fix the single quote with the "" quote:

echo "\r\n";

Otherwise if you mean to split the text, in our sample 'First line' and 'Second line' you have to use the html code: <br />:

First line<br />Second line

that will output:

First line
Second line

Also it would be more readable if you replace the entire script with:

echo "$clientid $lastname \r\n";

JavaScript - onClick to get the ID of the clicked button

Sorry its a late answer but its really quick if you do this :-

$(document).ready(function() {
  $('button').on('click', function() {
     alert (this.id);
  });
});

This gets the ID of any button clicked.

If you want to just get value of button clicked in a certain place, just put them in container like

<div id = "myButtons"> buttons here </div>

and change the code to :-

 $(document).ready(function() {
      $('.myButtons button').on('click', function() {
         alert (this.id);
      });
    });

I hope this helps

Where is the Microsoft.IdentityModel dll

I had this problem, but fixed it by referencing the DLL from "C:\Program Files\Reference Assemblies\Microsoft\Windows Identity Foundation\v3.5\Microsoft.IdentityModel.dll"

Go to reference properties and set Copy Local to True for the DLL. The DLL will now be included in the azure package.

OpenCV - Apply mask to a color image

Answer given by Abid Rahman K is not completely correct. I also tried it and found very helpful but got stuck.

This is how I copy image with a given mask.

x, y = np.where(mask!=0)
pts = zip(x, y)
# Assuming dst and src are of same sizes
for pt in pts:
   dst[pt] = src[pt]

This is a bit slow but gives correct results.

EDIT:

Pythonic way.

idx = (mask!=0)
dst[idx] = src[idx]

How do I validate a date in this format (yyyy-mm-dd) using jquery?

I expanded just slightly on the isValidDate function Thorbin posted above (using a regex). We use a regex to check the format (to prevent us from getting another format which would be valid for Date). After this loose check we then actually run it through the Date constructor and return true or false if it is valid within this format. If it is not a valid date we will get false from this function.

_x000D_
_x000D_
function isValidDate(dateString) {_x000D_
  var regEx = /^\d{4}-\d{2}-\d{2}$/;_x000D_
  if(!dateString.match(regEx)) return false;  // Invalid format_x000D_
  var d = new Date(dateString);_x000D_
  var dNum = d.getTime();_x000D_
  if(!dNum && dNum !== 0) return false; // NaN value, Invalid date_x000D_
  return d.toISOString().slice(0,10) === dateString;_x000D_
}_x000D_
_x000D_
_x000D_
/* Example Uses */_x000D_
console.log(isValidDate("0000-00-00"));  // false_x000D_
console.log(isValidDate("2015-01-40"));  // false_x000D_
console.log(isValidDate("2016-11-25"));  // true_x000D_
console.log(isValidDate("1970-01-01"));  // true = epoch_x000D_
console.log(isValidDate("2016-02-29"));  // true = leap day_x000D_
console.log(isValidDate("2013-02-29"));  // false = not leap day
_x000D_
_x000D_
_x000D_

Can I change the Android startActivity() transition animation?

 // CREATE anim 

 // CREATE animation,animation2  xml // animation like fade out 

  Intent myIntent1 = new Intent(getApplicationContext(), Attend.class);
  Bundle bndlanimation1 =  ActivityOptions.makeCustomAnimation(getApplicationContext(), 
  R.anim.animation, R.anim.animation2).toBundle();
  tartActivity(myIntent1, bndlanimation1);

Html.RenderPartial() syntax with Razor

  • RenderPartial() is a void method that writes to the response stream. A void method, in C#, needs a ; and hence must be enclosed by { }.

  • Partial() is a method that returns an MvcHtmlString. In Razor, You can call a property or a method that returns such a string with just a @ prefix to distinguish it from plain HTML you have on the page.

Find files in a folder using Java

  • Matcher.find and Files.walk methods could be an option to search files in more flexible way
  • String.format combines regular expressions to create search restrictions
  • Files.isRegularFile checks if a path is't directory, symbolic link, etc.

Usage:

//Searches file names (start with "temp" and extension ".txt")
//in the current directory and subdirectories recursively
Path initialPath = Paths.get(".");
PathUtils.searchRegularFilesStartsWith(initialPath, "temp", ".txt").
                                       stream().forEach(System.out::println);

Source:

public final class PathUtils {

    private static final String startsWithRegex = "(?<![_ \\-\\p{L}\\d\\[\\]\\(\\) ])";
    private static final String endsWithRegex = "(?=[\\.\\n])";
    private static final String containsRegex = "%s(?:[^\\/\\\\]*(?=((?i)%s(?!.))))";

    public static List<Path> searchRegularFilesStartsWith(final Path initialPath, 
                             final String fileName, final String fileExt) throws IOException {
        return searchRegularFiles(initialPath, startsWithRegex + fileName, fileExt);
    }

    public static List<Path> searchRegularFilesEndsWith(final Path initialPath, 
                             final String fileName, final String fileExt) throws IOException {
        return searchRegularFiles(initialPath, fileName + endsWithRegex, fileExt);
    }

    public static List<Path> searchRegularFilesAll(final Path initialPath) throws IOException {
        return searchRegularFiles(initialPath, "", "");
    }

    public static List<Path> searchRegularFiles(final Path initialPath,
                             final String fileName, final String fileExt)
            throws IOException {
        final String regex = String.format(containsRegex, fileName, fileExt);
        final Pattern pattern = Pattern.compile(regex);
        try (Stream<Path> walk = Files.walk(initialPath.toRealPath())) {
            return walk.filter(path -> Files.isRegularFile(path) &&
                                       pattern.matcher(path.toString()).find())
                    .collect(Collectors.toList());
        }
    }

    private PathUtils() {
    }
}

Try startsWith regex for \txt\temp\tempZERO0.txt:

(?<![_ \-\p{L}\d\[\]\(\) ])temp(?:[^\/\\]*(?=((?i)\.txt(?!.))))

Try endsWith regex for \txt\temp\ZERO0temp.txt:

temp(?=[\\.\\n])(?:[^\/\\]*(?=((?i)\.txt(?!.))))

Try contains regex for \txt\temp\tempZERO0tempZERO0temp.txt:

temp(?:[^\/\\]*(?=((?i)\.txt(?!.))))

Using Google Text-To-Speech in Javascript

I don't know of Google voice, but using the javaScript speech SpeechSynthesisUtterance, you can add a click event to the element you are reference to. eg:

_x000D_
_x000D_
const listenBtn = document.getElementById('myvoice');

listenBtn.addEventListener('click', (e) => {
  e.preventDefault();

  const msg = new SpeechSynthesisUtterance(
    "Hello, hope my code is helpful"
  );
  window.speechSynthesis.speak(msg);

});
_x000D_
<button type="button" id='myvoice'>Listen to me</button>
_x000D_
_x000D_
_x000D_

Convert any object to a byte[]

Alternative way to convert object to byte array:

TypeConverter objConverter = TypeDescriptor.GetConverter(objMsg.GetType());
byte[] data = (byte[])objConverter.ConvertTo(objMsg, typeof(byte[]));

Unable to import a module that is definitely installed

This Works!!!

This often happens when module is installed to an older version of python or another directory, no worries as solution is simple. - import module from directory in which module is installed. You can do this by first importing the python sys module then importing from the path in which the module is installed

import sys
sys.path.append("directory in which module is installed")

import <module_name>

How do you UrlEncode without using System.Web?

Here's an example of sending a POST request that properly encodes parameters using application/x-www-form-urlencoded content type:

using (var client = new WebClient())
{
    var values = new NameValueCollection
    {
        { "param1", "value1" },
        { "param2", "value2" },
    };
    var result = client.UploadValues("http://foo.com", values);
}

Could not locate Gemfile

You do not have Gemfile in a directory where you run that command. Gemfile is a file containing your gem settings for a current program.

How to convert an Object {} to an Array [] of key-value pairs in JavaScript

You can use Object.keys() and map() to do this

_x000D_
_x000D_
var obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0}
var result = Object.keys(obj).map((key) => [Number(key), obj[key]]);

console.log(result);
_x000D_
_x000D_
_x000D_

How to get Tensorflow tensor dimensions (shape) as int values?

2.0 Compatible Answer: In Tensorflow 2.x (2.1), you can get the dimensions (shape) of the tensor as integer values, as shown in the Code below:

Method 1 (using tf.shape):

import tensorflow as tf
c = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
Shape = c.shape.as_list()
print(Shape)   # [2,3]

Method 2 (using tf.get_shape()):

import tensorflow as tf
c = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
Shape = c.get_shape().as_list()
print(Shape)   # [2,3]

Column standard deviation R

If you want to use it with groups, you can use:

library(plyr)
mydata<-mtcars
ddply(mydata,.(carb),colwise(sd))



  carb      mpg       cyl      disp       hp      drat        wt     qsec        vs        am      gear
1    1 6.001349 0.9759001  75.90037 19.78215 0.5548702 0.6214499 0.590867 0.0000000 0.5345225 0.5345225
2    2 5.472152 2.0655911 122.50499 43.96413 0.6782568 0.8269761 1.967069 0.5270463 0.5163978 0.7888106
3    3 1.053565 0.0000000   0.00000  0.00000 0.0000000 0.1835756 0.305505 0.0000000 0.0000000 0.0000000
4    4 3.911081 1.0327956 132.06337 62.94972 0.4575102 1.0536001 1.394937 0.4216370 0.4830459 0.6992059
5    6       NA        NA        NA       NA        NA        NA       NA        NA        NA        NA
6    8       NA        NA        NA       NA        NA        NA       NA        NA        NA        NA

What does the regex \S mean in JavaScript?

\S matches anything but a whitespace, according to this reference.

Find a value anywhere in a database

Based on bnkdev's answer I modified Narayana's Code to search all columns even numeric ones.

It'll run slower, but this version actually finds all matches not just those found in text columns.

I can't thank this guy enough. Saved me days of searching by hand!

CREATE PROC SearchAllTables 
(
@SearchStr nvarchar(100)
)
AS
BEGIN

-- Copyright © 2002 Narayana Vyas Kondreddi. All rights reserved.
-- Purpose: To search all columns of all tables for a given search string
-- Written by: Narayana Vyas Kondreddi
-- Site: http://vyaskn.tripod.com
-- Tested on: SQL Server 7.0 and SQL Server 2000
-- Date modified: 28th July 2002 22:50 GMT


CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))

SET NOCOUNT ON

DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET  @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')

WHILE @TableName IS NOT NULL
BEGIN
    SET @ColumnName = ''
    SET @TableName = 
    (
        SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
        FROM    INFORMATION_SCHEMA.TABLES
        WHERE       TABLE_TYPE = 'BASE TABLE'
            AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
            AND OBJECTPROPERTY(
                    OBJECT_ID(
                        QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                         ), 'IsMSShipped'
                           ) = 0
    )

    WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
    BEGIN
        SET @ColumnName =
        (
            SELECT MIN(QUOTENAME(COLUMN_NAME))
            FROM    INFORMATION_SCHEMA.COLUMNS
            WHERE       TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                AND TABLE_NAME  = PARSENAME(@TableName, 1)                  
                AND QUOTENAME(COLUMN_NAME) > @ColumnName
        )

        IF @ColumnName IS NOT NULL
        BEGIN
            INSERT INTO #Results
            EXEC
            (
                'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(CONVERT(varchar(max), ' + @ColumnName + '), 3630) 
                FROM ' + @TableName + ' (NOLOCK) ' +
                ' WHERE CONVERT(varchar(max), ' + @ColumnName + ') LIKE ' + @SearchStr2
            )
        END
    END 
END

SELECT ColumnName, ColumnValue FROM #Results
END

No grammar constraints (DTD or XML schema) detected for the document

This worked for me in Eclipse 3.7.1: Go to the Preferences window, then XML -> XML Files -> Validation. Then in the Validating files section of the preferences panel on the right, choose Ignore in the drop down box for the "No grammar specified" preference. You may need to close the file and then reopen it to make the warning go away.

(I know this question is old but it was the first one I found when searching on the warning, so I'm posting the answer here for other searchers.)

Google Maps Android API v2 Authorization failure

  • Make sure Maps SDK for Android is enabled in API console.
  • Also you might need to add your package name and SHA-1 signing-certificate fingerprint to restrict usage for your key to be fully enabled.

enter image description here

HTML.ActionLink vs Url.Action in ASP.NET Razor

Html.ActionLink generates an <a href=".."></a> tag automatically.

Url.Action generates only an url.

For example:

@Html.ActionLink("link text", "actionName", "controllerName", new { id = "<id>" }, null)

generates:

<a href="/controllerName/actionName/<id>">link text</a>

and

@Url.Action("actionName", "controllerName", new { id = "<id>" }) 

generates:

/controllerName/actionName/<id>

Best plus point which I like is using Url.Action(...)

You are creating anchor tag by your own where you can set your own linked text easily even with some other html tag.

<a href="@Url.Action("actionName", "controllerName", new { id = "<id>" })">

   <img src="<ImageUrl>" style"width:<somewidth>;height:<someheight> />

   @Html.DisplayFor(model => model.<SomeModelField>)
</a>

"INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"

Something important to add: When using INSERT IGNORE and you do have key violations, MySQL does NOT raise a warning!

If you try for instance to insert 100 records at a time, with one faulty one, you would get in interactive mode:

Query OK, 99 rows affected (0.04 sec)

Records: 100 Duplicates: 1 Warnings: 0

As you see: No Warnings! This behavior is even wrongly described in the official Mysql Documentation.

If your script needs to be informed, if some records have not been added (due to key violations) you have to call mysql_info() and parse it for the "Duplicates" value.

PHP read and write JSON from file

You need to make the decode function return an array by passing in the true parameter.

json_decode(file_get_contents($file),true);

Why use #ifndef CLASS_H and #define CLASS_H in .h file but not in .cpp?

The CLASS_H is an include guard; it's used to avoid the same header file being included multiple times (via different routes) within the same CPP file (or, more accurately, the same translation unit), which would lead to multiple-definition errors.

Include guards aren't needed on CPP files because, by definition, the contents of the CPP file are only read once.

You seem to have interpreted the include guards as having the same function as import statements in other languages (such as Java); that's not the case, however. The #include itself is roughly equivalent to the import in other languages.

How to change file encoding in NetBeans?

On project explorer, right click on the project, Properties -> General -> Encoding. This will allow you to choose the encoding per project.

HTTP headers in Websockets client API

My case:

  • I want to connect to a production WS server a www.mycompany.com/api/ws...
  • using real credentials (a session cookie)...
  • from a local page (localhost:8000).

Setting document.cookie = "sessionid=foobar;path=/" won't help as domains don't match.

The solution:

Add 127.0.0.1 wsdev.company.com to /etc/hosts.

This way your browser will use cookies from mycompany.com when connecting to www.mycompany.com/api/ws as you are connecting from a valid subdomain wsdev.company.com.

How do you parse and process HTML/XML in PHP?

Advanced Html Dom is a simple HTML DOM replacement that offers the same interface, but it's DOM-based which means none of the associated memory issues occur.

It also has full CSS support, including jQuery extensions.

PHP DateTime __construct() Failed to parse time string (xxxxxxxx) at position x

$start_date = new DateTime();
$start_date->setTimestamp($dbResult->db_timestamp);

changing kafka retention period during runtime

I tested and used this command in kafka confluent V4.0.0 and apache kafka V 1.0.0 and 1.0.1

/opt/kafka/confluent-4.0.0/bin/kafka-configs --zookeeper XX.XX.XX.XX:2181 --entity-type topics --entity-name test --alter --add-config  retention.ms=55000

test is the topic name.

I think it works well in other versions too

Oracle TNS names not showing when adding new connection to SQL Developer

In SQLDeveloper browse Tools --> Preferences, as shown in below image.

enter image description here

In the Preferences options expand Database --> select Advanced --> under "Tnsnames Directory" --> Browse the directory where tnsnames.ora present.
Then click on Ok.
as shown in below diagram.

enter image description here

You have Done!

Now you can connect via the TNSnames options.

How do I get the project basepath in CodeIgniter

Obviously you mean the baseurl. If so:

base url: URL to your CodeIgniter root. Typically this will be your base URL, | WITH a trailing slash.

Root in codeigniter specifically means that the position where you can append your controller to your url.

For example, if the root is localhost/ci_installation/index.php/, then to access the mycont controller you should go to localhost/ci_installation/index.php/mycont.

So, instead of writing such a long link you can (after loading "url" helper) , replace the term localhost/ci_installation/index.php/ by base_url() and this function will return the same string url.

NOTE: if you hadn't appended index.php/ to your base_url in your config.php, then if you use base_url(), it will return something like that localhost/ci_installation/mycont. And that will not work, because you have to access your controllers from index.php, instead of that you can place a .htaccess file to your codeigniter installation position. Cope that the below code to it:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /imguplod/index.php/$1 [L]

And it should work :)

onKeyPress Vs. onKeyUp and onKeyDown

Just wanted to share a curiosity:

when using the onkeydown event to activate a JS method, the charcode for that event is NOT the same as the one you get with onkeypress!

For instance the numpad keys will return the same charcodes as the number keys above the letter keys when using onkeypress, but NOT when using onkeydown !

Took me quite a few seconds to figure out why my script which checked for certain charcodes failed when using onkeydown!

Demo: https://www.w3schools.com/code/tryit.asp?filename=FMMBXKZLP1MK

and yes. I do know the definition of the methods are different.. but the thing that is very confusing is that in both methods the result of the event is retrieved using event.keyCode.. but they do not return the same value.. not a very declarative implementation.

Failed to connect to mailserver at "localhost" port 25

PHP mail function can send email in 2 scenarios:

a. Try to send email via unix sendmail program At linux it will exec program "sendmail", put all params to sendmail and that all.

OR

b. Connect to mail server (using smtp protocol and host/port/username/pass from php.ini) and try to send email.

If php unable to connect to email server it will give warning (and you see such workning in your logs) To solve it, install smtp server on your local machine or use any available server. How to setup / configure smtp you can find on php.net

Is it possible in Java to access private fields via reflection

Yes it is possible.

You need to use the getDeclaredField method (instead of the getField method), with the name of your private field:

Field privateField = Test.class.getDeclaredField("str");

Additionally, you need to set this Field to be accessible, if you want to access a private field:

privateField.setAccessible(true);

Once that's done, you can use the get method on the Field instance, to access the value of the str field.

Codeigniter LIKE with wildcard(%)

If you do not want to use the wildcard (%) you can pass to the optional third argument the option 'none'.

$this->db->like('title', 'match', 'none'); 
// Produces: WHERE title LIKE 'match'

How to call a RESTful web service from Android?

Perhaps am late or maybe you've already used it before but there is another one called ksoap and its pretty amazing.. It also includes timeouts and can parse any SOAP based webservice efficiently. I also made a few changes to suit my parsing.. Look it up

Using Java to find substring of a bigger string using Regular Expression

String input = "FOO[BAR]";
String result = input.substring(input.indexOf("[")+1,input.lastIndexOf("]"));

This will return the value between first '[' and last ']'

Foo[Bar] => Bar

Foo[Bar[test]] => Bar[test]

Note: You should add error checking if the input string is not well formed.

HTML 5 Favicon - Support?

No, not all browsers support the sizes attribute:

Note that some platforms define specific sizes:

In Angular, how to pass JSON object/array into directive?

What you need is properly a service:

.factory('DataLayer', ['$http',

    function($http) {

        var factory = {};
        var locations;

        factory.getLocations = function(success) {
            if(locations){
                success(locations);
                return;
            }
            $http.get('locations/locations.json').success(function(data) {
                locations = data;
                success(locations);
            });
        };

        return factory;
    }
]);

The locations would be cached in the service which worked as singleton model. This is the right way to fetch data.

Use this service DataLayer in your controller and directive is ok as following:

appControllers.controller('dummyCtrl', function ($scope, DataLayer) {
    DataLayer.getLocations(function(data){
        $scope.locations = data;
    });
});

.directive('map', function(DataLayer) {
    return {
        restrict: 'E',
        replace: true,
        template: '<div></div>',
        link: function(scope, element, attrs) {

            DataLayer.getLocations(function(data) {
                angular.forEach(data, function(location, key){
                    //do something
                });
            });
        }
    };
});

C# difference between == and Equals()

There is another dimension to an earlier answer by @BlueMonkMN. The additional dimension is that the answer to the @Drahcir's title question as it is stated also depends on how we arrived at the string value. To illustrate:

string s1 = "test";
string s2 = "test";
string s3 = "test1".Substring(0, 4);
object s4 = s3;
string s5 = "te" + "st";
object s6 = s5;
Console.WriteLine("{0} {1} {2}", object.ReferenceEquals(s1, s2), s1 == s2, s1.Equals(s2));

Console.WriteLine("\n  Case1 - A method changes the value:");
Console.WriteLine("{0} {1} {2}", object.ReferenceEquals(s1, s3), s1 == s3, s1.Equals(s3));
Console.WriteLine("{0} {1} {2}", object.ReferenceEquals(s1, s4), s1 == s4, s1.Equals(s4));

Console.WriteLine("\n  Case2 - Having only literals allows to arrive at a literal:");
Console.WriteLine("{0} {1} {2}", object.ReferenceEquals(s1, s5), s1 == s5, s1.Equals(s5));
Console.WriteLine("{0} {1} {2}", object.ReferenceEquals(s1, s6), s1 == s6, s1.Equals(s6));

The output is:

True True True

  Case1 - A method changes the value:
False True True
False False True

  Case2 - Having only literals allows to arrive at a literal:
True True True
True True True

How do I bind Twitter Bootstrap tooltips to dynamically created elements?

I found a combination of these answers gave me the best outcome - allowing me to still position the tooltip and attach it to the relevant container:

$('body').on('mouseenter', '[rel=tooltip]', function(){
  var el = $(this);
  if (el.data('tooltip') === undefined) {
    el.tooltip({
      placement: el.data("placement") || "top",
      container: el.data("container") || false
    });
  }
  el.tooltip('show');
});

$('body').on('mouseleave', '[rel=tooltip]', function(){
  $(this).tooltip('hide');
});

Relevant HTML:

<button rel="tooltip" class="btn" data-placement="bottom" data-container=".some-parent" title="Show Tooltip">
    <i class="icon-some-icon"></i>
</button>

SQL "select where not in subquery" returns no results

select *,
(select COUNT(ID)  from ProductMaster where ProductMaster.CatID = CategoryMaster.ID) as coun 
from CategoryMaster

How to insert an object in an ArrayList at a specific position

Actually the way to do it on your specific question is arrayList.add(1,"INSERTED ELEMENT"); where 1 is the position

Increase days to php current Date()

You can also use Object Oriented Programming (OOP) instead of procedural programming:

$fiveDays = new DateInterval('P5D');
$today = new DateTime();
$fiveDaysAgo = $today->sub(fiveDays); // or ->add(fiveDays); to add 5 days

Or with just one line of code:

$fiveDaysAgo = (new DateTime())->sub(new DateInterval('P5D'));

What column type/length should I use for storing a Bcrypt hashed password in a Database?

If you are using PHP's password_hash() with the PASSWORD_DEFAULT algorithm to generate the bcrypt hash (which I would assume is a large percentage of people reading this question) be sure to keep in mind that in the future password_hash() might use a different algorithm as the default and this could therefore affect the length of the hash (but it may not necessarily be longer).

From the manual page:

Note that this constant is designed to change over time as new and stronger algorithms are added to PHP. For that reason, the length of the result from using this identifier can change over time. Therefore, it is recommended to store the result in a database column that can expand beyond 60 characters (255 characters would be a good choice).

Using bcrypt, even if you have 1 billion users (i.e. you're currently competing with facebook) to store 255 byte password hashes it would only ~255 GB of data - about the size of a smallish SSD hard drive. It is extremely unlikely that storing the password hash is going to be the bottleneck in your application. However in the off chance that storage space really is an issue for some reason, you can use PASSWORD_BCRYPT to force password_hash() to use bcrypt, even if that's not the default. Just be sure to stay informed about any vulnerabilities found in bcrypt and review the release notes every time a new PHP version is released. If the default algorithm is ever changed it would be good to review why and make an informed decision whether to use the new algorithm or not.

Restore a deleted file in the Visual Studio Code Recycle Bin

It uses the normal trash bin of your system. So you can grab it our of there.

In Windows you find it in the explorer, in Linux it is as well in Konquerer / Nemo / ...

How do I use Spring Boot to serve static content located in Dropbox folder?

Note that WebMvcConfigurerAdapter is deprecated now (see WebMvcConfigurerAdapter). Due to Java 8 default methods, you only have to implement WebMvcConfigurer.

Jquery Ajax, return success/error from mvc.net controller

Use Json class instead of Content as shown following:

    //  When I want to return an error:
    if (!isFileSupported)
    {
        Response.StatusCode = (int) HttpStatusCode.BadRequest;
        return Json("The attached file is not supported", MediaTypeNames.Text.Plain);
    }
    else
    {
        //  When I want to return sucess:
        Response.StatusCode = (int)HttpStatusCode.OK; 
        return Json("Message sent!", MediaTypeNames.Text.Plain);
    }

Also set contentType:

contentType: 'application/json; charset=utf-8',

How to copy and paste worksheets between Excel workbooks?

I'm using this code, hope this helps!

Application.ScreenUpdating = False
Application.EnableEvents = False

Dim destination_wb As Workbook
Set destination_wb = Workbooks.Open(DESTINATION_WORKBOOK_NAME)

worksheet_to_copy.Copy Before:=destination_wb.Worksheets(1)
destination_wb.Worksheets(1).Name = worksheet_to_copy.Name
'Add the sheets count to the name to avoid repeated worksheet names error
'& destination_wb.Worksheets.Count


'optional
destination_wb.Worksheets(1).UsedRange.Columns.AutoFit

'I use this to avoid macro errors in destination_wb
Call DeleteAllVBACode(destination_wb)

'Delete source worksheet
Application.DisplayAlerts = False
worksheet_to_copy.Delete
Application.DisplayAlerts = True

destination_wb.Save
destination_wb.Close

Application.EnableEvents = True
Application.ScreenUpdating = True

' From http://www.cpearson.com/Excel/vbe.aspx           

Public Sub DeleteAllVBACode(libro As Workbook)
    Dim VBProj As VBProject
    Dim VBComp As VBComponent
    Dim CodeMod As CodeModule

    Set VBProj = libro.VBProject

    For Each VBComp In VBProj.VBComponents
        If VBComp.Type = vbext_ct_Document Then
            Set CodeMod = VBComp.CodeModule
            With CodeMod
                .DeleteLines 1, .CountOfLines
            End With
        Else
            VBProj.VBComponents.Remove VBComp
        End If
    Next VBComp
End Sub

Align items in a stack panel?

Yo can set FlowDirection of Stack panel to RightToLeft, and then all items will be aligned to the right side.

Is there a way to include commas in CSV columns without breaking the formatting?

The problem with the CSV format, is there's not one spec, there are several accepted methods, with no way of distinguishing which should be used (for generate/interpret). I discussed all the methods to escape characters (newlines in that case, but same basic premise) in another post. Basically it comes down to using a CSV generation/escaping process for the intended users, and hoping the rest don't mind.

Reference spec document.

select2 changing items dynamically

I've made an example for you showing how this could be done.

Notice the js but also that I changed #value into an input element

<input id="value" type="hidden" style="width:300px"/>

and that I am triggering the change event for getting the initial values

$('#attribute').select2().on('change', function() {
    $('#value').select2({data:data[$(this).val()]});
}).trigger('change');

Code Example

Edit:

In the current version of select2 the class attribute is being transferred from the hidden input into the root element created by select2, even the select2-offscreen class which positions the element way outside the page limits.

To fix this problem all that's needed is to add removeClass('select2-offscreen') before applying select2 a second time on the same element.

$('#attribute').select2().on('change', function() {
    $('#value').removeClass('select2-offscreen').select2({data:data[$(this).val()]});
}).trigger('change');

I've added a new Code Example to address this issue.

Good tool to visualise database schema?

I looked for a long time for a decent, and preferably free, tool for linux and found this java application that is quite good (finally!!):

http://sqldeveloper.solyp.com/

Being Java it is cross-platform (I run it on Linux with no issues) and it will connect to any database you can get a JDBC driver for. ie: pretty much any database.

It is quite easy to import your database and get a visual (ERM) of the database schema. The auto-layout feature is good as well, but note that it is not done automatically and you need to click the "automatic layout" button after importing your objects into the diagram.

The application is also a pretty good generic database administration/browsing tool. As one small example, I use it instead of pgadmin for some base development work because of simple niceties like the column width of SQL query results automatically sizing to fit content (which drives me crazy in pgadmin).

Javascript change Div style

function abc() {
    var color = document.getElementById("test").style.color;
    color = (color=="red") ? "black" : "red" ;
    document.getElementById("test").style.color= color;
}

Compare two List<T> objects for equality, ignoring order

try this!!!

using following code you could compare one or many fields to generate a result list as per your need. result list will contain only modified item(s).

// veriables been used
List<T> diffList = new List<T>();
List<T> gotResultList = new List<T>();



// compare First field within my MyList
gotResultList = MyList1.Where(a => !MyList2.Any(a1 => a1.MyListTField1 == a.MyListTField1)).ToList().Except(gotResultList.Where(a => !MyList2.Any(a1 => a1.MyListTField1 == a.MyListTField1))).ToList();
// Generate result list
diffList.AddRange(gotResultList);

// compare Second field within my MyList
gotResultList = MyList1.Where(a => !MyList2.Any(a1 => a1.MyListTField2 == a.MyListTField2)).ToList().Except(gotResultList.Where(a => !MyList2.Any(a1 => a1.MyListTField2 == a.MyListTField2))).ToList();
// Generate result list
diffList.AddRange(gotResultList);


MessageBox.Show(diffList.Count.ToString);

Difference between multitasking, multithreading and multiprocessing?

MULTIPROCESSING is like the OS handling the different jobs in main memory in such a way that it gives its time to each and every job when other is busy for some task such as I/O operation. So as long as at least one job needs to execute, the cpu never sit idle. and here it is automatically handled by the OS, without user interaction with computer.

But when we say about MULTITASKING, the user is actually involved with different jobs as at one time - minesweeper or checking mail or anything. The cpu executes multiple jobs by switching among them, but the switching is so fast that user has the illusion that both the applications are running simultaneously.

So the main difference between mp and mt is that in mp the OS is handling different jobs in main memory in such a way that if some job is waiting for something then it will jump for the next job to execute. And in mt the user is in interaction with the system and getting the illusion as both or any of the applications are running simultaneously.

Set size on background image with CSS?

You can't set the size of your background image with the current version of CSS (2.1).

You can only set: position, fix, image-url, repeat-mode, and color.

Find character position and update file name

If you use Excel, then the command would be Find and MID. Here is what it would look like in Powershell.

 $text = "asdfNAME=PC123456<>Diweursejsfdjiwr"

asdfNAME=PC123456<>Diweursejsfdjiwr - Randon line of text, we want PC123456

 $text.IndexOf("E=")

7 - this is the "FIND" command for Powershell

 $text.substring(10,5)

C1234 - this is the "MID" command for Powershell

 $text.substring($text.IndexOf("E=")+2,8)

PC123456 - tada it has found and cut our text

-RavonTUS

How to remove the last element added into the List?

The direct answer to this question is:

if(rows.Any()) //prevent IndexOutOfRangeException for empty list
{
    rows.RemoveAt(rows.Count - 1);
}

However... in the specific case of this question, it makes more sense not to add the row in the first place:

Row row = new Row();
//...      

if (!row.cell[0].Equals("Something"))
{
    rows.Add(row);
}

TBH, I'd go a step further by testing "Something" against user."", and not even instantiating a Row unless the condition is satisfied, but seeing as user."" won't compile, I'll leave that as an exercise for the reader.

Format an Integer using Java String Format

If you are using a third party library called apache commons-lang, the following solution can be useful:

Use StringUtils class of apache commons-lang :

int i = 5;
StringUtils.leftPad(String.valueOf(i), 3, "0"); // --> "005"

As StringUtils.leftPad() is faster than String.format()

Drawable-hdpi, Drawable-mdpi, Drawable-ldpi Android

I got one good solution. Here I have attached it as the image below. So try it. It may be helpful to you...!

Enter image description here

How to use "Share image using" sharing Intent to share images in android?

I found the easiest way to do this is by using the MediaStore to temporarily store the image that you want to share:

Drawable mDrawable = mImageView.getDrawable();
Bitmap mBitmap = ((BitmapDrawable) mDrawable).getBitmap();

String path = MediaStore.Images.Media.insertImage(getContentResolver(), mBitmap, "Image Description", null);
Uri uri = Uri.parse(path);

Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(intent, "Share Image"));

From: Sharing Content With Intents

Difference between static STATIC_URL and STATIC_ROOT on Django

STATICFILES_DIRS: You can keep the static files for your project here e.g. the ones used by your templates.

STATIC_ROOT: leave this empty, when you do manage.py collectstatic, it will search for all the static files on your system and move them here. Your static file server is supposed to be mapped to this folder wherever it is located. Check it after running collectstatic and you'll find the directory structure django has built.

--------Edit----------------

As pointed out by @DarkCygnus, STATIC_ROOT should point at a directory on your filesystem, the folder should be empty since it will be populated by Django.

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

or

STATIC_ROOT = '/opt/web/project/static_files'

--------End Edit -----------------

STATIC_URL: '/static/' is usually fine, it's just a prefix for static files.

add/remove active class for ul list with jquery?

you can use siblings and removeClass method

$('.nav-link li').click(function() {
    $(this).addClass('active').siblings().removeClass('active');
});

How to dynamically build a JSON object with Python?

  myjson={}
  myjson["Country"]= {"KR": { "id": "220", "name": "South Korea"}}
  myjson["Creative"]= {
                    "1067405": {
                        "id": "1067405",
                        "url": "https://cdn.gowadogo.com/559d1ba1-8d50-4c7f-b3f5-d80f918006e0.jpg"
                    },
                    "1067406": {
                        "id": "1067406",
                        "url": "https://cdn.gowadogo.com/3799a70d-339c-4ecb-bc1f-a959dde675b8.jpg"
                    },
                    "1067407": {
                        "id": "1067407",
                        "url": "https://cdn.gowadogo.com/180af6a5-251d-4aa9-9cd9-51b2fc77d0c6.jpg"
                    }
                }
   myjson["Offer"]= {
                    "advanced_targeting_enabled": "f",
                    "category_name": "E-commerce/ Shopping",
                    "click_lifespan": "168",
                    "conversion_cap": "50",
                    "currency": "USD",
                    "default_payout": "1.5"
                }

   json_data = json.dumps(myjson)

   #reverse back into a json

   paths=[]
   def walk_the_tree(inputDict,suffix=None):
       for key, value in inputDict.items():
            if isinstance(value, dict):
                if suffix==None:
                    suffix=key
                else:
                    suffix+=":"+key

                walk_the_tree(value,suffix)
            else:
                paths.append(suffix+":"+key+":"+value)
 walk_the_tree(myjson)
 print(paths)  

 #split and build your nested dictionary
 json_specs = {}
 for path in paths:
     parts=path.split(':')
     value=(parts[-1])
     d=json_specs
     for p in parts[:-1]:
         if p==parts[-2]:
             d = d.setdefault(p,value)
         else:
             d = d.setdefault(p,{})
    
 print(json_specs)        

 Paths:
 ['Country:KR:id:220', 'Country:KR:name:South Korea', 'Country:Creative:1067405:id:1067405', 'Country:Creative:1067405:url:https://cdn.gowadogo.com/559d1ba1-8d50-4c7f-b3f5-d80f918006e0.jpg', 'Country:Creative:1067405:1067406:id:1067406', 'Country:Creative:1067405:1067406:url:https://cdn.gowadogo.com/3799a70d-339c-4ecb-bc1f-a959dde675b8.jpg', 'Country:Creative:1067405:1067406:1067407:id:1067407', 'Country:Creative:1067405:1067406:1067407:url:https://cdn.gowadogo.com/180af6a5-251d-4aa9-9cd9-51b2fc77d0c6.jpg', 'Country:Creative:Offer:advanced_targeting_enabled:f', 'Country:Creative:Offer:category_name:E-commerce/ Shopping', 'Country:Creative:Offer:click_lifespan:168', 'Country:Creative:Offer:conversion_cap:50', 'Country:Creative:Offer:currency:USD', 'Country:Creative:Offer:default_payout:1.5']

Definition of "downstream" and "upstream"

When you read in git tag man page:

One important aspect of git is it is distributed, and being distributed largely means there is no inherent "upstream" or "downstream" in the system.

, that simply means there is no absolute upstream repo or downstream repo.
Those notions are always relative between two repos and depends on the way data flows:

If "yourRepo" has declared "otherRepo" as a remote one, then:

  • you are pulling from upstream "otherRepo" ("otherRepo" is "upstream from you", and you are "downstream for otherRepo").
  • you are pushing to upstream ("otherRepo" is still "upstream", where the information now goes back to).

Note the "from" and "for": you are not just "downstream", you are "downstream from/for", hence the relative aspect.


The DVCS (Distributed Version Control System) twist is: you have no idea what downstream actually is, beside your own repo relative to the remote repos you have declared.

  • you know what upstream is (the repos you are pulling from or pushing to)
  • you don't know what downstream is made of (the other repos pulling from or pushing to your repo).

Basically:

In term of "flow of data", your repo is at the bottom ("downstream") of a flow coming from upstream repos ("pull from") and going back to (the same or other) upstream repos ("push to").


You can see an illustration in the git-rebase man page with the paragraph "RECOVERING FROM UPSTREAM REBASE":

It means you are pulling from an "upstream" repo where a rebase took place, and you (the "downstream" repo) is stuck with the consequence (lots of duplicate commits, because the branch rebased upstream recreated the commits of the same branch you have locally).

That is bad because for one "upstream" repo, there can be many downstream repos (i.e. repos pulling from the upstream one, with the rebased branch), all of them having potentially to deal with the duplicate commits.

Again, with the "flow of data" analogy, in a DVCS, one bad command "upstream" can have a "ripple effect" downstream.


Note: this is not limited to data.
It also applies to parameters, as git commands (like the "porcelain" ones) often call internally other git commands (the "plumbing" ones). See rev-parse man page:

Many git porcelainish commands take mixture of flags (i.e. parameters that begin with a dash '-') and parameters meant for the underlying git rev-list command they use internally and flags and parameters for the other commands they use downstream of git rev-list. This command is used to distinguish between them.

How to change value of process.env.PORT in node.js?

For just one run (from the unix shell prompt):

$ PORT=1234 node app.js

More permanently:

$ export PORT=1234
$ node app.js

In Windows:

set PORT=1234

In Windows PowerShell:

$env:PORT = 1234

WPF checkbox binding

You need a dependency property for this:

public BindingList<User> Users
{
    get { return (BindingList<User>)GetValue(UsersProperty); }
    set { SetValue(UsersProperty, value); }
}

public static readonly DependencyProperty UsersProperty =
    DependencyProperty.Register("Users", typeof(BindingList<User>), 
      typeof(OptionsDialog));

Once that is done, you bind the checkbox to the dependency property:

<CheckBox x:Name="myCheckBox"
          IsChecked="{Binding ElementName=window1, Path=CheckBoxIsChecked}" />

For that to work you have to name your Window or UserControl in its openning tag, and use that name in the ElementName parameter.

With this code, whenever you change the property on the code side, you will change the textbox. Also, whenever you check/uncheck the textbox, the Dependency Property will change too.

EDIT:

An easy way to create a dependency property is typing the snippet propdp, which will give you the general code for Dependency Properties.

All the code:

XAML:

<Window x:Class="StackOverflowTests.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" x:Name="window1" Height="300" Width="300">
    <Grid>
        <StackPanel Orientation="Vertical">
            <CheckBox Margin="10"
                      x:Name="myCheckBox"
                      IsChecked="{Binding ElementName=window1, Path=IsCheckBoxChecked}">
                Bound CheckBox
            </CheckBox>
            <Label Content="{Binding ElementName=window1, Path=IsCheckBoxChecked}"
                   ContentStringFormat="Is checkbox checked? {0}" />
        </StackPanel>
    </Grid>
</Window>

C#:

using System.Windows;

namespace StackOverflowTests
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public bool IsCheckBoxChecked
        {
           get { return (bool)GetValue(IsCheckBoxCheckedProperty); }
           set { SetValue(IsCheckBoxCheckedProperty, value); }
        }

        // Using a DependencyProperty as the backing store for 
         //IsCheckBoxChecked.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty IsCheckBoxCheckedProperty =
            DependencyProperty.Register("IsCheckBoxChecked", typeof(bool), 
            typeof(Window1), new UIPropertyMetadata(false));

        public Window1()
        {             
            InitializeComponent();
        }
    }
}

Notice how the only code behind is the Dependency Property. Both the label and the checkbox are bound to it. If the checkbox changes, the label changes too.

How to reset Django admin password?

You may try this:

1.Change Superuser password without console

python manage.py changepassword <username>

2.Change Superuser password through console

enter image description here enter image description here

What is the equivalent to getch() & getche() in Linux?

#include <termios.h>
#include <stdio.h>

static struct termios old, current;

/* Initialize new terminal i/o settings */
void initTermios(int echo) 
{
  tcgetattr(0, &old); /* grab old terminal i/o settings */
  current = old; /* make new settings same as old settings */
  current.c_lflag &= ~ICANON; /* disable buffered i/o */
  if (echo) {
      current.c_lflag |= ECHO; /* set echo mode */
  } else {
      current.c_lflag &= ~ECHO; /* set no echo mode */
  }
  tcsetattr(0, TCSANOW, &current); /* use these new terminal i/o settings now */
}

/* Restore old terminal i/o settings */
void resetTermios(void) 
{
  tcsetattr(0, TCSANOW, &old);
}

/* Read 1 character - echo defines echo mode */
char getch_(int echo) 
{
  char ch;
  initTermios(echo);
  ch = getchar();
  resetTermios();
  return ch;
}

/* Read 1 character without echo */
char getch(void) 
{
  return getch_(0);
}

/* Read 1 character with echo */
char getche(void) 
{
  return getch_(1);
}

/* Let's test it out */
int main(void) {
  char c;
  printf("(getche example) please type a letter: ");
  c = getche();
  printf("\nYou typed: %c\n", c);
  printf("(getch example) please type a letter...");
  c = getch();
  printf("\nYou typed: %c\n", c);
  return 0;
}

Output:

(getche example) please type a letter: g
You typed: g
(getch example) please type a letter...
You typed: g

Disable scrolling in all mobile devices

This prevents scrolling on mobile devices but not the single click/tap.

document.body.addEventListener('touchstart', function(e){ e.preventDefault(); });

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

The image below is from the article written by Erwin van der Valk:

image explaining MVC, MVP and MVVM - by Erwin Vandervalk

The article explains the differences and gives some code examples in C#

System.out.println() shortcut on Intellij IDEA

Yeah, you can do it. Just open Settings -> Live Templates. Create new one with syso as abbreviation and System.out.println($END$); as Template text.

How to use Select2 with JSON via Ajax request?

My ajax never gets fired until I wrapped the whole thing in

setTimeout(function(){ .... }, 3000);

I was using it in mounted section of Vue. it needs more time.

How can I plot separate Pandas DataFrames as subplots?

You can manually create the subplots with matplotlib, and then plot the dataframes on a specific subplot using the ax keyword. For example for 4 subplots (2x2):

import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=2, ncols=2)

df1.plot(ax=axes[0,0])
df2.plot(ax=axes[0,1])
...

Here axes is an array which holds the different subplot axes, and you can access one just by indexing axes.
If you want a shared x-axis, then you can provide sharex=True to plt.subplots.

Repeat rows of a data.frame

Another way to do this would to first get row indices, append extra copies of the df, and then order by the indices:

df$index = 1:nrow(df)
df = rbind(df,df)
df = df[order(df$index),][,-ncol(df)]

Although the other solutions may be shorter, this method may be more advantageous in certain situations.

Replacing characters in Ant property

Properties can't be changed but antContrib vars (http://ant-contrib.sourceforge.net/tasks/tasks/variable_task.html ) can.

Here is a macro to do a find/replace on a var:

    <macrodef name="replaceVarText">
        <attribute name="varName" />
        <attribute name="from" />
        <attribute name="to" />
        <sequential>
            <local name="replacedText"/>
            <local name="textToReplace"/>
            <local name="fromProp"/>
            <local name="toProp"/>
            <property name="textToReplace" value = "${@{varName}}"/>
            <property name="fromProp" value = "@{from}"/>
            <property name="toProp" value = "@{to}"/>

            <script language="javascript">
                project.setProperty("replacedText",project.getProperty("textToReplace").split(project.getProperty("fromProp")).join(project.getProperty("toProp")));
            </script>
            <ac:var name="@{varName}" value = "${replacedText}"/>
        </sequential>
    </macrodef>

Then call the macro like:

<ac:var name="updatedText" value="${oldText}"/>
<current:replaceVarText varName="updatedText" from="." to="_" />
<echo message="Updated Text will be ${updatedText}"/>

Code above uses javascript split then join, which is faster than regex. "local" properties are passed to JavaScript so no property leakage.

Removing Data From ElasticSearch

You can also use chrome extension elasticsearch-head to delete index

php: catch exception and continue execution, is it possible?

php > 7

use the new interface Throwable

    try {
        // Code that may throw an Exception or Error.
    } catch (Throwable $t) {
        // Handle exception
    }

echo "Script is still running..."; // this script will be executed.

Run git pull over all subdirectories

Most compact method, assuming all sub-dirs are git repos:

ls | parallel git -C {} pull

JavaScript to get rows count of a HTML table

This is another option, using jQuery and getting only tbody rows (with the data) and desconsidering thead/tfoot.

$("#tableId > tbody > tr").length

_x000D_
_x000D_
console.log($("#myTableId > tbody > tr").length);
_x000D_
.demo {
   width:100%;
   height:100%;
   border:1px solid #C0C0C0;
   border-collapse:collapse;
   border-spacing:2px;
   padding:5px;
}

.demo caption {
   caption-side:top;
   text-align:center;
}

.demo th {
   border:1px solid #C0C0C0;
   padding:5px;
   background:#F0F0F0;
}

.demo td {
   border:1px solid #C0C0C0;
   text-align:left;
   padding:5px;
   background:#FFFFFF;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTableId" class="demo">
   <caption>Table 1</caption>
   <thead>
      <tr>
         <th>Header 1</th>
         <th>Header 2</th>
         <th>Header 3</th>
         <th>Header 4</th>
      </tr>
   </thead>
   <tbody>
      <tr>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
      </tr>
      <tr>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
      </tr>
      <tr>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
      </tr>
      <tr>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
      </tr>
   </tbody>
   <tfoot>
      <tr>
         <td colspan=4 style="background:#F0F0F0">&nbsp; </td>
      </tr>
   </tfoot>
</table>
_x000D_
_x000D_
_x000D_

jQuery show/hide not working

Use this

<script>
$(document).ready(function(){
    $( '.expand' ).click(function() {
        $( '.img_display_content' ).show();
    });
});
</script>

Event assigning always after Document Object Model loaded

Mock MVC - Add Request Parameter to test

When i analyzed your code. I have also faced the same problem but my problem is if i give value for both first and last name means it is working fine. but when i give only one value means it says 400. anyway use the .andDo(print()) method to find out the error

public void testGetUserByName() throws Exception {
    String firstName = "Jack";
    String lastName = "s";       
    this.userClientObject = client.createClient();
    mockMvc.perform(get("/byName")
            .sessionAttr("userClientObject", this.userClientObject)
            .param("firstName", firstName)
            .param("lastName", lastName)               
    ).andDo(print())
     .andExpect(status().isOk())
            .andExpect(content().contentType("application/json"))
            .andExpect(jsonPath("$[0].id").exists())
            .andExpect(jsonPath("$[0].fn").value("Marge"));
}

If your problem is org.springframework.web.bind.missingservletrequestparameterexception you have to change your code to

@RequestMapping(value = "/byName", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    public
    @ResponseBody
    String getUserByName(
        @RequestParam( value="firstName",required = false) String firstName,
        @RequestParam(value="lastName",required = false) String lastName, 
        @ModelAttribute("userClientObject") UserClient userClient)
    {

        return client.getUserByName(userClient, firstName, lastName);
    }

Iterating over arrays in Python 3

While iterating over a list or array with this method:

ar = [10, 11, 12]
for i in ar:
    theSum = theSum + ar[i]

You are actually getting the values of list or array sequentially in i variable. If you print the variable i inside the for loop. You will get following output:

10
11
12

However, in your code you are confusing i variable with index value of array. Therefore, while doing ar[i] will mean ar[10] for the first iteration. Which is of course index out of range throwing IndexError

Edit You can read this for better understanding of different methods of iterating over array or list in Python

Can't connect to MySQL server on '127.0.0.1' (10061) (2003)

If you have already installed MySQL on a windows machine make sure it is running as a service.. You can do that by

Start --> services --> MySQL(ver) --> Right-Click --> Start

Switch statement: must default be the last case?

There's no defined order in a switch statement. You may look at the cases as something like a named label, like a goto label. Contrary to what people seem to think here, in the case of value 2 the default label is not jumped to. To illustrate with a classical example, here is Duff's device, which is the poster child of the extremes of switch/case in C.

send(to, from, count)
register short *to, *from;
register count;
{
  register n=(count+7)/8;
  switch(count%8){
    case 0: do{ *to = *from++;
    case 7:     *to = *from++;
    case 6:     *to = *from++;
    case 5:     *to = *from++;
    case 4:     *to = *from++;
    case 3:     *to = *from++;
    case 2:     *to = *from++;
    case 1:     *to = *from++;
            }while(--n>0);
  }
}

vertical-align: middle with Bootstrap 2

Try removing the float attribute from span6:

{ float:none !important; }

How to find array / dictionary value using key?

It looks like you're writing PHP, in which case you want:

<?
$arr=array('us'=>'United', 'ca'=>'canada');
$key='ca';
echo $arr[$key];
?>

Notice that the ('us'=>'United', 'ca'=>'canada') needs to be a parameter to the array function in PHP.

Most programming languages that support associative arrays or dictionaries use arr['key'] to retrieve the item specified by 'key'

For instance:

Ruby

ruby-1.9.1-p378 > h = {'us' => 'USA', 'ca' => 'Canada' }
 => {"us"=>"USA", "ca"=>"Canada"} 
ruby-1.9.1-p378 > h['ca']
 => "Canada" 

Python

>>> h = {'us':'USA', 'ca':'Canada'}
>>> h['ca']
'Canada'

C#

class P
{
    static void Main()
    {
        var d = new System.Collections.Generic.Dictionary<string, string> { {"us", "USA"}, {"ca", "Canada"}};
        System.Console.WriteLine(d["ca"]);
    }
}

Lua

t = {us='USA', ca='Canada'}
print(t['ca'])
print(t.ca) -- Lua's a little different with tables

Can I use return value of INSERT...RETURNING in another INSERT?

You can do so starting with Postgres 9.1:

with rows as (
INSERT INTO Table1 (name) VALUES ('a_title') RETURNING id
)
INSERT INTO Table2 (val)
SELECT id
FROM rows

In the meanwhile, if you're only interested in the id, you can do so with a trigger:

create function t1_ins_into_t2()
  returns trigger
as $$
begin
  insert into table2 (val) values (new.id);
  return new;
end;
$$ language plpgsql;

create trigger t1_ins_into_t2
  after insert on table1
for each row
execute procedure t1_ins_into_t2();

Replace or delete certain characters from filenames of all files in a folder

Use PowerShell to do anything smarter for a DOS prompt. Here, I've shown how to batch rename all the files and directories in the current directory that contain spaces by replacing them with _ underscores.

Dir |
Rename-Item -NewName { $_.Name -replace " ","_" }

EDIT :
Optionally, the Where-Object command can be used to filter out ineligible objects for the successive cmdlet (command-let). The following are some examples to illustrate the flexibility it can afford you:

  • To skip any document files

    Dir |
    Where-Object { $_.Name -notmatch "\.(doc|xls|ppt)x?$" } |
    Rename-Item -NewName { $_.Name -replace " ","_" }
    
  • To process only directories (pre-3.0 version)

    Dir |
    Where-Object { $_.Mode -match "^d" } |
    Rename-Item -NewName { $_.Name -replace " ","_" }
    

    PowerShell v3.0 introduced new Dir flags. You can also use Dir -Directory there.

  • To skip any files already containing an underscore (or some other character)

    Dir |
    Where-Object { -not $_.Name.Contains("_") } |
    Rename-Item -NewName { $_.Name -replace " ","_" }
    

How to align matching values in two columns in Excel, and bring along associated values in other columns

assuming the item numbers are unique, a VLOOKUP should get you the information you need.

first value would be =VLOOKUP(E1,A:B,2,FALSE), and the same type of formula to retrieve the second value would be =VLOOKUP(E1,C:D,2,FALSE). Wrap them in an IFERROR if you want to return anything other than #N/A if there is no corresponding value in the item column(s)

There are no primary or candidate keys in the referenced table that match the referencing column list in the foreign key

BookTitle have a Composite key. so if the key of BookTitle is referenced as a foreign key you have to bring the complete composite key.

So to resolve the problem you need to add the complete composite key in the BookCopy. So add ISBN column as well. and they at the end.

foreign key (ISBN, Title) references BookTitle (ISBN, Title)

How to remove old Docker containers

New way: spotify/docker-gc play the trick.

 docker run --rm -v /var/run/docker.sock:/var/run/docker.sock -v /etc:/etc spotify/docker-gc
  • Containers that exited more than an hour ago are removed.
  • Images that don't belong to any remaining container after that are removed

It has supported environmental settings

Forcing deletion of images that have multiple tags

 FORCE_IMAGE_REMOVAL=1

Forcing deletion of containers

 FORCE_CONTAINER_REMOVAL=1 

Excluding Recently Exited Containers and Images From Garbage Collection

 GRACE_PERIOD_SECONDS=86400

This setting also prevents the removal of images that have been created less than GRACE_PERIOD_SECONDS seconds ago.

Dry run

 DRY_RUN=1

Cleaning up orphaned container volumes CLEAN_UP_VOLUMES=1

Reference: docker-gc

Old way to do:

delete old, non-running containers

 docker ps -a -q -f status=exited | xargs --no-run-if-empty docker rm
             OR 
 docker rm $(docker ps -a -q)

delete all images associated with non-running docker containers

 docker images -q | xargs --no-run-if-empty docker rmi

cleanup orphaned docker volumes for docker version 1.10.x and above

 docker volume ls -qf dangling=true | xargs -r docker volume rm

Based on time period

 docker ps -a | grep "weeks ago" | awk "{print $1}" | xargs --no-run-if-empty docker rm
 docker ps -a | grep "days ago" | awk "{print $1}" | xargs --no-run-if-empty docker rm
 docker ps -a | grep "hours ago" | awk "{print $1}" | xargs --no-run-if-empty docker rm

Microsoft.Office.Core Reference Missing

Have you actually gone to your references and added a .NET reference to the 'Microsoft.Office.Core' library? If you downloaded the example application, the answer would be yes. If that is the case, follow the advice in the article:

If your system does not have Microsoft Office Outlook 2003 you may have to change the References used by the "OutlookConnector" project. That is to say, if you received a build error described as "The type of namespace name 'Outlook' could not be found", you probably don't have Office 2003. Simply expand the project references, remove the afflicted items, and add the COM Library appropriate for your system. If someone has a dynamic way to handle this, I'd be curious to see you've done.

That should solve your problem. If not, let us know.

Where can I find documentation on formatting a date in JavaScript?

Although JavaScript gives you many great ways of formatting and calculations, I prefer using the Moment.js (momentjs.com) library during application development as it's very intuitive and saves a lot of time.

Nonetheless, I suggest everyone to learn about the basic JavaScript API too for a better understanding.

Export to CSV via PHP

I personally use this function to create CSV content from any array.

function array2csv(array &$array)
{
   if (count($array) == 0) {
     return null;
   }
   ob_start();
   $df = fopen("php://output", 'w');
   fputcsv($df, array_keys(reset($array)));
   foreach ($array as $row) {
      fputcsv($df, $row);
   }
   fclose($df);
   return ob_get_clean();
}

Then you can make your user download that file using something like:

function download_send_headers($filename) {
    // disable caching
    $now = gmdate("D, d M Y H:i:s");
    header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
    header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
    header("Last-Modified: {$now} GMT");

    // force download  
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");

    // disposition / encoding on response body
    header("Content-Disposition: attachment;filename={$filename}");
    header("Content-Transfer-Encoding: binary");
}

Usage example:

download_send_headers("data_export_" . date("Y-m-d") . ".csv");
echo array2csv($array);
die();

Notepad++: Multiple words search in a file (may be in different lines)?

You need a new version of notepad++. Looks like old versions don't support |.

Note: egrep "CAT|TOWN" will search for lines containing CATOWN. (CAT)|(TOWN) is the proper or extension (matching 1,3,4). Strangely you wrote and which is btw (CAT.*TOWN)|(TOWN.*CAT)

Test if a string contains any of the strings from an array

import org.apache.commons.lang.StringUtils;

String Utils

Use:

StringUtils.indexOfAny(inputString, new String[]{item1, item2, item3})

It will return the index of the string found or -1 if none is found.

Is there a function to split a string in PL/SQL?

You could use a combination of SUBSTR and INSTR as follows :

Example string : field = 'DE124028#@$1048708#@$000#@$536967136#@$'

The seperator being #@$.

To get the '1048708' for example :

If the field is of fixed length ( 7 here ) :

substr(field,instr(field,'#@$',1,1)+3,7)

If the field is of variable length :

substr(field,instr(field,'#@$',1,1)+3,instr(field,'#@$',1,2) - (instr(field,'#@$',1,1)+3)) 

You should probably look into SUBSTR and INSTR functions for more flexibility.

How do I declare an array of undefined or no initial size?

malloc() (and its friends free() and realloc()) is the way to do this in C.

Modulo operator in Python

same as a normal modulo 3.14 % 6.28 = 3.14, just like 3.14%4 =3.14 3.14%2 = 1.14 (the remainder...)

Renaming files in a folder to sequential numbers

A very simple bash one liner that keeps the original extensions, adds leading zeros, and also works in OSX:

num=0; for i in *; do mv "$i" "$(printf '%04d' $num).${i#*.}"; ((num++)); done

Simplified version of http://ubuntuforums.org/showthread.php?t=1355021

Python: avoid new line with print command

You simply need to do:

print 'lakjdfljsdf', # trailing comma

However in:

print 'lkajdlfjasd', 'ljkadfljasf'

There is implicit whitespace (ie ' ').

You also have the option of:

import sys
sys.stdout.write('some data here without a new line')

Processing $http response in service

Let it be simple. It's as simple as

  1. Return promise in your service(no need to use then in service)
  2. Use then in your controller

Demo. http://plnkr.co/edit/cbdG5p?p=preview

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

app.factory('myService', function($http) {
  return {
    async: function() {
      return $http.get('test.json');  //1. this returns promise
    }
  };
});

app.controller('MainCtrl', function( myService,$scope) {
  myService.async().then(function(d) { //2. so you can use .then()
    $scope.data = d;
  });
});

Fatal error: iostream: No such file or directory in compiling C program using GCC

Neither <iostream> nor <iostream.h> are standard C header files. Your code is meant to be C++, where <iostream> is a valid header. Use g++ (and a .cpp file extension) for C++ code.

Alternatively, this program uses mostly constructs that are available in C anyway. It's easy enough to convert the entire program to compile using a C compiler. Simply remove #include <iostream> and using namespace std;, and replace cout << endl; with putchar('\n');... I advise compiling using C99 (eg. gcc -std=c99)

What does HTTP/1.1 302 mean exactly?

From Wikipedia:

The HTTP response status code 302 Found is the most common way of performing a redirection. It is an example of industrial practice contradicting the standard.

Remove multiple objects with rm()

Or using regular expressions

"rmlike" <- function(...) {
  names <- sapply(
    match.call(expand.dots = FALSE)$..., as.character)
  names = paste(names,collapse="|")
  Vars <- ls(1)
  r <- Vars[grep(paste("^(",names,").*",sep=""),Vars)]
  rm(list=r,pos=1)
}

rmlike(temp)

Difference between .dll and .exe?

? .exe and dll are the compiled version of c# code which are also called as assemblies.

? .exe is a stand alone executable file, which means it can executed directly.

? .dll is a reusable component which cannot be executed directly and it requires other programs to execute it.

How do I make WRAP_CONTENT work on a RecyclerView

Instead of using any library, easiest solution till the new version comes out is to just open b.android.com/74772. You'll easily find the best solution known to date there.

PS: b.android.com/74772#c50 worked for me

Where does npm install packages?

In earlier versions of NPM modules were always placed in /usr/local/lib/node or wherever you specified the npm root within the .npmrc file. However, in NPM 1.0+ modules are installed in two places. You can have modules installed local to your application in /.node_modules or you can have them installed globally which will use the above.

More information can be found at https://github.com/isaacs/npm/blob/master/doc/install.md

Html encode in PHP

By encode, do you mean: Convert all applicable characters to HTML entities?

htmlspecialchars or htmlentities

You can also use strip_tags if you want to remove all HTML tags :

strip_tags

Note: this will NOT stop all XSS attacks

How to generate javadoc comments in Android Studio

Javadoc comments can be automatically appended by using your IDE's autocomplete feature. Try typing /** and hitting Enter to generate a sample Javadoc comment.

 /**
 *
 * @param action          The action to execute.
 * @param args            The exec() arguments.
 * @param callbackContext The callback context used when calling back into JavaScript.
 * @return
 * @throws JSONException
 */

Do HTTP POST methods send data as a QueryString?

The best way to visualize this is to use a packet analyzer like Wireshark and follow the TCP stream. HTTP simply uses TCP to send a stream of data starting with a few lines of HTTP headers. Often this data is easy to read because it consists of HTML, CSS, or XML, but it can be any type of data that gets transfered over the internet (Executables, Images, Video, etc).

For a GET request, your computer requests a specific URL and the web server usually responds with a 200 status code and the the content of the webpage is sent directly after the HTTP response headers. This content is the same content you would see if you viewed the source of the webpage in your browser. The query string you mentioned is just part of the URL and gets included in the HTTP GET request header that your computer sends to the web server. Below is an example of an HTTP GET request to http://accel91.citrix.com:8000/OA_HTML/OALogout.jsp?menu=Y, followed by a 302 redirect response from the server. Some of the HTTP Headers are wrapped due to the size of the viewing window (these really only take one line each), and the 302 redirect includes a simple HTML webpage with a link to the redirected webpage (Most browsers will automatically redirect any 302 response to the URL listed in the Location header instead of displaying the HTML response):

HTTP GET with 302 redirect

For a POST request, you may still have a query string, but this is uncommon and does not have anything to do with the data that you are POSTing. Instead, the data is included directly after the HTTP headers that your browser sends to the server, similar to the 200 response that the web server uses to respond to a GET request. In the case of POSTing a simple web form this data is encoded using the same URL encoding that a query string uses, but if you are using a SOAP web service it could also be encoded using a multi-part MIME format and XML data.

For example here is what an HTTP POST to an XML based SOAP web service located at http://192.168.24.23:8090/msh looks like in Wireshark Follow TCP Stream:

HTTP POST TCP Stream

Application Installation Failed in Android Studio

Go to Build --> Clean Project --> Run

Thats all it takes.

Why am I getting a "401 Unauthorized" error in Maven?

Had similar issue. Had to pin the maven deploy plugin to specific version in pom.xml:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-deploy-plugin</artifactId>
     <version>2.8.2</version>
</plugin>

This version is what broke my builds:

[INFO] --- maven-deploy-plugin:3.0.0-M1:deploy (default-cli) @ dbl ---

jQuery: Change button text on click

$('.SeeMore2').click(function(){
    var $this = $(this);
    $this.toggleClass('SeeMore2');
    if($this.hasClass('SeeMore2')){
        $this.text('See More');         
    } else {
        $this.text('See Less');
    }
});

This should do it. You have to make sure you toggle the correct class and take out the "." from the hasClass

http://jsfiddle.net/V4u5X/2/

How to get current memory usage in android?

It depends on your definition of what memory query you wish to get.


Usually, you'd like to know the status of the heap memory, since if it uses too much memory, you get OOM and crash the app.

For this, you can check the next values:

final Runtime runtime = Runtime.getRuntime();
final long usedMemInMB=(runtime.totalMemory() - runtime.freeMemory()) / 1048576L;
final long maxHeapSizeInMB=runtime.maxMemory() / 1048576L;
final long availHeapSizeInMB = maxHeapSizeInMB - usedMemInMB;

The more the "usedMemInMB" variable gets close to "maxHeapSizeInMB", the closer availHeapSizeInMB gets to zero, the closer you get OOM. (Due to memory fragmentation, you may get OOM BEFORE this reaches zero.)

That's also what the DDMS tool of memory usage shows.


Alternatively, there is the real RAM usage, which is how much the entire system uses - see accepted answer to calculate that.


Update: since Android O makes your app also use the native RAM (at least for Bitmaps storage, which is usually the main reason for huge memory usage), and not just the heap, things have changed, and you get less OOM (because the heap doesn't contain bitmaps anymore,check here), but you should still keep an eye on memory use if you suspect you have memory leaks. On Android O, if you have memory leaks that should have caused OOM on older versions, it seems it will just crash without you being able to catch it. Here's how to check for memory usage:

val nativeHeapSize = Debug.getNativeHeapSize()
val nativeHeapFreeSize = Debug.getNativeHeapFreeSize()
val usedMemInBytes = nativeHeapSize - nativeHeapFreeSize
val usedMemInPercentage = usedMemInBytes * 100 / nativeHeapSize

But I believe it might be best to use the profiler of the IDE, which shows the data in real time, using a graph.

So the good news on Android O is that it's much harder to get crashes due to OOM of storing too many large bitmaps, but the bad news is that I don't think it's possible to catch such a case during runtime.


EDIT: seems Debug.getNativeHeapSize() changes over time, as it shows you the total max memory for your app. So those functions are used only for the profiler, to show how much your app is using.

If you want to get the real total and available native RAM , use this:

val memoryInfo = ActivityManager.MemoryInfo()
(getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager).getMemoryInfo(memoryInfo)
val nativeHeapSize = memoryInfo.totalMem
val nativeHeapFreeSize = memoryInfo.availMem
val usedMemInBytes = nativeHeapSize - nativeHeapFreeSize
val usedMemInPercentage = usedMemInBytes * 100 / nativeHeapSize
Log.d("AppLog", "total:${Formatter.formatFileSize(this, nativeHeapSize)} " +
        "free:${Formatter.formatFileSize(this, nativeHeapFreeSize)} " +
        "used:${Formatter.formatFileSize(this, usedMemInBytes)} ($usedMemInPercentage%)")

lodash multi-column sortBy descending

Is there some handy way of defining direction per column?

No. You cannot specify the sort order other than by a callback function that inverses the value. Not even this is possible for a multicolumn sort.

You might be able to do

 _.each(array_of_objects, function(o) {
     o.typeDesc = -o.type; // assuming a number
 });
 _.sortBy(array_of_objects, ['typeDesc', 'name'])

For everything else, you will need to resort to the native .sort() with a custom comparison function:

 array_of_objects.sort(function(a, b) {
     return a.type - b.type // asc
         || +(b.name>a.name)||-(a.name>b.name) // desc
         || …;
 });

Total memory used by Python process?

For Python 3.6 and psutil 5.4.5 it is easier to use memory_percent() function listed here.

import os
import psutil
process = psutil.Process(os.getpid())
print(process.memory_percent())

Load json from local file with http.get() in angular 2

If you are using Angular CLI: 7.3.3 What I did is, On my assets folder I put my fake json data then on my services I just did this.

const API_URL = './assets/data/db.json';

getAllPassengers(): Observable<PassengersInt[]> {
    return this.http.get<PassengersInt[]>(API_URL);
  }

enter image description here

Inverse of matrix in R

You can use the function ginv() (Moore-Penrose generalized inverse) in the MASS package

How to get Android crash logs?

If you're using Eclipse, make sure you use debug and not run. Make sure you are in the debug perspective (top right) You may have to hit 'Resume' (F8) a few times for the log to print. The crash log will be in the Logcat window at the bottom- double click for fullscreen and make sure you scroll to the bottom. You'll see red text for errors, the crash trace will be something like

09-04 21:35:15.228: ERROR/AndroidRuntime(778): Uncaught handler: thread main exiting due to uncaught exception
09-04 21:35:15.397: ERROR/AndroidRuntime(778): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.dazlious.android.helloworld/com.dazlious.android.helloworld.main}: java.lang.ArrayIndexOutOfBoundsException
09-04 21:35:15.397: ERROR/AndroidRuntime(778):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2268) 
09-04 21:35:15.397: ERROR/AndroidRuntime(778):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2284)
09-04 21:35:15.397: ERROR/AndroidRuntime(778):     at android.app.ActivityThread.access$1800(ActivityThread.java:112)
09-04 21:35:15.397: ERROR/AndroidRuntime(778):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1692)
09-04 21:35:15.397: ERROR/AndroidRuntime(778):     at android.os.Handler.dispatchMessage(Handler.java:99)
09-04 21:35:15.397: ERROR/AndroidRuntime(778):     at android.os.Looper.loop(Looper.java:123)
09-04 21:35:15.397: ERROR/AndroidRuntime(778):     at android.app.ActivityThread.main(ActivityThread.java:3948)
09-04 21:35:15.397: ERROR/AndroidRuntime(778):     at java.lang.reflect.Method.invokeNative(Native Method)
09-04 21:35:15.397: ERROR/AndroidRuntime(778):     at java.lang.reflect.Method.invoke(Method.java:521)
09-04 21:35:15.397: ERROR/AndroidRuntime(778):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:782)
09-04 21:35:15.397: ERROR/AndroidRuntime(778):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:540)
09-04 21:35:15.397: ERROR/AndroidRuntime(778):     at dalvik.system.NativeStart.main(Native Method)
09-04 21:35:15.397: ERROR/AndroidRuntime(778): Caused by: java.lang.ArrayIndexOutOfBoundsException
09-04 21:35:15.397: ERROR/AndroidRuntime(778):     at com.example.android.helloworld.main.onCreate(main.java:13)
09-04 21:35:15.397: ERROR/AndroidRuntime(778):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123)
09-04 21:35:15.397: ERROR/AndroidRuntime(778):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2231)
09-04 21:35:15.397: ERROR/AndroidRuntime(778):     ... 11 more

The important parts for this one are

09-04 21:35:15.397: ERROR/AndroidRuntime(778): Caused by: java.lang.ArrayIndexOutOfBoundsException
09-04 21:35:15.397: ERROR/AndroidRuntime(778):     at com.example.android.helloworld.main.onCreate(main.java:13)

those tell us it was an array out of bounds exception on on line 13 of main.java in the onCrate method.

Get LatLng from Zip Code - Google Maps API

<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY"></script>
<script>
    var latitude = '';
    var longitude = '';

    var geocoder = new google.maps.Geocoder();
    geocoder.geocode(
    { 
       componentRestrictions: { 
           country: 'IN', 
           postalCode: '744102'
       } 
    }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            latitude = results[0].geometry.location.lat();
            longitude = results[0].geometry.location.lng();
            console.log(latitude + ", " + longitude);
        } else {
            alert("Request failed.")
        }
    });
</script>

https://developers.google.com/maps/documentation/javascript/geocoding#ComponentFiltering

Inner join with 3 tables in mysql

SELECT
  student.firstname,
  student.lastname,
  exam.name,
  exam.date,
  grade.grade
FROM grade
 INNER JOIN student
   ON student.studentId = grade.fk_studentId
 INNER JOIN exam
   ON exam.examId = grade.fk_examId
 GROUP BY grade.gradeId
 ORDER BY exam.date

Can a div have multiple classes (Twitter Bootstrap)

Sure, a div can have as many classes as you want (this is both regarding to bootstrap and HTML in general):

<div class="active dropdown-toggle"></div>

Just separate the classes by space.

Also: Keep in mind some bootstrap classes are supposed to be used for the same stuff but in different cases (for example alignment classes, you might want something aligned left, right or center, but it has to be only one of them) and you shouldn't use them together, or you'd get an unexpected result, basically what will happen is that the class with the highest specificity will be the one applied (or if they have the same then it'll be the one that's defined last on the CSS). So you better avoid doing stuff like this:

<p class="text-center text-left">Some text</p>

Does WGET timeout?

The default timeout is 900 second. You can specify different timeout.

-T seconds
--timeout=seconds

The default is to retry 20 times. You can specify different tries.

-t number
--tries=number

link: wget man document

Find the item with maximum occurrences in a list

My (simply) code (three months studying Python):

def more_frequent_item(lst):
    new_lst = []
    times = 0
    for item in lst:
        count_num = lst.count(item)
        new_lst.append(count_num)
        times = max(new_lst)
    key = max(lst, key=lst.count)
    print("In the list: ")
    print(lst)
    print("The most frequent item is " + str(key) + ". Appears " + str(times) + " times in this list.")


more_frequent_item([1, 2, 45, 55, 5, 4, 4, 4, 4, 4, 4, 5456, 56, 6, 7, 67])

The output will be:

In the list: 
[1, 2, 45, 55, 5, 4, 4, 4, 4, 4, 4, 5456, 56, 6, 7, 67]
The most frequent item is 4. Appears 6 times in this list.

Android check null or empty string in Android

This worked for me

EditText   etname = (EditText) findViewById(R.id.etname);
 if(etname.length() == 0){
                    etname.setError("Required field");
                }else{
                    Toast.makeText(getApplicationContext(),"Saved",Toast.LENGTH_LONG).show();
                }

or Use this for strings

String DEP_DATE;
if (DEP_DATE.equals("") || DEP_DATE.length() == 0 || DEP_DATE.isEmpty() || DEP_DATE == null){
}

Kill detached screen session

You can kill a detached session which is not responding within the screen session by doing the following.

  1. Type screen -list to identify the detached screen session.

    ~$ screen -list  
        There are screens on:  
             20751.Melvin_Peter_V42  (Detached)  
    

    Note: 20751.Melvin_Peter_V42 is your session id.

  2. Get attached to the detached screen session

    screen -r 20751.Melvin_Peter_V42
  3. Once connected to the session press Ctrl + A then type :quit

Changing the position of Bootstrap popovers based on the popover's X position in relation to window edge?

You can also try this one if u need it in almost all places in the page.

U can configure it in a general way then just use it.

In this way u can also use HTML element and anything u want :)

_x000D_
_x000D_
$(document).ready(function()_x000D_
                  {_x000D_
  var options =_x000D_
      {_x000D_
        placement: function (context, source)_x000D_
        {_x000D_
          var position = $(source).position();_x000D_
          var content_width = 515;  //Can be found from a JS function for more dynamic output_x000D_
          var content_height = 110;  //Can be found from a JS function for more dynamic output_x000D_
_x000D_
          if (position.left > content_width)_x000D_
          {_x000D_
            return "left";_x000D_
          }_x000D_
_x000D_
          if (position.left < content_width)_x000D_
          {_x000D_
            return "right";_x000D_
          }_x000D_
_x000D_
          if (position.top < content_height)_x000D_
          {_x000D_
            return "bottom";_x000D_
          }_x000D_
_x000D_
          return "top";_x000D_
        }_x000D_
        , trigger: "hover"_x000D_
        , animation: "true"_x000D_
        , html:"true"_x000D_
      };_x000D_
  $('[data-toggle="popover"]').popover(options);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>_x000D_
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
<div class="container">_x000D_
 <h3>Popover Example</h3>_x000D_
 <a id="try_ppover" href="#" data-toggle="popover" title="Popover HTML Header" data-content="<div class='jumbotron'>Some HTML content inside the popover</div>">Toggle popover</a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Addition


For setting more options, u can go here.

Even more can be found here.

Update


If u want the popup after click, u can change the JS option to trigger: "click" like this-

        return ..;
    }
    ......
    , trigger: "click"
    ......
};

U also can customize it in HTML ading data-trigger="click" like this-

<a id="try_ppover" href="#" data-toggle="popover" data-trigger="click" title="Popover Header" data-content="<div class='jumbotron'>Some content inside the popover</div>">Toggle popover</a>

I think it will be more oriented code and more re-usable and more helpful to all :).

How to sort by Date with DataTables jquery plugin?

As of 2015, the most convenient way according to me to sort Date column in a DataTable, is using the required sort plugin. Since the date format in my case was dd/mm/yyyy hh:mm:ss, I ended up using the date-euro plugin. All one needs to do is:

Step 1: Include the sorting plugin JavaScript file or code and;

Step 2: Add columnDefs as shown below to target appropriate column(s).

$('#example').dataTable( {
    columnDefs: [
       { type: 'date-euro', targets: 0 }
    ]
});

VBA - how to conditionally skip a for loop iteration

Hi I am also facing this issue and I solve this using below example code

For j = 1 To MyTemplte.Sheets.Count

       If MyTemplte.Sheets(j).Visible = 0 Then
           GoTo DoNothing        
       End If 


'process for this for loop
DoNothing:

Next j 

"cannot be used as a function error"

This line is the problem:

int estimatedPopulation (int currentPopulation,
                         float growthRate (birthRate, deathRate))

Make it:

int estimatedPopulation (int currentPopulation, float birthRate, float deathRate)

instead and invoke the function with three arguments like

estimatePopulation( currentPopulation, birthRate, deathRate );

OR declare it with two arguments like:

int estimatedPopulation (int currentPopulation, float growthrt ) { ... }

and call it as

estimatedPopulation( currentPopulation, growthRate (birthRate, deathRate));

Edit:

Probably more important here - C++ (and C) names have scope. You can have two things named the same but not at the same time. In your particular case your grouthRate variable in the main() hides the function with the same name. So within main() you can only access grouthRate as float. On the other hand, outside of the main() you can only access that name as a function, since that automatic variable is only visible within the scope of main().

Just hope I didn't confuse you further :)

Eclipse DDMS error "Can't bind to local 8600 for debugger"

Don't uninstall, this is just a dumb thing done by the system which as trouble finding localhost it seems. Take a look in here, it's quite easy to fix. I had the same issue a few weeks ago and solved it this way.

the window Host file that is messed up:
the file is at this place :
C:\WINDOWS\system32\drivers\etc

And should contain this line : 127.0.0.1 localhost

How to check the input is an integer or not in Java?

You can use try-catch block to check for integer value

for eg:

User inputs in form of string

try
{
   int num=Integer.parseInt("Some String Input");
}
catch(NumberFormatException e)
{
  //If number is not integer,you wil get exception and exception message will be printed
  System.out.println(e.getMessage());
}

String.equals versus ==

Use Split rather than tokenizer,it will surely provide u exact output for E.g:

string name="Harry";
string salary="25000";
string namsal="Harry 25000";
string[] s=namsal.split(" ");
for(int i=0;i<s.length;i++)
{
System.out.println(s[i]);
}
if(s[0].equals("Harry"))
{
System.out.println("Task Complete");
}

After this I am sure you will get better results.....

How do I invoke a Java method when given the method name as a string?

For those who are calling the method within the same class from a non-static method, see below codes:

class Person {
    public void method1() {
        try {
            Method m2 = this.getClass().getDeclaredMethod("method2");
            m1.invoke(this);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    public void method2() {
        // Do something
    }

}

How do I show/hide a UIBarButtonItem?

Improving From @lnafziger answer

Save your Barbuttons in a strong outlet and do this to hide/show it:

-(void) hideBarButtonItem :(UIBarButtonItem *)myButton {
    // Get the reference to the current toolbar buttons
    NSMutableArray *navBarBtns = [self.navigationItem.rightBarButtonItems mutableCopy];

    // This is how you remove the button from the toolbar and animate it
    [navBarBtns removeObject:myButton];
    [self.navigationItem setRightBarButtonItems:navBarBtns animated:YES];
}


-(void) showBarButtonItem :(UIBarButtonItem *)myButton {
    // Get the reference to the current toolbar buttons
    NSMutableArray *navBarBtns = [self.navigationItem.rightBarButtonItems mutableCopy];

    // This is how you add the button to the toolbar and animate it
    if (![navBarBtns containsObject:myButton]) {
        [navBarBtns addObject:myButton];
        [self.navigationItem setRightBarButtonItems:navBarBtns animated:YES];
    }
}

When ever required use below Function..

[self showBarButtonItem:self.rightBarBtn1];
[self hideBarButtonItem:self.rightBarBtn1];

Onclick event to remove default value in a text input field

This should do it:

HTML

<input name="Name" value="Enter Your Name" onClick="blankDefault('Enter Your Name', this)">

JavaScript

function blankDefault(_text, _this) {
    if(_text == _this.value)
        _this.value = '';
}

There are better/less obtrusive ways though, but this will get the job done.

AVD Manager - No system image installed for this target

Open your Android SDK Manager and ensure that you download/install a system image for the API level you are developing with.

ImportError: No module named xlsxwriter

I have the same issue. It seems that pip is the problem. Try

pip uninstall xlsxwriter
easy_install xlsxwriter

Jquery open popup on button click for bootstrap

Give an ID to uniquely identify the button, lets say myBtn

// when DOM is ready
$(document).ready(function () {

     // Attach Button click event listener 
    $("#myBtn").click(function(){

         // show Modal
         $('#myModal').modal('show');
    });
});

JSFIDDLE

eloquent laravel: How to get a row count from a ->get()

Its better to access the count with the laravels count method

$count = Model::where('status','=','1')->count();

or

$count = Model::count();

Selecting Values from Oracle Table Variable / Array?

In Oracle, the PL/SQL and SQL engines maintain some separation. When you execute a SQL statement within PL/SQL, it is handed off to the SQL engine, which has no knowledge of PL/SQL-specific structures like INDEX BY tables.

So, instead of declaring the type in the PL/SQL block, you need to create an equivalent collection type within the database schema:

CREATE OR REPLACE TYPE array is table of number;
/

Then you can use it as in these two examples within PL/SQL:

SQL> l
  1  declare
  2    p  array := array();
  3  begin
  4    for i in (select level from dual connect by level < 10) loop
  5      p.extend;
  6      p(p.count) := i.level;
  7    end loop;
  8    for x in (select column_value from table(cast(p as array))) loop
  9       dbms_output.put_line(x.column_value);
 10    end loop;
 11* end;
SQL> /
1
2
3
4
5
6
7
8
9

PL/SQL procedure successfully completed.

SQL> l
  1  declare
  2    p  array := array();
  3  begin
  4    select level bulk collect into p from dual connect by level < 10;
  5    for x in (select column_value from table(cast(p as array))) loop
  6       dbms_output.put_line(x.column_value);
  7    end loop;
  8* end;
SQL> /
1
2
3
4
5
6
7
8
9

PL/SQL procedure successfully completed.

Additional example based on comments

Based on your comment on my answer and on the question itself, I think this is how I would implement it. Use a package so the records can be fetched from the actual table once and stored in a private package global; and have a function that returns an open ref cursor.

CREATE OR REPLACE PACKAGE p_cache AS
  FUNCTION get_p_cursor RETURN sys_refcursor;
END p_cache;
/

CREATE OR REPLACE PACKAGE BODY p_cache AS

  cache_array  array;

  FUNCTION get_p_cursor RETURN sys_refcursor IS
    pCursor  sys_refcursor;
  BEGIN
    OPEN pCursor FOR SELECT * from TABLE(CAST(cache_array AS array));
    RETURN pCursor;
  END get_p_cursor;

  -- Package initialization runs once in each session that references the package
  BEGIN
    SELECT level BULK COLLECT INTO cache_array FROM dual CONNECT BY LEVEL < 10;
  END p_cache;
/

Convert an int to ASCII character

This is how I converted a number to an ASCII code. 0 though 9 in hex code is 0x30-0x39. 6 would be 0x36.

unsigned int temp = 6;
or you can use unsigned char temp = 6;
unsigned char num;
 num = 0x30| temp;

this will give you the ASCII value for 6. You do the same for 0 - 9

to convert ASCII to a numeric value I came up with this code.

unsigned char num,code;
code = 0x39; // ASCII Code for 9 in Hex
num = 0&0F & code;

Best IDE for HTML5, Javascript, CSS, Jquery support with GUI building tools

My personal experience to build website with html, css en javascript is just to stick with plain text editors with ftp support. I am using Espresso or/and Coda on my mac. But Textmate with Cyberduck(ftp client) is also a great combination, imo. For developing in Windows I recommend notepad++.

What's the foolproof way to tell which version(s) of .NET are installed on a production Windows Server?

To get the installed dotnet version,
Create a Console app. Add this class Run that

using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    public class GetDotNetVersion
    {
        public static void Get45PlusFromRegistry()
        {
            const string subkey = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\";
            using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(subkey))
            {
                if (ndpKey != null && ndpKey.GetValue("Release") != null)
                {
                    Console.WriteLine(".NET Framework Version: " + CheckFor45PlusVersion((int)ndpKey.GetValue("Release")));
                }
                else
                {
                    Console.WriteLine(".NET Framework Version 4.5 or later is not detected.");
                }
            }
        }

        // Checking the version using >= will enable forward compatibility.
        private static string CheckFor45PlusVersion(int releaseKey)
        {
            if (releaseKey >= 394802)
                return "4.6.2 or later";
            if (releaseKey >= 394254)
            {
                return "4.6.1";
            }
            if (releaseKey >= 393295)
            {
                return "4.6";
            }
            if ((releaseKey >= 379893))
            {
                return "4.5.2";
            }
            if ((releaseKey >= 378675))
            {
                return "4.5.1";
            }
            if ((releaseKey >= 378389))
            {
                return "4.5";
            }
            // This code should never execute. A non-null release key shoul
            // that 4.5 or later is installed.
            return "No 4.5 or later version detected";
        }
    }
    // Calling the GetDotNetVersion.Get45PlusFromRegistry method produces 
    // output like the following:
    //       .NET Framework Version: 4.6.1
}

C++ - unable to start correctly (0xc0150002)

I met such problem. Visual Studio 2008 clearly said: problem was caused by libtiff.dll. It cannot be loaded for some reasom, caused by its manifest (as a matter of fact, this dll has no manifest at all). I fixed it, when I had removed libtiff.dll from my project (but simultaneously I lost ability to open compressed TIFFs!). I recompiled aforementioned dll, but problem still remains. Interesting, that at my own machine I have no such error. Three others comps refused to load my prog. Attention!!! Here http://www.error-repair-tools.com/ppc/error.php?t=0xc0150002 one wise boy wrote, that this error was caused by problem with registry and offers repair tool. I have a solid guess, that this "repair tool" will install some malicious soft at your comp.

How to get Spinner value?

Yes, you can register a listener via setOnItemSelectedListener(), as is demonstrated here.

Has Facebook sharer.php changed to no longer accept detailed parameters?

Facebook no longer supports custom parameters in sharer.php

The sharer will no longer accept custom parameters and facebook will pull the information that is being displayed in the preview the same way that it would appear on facebook as a post from the url OG meta tags.

Use dialog/feeds instead of sharer.php

https://www.facebook.com/dialog/feed?
  app_id=145634995501895
  &display=popup&caption=An%20example%20caption 
  &link=https%3A%2F%2Fdevelopers.facebook.com%2Fdocs%2Fdialogs%2F
  &redirect_uri=https://developers.facebook.com/tools/explorer

Official answer from fb team

list all files in the folder and also sub folders

You can return a List instead of an array and things gets much simpler.

    public static List<File> listf(String directoryName) {
        File directory = new File(directoryName);

        List<File> resultList = new ArrayList<File>();

        // get all the files from a directory
        File[] fList = directory.listFiles();
        resultList.addAll(Arrays.asList(fList));
        for (File file : fList) {
            if (file.isFile()) {
                System.out.println(file.getAbsolutePath());
            } else if (file.isDirectory()) {
                resultList.addAll(listf(file.getAbsolutePath()));
            }
        }
        //System.out.println(fList);
        return resultList;
    } 

HTML display result in text (input) field?

With .value and INPUT tag

<HTML>
  <HEAD>
    <TITLE>Sum</TITLE>

    <script type="text/javascript">
      function sum()
      {

         var num1 = document.myform.number1.value;
         var num2 = document.myform.number2.value;
         var sum = parseInt(num1) + parseInt(num2);
         document.getElementById('add').value = sum;
      }
    </script>
  </HEAD>

  <BODY>
    <FORM NAME="myform">
      <INPUT TYPE="text" NAME="number1" VALUE=""/> + 
      <INPUT TYPE="text" NAME="number2" VALUE=""/>
      <INPUT TYPE="button" NAME="button" Value="=" onClick="sum()"/>
      <INPUT TYPE="text" ID="add" NAME="result" VALUE=""/>
    </FORM>

  </BODY>
</HTML>

with innerHTML and DIV

<HTML>
  <HEAD>
    <TITLE>Sum</TITLE>

    <script type="text/javascript">
      function sum()
      {

         var num1 = document.myform.number1.value;
         var num2 = document.myform.number2.value;
         var sum = parseInt(num1) + parseInt(num2);
         document.getElementById('add').innerHTML = sum;
      }
    </script>
  </HEAD>

  <BODY>
    <FORM NAME="myform">
      <INPUT TYPE="text" NAME="number1" VALUE=""/> + 
      <INPUT TYPE="text" NAME="number2" VALUE=""/>
      <INPUT TYPE="button" NAME="button" Value="=" onClick="sum()"/>
      <DIV  ID="add"></DIV>
    </FORM>

  </BODY>
</HTML>

How to check if internet connection is present in Java?

I usually break it down into three steps.

  1. I first see if I can resolve the domain name to an IP address.
  2. I then try to connect via TCP (port 80 and/or 443) and close gracefully.
  3. Finally, I'll issue an HTTP request and check for a 200 response back.

If it fails at any point, I provide the appropriate error message to the user.

How to search all loaded scripts in Chrome Developer Tools?

In Widows it is working for me. Control Shift F and then it opens a search window at the bottom. Make sure you expand the bottom area to see the new search window.

enter image description here

How to convert a color integer to a hex String in Android?

The mask makes sure you only get RRGGBB, and the %06X gives you zero-padded hex (always 6 chars long):

String hexColor = String.format("#%06X", (0xFFFFFF & intColor));

Best/Most Comprehensive API for Stocks/Financial Data

Last I looked -- a couple of years ago -- there wasn't an easy option and the "solution" (which I did not agree with) was screen-scraping a number of websites. It may be easier now but I would still be surprised to see something, well, useful.

The problem here is that the data is immensely valuable (and very expensive), so while defining a method of retrieving it would be easy, getting the trading venues to part with their data would be next to impossible. Some of the MTFs (currently) provide their data for free but I'm not sure how you would get it without paying someone else, like Reuters, for it.

Windows Application has stopped working :: Event Name CLR20r3

Some times this problem arise when Application is build in one PC and try to run another PC. And also build the application with Visual Studio 2010.I have the following problem

Problem Description
    Stop Working
Problem Signature
  Problem Event Name:   CLR20r3
  Problem Signature 01: diagnosticcentermngr.exe
  Problem Signature 02: 1.0.0.0
  Problem Signature 03: 4f8c1772
  Problem Signature 04: System.Drawing
  Problem Signature 05: 2.0.0.0
  Problem Signature 06: 4a275e83
  Problem Signature 07: 7af
  Problem Signature 08: 6c
  Problem Signature 09: System.ArgumentException
  OS Version:   6.1.7600.2.0.0.256.1
  Locale ID:    1033

Read our privacy statement online:
  http://go.microsoft.com/fwlink/?linkid=104288&clcid=0x0409

If the online privacy statement is not available, please read our privacy statement offline:
  C:\Windows\system32\en-US\erofflps.txt

Dont worry, Please check out following link and install .net framework 4.Although my application .net properties was .net framework 2.

http://www.microsoft.com/download/en/details.aspx?id=17718

restart your PC and try again.

Convert file to byte array and vice versa

You cannot do it for File, which is primarily an intelligent file path. Can you refactor your code so that it declares the variables, and passes around arguments, with type OutputStream instead of FileOutputStream? If so, see classes java.io.ByteArrayOutputStream and java.io.ByteArrayInputStream

OutputStream outStream = new ByteArrayOutputStream();
outStream.write(whatever);
outStream.close();
byte[] data = outStream.toByteArray();
InputStream inStream = new ByteArrayInputStream(data);
...

Prevent Default on Form Submit jQuery

$(document).ready(function(){
    $("#form_id").submit(function(){
        return condition;
    });
});

error: member access into incomplete type : forward declaration of

You must have the definition of class B before you use the class. How else would the compiler otherwise know that there exists such a function as B::add?

Either define class B before class A, or move the body of A::doSomething to after class B have been defined, like

class B;

class A
{
    B* b;

    void doSomething();
};

class B
{
    A* a;

    void add() {}
};

void A::doSomething()
{
    b->add();
}

SQL Server: Get data for only the past year

The most readable, IMO:

SELECT * FROM TABLE WHERE Date >
   DATEADD(yy, -1, CONVERT(datetime, CONVERT(varchar, GETDATE(), 101)))

Which:

  1. Gets now's datetime GETDATE() = #8/27/2008 10:23am#
  2. Converts to a string with format 101 CONVERT(varchar, #8/27/2008 10:23am#, 101) = '8/27/2007'
  3. Converts to a datetime CONVERT(datetime, '8/27/2007') = #8/27/2008 12:00AM#
  4. Subtracts 1 year DATEADD(yy, -1, #8/27/2008 12:00AM#) = #8/27/2007 12:00AM#

There's variants with DATEDIFF and DATEADD to get you midnight of today, but they tend to be rather obtuse (though slightly better on performance - not that you'd notice compared to the reads required to fetch the data).

PostgreSQL : cast string to date DD/MM/YYYY

A DATE column does not have a format. You cannot specify a format for it.

You can use DateStyle to control how PostgreSQL emits dates, but it's global and a bit limited.

Instead, you should use to_char to format the date when you query it, or format it in the client application. Like:

SELECT to_char("date", 'DD/MM/YYYY') FROM mytable;

e.g.

regress=> SELECT to_char(DATE '2014-04-01', 'DD/MM/YYYY');
  to_char   
------------
 01/04/2014
(1 row)

How to connect a Windows Mobile PDA to Windows 10

I haven't managed to get WMDC working on Windows 10 (it hanged on splash screen upon start), so I've finally uninstalled it. But now I have a Portable Devices / Compact device in the Device Manager and I can browse my Windows Compact 7 device within Windows Explorer. All my apps using RAPI also work. Maybe this is the result of installing/uninstalling WMDC, or probably this functionality was already presented on Windows 10 and I've just overlooked it initially.

Call to getLayoutInflater() in places not in activity

You can use this outside activities - all you need is to provide a Context:

LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );

Then to retrieve your different widgets, you inflate a layout:

View view = inflater.inflate( R.layout.myNewInflatedLayout, null );
Button myButton = (Button) view.findViewById( R.id.myButton );

EDIT as of July 2014

Davide's answer on how to get the LayoutInflater is actually more correct than mine (which is still valid though).

library not found for -lPods

I found that selecting "Find implicit Dependencies" (under product / edit scheme) will resolve this issue instead of having to add pods as a target.

ValueError : I/O operation on closed file

I was getting this exception when debugging in PyCharm, given that no breakpoint was being hit. To prevent it, I added a breakpoint just after the with block, and then it stopped happening.

Call a method of a controller from another controller using 'scope' in AngularJS

Here is good Demo in Fiddle how to use shared service in directive and other controllers through $scope.$on

HTML

<div ng-controller="ControllerZero">
    <input ng-model="message" >
    <button ng-click="handleClick(message);">BROADCAST</button>
</div>

<div ng-controller="ControllerOne">
    <input ng-model="message" >
</div>

<div ng-controller="ControllerTwo">
    <input ng-model="message" >
</div>

<my-component ng-model="message"></my-component>

JS

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

myModule.factory('mySharedService', function($rootScope) {
    var sharedService = {};

    sharedService.message = '';

    sharedService.prepForBroadcast = function(msg) {
        this.message = msg;
        this.broadcastItem();
    };

    sharedService.broadcastItem = function() {
        $rootScope.$broadcast('handleBroadcast');
    };

    return sharedService;
});

By the same way we can use shared service in directive. We can implement controller section into directive and use $scope.$on

myModule.directive('myComponent', function(mySharedService) {
    return {
        restrict: 'E',
        controller: function($scope, $attrs, mySharedService) {
            $scope.$on('handleBroadcast', function() {
                $scope.message = 'Directive: ' + mySharedService.message;
            });
        },
        replace: true,
        template: '<input>'
    };
});

And here three our controllers where ControllerZero used as trigger to invoke prepForBroadcast

function ControllerZero($scope, sharedService) {
    $scope.handleClick = function(msg) {
        sharedService.prepForBroadcast(msg);
    };

    $scope.$on('handleBroadcast', function() {
        $scope.message = sharedService.message;
    });
}

function ControllerOne($scope, sharedService) {
    $scope.$on('handleBroadcast', function() {
        $scope.message = 'ONE: ' + sharedService.message;
    });
}

function ControllerTwo($scope, sharedService) {
    $scope.$on('handleBroadcast', function() {
        $scope.message = 'TWO: ' + sharedService.message;
    });
}

The ControllerOne and ControllerTwo listen message change by using $scope.$on handler.

Bootstrap Carousel : Remove auto slide

From the official docs:

interval The amount of time to delay between automatically cycling an item. If false, carousel will not automatically cycle.

You can either pass this value with javascript or using a data-interval="false" attribute.

Sort rows in data.table in decreasing order on string key `order(-x,v)` gives error on data.table 1.9.4 or earlier

Update

data.table v1.9.6+ now supports OP's original attempt and the following answer is no longer necessary.


You can use DT[order(-rank(x), y)].

   x y v
1: c 1 7
2: c 3 8
3: c 6 9
4: b 1 1
5: b 3 2
6: b 6 3
7: a 1 4
8: a 3 5
9: a 6 6

Generate your own Error code in swift 3

You can create enums to deal with errors :)

enum RikhError: Error {
    case unknownError
    case connectionError
    case invalidCredentials
    case invalidRequest
    case notFound
    case invalidResponse
    case serverError
    case serverUnavailable
    case timeOut
    case unsuppotedURL
 }

and then create a method inside enum to receive the http response code and return the corresponding error in return :)

static func checkErrorCode(_ errorCode: Int) -> RikhError {
        switch errorCode {
        case 400:
            return .invalidRequest
        case 401:
            return .invalidCredentials
        case 404:
            return .notFound
        //bla bla bla
        default:
            return .unknownError
        }
    }

Finally update your failure block to accept single parameter of type RikhError :)

I have a detailed tutorial on how to restructure traditional Objective - C based Object Oriented network model to modern Protocol Oriented model using Swift3 here https://learnwithmehere.blogspot.in Have a look :)

Hope it helps :)

Is floating point math broken?

A Hardware Designer's Perspective

I believe I should add a hardware designer’s perspective to this since I design and build floating point hardware. Knowing the origin of the error may help in understanding what is happening in the software, and ultimately, I hope this helps explain the reasons for why floating point errors happen and seem to accumulate over time.

1. Overview

From an engineering perspective, most floating point operations will have some element of error since the hardware that does the floating point computations is only required to have an error of less than one half of one unit in the last place. Therefore, much hardware will stop at a precision that's only necessary to yield an error of less than one half of one unit in the last place for a single operation which is especially problematic in floating point division. What constitutes a single operation depends upon how many operands the unit takes. For most, it is two, but some units take 3 or more operands. Because of this, there is no guarantee that repeated operations will result in a desirable error since the errors add up over time.

2. Standards

Most processors follow the IEEE-754 standard but some use denormalized, or different standards . For example, there is a denormalized mode in IEEE-754 which allows representation of very small floating point numbers at the expense of precision. The following, however, will cover the normalized mode of IEEE-754 which is the typical mode of operation.

In the IEEE-754 standard, hardware designers are allowed any value of error/epsilon as long as it's less than one half of one unit in the last place, and the result only has to be less than one half of one unit in the last place for one operation. This explains why when there are repeated operations, the errors add up. For IEEE-754 double precision, this is the 54th bit, since 53 bits are used to represent the numeric part (normalized), also called the mantissa, of the floating point number (e.g. the 5.3 in 5.3e5). The next sections go into more detail on the causes of hardware error on various floating point operations.

3. Cause of Rounding Error in Division

The main cause of the error in floating point division is the division algorithms used to calculate the quotient. Most computer systems calculate division using multiplication by an inverse, mainly in Z=X/Y, Z = X * (1/Y). A division is computed iteratively i.e. each cycle computes some bits of the quotient until the desired precision is reached, which for IEEE-754 is anything with an error of less than one unit in the last place. The table of reciprocals of Y (1/Y) is known as the quotient selection table (QST) in the slow division, and the size in bits of the quotient selection table is usually the width of the radix, or a number of bits of the quotient computed in each iteration, plus a few guard bits. For the IEEE-754 standard, double precision (64-bit), it would be the size of the radix of the divider, plus a few guard bits k, where k>=2. So for example, a typical Quotient Selection Table for a divider that computes 2 bits of the quotient at a time (radix 4) would be 2+2= 4 bits (plus a few optional bits).

3.1 Division Rounding Error: Approximation of Reciprocal

What reciprocals are in the quotient selection table depend on the division method: slow division such as SRT division, or fast division such as Goldschmidt division; each entry is modified according to the division algorithm in an attempt to yield the lowest possible error. In any case, though, all reciprocals are approximations of the actual reciprocal and introduce some element of error. Both slow division and fast division methods calculate the quotient iteratively, i.e. some number of bits of the quotient are calculated each step, then the result is subtracted from the dividend, and the divider repeats the steps until the error is less than one half of one unit in the last place. Slow division methods calculate a fixed number of digits of the quotient in each step and are usually less expensive to build, and fast division methods calculate a variable number of digits per step and are usually more expensive to build. The most important part of the division methods is that most of them rely upon repeated multiplication by an approximation of a reciprocal, so they are prone to error.

4. Rounding Errors in Other Operations: Truncation

Another cause of the rounding errors in all operations are the different modes of truncation of the final answer that IEEE-754 allows. There's truncate, round-towards-zero, round-to-nearest (default), round-down, and round-up. All methods introduce an element of error of less than one unit in the last place for a single operation. Over time and repeated operations, truncation also adds cumulatively to the resultant error. This truncation error is especially problematic in exponentiation, which involves some form of repeated multiplication.

5. Repeated Operations

Since the hardware that does the floating point calculations only needs to yield a result with an error of less than one half of one unit in the last place for a single operation, the error will grow over repeated operations if not watched. This is the reason that in computations that require a bounded error, mathematicians use methods such as using the round-to-nearest even digit in the last place of IEEE-754, because, over time, the errors are more likely to cancel each other out, and Interval Arithmetic combined with variations of the IEEE 754 rounding modes to predict rounding errors, and correct them. Because of its low relative error compared to other rounding modes, round to nearest even digit (in the last place), is the default rounding mode of IEEE-754.

Note that the default rounding mode, round-to-nearest even digit in the last place, guarantees an error of less than one half of one unit in the last place for one operation. Using the truncation, round-up, and round down alone may result in an error that is greater than one half of one unit in the last place, but less than one unit in the last place, so these modes are not recommended unless they are used in Interval Arithmetic.

6. Summary

In short, the fundamental reason for the errors in floating point operations is a combination of the truncation in hardware, and the truncation of a reciprocal in the case of division. Since the IEEE-754 standard only requires an error of less than one half of one unit in the last place for a single operation, the floating point errors over repeated operations will add up unless corrected.

How do I get the raw request body from the Request.Content object using .net 4 api endpoint

For other future users who do not want to make their controllers asynchronous, or cannot access the HttpContext, or are using dotnet core (this answer is the first I found on Google trying to do this), the following worked for me:

[HttpPut("{pathId}/{subPathId}"),
public IActionResult Put(int pathId, int subPathId, [FromBody] myViewModel viewModel)
{

    var body = new StreamReader(Request.Body);
    //The modelbinder has already read the stream and need to reset the stream index
    body.BaseStream.Seek(0, SeekOrigin.Begin); 
    var requestBody = body.ReadToEnd();
    //etc, we use this for an audit trail
}

How to vertically center <div> inside the parent element with CSS?

if you are using fix height div than you can use padding-top according your design need. or you can use top:50%. if we are using div than vertical align does not work so we use padding top or position according need.

Writing files in Node.js

fs.createWriteStream(path[,options])

options may also include a start option to allow writing data at some position past the beginning of the file. Modifying a file rather than replacing it may require a flags mode of r+ rather than the default mode w. The encoding can be any one of those accepted by Buffer.

If autoClose is set to true (default behavior) on 'error' or 'finish' the file descriptor will be closed automatically. If autoClose is false, then the file descriptor won't be closed, even if there's an error. It is the application's responsibility to close it and make sure there's no file descriptor leak.

Like ReadStream, if fd is specified, WriteStream will ignore the path argument and will use the specified file descriptor. This means that no 'open' event will be emitted. fd should be blocking; non-blocking fds should be passed to net.Socket.

If options is a string, then it specifies the encoding.

After, reading this long article. You should understand how it works. So, here's an example of createWriteStream().

/* The fs.createWriteStream() returns an (WritableStream {aka} internal.Writeable) and we want the encoding as 'utf'-8 */
/* The WriteableStream has the method write() */
fs.createWriteStream('out.txt', 'utf-8')
.write('hello world');

How do I vertically align text in a div?

Here's a great resource

From http://howtocenterincss.com/:

Centering in CSS is a pain in the ass. There seems to be a gazillion ways to do it, depending on a variety of factors. This consolidates them and gives you the code you need for each situation.

Using Flexbox

Inline with keeping this post up to date with the latest tech, here's a much easier way to center something using Flexbox. Flexbox isn't supported in Internet Explorer 9 and lower.

Here are some great resources:

JSFiddle with browser prefixes

_x000D_
_x000D_
li {_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
  align-content: center;_x000D_
  flex-direction: column;_x000D_
  /* Column | row */_x000D_
}
_x000D_
<ul>_x000D_
  <li>_x000D_
    <p>Some Text</p>_x000D_
  </li>_x000D_
  <li>_x000D_
    <p>A bit more text that goes on two lines</p>_x000D_
  </li>_x000D_
  <li>_x000D_
    <p>Even more text that demonstrates how lines can span multiple lines</p>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Another solution

This is from zerosixthree and lets you center anything with six lines of CSS

This method isn't supported in Internet Explorer 8 and lower.

jsfiddle

_x000D_
_x000D_
p {_x000D_
  text-align: center;_x000D_
  position: relative;_x000D_
  top: 50%;_x000D_
  -ms-transform: translateY(-50%);_x000D_
  -webkit-transform: translateY(-50%);_x000D_
  transform: translateY(-50%);_x000D_
}
_x000D_
<ul>_x000D_
  <li>_x000D_
    <p>Some Text</p>_x000D_
  </li>_x000D_
  <li>_x000D_
    <p>A bit more text that goes on two lines</p>_x000D_
  </li>_x000D_
  <li>_x000D_
    <p>Even more text that demonstrates how lines can span multiple lines</p>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Previous answer

A simple and cross-browser approach, useful as links in the marked answer are slightly outdated.

How to vertically and horizontally center text in both an unordered list and a div without resorting to JavaScript or CSS line heights. No matter how much text you have you won't have to apply any special classes to specific lists or divs (the code is the same for each). This works on all major browsers including Internet Explorer 9, Internet Explorer 8, Internet Explorer 7, Internet Explorer 6, Firefox, Chrome, Opera and Safari. There are two special stylesheets (one for Internet Explorer 7 and another for Internet Explorer 6) to help them along due to their CSS limitations which modern browsers don't have.

Andy Howard - How to vertically and horizontally center text in an unordered list or div

As I didn't care much for Internet Explorer 7/6 for the last project I worked on, I used a slightly stripped down version (i.e. removed the stuff that made it work in Internet Explorer 7 and 6). It might be useful for somebody else...

JSFiddle

_x000D_
_x000D_
.outerContainer {_x000D_
  display: table;_x000D_
  width: 100px;_x000D_
  /* Width of parent */_x000D_
  height: 100px;_x000D_
  /* Height of parent */_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
.outerContainer .innerContainer {_x000D_
  display: table-cell;_x000D_
  vertical-align: middle;_x000D_
  width: 100%;_x000D_
  margin: 0 auto;_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
li {_x000D_
  background: #ddd;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
}
_x000D_
<ul>_x000D_
  <li>_x000D_
    <div class="outerContainer">_x000D_
      <div class="innerContainer">_x000D_
        <div class="element">_x000D_
          <p>_x000D_
            <!-- Content -->_x000D_
            Content_x000D_
          </p>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </li>_x000D_
_x000D_
  <li>_x000D_
    <div class="outerContainer">_x000D_
      <div class="innerContainer">_x000D_
        <div class="element">_x000D_
          <p>_x000D_
            <!-- Content -->_x000D_
            Content_x000D_
          </p>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

What is external linkage and internal linkage?

Before talking about the question, it is better to know the term translation unit, program and some basic concepts of C++ (actually linkage is one of them in general) precisely. You will also have to know what is a scope.

I will emphasize some key points, esp. those missing in previous answers.

Linkage is a property of a name, which is introduced by a declaration. Different names can denote same entity (typically, an object or a function). So talking about linkage of an entity is usually nonsense, unless you are sure that the entity will only be referred by the unique name from some specific declarations (usually one declaration, though).

Note an object is an entity, but a variable is not. While talking about the linkage of a variable, actually the name of the denoted entity (which is introduced by a specific declaration) is concerned. The linkage of the name is in one of the three: no linkage, internal linkage or external linkage.

Different translation units can share the same declaration by header/source file (yes, it is the standard's wording) inclusion. So you may refer the same name in different translation units. If the name declared has external linkage, the identity of the entity referred by the name is also shared. If the name declared has internal linkage, the same name in different translation units denotes different entities, but you can refer the entity in different scopes of the same translation unit. If the name has no linkage, you simply cannot refer the entity from other scopes.

(Oops... I found what I have typed was somewhat just repeating the standard wording ...)

There are also some other confusing points which are not covered by the language specification.

  1. Visibility (of a name). It is also a property of declared name, but with a meaning different to linkage.
  2. Visibility (of a side effect). This is not related to this topic.
  3. Visibility (of a symbol). This notion can be used by actual implementations. In such implementations, a symbol with specific visibility in object (binary) code is usually the target mapped from the entity definition whose names having the same specific linkage in the source (C++) code. However, it is usually not guaranteed one-to-one. For example, a symbol in a dynamic library image can be specified only shared in that image internally from source code (involved with some extensions, typically, __attribute__ or __declspec) or compiler options, and the image is not the whole program or the object file translated from a translation unit, thus no standard concept can describe it accurately. Since symbol is not a normative term in C++, it is only an implementation detail, even though the related extensions of dialects may have been widely adopted.
  4. Accessibility. In C++, this is usually about property of class members or base classes, which is again a different concept unrelated to the topic.
  5. Global. In C++, "global" refers something of global namespace or global namespace scope. The latter is roughly equivalent to file scope in the C language. Both in C and C++, the linkage has nothing to do with scope, although scope (like linkage) is also tightly concerned with an identifier (in C) or a name (in C++) introduced by some declaration.

The linkage rule of namespace scope const variable is something special (and particularly different to the const object declared in file scope in C language which also has the concept of linkage of identifiers). Since ODR is enforced by C++, it is important to keep no more than one definition of the same variable or function occurred in the whole program except for inline functions. If there is no such special rule of const, a simplest declaration of const variable with initializers (e.g. = xxx) in a header or a source file (often a "header file") included by multiple translation units (or included by one translation unit more than once, though rarely) in a program will violate ODR, which makes to use const variable as replacement of some object-like macros impossible.

Where can I find the API KEY for Firebase Cloud Messaging?

You can also get the API key in the android studio. Switch to Project view in android then find the google-services.json. Scroll down and you will find the api_key

Android ADB stop application command like "force-stop" for non rooted device

The first way
Needs root

Use kill:

adb shell ps => Will list all running processes on the device and their process ids
adb shell kill <PID> => Instead of <PID> use process id of your application

The second way
In Eclipse open DDMS perspective.
In Devices view you will find all running processes.
Choose the process and click on Stop.

enter image description here

The third way
It will kill only background process of an application.

adb shell am kill [options] <PACKAGE> => Kill all processes associated with (the app's package name). This command kills only processes that are safe to kill and that will not impact the user experience.
Options are:

--user | all | current: Specify user whose processes to kill; all users if not specified.

The fourth way
Needs root

adb shell pm disable <PACKAGE> => Disable the given package or component (written as "package/class").

The fifth way
Note that run-as is only supported for apps that are signed with debug keys.

run-as <package-name> kill <pid>

The sixth way
Introduced in Honeycomb

adb shell am force-stop <PACKAGE> => Force stop everything associated with (the app's package name).

P.S.: I know that the sixth method didn't work for you, but I think that it's important to add this method to the list, so everyone will know it.

Center Contents of Bootstrap row container

With Bootstrap 4, there is a css class specifically for this. The below will center row content:

<div class="row justify-content-center">
  ...inner divs and content...
</div>

See: https://v4-alpha.getbootstrap.com/layout/grid/#horizontal-alignment, for more information.

C++ vector's insert & push_back difference

Beside the fact, that push_back(x) does the same as insert(x, end()) (maybe with slightly better performance), there are several important thing to know about these functions:

  1. push_back exists only on BackInsertionSequence containers - so, for example, it doesn't exist on set. It couldn't because push_back() grants you that it will always add at the end.
  2. Some containers can also satisfy FrontInsertionSequence and they have push_front. This is satisfied by deque, but not by vector.
  3. The insert(x, ITERATOR) is from InsertionSequence, which is common for set and vector. This way you can use either set or vector as a target for multiple insertions. However, set has additionally insert(x), which does practically the same thing (this first insert in set means only to speed up searching for appropriate place by starting from a different iterator - a feature not used in this case).

Note about the last case that if you are going to add elements in the loop, then doing container.push_back(x) and container.insert(x, container.end()) will do effectively the same thing. However this won't be true if you get this container.end() first and then use it in the whole loop.

For example, you could risk the following code:

auto pe = v.end();
for (auto& s: a)
    v.insert(pe, v);

This will effectively copy whole a into v vector, in reverse order, and only if you are lucky enough to not get the vector reallocated for extension (you can prevent this by calling reserve() first); if you are not so lucky, you'll get so-called UndefinedBehavior(tm). Theoretically this isn't allowed because vector's iterators are considered invalidated every time a new element is added.

If you do it this way:

copy(a.begin(), a.end(), back_inserter(v);

it will copy a at the end of v in the original order, and this doesn't carry a risk of iterator invalidation.

[EDIT] I made previously this code look this way, and it was a mistake because inserter actually maintains the validity and advancement of the iterator:

copy(a.begin(), a.end(), inserter(v, v.end());

So this code will also add all elements in the original order without any risk.