Programs & Examples On #Dscl

dscl is a general-purpose utility for operating on Directory Service directory nodes.

Authorize a non-admin developer in Xcode / Mac OS

Here is a better solution from
Mac OS X wants to use system keychain when compiling the project

  1. Open Keychain Access.
  2. In the top-left corner, unlock the keychain (if it is locked).
  3. Choose the System keychain from the top-left corner.
  4. Find your distribution certificate and click the disclosure triangle.
  5. Double-click ‘Private key’ under your distribution certificate.
  6. In the popup, go to the Access Control tab.
  7. Select ‘Allow all applications to access this item’.
  8. Save the changes.
  9. Close all windows.
  10. Run the application.

Parsing json and searching through it

Functions to search through and print dicts, like JSON. *made in python 3

Search:

def pretty_search(dict_or_list, key_to_search, search_for_first_only=False):
    """
    Give it a dict or a list of dicts and a dict key (to get values of),
    it will search through it and all containing dicts and arrays
    for all values of dict key you gave, and will return you set of them
    unless you wont specify search_for_first_only=True

    :param dict_or_list: 
    :param key_to_search: 
    :param search_for_first_only: 
    :return: 
    """
    search_result = set()
    if isinstance(dict_or_list, dict):
        for key in dict_or_list:
            key_value = dict_or_list[key]
            if key == key_to_search:
                if search_for_first_only:
                    return key_value
                else:
                    search_result.add(key_value)
            if isinstance(key_value, dict) or isinstance(key_value, list) or isinstance(key_value, set):
                _search_result = pretty_search(key_value, key_to_search, search_for_first_only)
                if _search_result and search_for_first_only:
                    return _search_result
                elif _search_result:
                    for result in _search_result:
                        search_result.add(result)
    elif isinstance(dict_or_list, list) or isinstance(dict_or_list, set):
        for element in dict_or_list:
            if isinstance(element, list) or isinstance(element, set) or isinstance(element, dict):
                _search_result = pretty_search(element, key_to_search, search_result)
                if _search_result and search_for_first_only:
                    return _search_result
                elif _search_result:
                    for result in _search_result:
                        search_result.add(result)
    return search_result if search_result else None

Print:

def pretty_print(dict_or_list, print_spaces=0):
    """
    Give it a dict key (to get values of),
    it will return you a pretty for print version
    of a dict or a list of dicts you gave.

    :param dict_or_list: 
    :param print_spaces: 
    :return: 
    """
    pretty_text = ""
    if isinstance(dict_or_list, dict):
        for key in dict_or_list:
            key_value = dict_or_list[key]
            if isinstance(key_value, dict):
                key_value = pretty_print(key_value, print_spaces + 1)
                pretty_text += "\t" * print_spaces + "{}:\n{}\n".format(key, key_value)
            elif isinstance(key_value, list) or isinstance(key_value, set):
                pretty_text += "\t" * print_spaces + "{}:\n".format(key)
                for element in key_value:
                    if isinstance(element, dict) or isinstance(element, list) or isinstance(element, set):
                        pretty_text += pretty_print(element, print_spaces + 1)
                    else:
                        pretty_text += "\t" * (print_spaces + 1) + "{}\n".format(element)
            else:
                pretty_text += "\t" * print_spaces + "{}: {}\n".format(key, key_value)
    elif isinstance(dict_or_list, list) or isinstance(dict_or_list, set):
        for element in dict_or_list:
            if isinstance(element, dict) or isinstance(element, list) or isinstance(element, set):
                pretty_text += pretty_print(element, print_spaces + 1)
            else:
                pretty_text += "\t" * print_spaces + "{}\n".format(element)
    else:
        pretty_text += str(dict_or_list)
    if print_spaces == 0:
        print(pretty_text)
    return pretty_text

Remove pandas rows with duplicate indices

If anyone like me likes chainable data manipulation using the pandas dot notation (like piping), then the following may be useful:

df3 = df3.query('~index.duplicated()')

This enables chaining statements like this:

df3.assign(C=2).query('~index.duplicated()').mean()

Python import csv to list

Next is a piece of code which uses csv module but extracts file.csv contents to a list of dicts using the first line which is a header of csv table

import csv
def csv2dicts(filename):
  with open(filename, 'rb') as f:
    reader = csv.reader(f)
    lines = list(reader)
    if len(lines) < 2: return None
    names = lines[0]
    if len(names) < 1: return None
    dicts = []
    for values in lines[1:]:
      if len(values) != len(names): return None
      d = {}
      for i,_ in enumerate(names):
        d[names[i]] = values[i]
      dicts.append(d)
    return dicts
  return None

if __name__ == '__main__':
  your_list = csv2dicts('file.csv')
  print your_list

Elastic Search: how to see the indexed data

Following @JanKlimo example, on terminal all you have to do is:

to see all the Index: $ curl -XGET 'http://127.0.0.1:9200/_cat/indices?v'

to see content of Index products_development_20160517164519304: $ curl -XGET 'http://127.0.0.1:9200/products_development_20160517164519304/_search?pretty=1'

Correct way to use get_or_create?

get_or_create returns a tuple.

customer.source, created = Source.objects.get_or_create(name="Website")

How can I generate an ObjectId with mongoose?

I needed to generate mongodb ids on client side.

After digging into the mongodb source code i found they generate ObjectIDs using npm bson lib.

If ever you need only to generate an ObjectID without installing the whole mongodb / mongoose package, you can import the lighter bson library :

const bson = require('bson');
new bson.ObjectId(); // 5cabe64dcf0d4447fa60f5e2

Note: There is also an npm project named bson-objectid being even lighter

If "0" then leave the cell blank

An example of an IF Statement that can be used to add a calculation into the cell you wish to hide if value = 0 but displayed upon another cell value reference.

=IF(/Your reference cell/=0,"",SUM(/Here you put your SUM/))

(unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

You can just put r in front of the string with your actual path, which denotes a raw string. For example:

data = open(r"C:\Users\miche\Documents\school\jaar2\MIK\2.6\vektis_agb_zorgverlener")

Exploitable PHP functions

Several buffer overflows were discovered using 4bit characters functions that interpret text. htmlentities() htmlspecialchars()

were at the top, a good defence is to use mb_convert_encoding() to convert to single encoding prior to interpretation.

Creating a simple configuration file and parser in C++

So I merged some of the above solutions into my own, which for me made more sense, became more intuitive and a bit less error prone. I use a public stp::map to keep track of the possible config ids, and a struct to keep track of the possible values. Her it goes:

struct{
    std::string PlaybackAssisted = "assisted";
    std::string Playback = "playback";
    std::string Recording = "record";
    std::string Normal = "normal";
} mode_def;

std::map<std::string, std::string> settings = {
    {"mode", mode_def.Normal},
    {"output_log_path", "/home/root/output_data.log"},
    {"input_log_path", "/home/root/input_data.log"},
};

void read_config(const std::string & settings_path){
std::ifstream settings_file(settings_path);
std::string line;

if (settings_file.fail()){
    LOG_WARN("Config file does not exist. Default options set to:");
    for (auto it = settings.begin(); it != settings.end(); it++){
        LOG_INFO("%s=%s", it->first.c_str(), it->second.c_str());
    }
}

while (std::getline(settings_file, line)){
    std::istringstream iss(line);
    std::string id, eq, val;

    if (std::getline(iss, id, '=')){
        if (std::getline(iss, val)){
            if (settings.find(id) != settings.end()){
                if (val.empty()){
                    LOG_INFO("Config \"%s\" is empty. Keeping default \"%s\"", id.c_str(), settings[id].c_str());
                }
                else{
                    settings[id] = val;
                    LOG_INFO("Config \"%s\" read as \"%s\"", id.c_str(), settings[id].c_str());
                }
            }
            else{ //Not present in map
                LOG_ERROR("Setting \"%s\" not defined, ignoring it", id.c_str());
                continue;
            }
        }
        else{
            // Comment line, skiping it
            continue;
        }
    }
    else{
        //Empty line, skipping it
        continue;            
    }
}

}

How to do paging in AngularJS?

I've extracted the relevant bits here. This is a 'no frills' tabular pager, so sorting or filtering is not included. Feel free to change/add as needed:

_x000D_
_x000D_
     //your data source may be different. the following line is _x000D_
     //just for demonstration purposes only_x000D_
    var modelData = [{_x000D_
      text: 'Test1'_x000D_
    }, {_x000D_
      text: 'Test2'_x000D_
    }, {_x000D_
      text: 'Test3'_x000D_
    }];_x000D_
_x000D_
    (function(util) {_x000D_
_x000D_
      util.PAGE_SIZE = 10;_x000D_
_x000D_
      util.range = function(start, end) {_x000D_
        var rng = [];_x000D_
_x000D_
        if (!end) {_x000D_
          end = start;_x000D_
          start = 0;_x000D_
        }_x000D_
_x000D_
        for (var i = start; i < end; i++)_x000D_
          rng.push(i);_x000D_
_x000D_
        return rng;_x000D_
      };_x000D_
_x000D_
      util.Pager = function(data) {_x000D_
        var self = this,_x000D_
          _size = util.PAGE_SIZE;;_x000D_
_x000D_
        self.current = 0;_x000D_
_x000D_
        self.content = function(index) {_x000D_
          var start = index * self.size,_x000D_
            end = (index * self.size + self.size) > data.length ? data.length : (index * self.size + self.size);_x000D_
_x000D_
          return data.slice(start, end);_x000D_
        };_x000D_
_x000D_
        self.next = function() {_x000D_
          if (!self.canPage('Next')) return;_x000D_
          self.current++;_x000D_
        };_x000D_
_x000D_
        self.prev = function() {_x000D_
          if (!self.canPage('Prev')) return;_x000D_
          self.current--;_x000D_
        };_x000D_
_x000D_
        self.canPage = function(dir) {_x000D_
          if (dir === 'Next') return self.current < self.count - 1;_x000D_
          if (dir === 'Prev') return self.current > 0;_x000D_
          return false;_x000D_
        };_x000D_
_x000D_
        self.list = function() {_x000D_
          var start, end;_x000D_
          start = self.current < 5 ? 0 : self.current - 5;_x000D_
          end = self.count - self.current < 5 ? self.count : self.current + 5;_x000D_
          return Util.range(start, end);_x000D_
        };_x000D_
_x000D_
        Object.defineProperty(self, 'size', {_x000D_
          configurable: false,_x000D_
          enumerable: false,_x000D_
          get: function() {_x000D_
            return _size;_x000D_
          },_x000D_
          set: function(val) {_x000D_
            _size = val || _size;_x000D_
          }_x000D_
        });_x000D_
_x000D_
        Object.defineProperty(self, 'count', {_x000D_
          configurable: false,_x000D_
          enumerable: false,_x000D_
          get: function() {_x000D_
            return Math.ceil(data.length / self.size);_x000D_
          }_x000D_
        });_x000D_
      };_x000D_
_x000D_
    })(window.Util = window.Util || {});_x000D_
_x000D_
    (function(ns) {_x000D_
      ns.SampleController = function($scope, $window) {_x000D_
        $scope.ModelData = modelData;_x000D_
        //instantiate pager with array (i.e. our model)_x000D_
        $scope.pages = new $window.Util.Pager($scope.ModelData);_x000D_
      };_x000D_
    })(window.Controllers = window.Controllers || {});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<table ng-controller="Controllers.SampleController">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>_x000D_
        Col1_x000D_
      </th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr ng-repeat="item in pages.content(pages.current)" title="{{item.text}}">_x000D_
      <td ng-bind-template="{{item.text}}"></td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
  <tfoot>_x000D_
    <tr>_x000D_
      <td colspan="4">_x000D_
        <a href="#" ng-click="pages.prev()">&laquo;</a>_x000D_
        <a href="#" ng-repeat="n in pages.list()" ng-click="pages.current = n" style="margin: 0 2px;">{{n + 1}}</a>_x000D_
        <a href="#" ng-click="pages.next()">&raquo;</a>_x000D_
      </td>_x000D_
    </tr>_x000D_
  </tfoot>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How do I remove objects from a JavaScript associative array?

All objects in JavaScript are implemented as hashtables/associative arrays. So, the following are the equivalent:

alert(myObj["SomeProperty"]);
alert(myObj.SomeProperty);

And, as already indicated, you "remove" a property from an object via the delete keyword, which you can use in two ways:

delete myObj["SomeProperty"];
delete myObj.SomeProperty;

Hope the extra info helps...

How to make HTML Text unselectable

No one here posted an answer with all of the correct CSS variations, so here it is:

-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;

Getting the parent of a directory in Bash

Motivation for another answer

I like very short, clear, guaranteed code. Bonus point if it does not run an external program, since the day you need to process a huge number of entries, it will be noticeably faster.

Principle

Not sure about what guarantees you have and want, so offering anyway.

If you have guarantees you can do it with very short code. The idea is to use bash text substitution feature to cut the last slash and whatever follows.

Answer from simple to more complex cases of the original question.

If path is guaranteed to end without any slash (in and out)

P=/home/smith/Desktop/Test ; echo "${P%/*}"
/home/smith/Desktop

If path is guaranteed to end with exactly one slash (in and out)

P=/home/smith/Desktop/Test/ ; echo "${P%/*/}/"
/home/smith/Desktop/

If input path may end with zero or one slash (not more) and you want output path to end without slash

for P in \
    /home/smith/Desktop/Test \
    /home/smith/Desktop/Test/
do
    P_ENDNOSLASH="${P%/}" ; echo "${P_ENDNOSLASH%/*}"
done

/home/smith/Desktop
/home/smith/Desktop

If input path may have many extraneous slashes and you want output path to end without slash

for P in \
    /home/smith/Desktop/Test \
    /home/smith/Desktop/Test/ \
    /home/smith///Desktop////Test// 
do
    P_NODUPSLASH="${P//\/*(\/)/\/}"
    P_ENDNOSLASH="${P_NODUPSLASH%%/}"
    echo "${P_ENDNOSLASH%/*}";   
done

/home/smith/Desktop
/home/smith/Desktop
/home/smith/Desktop

How to link to specific line number on github

a permalink to a code snippet is pasted into a pull request comment field

You can you use permalinks to include code snippets in issues, PRs, etc.

References:

https://help.github.com/en/articles/creating-a-permanent-link-to-a-code-snippet

How do I capture the output of a script if it is being ran by the task scheduler?

To supplement @user2744787's answer, here is a screenshot to show how to use cmd with arguments in a Scheduled Task:

Scheduled Task cmd output to logfile

Program/script: cmd

Add arguments: /c run_with_default_port.bat > IMQuantWebServices.log

UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)

I just used the following:

import unicodedata
message = unicodedata.normalize("NFKD", message)

Check what documentation says about it:

unicodedata.normalize(form, unistr) Return the normal form form for the Unicode string unistr. Valid values for form are ‘NFC’, ‘NFKC’, ‘NFD’, and ‘NFKD’.

The Unicode standard defines various normalization forms of a Unicode string, based on the definition of canonical equivalence and compatibility equivalence. In Unicode, several characters can be expressed in various way. For example, the character U+00C7 (LATIN CAPITAL LETTER C WITH CEDILLA) can also be expressed as the sequence U+0043 (LATIN CAPITAL LETTER C) U+0327 (COMBINING CEDILLA).

For each character, there are two normal forms: normal form C and normal form D. Normal form D (NFD) is also known as canonical decomposition, and translates each character into its decomposed form. Normal form C (NFC) first applies a canonical decomposition, then composes pre-combined characters again.

In addition to these two forms, there are two additional normal forms based on compatibility equivalence. In Unicode, certain characters are supported which normally would be unified with other characters. For example, U+2160 (ROMAN NUMERAL ONE) is really the same thing as U+0049 (LATIN CAPITAL LETTER I). However, it is supported in Unicode for compatibility with existing character sets (e.g. gb2312).

The normal form KD (NFKD) will apply the compatibility decomposition, i.e. replace all compatibility characters with their equivalents. The normal form KC (NFKC) first applies the compatibility decomposition, followed by the canonical composition.

Even if two unicode strings are normalized and look the same to a human reader, if one has combining characters and the other doesn’t, they may not compare equal.

Solves it for me. Simple and easy.

Adding a regression line on a ggplot

As I just figured, in case you have a model fitted on multiple linear regression, the above mentioned solution won't work.

You have to create your line manually as a dataframe that contains predicted values for your original dataframe (in your case data).

It would look like this:

# read dataset
df = mtcars

# create multiple linear model
lm_fit <- lm(mpg ~ cyl + hp, data=df)
summary(lm_fit)

# save predictions of the model in the new data frame 
# together with variable you want to plot against
predicted_df <- data.frame(mpg_pred = predict(lm_fit, df), hp=df$hp)

# this is the predicted line of multiple linear regression
ggplot(data = df, aes(x = mpg, y = hp)) + 
  geom_point(color='blue') +
  geom_line(color='red',data = predicted_df, aes(x=mpg_pred, y=hp))

Multiple LR

# this is predicted line comparing only chosen variables
ggplot(data = df, aes(x = mpg, y = hp)) + 
  geom_point(color='blue') +
  geom_smooth(method = "lm", se = FALSE)

Single LR

How to split() a delimited string to a List<String>

string[] thisArray = myString.Split('/');//<string1/string2/string3/--->     
List<string> myList = new List<string>(); //make a new string list    
myList.AddRange(thisArray);    

Use AddRange to pass string[] and get a string list.

Convert long/lat to pixel x/y on a given picture

The translation you are addressing has to do with Map Projection, which is how the spherical surface of our world is translated into a 2 dimensional rendering. There are multiple ways (projections) to render the world on a 2-D surface.

If your maps are using just a specific projection (Mercator being popular), you should be able to find the equations, some sample code, and/or some library (e.g. one Mercator solution - Convert Lat/Longs to X/Y Co-ordinates. If that doesn't do it, I'm sure you can find other samples - https://stackoverflow.com/search?q=mercator. If your images aren't map(s) using a Mercator projection, you'll need to determine what projection it does use to find the right translation equations.

If you are trying to support multiple map projections (you want to support many different maps that use different projections), then you definitely want to use a library like PROJ.4, but again I'm not sure what you'll find for Javascript or PHP.

IIS URL Rewrite and Web.config

Just wanted to point out one thing missing in LazyOne's answer (I would have just commented under the answer but don't have enough rep)

In rule #2 for permanent redirect there is thing missing:

redirectType="Permanent"

So rule #2 should look like this:

<system.webServer>
    <rewrite>
        <rules>
            <rule name="SpecificRedirect" stopProcessing="true">
                <match url="^page$" />
                <action type="Redirect" url="/page.html" redirectType="Permanent" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

Edit

For more information on how to use the URL Rewrite Module see this excellent documentation: URL Rewrite Module Configuration Reference

In response to @kneidels question from the comments; To match the url: topic.php?id=39 something like the following could be used:

<system.webServer>
  <rewrite>
    <rules>
      <rule name="SpecificRedirect" stopProcessing="true">
        <match url="^topic.php$" />
        <conditions logicalGrouping="MatchAll">
          <add input="{QUERY_STRING}" pattern="(?:id)=(\d{2})" />
        </conditions>
        <action type="Redirect" url="/newpage/{C:1}" appendQueryString="false" redirectType="Permanent" />
      </rule>
    </rules>
  </rewrite>
</system.webServer>

This will match topic.php?id=ab where a is any number between 0-9 and b is also any number between 0-9. It will then redirect to /newpage/xy where xy comes from the original url. I have not tested this but it should work.

Does adding a duplicate value to a HashSet/HashMap replace the previous value

The first thing you need to know is that HashSet acts like a Set, which means you add your object directly to the HashSet and it cannot contain duplicates. You just add your value directly in HashSet.

However, HashMap is a Map type. That means every time you add an entry, you add a key-value pair.

In HashMap you can have duplicate values, but not duplicate keys. In HashMap the new entry will replace the old one. The most recent entry will be in the HashMap.

Understanding Link between HashMap and HashSet:

Remember, HashMap can not have duplicate keys. Behind the scene HashSet uses a HashMap.

When you attempt to add any object into a HashSet, this entry is actually stored as a key in the HashMap - the same HashMap that is used behind the scene of HashSet. Since this underlying HashMap needs a key-value pair, a dummy value is generated for us.

Now when you try to insert another duplicate object into the same HashSet, it will again attempt to be insert it as a key in the HashMap lying underneath. However, HashMap does not support duplicates. Hence, HashSet will still result in having only one value of that type. As a side note, for every duplicate key, since the value generated for our entry in HashSet is some random/dummy value, the key is not replaced at all. it will be ignored as removing the key and adding back the same key (the dummy value is the same) would not make any sense at all.

Summary:

HashMap allows duplicate values, but not keys. HashSet cannot contains duplicates.

To play with whether the addition of an object is successfully completed or not, you can check the boolean value returned when you call .add() and see if it returns true or false. If it returned true, it was inserted.

nodejs - first argument must be a string or Buffer - when using response.write with http.request

if u want to write a JSON object to the response then change the header content type to application/json

response.writeHead(200, {"Content-Type": "application/json"});
var d = new Date(parseURL.query.iso);
var postData = {
    "hour" : d.getHours(),
    "minute" : d.getMinutes(),
    "second" : d.getSeconds()
}
response.write(postData)
response.end();

How can I decrypt a password hash in PHP?

Use the password_verify() function

if (password_vertify($inputpassword, $row['password'])) {
  print "Logged in";
else {
    print "Password Incorrect";
}

Creating files and directories via Python

    import os
    os.mkdir('directory name') #### this command for creating directory
    os.mknod('file name') #### this for creating files
    os.system('touch filename') ###this is another method for creating file by using unix commands in os modules 

Capture Video of Android's Screen

This is old, but what about ASC?

How to discover number of *logical* cores on Mac OS X?

This can be done in a more portable way:

$ nproc --all
32

Compatible with macOS and Linux.

How to find the cumulative sum of numbers in a list?

In Python3, To find the cumulative sum of a list where the ith element is the sum of the first i+1 elements from the original list, you may do:

a = [4 , 6 , 12]
b = []
for i in range(0,len(a)):
    b.append(sum(a[:i+1]))
print(b)

OR you may use list comprehension:

b = [sum(a[:x+1]) for x in range(0,len(a))]

Output

[4,10,22]

$.ajax( type: "POST" POST method to php

try this

$(document).on("submit", "#form-data", function(e){
    e.preventDefault()
    $.ajax({
        url: "edit.php",
        method: "POST",
        data: new FormData(this),
        contentType: false,
        processData: false,
        success: function(data){
            $('.center').html(data); 
        }
    })
})

in the form the button needs to be type="submit"

I have never set any passwords to my keystore and alias, so how are they created?

Better than all options, you can set your signingConfig to be equals your debug.signingConfig. To do that you just need to do the following:

android {
  ...
  buildTypes {
    ...
    wantedBuildType {
      signingConfig debug.signingConfig
    }
  }
}

With that you will not need to know where the debug.keystore is, the app will work for all team, even if someone use a different environment.

Undefined symbols for architecture i386: _OBJC_CLASS_$_SKPSMTPMessage", referenced from: error

Is your framework compiled for armv(x)? It looks to me like it's compiled for i386, which code won't run on an iOS device. Or else it's compiled for armv(x) and you're trying to run it on the simulator, which is i386 code. Make sure, using the build settings Akshay displayed above, that your framework is correctly compiled for the chip you're going to run it on.

Turn off deprecated errors in PHP 5.3

In file wp-config.php you can find constant WP_DEBUG. Make sure it is set to false.

define('WP_DEBUG', false);

This is for WordPress 3.x.

Array.Add vs +=

The most common idiom for creating an array without using the inefficient += is something like this, from the output of a loop:

$array = foreach($i in 1..10) { 
  $i
}
$array

Set cellpadding and cellspacing in CSS?

Try this:

table {
    border-collapse: separate;
    border-spacing: 10px;
}
table td, table th {
    padding: 10px;
}

Or try this:

table {
    border-collapse: collapse;
}
table td, table th {
    padding: 10px;
}

How much faster is C++ than C#?

Well, it depends. If the byte-code is translated into machine-code (and not just JIT) (I mean if you execute the program) and if your program uses many allocations/deallocations it could be faster because the GC algorithm just need one pass (theoretically) through the whole memory once, but normal malloc/realloc/free C/C++ calls causes an overhead on every call (call-overhead, data-structure overhead, cache misses ;) ).

So it is theoretically possible (also for other GC languages).

I don't really see the extreme disadvantage of not to be able to use metaprogramming with C# for the most applications, because the most programmers don't use it anyway.

Another big advantage is that the SQL, like the LINQ "extension", provides opportunities for the compiler to optimize calls to databases (in other words, the compiler could compile the whole LINQ to one "blob" binary where the called functions are inlined or for your use optimized, but I'm speculating here).

Writing .csv files from C++

If you wirte to a .csv file in C++ - you should use the syntax of :

myfile <<" %s; %s; %d", string1, string2, double1 <<endl;

This will write the three variables (string 1&2 and double1) into separate columns and leave an empty row below them. In excel the ; means the new row, so if you want to just take a new row - you can alos write a simple ";" before writing your new data into the file. If you don't want to have an empty row below - you should delete the endl and use the:

myfile.open("result.csv", std::ios::out | std::ios::app);

syntax when opening the .csv file (example the result.csv). In this way next time you write something into your result.csv file - it will write it into a new row directly below the last one - so you can easily manage a for cycle if you would like to.

RSA: Get exponent and modulus given a public key

If you need to parse ASN.1 objects in script, there's a library for that: https://github.com/lapo-luchini/asn1js

For doing the math, I found jsbn convenient: http://www-cs-students.stanford.edu/~tjw/jsbn/

Walking the ASN.1 structure and extracting the exp/mod/subject/etc. is up to you -- I never got that far!

How to implement a binary search tree in Python?

    def BinaryST(list1,key):
    start = 0
    end = len(list1)
    print("Length of List: ",end)

    for i in range(end):
        for j in range(0, end-i-1):
            if(list1[j] > list1[j+1]):
                temp = list1[j]
                list1[j] = list1[j+1]
                list1[j+1] = temp

    print("Order List: ",list1)

    mid = int((start+end)/2)
    print("Mid Index: ",mid)

    if(key == list1[mid]):
        print(key," is on ",mid," Index")

    elif(key > list1[mid]):
        for rindex in range(mid+1,end):
            if(key == list1[rindex]):
                print(key," is on ",rindex," Index")
                break
            elif(rindex == end-1):
                print("Given key: ",key," is not in List")
                break
            else:
                continue

    elif(key < list1[mid]):
        for lindex in range(0,mid):
            if(key == list1[lindex]):
                print(key," is on ",lindex," Index")
                break
            elif(lindex == mid-1):
                print("Given key: ",key," is not in List")
                break
            else:
                continue


size = int(input("Enter Size of List: "))
list1 = []
for e in range(size):
    ele = int(input("Enter Element in List: "))
    list1.append(ele)

key = int(input("\nEnter Key for Search: "))

print("\nUnorder List: ",list1)
BinaryST(list1,key)

Opening port 80 EC2 Amazon web services

Some quick tips:

  1. Disable the inbuilt firewall on your Windows instances.
  2. Use the IP address rather than the DNS entry.
  3. Create a security group for tcp ports 1 to 65000 and for source 0.0.0.0/0. It's obviously not to be used for production purposes, but it will help avoid the Security Groups as a source of problems.
  4. Check that you can actually ping your server. This may also necessitate some Security Group modification.

Convert SVG to image (JPEG, PNG, etc.) in the browser

I wrote this ES6 Class which does the Job.

class SvgToPngConverter {
  constructor() {
    this._init = this._init.bind(this);
    this._cleanUp = this._cleanUp.bind(this);
    this.convertFromInput = this.convertFromInput.bind(this);
  }

  _init() {
    this.canvas = document.createElement("canvas");
    this.imgPreview = document.createElement("img");
    this.imgPreview.style = "position: absolute; top: -9999px";

    document.body.appendChild(this.imgPreview);
    this.canvasCtx = this.canvas.getContext("2d");
  }

  _cleanUp() {
    document.body.removeChild(this.imgPreview);
  }

  convertFromInput(input, callback) {
    this._init();
    let _this = this;
    this.imgPreview.onload = function() {
      const img = new Image();
      _this.canvas.width = _this.imgPreview.clientWidth;
      _this.canvas.height = _this.imgPreview.clientHeight;
      img.crossOrigin = "anonymous";
      img.src = _this.imgPreview.src;
      img.onload = function() {
        _this.canvasCtx.drawImage(img, 0, 0);
        let imgData = _this.canvas.toDataURL("image/png");
        if(typeof callback == "function"){
            callback(imgData)
        }
        _this._cleanUp();
      };
    };

    this.imgPreview.src = input;
  }
}

Here is how you use it

let input = "https://restcountries.eu/data/afg.svg"
new SvgToPngConverter().convertFromInput(input, function(imgData){
    // You now have your png data in base64 (imgData). 
    // Do what ever you wish with it here.
});

If you want a vanilla JavaScript version, you could head over to Babel website and transpile the code there.

Transfer data from one HTML file to another

I use this to set Profile image on each page.

On first page set value as:

localStorage.setItem("imageurl", "ur image url");

or on second page get value as :

var imageurl=localStorage.getItem("imageurl");
document.getElementById("profilePic").src = (imageurl);

JavaScript module pattern with example

I thought i'd expand on the above answer by talking about how you'd fit modules together into an application. I'd read about this in the doug crockford book but being new to javascript it was all still a bit mysterious.

I come from a c# background so have added some terminology I find useful from there.

Html

You'll have some kindof top level html file. It helps to think of this as your project file. Every javascript file you add to the project wants to go into this, unfortunately you dont get tool support for this (I'm using IDEA).

You need add files to the project with script tags like this:

        <script type="text/javascript" src="app/native/MasterFile.js" /></script>
        <script type="text/javascript" src="app/native/SomeComponent.js" /></script>

It appears collapsing the tags causes things to fail - whilst it looks like xml it's really something with crazier rules!

Namespace file

MasterFile.js

myAppNamespace = {};

that's it. This is just for adding a single global variable for the rest of our code to live in. You could also declare nested namespaces here (or in their own files).

Module(s)

SomeComponent.js

myAppNamespace.messageCounter= (function(){

    var privateState = 0;

    var incrementCount = function () {
        privateState += 1;
    };

    return function (message) {
        incrementCount();
        //TODO something with the message! 
    }
})();

What we're doing here is assigning a message counter function to a variable in our application. It's a function which returns a function which we immediately execute.

Concepts

I think it helps to think of the top line in SomeComponent as being the namespace where you are declaring something. The only caveat to this is all your namespaces need to appear in some other file first - they are just objects rooted by our application variable.

I've only taken minor steps with this at the moment (i'm refactoring some normal javascript out of an extjs app so I can test it) but it seems quite nice as you can define little functional units whilst avoiding the quagmire of 'this'.

You can also use this style to define constructors by returning a function which returns an object with a collection of functions and not calling it immediately.

How to use OpenSSL to encrypt/decrypt files?

To Encrypt:

$ openssl bf < arquivo.txt > arquivo.txt.bf

To Decrypt:

$ openssl bf -d < arquivo.txt.bf > arquivo.txt

bf === Blowfish in CBC mode

jQuery get an element by its data-id

This worked for me, in my case I had a button with a data-id attribute:

$("a").data("item-id");

Fiddle

Do I need to compile the header files in a C program?

Firstly, in general:

If these .h files are indeed typical C-style header files (as opposed to being something completely different that just happens to be named with .h extension), then no, there's no reason to "compile" these header files independently. Header files are intended to be included into implementation files, not fed to the compiler as independent translation units.

Since a typical header file usually contains only declarations that can be safely repeated in each translation unit, it is perfectly expected that "compiling" a header file will have no harmful consequences. But at the same time it will not achieve anything useful.

Basically, compiling hello.h as a standalone translation unit equivalent to creating a degenerate dummy.c file consisting only of #include "hello.h" directive, and feeding that dummy.c file to the compiler. It will compile, but it will serve no meaningful purpose.


Secondly, specifically for GCC:

Many compilers will treat files differently depending on the file name extension. GCC has special treatment for files with .h extension when they are supplied to the compiler as command-line arguments. Instead of treating it as a regular translation unit, GCC creates a precompiled header file for that .h file.

You can read about it here: http://gcc.gnu.org/onlinedocs/gcc/Precompiled-Headers.html

So, this is the reason you might see .h files being fed directly to GCC.

Converting a float to a string without rounding it

Some form of rounding is often unavoidable when dealing with floating point numbers. This is because numbers that you can express exactly in base 10 cannot always be expressed exactly in base 2 (which your computer uses).

For example:

>>> .1
0.10000000000000001

In this case, you're seeing .1 converted to a string using repr:

>>> repr(.1)
'0.10000000000000001'

I believe python chops off the last few digits when you use str() in order to work around this problem, but it's a partial workaround that doesn't substitute for understanding what's going on.

>>> str(.1)
'0.1'

I'm not sure exactly what problems "rounding" is causing you. Perhaps you would do better with string formatting as a way to more precisely control your output?

e.g.

>>> '%.5f' % .1
'0.10000'
>>> '%.5f' % .12345678
'0.12346'

Documentation here.

Uses for the '&quot;' entity in HTML

It is likely because they used a single function for escaping attributes and text nodes. &amp; doesn't do any harm so why complicate your code and make it more error-prone by having two escaping functions and having to pick between them?

Spark dataframe: collect () vs select ()

To answer the questions directly:

Will collect() behave the same way if called on a dataframe?

Yes, spark.DataFrame.collect is functionally the same as spark.RDD.collect. They serve the same purpose on these different objects.

What about the select() method?

There is no such thing as spark.RDD.select, so it cannot be the same as spark.DataFrame.select.

Does it also work the same way as collect() if called on a dataframe?

The only thing that is similar between select and collect is that they are both functions on a DataFrame. They have absolutely zero overlap in functionality.

Here's my own description: collect is the opposite of sc.parallelize. select is the same as the SELECT in any SQL statement.

If you are still having trouble understanding what collect actually does (for either RDD or DataFrame), then you need to look up some articles about what spark is doing behind the scenes. e.g.:

Animated GIF in IE stopping

Just had a similar issue. These worked perfectly for me.

$('#myElement').prepend('<img src="/path/to/img.gif" alt="My Gif" title="Loading" />');

$('<img src="/path/to/img.gif" alt="My Gif" title="Loading" />').prependTo('#myElement');

Another idea was to use jQuery's .load(); to load and then prepend the image.

Works in IE 7+

Heroku deployment error H10 (App crashed)

I had the same problem, I did the following

heroku run rails c

It identified a syntax error and missing comma within a controller permitted params. As mentioned above the Heroku logs did not provide sufficient information to problem solve the problem.

I have not seen the application crashed message on Heroku previously.

How to grep a string in a directory and all its subdirectories?

grep -r -e string directory

-r is for recursive; -e is optional but its argument specifies the regex to search for. Interestingly, POSIX grep is not required to support -r (or -R), but I'm practically certain that System V grep did, so in practice they (almost) all do. Some versions of grep support -R as well as (or conceivably instead of) -r; AFAICT, it means the same thing.

Why does comparing strings using either '==' or 'is' sometimes produce a different result?

is will compare the memory location. It is used for object-level comparison.

== will compare the variables in the program. It is used for checking at a value level.

is checks for address level equivalence

== checks for value level equivalence

How do I check if a C++ string is an int?

Since C++11 you can make use of std::all_of and ::isdigit:

#include <algorithm>
#include <cctype>
#include <iostream>
#include <string_view>

int main([[maybe_unused]] int argc, [[maybe_unused]] char *argv[])
{
    auto isInt = [](std::string_view str) -> bool {
        return std::all_of(str.cbegin(), str.cend(), ::isdigit);
    };

    for(auto &test : {"abc", "123abc", "123.0", "+123", "-123", "123"}) {
        std::cout << "Is '" << test << "' numeric? " 
            << (isInt(test) ? "true" : "false") << std::endl;
    }

    return 0;
}

Check out the result with Godbolt.

jQuery "blinking highlight" effect on div?

This is a custom blink effect I created, which uses setInterval and fadeTo

HTML -

<div id="box">Box</div>

JS -

setInterval(function(){blink()}, 1000);


    function blink() {
        $("#box").fadeTo(100, 0.1).fadeTo(200, 1.0);
    }

As simple as it gets.

http://jsfiddle.net/Ajey/25Wfn/

What is the difference between bindParam and bindValue?

The simplest way to put this into perspective for memorization by behavior (in terms of PHP):

  • bindParam: reference
  • bindValue: variable

CSS horizontal scroll

check this link here i change display:inline-block http://cssdesk.com/gUGBH

header('HTTP/1.0 404 Not Found'); not doing anything

You could try specifying an HTTP response code using an optional parameter:

header('HTTP/1.0 404 Not Found', true, 404);

'printf' vs. 'cout' in C++

More differences: "printf" returns an integer value (equal to the number of characters printed) and "cout" does not return anything

And.

cout << "y = " << 7; is not atomic.

printf("%s = %d", "y", 7); is atomic.

cout performs typechecking, printf doesn't.

There's no iostream equivalent of "% d"

string.Replace in AngularJs

In Javascript method names are camel case, so it's replace, not Replace:

$scope.newString = oldString.replace("stackover","NO");

Note that contrary to how the .NET Replace method works, the Javascript replace method replaces only the first occurrence if you are using a string as first parameter. If you want to replace all occurrences you need to use a regular expression so that you can specify the global (g) flag:

$scope.newString = oldString.replace(/stackover/g,"NO");

See this example.

Simulate limited bandwidth from within Chrome?

Original article: https://helpdeskgeek.com/networking/simulate-slow-internet-connection-testing/

Simulate Slow Connection using Chrome Go ahead and install Chrome if you don’t already have it installed on your system. Once you do, open a new tab and then press CTRL + SHIFT + I to open the developer tools window or click on the hamburger icon, then More tools and then Developer tools.

enter image description here

This will bring up the Developer Tools window, which will probably be docked on the right side of the screen. I prefer it docked at the bottom of the screen since you can see more data. To do this, click on the three vertical dots and then click on the middle dock position.

enter image description here

Now go ahead and click on the Network tab. On the right, you should see a label called No Throttling.

enter image description here

If you click on that, you’ll get a dropdown list of a pre-configured speed that you can use to simulate a slow connection.

enter image description here

The choices range from Offline to WiFi and the numbers are shown as Latency, Download, Upload. The slowest is GPRS followed by Regular 2G, then Good 2G, then Regular 3G, Good 3G, Regular 4G, DSL and then WiFi. Pick one of the options and then reload the page you are on or type in another URL in the address bar. Just make sure you are in the same tab where the developer tools are being displayed. The throttling only works for the tab you have it enabled for.

If you want to use your own specific values, you can click the Add button under Custom. Click on the Add Custom Profile button to add a new profile.

enter image description here

When using GPRS, it took www.google.com a whopping 16 seconds to load! Overall, this is a great tool that is built right into Chrome that you can use for testing your website load time on slower connections. If you have any questions, feel free to comment. Enjoy!

How to change MenuItem icon in ActionBar programmatically

Instead of getViewById(), use

MenuItem item = getToolbar().getMenu().findItem(Menu.FIRST);

replacing the Menu.FIRST with your menu item id.

How to List All Redis Databases?

There is no command to do it (like you would do it with MySQL for instance). The number of Redis databases is fixed, and set in the configuration file. By default, you have 16 databases. Each database is identified by a number (not a name).

You can use the following command to know the number of databases:

CONFIG GET databases
1) "databases"
2) "16"

You can use the following command to list the databases for which some keys are defined:

INFO keyspace
# Keyspace
db0:keys=10,expires=0
db1:keys=1,expires=0
db3:keys=1,expires=0

Please note that you are supposed to use the "redis-cli" client to run these commands, not telnet. If you want to use telnet, then you need to run these commands formatted using the Redis protocol.

For instance:

*2
$4
INFO
$8
keyspace

$79
# Keyspace
db0:keys=10,expires=0
db1:keys=1,expires=0
db3:keys=1,expires=0

You can find the description of the Redis protocol here: http://redis.io/topics/protocol

MS Access VBA: Sending an email through Outlook

Here is email code I used in one of my databases. I just made variables for the person I wanted to send it to, CC, subject, and the body. Then you just use the DoCmd.SendObject command. I also set it to "True" after the body so you can edit the message before it automatically sends.

Public Function SendEmail2()

Dim varName As Variant          
Dim varCC As Variant            
Dim varSubject As Variant      
Dim varBody As Variant          

varName = "[email protected]"
varCC = "[email protected], [email protected]"
'separate each email by a ','

varSubject = "Hello"
'Email subject

varBody = "Let's get ice cream this week"

'Body of the email
DoCmd.SendObject , , , varName, varCC, , varSubject, varBody, True, False
'Send email command. The True after "varBody" allows user to edit email before sending.
'The False at the end will not send it as a Template File

End Function

vertical alignment of text element in SVG

If you're testing this in IE, dominant-baseline and alignment-baseline are not supported.

The most effective way to center text in IE is to use something like this with "dy":

<text font-size="ANY SIZE" text-anchor="middle" "dy"="-.4em"> Ya Text </text>

The negative value will shift it up and a positive value of dy will shift it down. I've found using -.4em seems a bit more centered vertically to me than -.5em, but you'll be the judge of that.

Return multiple values from a function in swift

Return a tuple:

func getTime() -> (Int, Int, Int) {
    ...
    return ( hour, minute, second)
}

Then it's invoked as:

let (hour, minute, second) = getTime()

or:

let time = getTime()
println("hour: \(time.0)")

Return different type of data from a method in java?

the approach you took is good. Just Implementation may need to be better. For instance ReturningValues should be well defined and Its better if you can make ReturningValues as immutable.

// this approach is better
public static ReturningValues myMethod() {
    ReturningValues rv = new ReturningValues("value", 12);
    return rv;
}


public final class ReturningValues {
    private final String value;
    private final int index;


    public ReturningValues(String value, int index) {
      this.value = value;
      this.index = index;
     }

} 

Or if you have lots of key value pairs you can use HashMap then

public static Map<String,Object> myMethod() {
  Map<String,Object> map = new HashMap<String,Object>();
  map.put(VALUE, "value");
  map.put(INDEX, 12);
  return Collections.unmodifiableMap(map); // try to use this 
}

Passing multiple variables in @RequestBody to a Spring MVC controller using Ajax

Good. I suggest creating a Value Object (Vo) that contains the fields you need. The code is simpler, we do not change the functioning of Jackson and it is even easier to understand. Regards!

Converting list to *args when calling function

You can use the * operator before an iterable to expand it within the function call. For example:

timeseries_list = [timeseries1 timeseries2 ...]
r = scikits.timeseries.lib.reportlib.Report(*timeseries_list)

(notice the * before timeseries_list)

From the python documentation:

If the syntax *expression appears in the function call, expression must evaluate to an iterable. Elements from this iterable are treated as if they were additional positional arguments; if there are positional arguments x1, ..., xN, and expression evaluates to a sequence y1, ..., yM, this is equivalent to a call with M+N positional arguments x1, ..., xN, y1, ..., yM.

This is also covered in the python tutorial, in a section titled Unpacking argument lists, where it also shows how to do a similar thing with dictionaries for keyword arguments with the ** operator.

How can I rename a single column in a table at select?

Another option you can choose:

select price = table1.price , other_price = table2.price from .....

Reference:

In case you are curious about the performance or otherwise of aliasing a column using “=” versus “as”.

You have to be inside an angular-cli project in order to use the build command after reinstall of angular-cli

In my case (Mac OS X and previously used Angular 1.5 environment)

npm -g cache clean --force

npm cache clean --force

worked. (npm install -g @angular/cli@latest afterwards)

How to get json key and value in javascript?

A simple approach instead of using JSON.parse

 success: function(response){
     var resdata = response;
     alert(resdata['name']);
}

Command to get latest Git commit hash from a branch

In a comment you wrote

i want to show that there is a difference in local and github repo

As already mentioned in another answer, you should do a git fetch origin first. Then, if the remote is ahead of your current branch, you can list all commits between your local branch and the remote with

git log master..origin/master --stat

If your local branch is ahead:

git log origin/master..master --stat

--stat shows a list of changed files as well.

If you want to explicitly list the additions and deletions, use git diff:

git diff master origin/master

Remove a JSON attribute

Simple:

delete myObj.test.key1;

Obtaining only the filename when using OpenFileDialog property "FileName"

Use: Path.GetFileName Method

var onlyFileName = System.IO.Path.GetFileName(ofd.FileName);

Removing "NUL" characters

Highlight a single null character, goto find replace - it usually automatically inserts the highlighted text into the find box. Enter a space into or leave blank the replace box.

What's the algorithm to calculate aspect ratio?

Based on the other answers, here is how I got the numbers I needed in Python;

from decimal import Decimal

def gcd(a,b):
    if b == 0:
        return a
    return gcd(b, a%b)

def closest_aspect_ratio(width, height):
    g = gcd(width, height)
    x = Decimal(str(float(width)/float(g)))
    y = Decimal(str(float(height)/float(g)))
    dec = Decimal(str(x/y))
    return dict(x=x, y=y, dec=dec)

>>> closest_aspect_ratio(1024, 768)
{'y': Decimal('3.0'), 
 'x': Decimal('4.0'), 
 'dec': Decimal('1.333333333333333333333333333')}

Why doesn't Mockito mock static methods?

Mockito returns objects but static means "class level,not object level"So mockito will give null pointer exception for static.

String to LocalDate

You may have to go from DateTime to LocalDate.

Using Joda Time:

DateTimeFormatter FORMATTER = DateTimeFormat.forPattern("yyyy-MMM-dd");
DateTime dateTime = FORMATTER.parseDateTime("2005-nov-12");
LocalDate localDate = dateTime.toLocalDate();

Iterator invalidation rules

It is probably worth adding that an insert iterator of any kind (std::back_insert_iterator, std::front_insert_iterator, std::insert_iterator) is guaranteed to remain valid as long as all insertions are performed through this iterator and no other independent iterator-invalidating event occurs.

For example, when you are performing a series of insertion operations into a std::vector by using std::insert_iterator it is quite possible that these insertions will trigger vector reallocation, which will invalidate all iterators that "point" into that vector. However, the insert iterator in question is guaranteed to remain valid, i.e. you can safely continue the sequence of insertions. There's no need to worry about triggering vector reallocation at all.

This, again, applies only to insertions performed through the insert iterator itself. If iterator-invalidating event is triggered by some independent action on the container, then the insert iterator becomes invalidated as well in accordance with the general rules.

For example, this code

std::vector<int> v(10);
std::vector<int>::iterator it = v.begin() + 5;
std::insert_iterator<std::vector<int> > it_ins(v, it);

for (unsigned n = 20; n > 0; --n)
  *it_ins++ = rand();

is guaranteed to perform a valid sequence of insertions into the vector, even if the vector "decides" to reallocate somewhere in the middle of this process. Iterator it will obviously become invalid, but it_ins will continue to remain valid.

Doing a join across two databases with different collations on SQL Server and getting an error

A general purpose way is to coerce the collation to DATABASE_DEFAULT. This removes hardcoding the collation name which could change.

It's also useful for temp table and table variables, and where you may not know the server collation (eg you are a vendor placing your system on the customer's server)

select
    sone_field collate DATABASE_DEFAULT
from
    table_1
    inner join
    table_2 on table_1.field collate DATABASE_DEFAULT = table_2.field
where whatever

Is there possibility of sum of ArrayList without looping

Write a util function like

public class ListUtil{

    public static int sum(List<Integer> list){
      if(list==null || list.size()<1)
        return 0;

      int sum = 0;
      for(Integer i: list)
        sum = sum+i;

      return sum;
    }
}

Then use like

int sum = ListUtil.sum(yourArrayList)

Appending to an empty DataFrame in Pandas?

You can concat the data in this way:

InfoDF = pd.DataFrame()
tempDF = pd.DataFrame(rows,columns=['id','min_date'])

InfoDF = pd.concat([InfoDF,tempDF])

Set focus on <input> element

This is working i Angular 8 without setTimeout:

import {AfterContentChecked, Directive, ElementRef} from '@angular/core';

@Directive({
  selector: 'input[inputAutoFocus]'
})
export class InputFocusDirective implements AfterContentChecked {
  constructor(private element: ElementRef<HTMLInputElement>) {}

  ngAfterContentChecked(): void {
    this.element.nativeElement.focus();
  }
}

Explanation: Ok so this works because of: Change detection. It's the same reason that setTimout works, but when running a setTimeout in Angular it will bypass Zone.js and run all checks again, and it works because when the setTimeout is complete all changes are completed. With the correct lifecycle hook (AfterContentChecked) the same result can be be reached, but with the advantage that the extra cycle won't be run. The function will fire when all changes are checked and passed, and runs after the hooks AfterContentInit and DoCheck. If i'm wrong here please correct me.

More one lifecycles and change detection on https://angular.io/guide/lifecycle-hooks

UPDATE: I found an even better way to do this if one is using Angular Material CDK, the a11y-package. First import A11yModule in the the module declaring the component you have the input-field in. Then use cdkTrapFocus and cdkTrapFocusAutoCapture directives and use like this in html and set tabIndex on the input:

<div class="dropdown" cdkTrapFocus cdkTrapFocusAutoCapture>
    <input type="text tabIndex="0">
</div>

We had some issues with our dropdowns regarding positioning and responsiveness and started using the OverlayModule from the cdk instead, and this method using A11yModule works flawlessly.

Best way to do a split pane in HTML

In the old days, you would use frames to achieve this. There are several reasons why this approach is not so good. See Reece's response to Why are HTML frames bad?. See also Jakob Nielson's Why Frames Suck (Most of the Time).

A somewhat newer approach is to use inline frames. This has pluses and minuses as well: Are iframes considered 'bad practice'?

An even better approach is to use fixed positioning. By placing the navigation content (e.g. the favorites links in your example) in a block element (like a div) then applying position:fixed to that element and setting the left, top and bottom properties like this:

#myNav {
    position: fixed;
    left: 0px;
    top: 0px;
    bottom: 0px;
    width: 200px;
}

... you will achieve a vertical column down the left side of the page that will not move when the user scrolls the page.

The rest of the content on the page will not "feel" the presence of this nav element, so it must take into account the 200px of space it occupies. You can do this by placing the rest for the content in another div and setting margin-left:200px;.

sort files by date in PHP

You need to put the files into an array in order to sort and find the last modified file.

$files = array();
if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
           $files[filemtime($file)] = $file;
        }
    }
    closedir($handle);

    // sort
    ksort($files);
    // find the last modification
    $reallyLastModified = end($files);

    foreach($files as $file) {
        $lastModified = date('F d Y, H:i:s',filemtime($file));
        if(strlen($file)-strpos($file,".swf")== 4){
           if ($file == $reallyLastModified) {
             // do stuff for the real last modified file
           }
           echo "<tr><td><input type=\"checkbox\" name=\"box[]\"></td><td><a href=\"$file\" target=\"_blank\">$file</a></td><td>$lastModified</td></tr>";
        }
    }
}

Not tested, but that's how to do it.

How do I test if a variable is a number in Bash?

You could use "let" too like this :

[ ~]$ var=1
[ ~]$ let $var && echo "It's a number" || echo "It's not a number"
It\'s a number
[ ~]$ var=01
[ ~]$ let $var && echo "It's a number" || echo "It's not a number"
It\'s a number
[ ~]$ var=toto
[ ~]$ let $var && echo "It's a number" || echo "It's not a number"
It\'s not a number
[ ~]$ 

But I prefer use the "=~" Bash 3+ operator like some answers in this thread.

How to implement onBackPressed() in Fragments?

How about using onDestroyView()?

@Override
public void onDestroyView() {
    super.onDestroyView();
}

Installing cmake with home-brew

Typing brew install cmake as you did installs cmake. Now you can type cmake and use it.

If typing cmake doesn’t work make sure /usr/local/bin is your PATH. You can see it with echo $PATH. If you don’t see /usr/local/bin in it add the following to your ~/.bashrc:

export PATH="/usr/local/bin:$PATH"

Then reload your shell session and try again.


(all the above assumes Homebrew is installed in its default location, /usr/local. If not you’ll have to replace /usr/local with $(brew --prefix) in the export line)

How to delete migration files in Rails 3

We can use,

$ rails d migration table_name  

Which will delete the migration.

Why is 2 * (i * i) faster than 2 * i * i in Java?

Interesting observation using Java 11 and switching off loop unrolling with the following VM option:

-XX:LoopUnrollLimit=0

The loop with the 2 * (i * i) expression results in more compact native code1:

L0001: add    eax,r11d
       inc    r8d
       mov    r11d,r8d
       imul   r11d,r8d
       shl    r11d,1h
       cmp    r8d,r10d
       jl     L0001

in comparison with the 2 * i * i version:

L0001: add    eax,r11d
       mov    r11d,r8d
       shl    r11d,1h
       add    r11d,2h
       inc    r8d
       imul   r11d,r8d
       cmp    r8d,r10d
       jl     L0001

Java version:

java version "11" 2018-09-25
Java(TM) SE Runtime Environment 18.9 (build 11+28)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11+28, mixed mode)

Benchmark results:

Benchmark          (size)  Mode  Cnt    Score     Error  Units
LoopTest.fast  1000000000  avgt    5  694,868 ±  36,470  ms/op
LoopTest.slow  1000000000  avgt    5  769,840 ± 135,006  ms/op

Benchmark source code:

@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Warmup(iterations = 5, time = 5, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 5, timeUnit = TimeUnit.SECONDS)
@State(Scope.Thread)
@Fork(1)
public class LoopTest {

    @Param("1000000000") private int size;

    public static void main(String[] args) throws RunnerException {
        Options opt = new OptionsBuilder()
            .include(LoopTest.class.getSimpleName())
            .jvmArgs("-XX:LoopUnrollLimit=0")
            .build();
        new Runner(opt).run();
    }

    @Benchmark
    public int slow() {
        int n = 0;
        for (int i = 0; i < size; i++)
            n += 2 * i * i;
        return n;
    }

    @Benchmark
    public int fast() {
        int n = 0;
        for (int i = 0; i < size; i++)
            n += 2 * (i * i);
        return n;
    }
}

1 - VM options used: -XX:+UnlockDiagnosticVMOptions -XX:+PrintAssembly -XX:LoopUnrollLimit=0

Can we convert a byte array into an InputStream in Java?

Use ByteArrayInputStream:

InputStream is = new ByteArrayInputStream(decodedBytes);

Best cross-browser method to capture CTRL+S with JQuery?

I solved my problem on IE, using an alert("With a message") to prevent default Behavior:

window.addEventListener("keydown", function (e) {
    if(e.ctrlKey || e.metaKey){
        e.preventDefault(); //Good browsers
        if (navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > 0) { //hack for ie
            alert("Please, use the print button located on the top bar");
            return;
        }
    }
});

jQuery 'each' loop with JSON array

Brief code but full-featured

The following is a hybrid jQuery solution that formats each data "record" into an HTML element and uses the data's properties as HTML attribute values.

The jquery each runs the inner loop; I needed the regular JavaScript for on the outer loop to be able to grab the property name (instead of value) for display as the heading. According to taste it can be modified for slightly different behaviour.

This is only 5 main lines of code but wrapped onto multiple lines for display:

$.get("data.php", function(data){

    for (var propTitle in data) {

        $('<div></div>') 
            .addClass('heading')
            .insertBefore('#contentHere')
            .text(propTitle);

            $(data[propTitle]).each(function(iRec, oRec) {

                $('<div></div>')
                    .addClass(oRec.textType)
                    .attr('id', 'T'+oRec.textId)
                    .insertBefore('#contentHere')
                    .text(oRec.text);
            });
    }

});

Produces the output

(Note: I modified the JSON data text values by prepending a number to ensure I was displaying the proper records in the proper sequence - while "debugging")

<div class="heading">
    justIn
</div>
<div id="T123" class="Greeting">
    1Hello
</div>
<div id="T514" class="Question">
    1What's up?
</div>
<div id="T122" class="Order">
    1Come over here
</div>
<div class="heading">
    recent
</div>
<div id="T1255" class="Greeting">
    2Hello
</div>
<div id="T6564" class="Question">
    2What's up?
</div>
<div id="T0192" class="Order">
    2Come over here
</div>
<div class="heading">
    old
</div>
<div id="T5213" class="Greeting">
    3Hello
</div>
<div id="T9758" class="Question">
    3What's up?
</div>
<div id="T7655" class="Order">
    3Come over here
</div>
<div id="contentHere"></div>

Apply a style sheet

<style>
.heading { font-size: 24px; text-decoration:underline }
.Greeting { color: green; }
.Question { color: blue; }
.Order { color: red; }
</style>

to get a "beautiful" looking set of data

alt text

More Info
The JSON data was used in the following way:

for each category (key name the array is held under):

  • the key name is used as the section heading (e.g. justIn)

for each object held inside an array:

  • 'text' becomes the content of a div
  • 'textType' becomes the class of the div (hooked into a style sheet)
  • 'textId' becomes the id of the div
  • e.g. <div id="T122" class="Order">Come over here</div>

How do I POST with multipart form data using fetch?

I was recently working with IPFS and worked this out. A curl example for IPFS to upload a file looks like this:

curl -i -H "Content-Type: multipart/form-data; boundary=CUSTOM" -d $'--CUSTOM\r\nContent-Type: multipart/octet-stream\r\nContent-Disposition: file; filename="test"\r\n\r\nHello World!\n--CUSTOM--' "http://localhost:5001/api/v0/add"

The basic idea is that each part (split by string in boundary with --) has it's own headers (Content-Type in the second part, for example.) The FormData object manages all this for you, so it's a better way to accomplish our goals.

This translates to fetch API like this:

const formData = new FormData()
formData.append('blob', new Blob(['Hello World!\n']), 'test')

fetch('http://localhost:5001/api/v0/add', {
  method: 'POST',
  body: formData
})
.then(r => r.json())
.then(data => {
  console.log(data)
})

How to run TestNG from command line

You need to have the testng.jar under classpath.

try C:\projectfred> java -cp "path-tojar/testng.jar:path_to_yourtest_classes" org.testng.TestNG testng.xml

Update:

Under linux I ran this command and it would be some thing similar on Windows either

test/bin# java -cp ".:../lib/*" org.testng.TestNG testng.xml

Directory structure:

/bin - All my test packages are under bin including testng.xml
/src - All source files are under src
/lib - All libraries required for the execution of tests are under this.

Once I compile all sources they go under bin directory. So, in the classpath I need to specify contents of bin directory and all the libraries like testng.xml, loggers etc over here. Also copy testng.xml to bin folder if you dont want to specify the full path where the testng.xml is available.

 /bin
    -- testng.xml
    -- testclasses
    -- Properties files if any.
 /lib
    -- testng.jar
    -- log4j.jar

Update:

Go to the folder MyProject and type run the java command like the way shown below:-

java -cp ".: C:\Program Files\jbdevstudio4\studio\plugins\*" org.testng.TestNG testng.xml

I believe the testng.xml file is under C:\Users\me\workspace\MyProject if not please give the full path for testng.xml file

XAMPP Port 80 in use by "Unable to open process" with PID 4

So I have faced the same problem when trying to start apache service and I would like to share my solutions with you. Here is some notes about services or programs that may use port 80:

  1. Skype: skype uses port 80/443 by default. You can change this from tools->options-> advanced->connections and disable checkbox "use port 80 and 443 for addtional incoming connections".
  2. IIS: IIS uses port 80 be default so you need to shut down it. You can use the following two commands net stop w3svc net stop iisadmin
  3. SQL Server Reporting Service: You need to stop this service because it may take port 80 if IIS is not running. Go to local services and stop it.

These options work great with me and I can start apache service without errors.

The other option is to change apache listen port from httpd.conf and set another port number.

Hope this solution helps anyone who face the same problem again.

How to specify a port number in SQL Server connection string?

The correct SQL connection string for SQL with specify port is use comma between ip address and port number like following pattern: xxx.xxx.xxx.xxx,yyyy

VBA: Convert Text to Number

This converts all text in columns of an Excel Workbook to numbers.

Sub ConvertTextToNumbers()
Dim wBook As Workbook
Dim LastRow As Long, LastCol As Long
Dim Rangetemp As Range

'Enter here the path of your workbook
Set wBook = Workbooks.Open("yourWorkbook")
LastRow = Cells.Find(What:="*", After:=Range("A1"), SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
LastCol = Cells.Find(What:="*", After:=Range("A1"), SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column

For c = 1 To LastCol
Set Rangetemp = Cells(c).EntireColumn
Rangetemp.TextToColumns DataType:=xlDelimited, _
    TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
    Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
    :=Array(1, 1), TrailingMinusNumbers:=True
Next c
End Sub

Difference between uint32 and uint32_t

uint32_t is defined in the standard, in

18.4.1 Header <cstdint> synopsis [cstdint.syn]

namespace std {
//...
typedef unsigned integer type uint32_t; // optional
//...
}

uint32 is not, it's a shortcut provided by some compilers (probably as typedef uint32_t uint32) for ease of use.

disable editing default value of text input

I'm not sure I understand the question correctly, but if you want to prevent people from writing in the input field you can use the disabled attribute.

<input disabled="disabled" id="price_from" value="price from ">

Decrementing for loops

range step should be -1

   for k in range(10,0,-1):
      print k

getting exception "IllegalStateException: Can not perform this action after onSaveInstanceState"

I have got the same issue in my App. I have been solved this issue just calling the super.onBackPressed(); on previous class and calling the commitAllowingStateLoss() on the current class with that fragment.

Multiple file upload in php

this simple script worked for me.

<?php

foreach($_FILES as $file){
  //echo $file['name']; 
  echo $file['tmp_name'].'</br>'; 
  move_uploaded_file($file['tmp_name'], "./uploads/".$file["name"]);
}

?>

Prevent nginx 504 Gateway timeout using PHP set_time_limit()

You need to add extra nginx directive (for ngx_http_proxy_module) in nginx.conf, e.g.:

proxy_read_timeout 300;

Basically the nginx proxy_read_timeout directive changes the proxy timeout, the FcgidIOTimeout is for scripts that are quiet too long, and FcgidBusyTimeout is for scripts that take too long to execute.

Also if you're using FastCGI application, increase these options as well:

FcgidBusyTimeout 300
FcgidIOTimeout 250

Then reload nginx and PHP5-FPM.

Plesk

In Plesk, you can add it in Web Server Settings under Additional nginx directives.

For FastCGI check in Web Server Settings under Additional directives for HTTP.

See: How to fix FastCGI timeout issues in Plesk?

Get first day of week in PHP?

strtotime('this week', time());

Replace time(). Next sunday/last monday methods won't work when the current day is sunday/monday.

Convert nullable bool? to bool

This answer is for the use case when you simply want to test the bool? in a condition. It can also be used to get a normal bool. It is an alternative I personnaly find easier to read than the coalescing operator ??.

If you want to test a condition, you can use this

bool? nullableBool = someFunction();
if(nullableBool == true)
{
    //Do stuff
}

The above if will be true only if the bool? is true.

You can also use this to assign a regular bool from a bool?

bool? nullableBool = someFunction();
bool regularBool = nullableBool == true;

witch is the same as

bool? nullableBool = someFunction();
bool regularBool = nullableBool ?? false;

Is there a standard sign function (signum, sgn) in C/C++?

Is there a standard sign function (signum, sgn) in C/C++?

Yes, depending on definition.

C99 and later has the signbit() macro in <math.h>

int signbit(real-floating x);
The signbit macro returns a nonzero value if and only if the sign of its argument value is negative. C11 §7.12.3.6


Yet OP wants something a little different.

I want a function that returns -1 for negative numbers and +1 for positive numbers. ... a function working on floats.

#define signbit_p1_or_n1(x)  ((signbit(x) ?  -1 : 1)

Deeper:

The post is not specific in the following cases: x = 0.0, -0.0, +NaN, -NaN.

A classic signum() returns +1 on x>0, -1 on x<0 and 0 on x==0.

Many answers have already covered that, but do not address x = -0.0, +NaN, -NaN. Many are geared for an integer point-of-view that usually lacks Not-a-Numbers (NaN) and -0.0.

Typical answers function like signnum_typical() On -0.0, +NaN, -NaN, they return 0.0, 0.0, 0.0.

int signnum_typical(double x) {
  if (x > 0.0) return 1;
  if (x < 0.0) return -1;
  return 0;
}

Instead, I propose this functionality: On -0.0, +NaN, -NaN, it returns -0.0, +NaN, -NaN.

double signnum_c(double x) {
  if (x > 0.0) return 1.0;
  if (x < 0.0) return -1.0;
  return x;
}

How to specify 64 bit integers in c

Use int64_t, that portable C99 code.

int64_t var = 0x0000444400004444LL;

For printing:

#define __STDC_FORMAT_MACROS
#include <inttypes.h>

printf("blabla %" PRIi64 " blabla\n", var);

Create a .tar.bz2 file Linux

Try this from different folder:

sudo tar -cvjSf folder.tar.bz2 folder/*

How to get the host name of the current machine as defined in the Ansible hosts file?

The necessary variable is inventory_hostname.

- name: Install this only for local dev machine
  pip: name=pyramid
  when: inventory_hostname == "local"

It is somewhat hidden in the documentation at the bottom of this section.

SQL grammar for SELECT MIN(DATE)

You need to use GROUP BY instead of DISTINCT if you want to use aggregation functions.

SELECT title, MIN(date)
FROM table
GROUP BY title

Taking inputs with BufferedReader in Java

The problem id because of inp.read(); method. Its return single character at a time and because you are storing it into int type of array so that is just storing ascii value of that.

What you can do simply

for(int i=0;i<T;i++) {
    String s= inp.readLine();
    String[] intValues = inp.readLine().split(" ");
    int[] m= new int[2];
    m[0]=Integer.parseInt(intValues[0]);
    m[1]=Integer.parseInt(intValues[1]);

    // Checking whether I am taking the inputs correctly
    System.out.println(s);
    System.out.println(m[0]);
    System.out.println(m[1]);
}

Checking for directory and file write permissions in .NET

Since the static method 'GetAccessControl' seems to be missing from the present version of .Net core/Standard I had to modify @Bryce Wagner's answer (I went ahead and used more modern syntax):

public static class PermissionHelper
{
  public static bool? CurrentUserHasWritePermission(string filePath)

     => new WindowsPrincipal(WindowsIdentity.GetCurrent())
        .SelectWritePermissions(filePath)
        .FirstOrDefault();


  private static IEnumerable<bool?> SelectWritePermissions(this WindowsPrincipal user, string filePath)
     => from rule in filePath
                    .GetFileSystemSecurity()
                    .GetAccessRules(true, true, typeof(NTAccount))
                    .Cast<FileSystemAccessRule>()
        let right = user.HasRightSafe(rule)
        where right.HasValue
        // Deny takes precedence over allow
        orderby right.Value == false descending
        select right;


  private static bool? HasRightSafe(this WindowsPrincipal user, FileSystemAccessRule rule)
  {
     try
     {
        return user.HasRight(rule);
     }
     catch
     {
        return null;
     }
  }

  private static bool? HasRight(this WindowsPrincipal user,FileSystemAccessRule rule )
     => rule switch
     {
        { FileSystemRights: FileSystemRights fileSystemRights } when (fileSystemRights &
                                                                      (FileSystemRights.WriteData | FileSystemRights.Write)) == 0 => null,
        { IdentityReference: { Value: string value } } when value.StartsWith("S-1-") &&
                                                            !user.IsInRole(new SecurityIdentifier(rule.IdentityReference.Value)) => null,
        { IdentityReference: { Value: string value } } when value.StartsWith("S-1-") == false &&
                                                            !user.IsInRole(rule.IdentityReference.Value) => null,
        { AccessControlType: AccessControlType.Deny } => false,
        { AccessControlType: AccessControlType.Allow } => true,
        _ => null
     };


  private static FileSystemSecurity GetFileSystemSecurity(this string filePath)
    => new FileInfo(filePath) switch
    {
       { Exists: true } fileInfo => fileInfo.GetAccessControl(),
       { Exists: false } fileInfo => (FileSystemSecurity)fileInfo.Directory.GetAccessControl(),
       _ => throw new Exception($"Check the file path, {filePath}: something's wrong with it.")
    };
}

RuntimeWarning: DateTimeField received a naive datetime

If you are trying to transform a naive datetime into a datetime with timezone in django, here is my solution:

>>> import datetime
>>> from django.utils import timezone
>>> t1 = datetime.datetime.strptime("2019-07-16 22:24:00", "%Y-%m-%d %H:%M:%S")
>>> t1
    datetime.datetime(2019, 7, 16, 22, 24)
>>> current_tz = timezone.get_current_timezone()
>>> t2 = current_tz.localize(t1)
>>> t2
    datetime.datetime(2019, 7, 16, 22, 24, tzinfo=<DstTzInfo 'Asia/Shanghai' CST+8:00:00 STD>)
>>>

t1 is a naive datetime and t2 is a datetime with timezone in django's settings.

How to find out if an installed Eclipse is 32 or 64 bit version?

Go to the Eclipse base folder ? open eclipse.ini ? you will find the below line at line no 4:

plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.200.v20150204-1316 plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.200.v20120913-144807

As you can see, line 1 is of 64-bit Eclipse. It contains x86_64 and line 2 is of 32-bit Eclipse. It contains x_86.

For 32-bit Eclipse only x86 will be present and for 64-bit Eclipse x86_64 will be present.

How to instantiate a File object in JavaScript?

According to the W3C File API specification, the File constructor requires 2 (or 3) parameters.

So to create a empty file do:

var f = new File([""], "filename");
  • The first argument is the data provided as an array of lines of text;
  • The second argument is the filename ;
  • The third argument looks like:

    var f = new File([""], "filename.txt", {type: "text/plain", lastModified: date})
    

It works in FireFox, Chrome and Opera, but not in Safari or IE/Edge.

Groovy String to Date

The first argument to parse() is the expected format. You have to change that to Date.parse("E MMM dd H:m:s z yyyy", testDate) for it to work. (Note you don't need to create a new Date object, it's a static method)

If you don't know in advance what format, you'll have to find a special parsing library for that. In Ruby there's a library called Chronic, but I'm not aware of a Groovy equivalent. Edit: There is a Java port of the library called jChronic, you might want to check it out.

How to get a DOM Element from a JQuery Selector

I needed to get the element as a string.

jQuery("#bob").get(0).outerHTML;

Which will give you something like:

<input type="text" id="bob" value="hello world" />

...as a string rather than a DOM element.

sys.argv[1], IndexError: list index out of range

I've done some research and it seems that the sys.argv might require an argument at the command line when running the script

Not might, but definitely requires. That's the whole point of sys.argv, it contains the command line arguments. Like any python array, accesing non-existent element raises IndexError.

Although the code uses try/except to trap some errors, the offending statement occurs in the first line.

So the script needs a directory name, and you can test if there is one by looking at len(sys.argv) and comparing to 1+number_of_requirements. The argv always contains the script name plus any user supplied parameters, usually space delimited but the user can override the space-split through quoting. If the user does not supply the argument, your choices are supplying a default, prompting the user, or printing an exit error message.

To print an error and exit when the argument is missing, add this line before the first use of sys.argv:

if len(sys.argv)<2:
    print "Fatal: You forgot to include the directory name on the command line."
    print "Usage:  python %s <directoryname>" % sys.argv[0]
    sys.exit(1)

sys.argv[0] always contains the script name, and user inputs are placed in subsequent slots 1, 2, ...

see also:

How to comment/uncomment in HTML code

No. Unless you find a tool that does what you described for you.

Java - creating a new thread

You can do like:

    Thread t1 = new Thread(new Runnable() {
    public void run()
    {
         // code goes here.
    }});  
    t1.start();

ViewBag, ViewData and TempData

ASP.NET MVC offers us three options ViewData, ViewBag, and TempData for passing data from controller to view and in next request. ViewData and ViewBag are almost similar and TempData performs additional responsibility. Lets discuss or get key points on those three objects:

Similarities between ViewBag & ViewData :

  • Helps to maintain data when you move from controller to view.
  • Used to pass data from controller to corresponding view.
  • Short life means value becomes null when redirection occurs. This is because their goal is to provide a way to communicate between controllers and views. It’s a communication mechanism within the server call.

Difference between ViewBag & ViewData:

  • ViewData is a dictionary of objects that is derived from ViewDataDictionary class and accessible using strings as keys.
  • ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
  • ViewData requires typecasting for complex data type and check for null values to avoid error.
  • ViewBag doesn’t require typecasting for complex data type.

ViewBag & ViewData Example:

public ActionResult Index()
{
    ViewBag.Name = "Monjurul Habib";
    return View();
}


public ActionResult Index()
{
    ViewData["Name"] = "Monjurul Habib";
    return View();
} 

In View:

@ViewBag.Name 
@ViewData["Name"] 

TempData:

TempData is also a dictionary derived from TempDataDictionary class and stored in short lives session and it is a string key and object value. The difference is that the life cycle of the object. TempData keep the information for the time of an HTTP Request. This mean only from one page to another. This also work with a 302/303 redirection because it’s in the same HTTP Request. Helps to maintain data when you move from one controller to other controller or from one action to other action. In other words when you redirect, “TempData” helps to maintain data between those redirects. It internally uses session variables. Temp data use during the current and subsequent request only means it is use when you are sure that next request will be redirecting to next view. It requires typecasting for complex data type and check for null values to avoid error. Generally used to store only one time messages like error messages, validation messages.

public ActionResult Index()
{
  var model = new Review()
            {
                Body = "Start",
                Rating=5
            };
    TempData["ModelName"] = model;
    return RedirectToAction("About");
}

public ActionResult About()
{
    var model= TempData["ModelName"];
    return View(model);
}

The last mechanism is the Session which work like the ViewData, like a Dictionary that take a string for key and object for value. This one is stored into the client Cookie and can be used for a much more long time. It also need more verification to never have any confidential information. Regarding ViewData or ViewBag you should use it intelligently for application performance. Because each action goes through the whole life cycle of regular asp.net mvc request. You can use ViewData/ViewBag in your child action but be careful that you are not using it to populate the unrelated data which can pollute your controller.

How To Save Canvas As An Image With canvas.toDataURL()?

@Wardenclyffe and @SColvin, you both are trying to save image using the canvas, not by using canvas's context. both you should try to ctx.toDataURL(); Try This:

var canvas1 = document.getElementById("yourCanvasId");  <br>
var ctx = canvas1.getContext("2d");<br>
var img = new Image();<br>
img.src = ctx.toDataURL('image/png');<br>
ctx.drawImage(img,200,150);<br>

Also you may refer to following links:

http://tutorials.jenkov.com/html5-canvas/todataurl.html

http://www.w3.org/TR/2012/WD-html5-author-20120329/the-canvas-element.html#the-canvas-element

Windows ignores JAVA_HOME: how to set JDK as default?

For my Case in 'Path' variable there was a parameter added like 'C:\ProgramData\Oracle\Java\javapath;'. This location was having java.exe, javaw.exe and javaws.exe from java 8 which is newly installed via jdk.exe from Oracle.

I've removed this text from Path where my Path already having %JAVA_HOME%\bin with it.

Now, the variable 'JAVA_HOME' is controlling my Java version which is I wanted.

HTTP Error 404.3-Not Found in IIS 7.5

In windows server 2012, even after installing asp.net you might run into this issue.

Check for "Http activation" feature. This feature is present under Web services as well.

Make sure you add the above and everything should be awesome for you !!!

How to Call a JS function using OnClick event

Using the onclick attribute or applying a function to your JS onclick properties will erase your onclick initialization in <head>.

What you need to do is add click events on your button. To do that you’ll need the addEventListener or attachEvent (IE) method.

<!DOCTYPE html>
<html>
<head>
    <script>
        function addEvent(obj, event, func) {
            if (obj.addEventListener) {
                obj.addEventListener(event, func, false);
                return true;
            } else if (obj.attachEvent) {
                obj.attachEvent('on' + event, func);
            } else {
                var f = obj['on' + event];
                obj['on' + event] = typeof f === 'function' ? function() {
                    f();
                    func();
                } : func
            }
        }

        function f1()
        {
            alert("f1 called");
            //form validation that recalls the page showing with supplied inputs.    
        }
    </script>
</head>
<body>
    <form name="form1" id="form1" method="post">
        State: <select id="state ID">
        <option></option>
        <option value="ap">ap</option>
        <option value="bp">bp</option>
        </select>
    </form>

    <table><tr><td id="Save" onclick="f1()">click</td></tr></table>

    <script>
        addEvent(document.getElementById('Save'), 'click', function() {
            alert('hello');
        });
    </script>
</body>
</html>

AngularJS ng-style with a conditional expression

You can achieve it like that:

ng-style="{ 'width' : (myObject.value == 'ok') ? '100%' : '0%' }"

Detect whether a Python string is a number or a letter

Check if string is positive digit (integer) and alphabet

You may use str.isdigit() and str.isalpha() to check whether given string is positive integer and alphabet respectively.

Sample Results:

# For alphabet
>>> 'A'.isdigit()
False
>>> 'A'.isalpha()
True

# For digit
>>> '1'.isdigit()
True
>>> '1'.isalpha()
False

Check for strings as positive/negative - integer/float

str.isdigit() returns False if the string is a negative number or a float number. For example:

# returns `False` for float
>>> '123.3'.isdigit()
False
# returns `False` for negative number
>>> '-123'.isdigit()
False

If you want to also check for the negative integers and float, then you may write a custom function to check for it as:

def is_number(n):
    try:
        float(n)   # Type-casting the string to `float`.
                   # If string is not a valid `float`, 
                   # it'll raise `ValueError` exception
    except ValueError:
        return False
    return True

Sample Run:

>>> is_number('123')    # positive integer number
True

>>> is_number('123.4')  # positive float number
True
 
>>> is_number('-123')   # negative integer number
True

>>> is_number('-123.4') # negative `float` number
True

>>> is_number('abc')    # `False` for "some random" string
False

Discard "NaN" (not a number) strings while checking for number

The above functions will return True for the "NAN" (Not a number) string because for Python it is valid float representing it is not a number. For example:

>>> is_number('NaN')
True

In order to check whether the number is "NaN", you may use math.isnan() as:

>>> import math
>>> nan_num = float('nan')

>>> math.isnan(nan_num)
True

Or if you don't want to import additional library to check this, then you may simply check it via comparing it with itself using ==. Python returns False when nan float is compared with itself. For example:

# `nan_num` variable is taken from above example
>>> nan_num == nan_num
False

Hence, above function is_number can be updated to return False for "NaN" as:

def is_number(n):
    is_number = True
    try:
        num = float(n)
        # check for "nan" floats
        is_number = num == num   # or use `math.isnan(num)`
    except ValueError:
        is_number = False
    return is_number

Sample Run:

>>> is_number('Nan')   # not a number "Nan" string
False

>>> is_number('nan')   # not a number string "nan" with all lower cased
False

>>> is_number('123')   # positive integer
True

>>> is_number('-123')  # negative integer
True

>>> is_number('-1.12') # negative `float`
True

>>> is_number('abc')   # "some random" string
False

Allow Complex Number like "1+2j" to be treated as valid number

The above function will still return you False for the complex numbers. If you want your is_number function to treat complex numbers as valid number, then you need to type cast your passed string to complex() instead of float(). Then your is_number function will look like:

def is_number(n):
    is_number = True
    try:
        #      v type-casting the number here as `complex`, instead of `float`
        num = complex(n)
        is_number = num == num
    except ValueError:
        is_number = False
    return is_number

Sample Run:

>>> is_number('1+2j')    # Valid 
True                     #      : complex number 

>>> is_number('1+ 2j')   # Invalid 
False                    #      : string with space in complex number represetantion
                         #        is treated as invalid complex number

>>> is_number('123')     # Valid
True                     #      : positive integer

>>> is_number('-123')    # Valid 
True                     #      : negative integer

>>> is_number('abc')     # Invalid 
False                    #      : some random string, not a valid number

>>> is_number('nan')     # Invalid
False                    #      : not a number "nan" string

PS: Each operation for each check depending on the type of number comes with additional overhead. Choose the version of is_number function which fits your requirement.

codes for ADD,EDIT,DELETE,SEARCH in vb2010

A good resource start off point would be MSDN as your looking into a microsoft product

Laravel 5.1 - Checking a Database Connection

You can use this, in a controller method or in an inline function of a route:

   try {
        DB::connection()->getPdo();
        if(DB::connection()->getDatabaseName()){
            echo "Yes! Successfully connected to the DB: " . DB::connection()->getDatabaseName();
        }else{
            die("Could not find the database. Please check your configuration.");
        }
    } catch (\Exception $e) {
        die("Could not open connection to database server.  Please check your configuration.");
    }

Difference between PACKETS and FRAMES

Packet

A packet is the unit of data that is routed between an origin and a destination on the Internet or any other packet-switched network. When any file (e-mail message, HTML file, Graphics Interchange Format file, Uniform Resource Locator request, and so forth) is sent from one place to another on the Internet, the Transmission Control Protocol (TCP) layer of TCP/IP divides the file into "chunks" of an efficient size for routing. Each of these packets is separately numbered and includes the Internet address of the destination. The individual packets for a given file may travel different routes through the Internet. When they have all arrived, they are reassembled into the original file (by the TCP layer at the receiving end).

Frame

1) In telecommunications, a frame is data that is transmitted between network points as a unit complete with addressing and necessary protocol control information. A frame is usually transmitted serial bit by bit and contains a header field and a trailer field that "frame" the data. (Some control frames contain no data.)

2) In time-division multiplexing (TDM), a frame is a complete cycle of events within the time division period.

3) In film and video recording and playback, a frame is a single image in a sequence of images that are recorded and played back.

4) In computer video display technology, a frame is the image that is sent to the display image rendering devices. It is continuously updated or refreshed from a frame buffer, a highly accessible part of video RAM.

5) In artificial intelligence (AI) applications, a frame is a set of data with information about a particular object, process, or image. An example is the iris-print visual recognition system used to identify users of certain bank automated teller machines. This system compares the frame of data for a potential user with the frames in its database of authorized users.

Why does Math.Round(2.5) return 2 instead of 3?

Here's the way i had to work it around :

Public Function Round(number As Double, dec As Integer) As Double
    Dim decimalPowerOfTen = Math.Pow(10, dec)
    If CInt(number * decimalPowerOfTen) = Math.Round(number * decimalPowerOfTen, 2) Then
        Return Math.Round(number, 2, MidpointRounding.AwayFromZero)
    Else
        Return CInt(number * decimalPowerOfTen + 0.5) / 100
    End If
End Function

Trying with 1.905 with 2 decimals will give 1.91 as expected but Math.Round(1.905,2,MidpointRounding.AwayFromZero) gives 1.90! Math.Round method is absolutely inconsistent and unusable for most of the basics problems programmers may encounter. I have to check if (int) 1.905 * decimalPowerOfTen = Math.Round(number * decimalPowerOfTen, 2) cause i don not want to round up what should be round down.

Bootstrap - 5 column layout

Why not using grid?

.container {
  display: grid;
  grid-template-columns: repeat(5, minmax(0, 1fr));
  grid-column-gap: 20px
}

What is the best algorithm for overriding GetHashCode?

This is a good one:

/// <summary>
/// Helper class for generating hash codes suitable 
/// for use in hashing algorithms and data structures like a hash table. 
/// </summary>
public static class HashCodeHelper
{
    private static int GetHashCodeInternal(int key1, int key2)
    {
        unchecked
        {
           var num = 0x7e53a269;
           num = (-1521134295 * num) + key1;
           num += (num << 10);
           num ^= (num >> 6);

           num = ((-1521134295 * num) + key2);
           num += (num << 10);
           num ^= (num >> 6);

           return num;
        }
    }

    /// <summary>
    /// Returns a hash code for the specified objects
    /// </summary>
    /// <param name="arr">An array of objects used for generating the 
    /// hash code.</param>
    /// <returns>
    /// A hash code, suitable for use in hashing algorithms and data 
    /// structures like a hash table. 
    /// </returns>
    public static int GetHashCode(params object[] arr)
    {
        int hash = 0;
        foreach (var item in arr)
            hash = GetHashCodeInternal(hash, item.GetHashCode());
        return hash;
    }

    /// <summary>
    /// Returns a hash code for the specified objects
    /// </summary>
    /// <param name="obj1">The first object.</param>
    /// <param name="obj2">The second object.</param>
    /// <param name="obj3">The third object.</param>
    /// <param name="obj4">The fourth object.</param>
    /// <returns>
    /// A hash code, suitable for use in hashing algorithms and
    /// data structures like a hash table.
    /// </returns>
    public static int GetHashCode<T1, T2, T3, T4>(T1 obj1, T2 obj2, T3 obj3,
        T4 obj4)
    {
        return GetHashCode(obj1, GetHashCode(obj2, obj3, obj4));
    }

    /// <summary>
    /// Returns a hash code for the specified objects
    /// </summary>
    /// <param name="obj1">The first object.</param>
    /// <param name="obj2">The second object.</param>
    /// <param name="obj3">The third object.</param>
    /// <returns>
    /// A hash code, suitable for use in hashing algorithms and data 
    /// structures like a hash table. 
    /// </returns>
    public static int GetHashCode<T1, T2, T3>(T1 obj1, T2 obj2, T3 obj3)
    {
        return GetHashCode(obj1, GetHashCode(obj2, obj3));
    }

    /// <summary>
    /// Returns a hash code for the specified objects
    /// </summary>
    /// <param name="obj1">The first object.</param>
    /// <param name="obj2">The second object.</param>
    /// <returns>
    /// A hash code, suitable for use in hashing algorithms and data 
    /// structures like a hash table. 
    /// </returns>
    public static int GetHashCode<T1, T2>(T1 obj1, T2 obj2)
    {
        return GetHashCodeInternal(obj1.GetHashCode(), obj2.GetHashCode());
    }
}

And here is how to use it:

private struct Key
{
    private Type _type;
    private string _field;

    public Type Type { get { return _type; } }
    public string Field { get { return _field; } }

    public Key(Type type, string field)
    {
        _type = type;
        _field = field;
    }

    public override int GetHashCode()
    {
        return HashCodeHelper.GetHashCode(_field, _type);
    }

    public override bool Equals(object obj)
    {
        if (!(obj is Key))
            return false;
        var tf = (Key)obj;
        return tf._field.Equals(_field) && tf._type.Equals(_type);
    }
}

Parsing JSON in Java without knowing JSON format

To get JSON quickly into Java objects (Maps) that you can then 'drill' and work with, you can use json-io (https://github.com/jdereg/json-io). This library will let you read in a JSON String, and get back a 'Map of Maps' representation.

If you have the corresponding Java classes in your JVM, you can read the JSON in and it will parse it directly into instances of the Java classes.

JsonReader.jsonToMaps(String json)

where json is the String containing the JSON to be read. The return value is a Map where the keys will contain the JSON fields, and the values will contain the associated values.

JsonReader.jsonToJava(String json) 

will read the same JSON string in, and the return value will be the Java instance that was serialized into the JSON. Use this API if you have the classes in your JVM that were written by

JsonWriter.objectToJson(MyClass foo).

How do you see the entire command history in interactive Python?

In IPython %history -g should give you the entire command history. The default configuration also saves your history into a file named .python_history in your user directory.

Is there a way to delete all the data from a topic or delete the topic before every run?

In manually deleting a topic from a kafka cluster , you just might check this out https://github.com/darrenfu/bigdata/issues/6 A vital step missed a lot in most solution is in deleting the /config/topics/<topic_name> in ZK.

Uploading Images to Server android

use below code it helps you....

        BitmapFactory.Options options = new BitmapFactory.Options();

        options.inSampleSize = 4;
        options.inPurgeable = true;
        Bitmap bm = BitmapFactory.decodeFile("your path of image",options);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        bm.compress(Bitmap.CompressFormat.JPEG,40,baos); 


        // bitmap object

        byteImage_photo = baos.toByteArray();

                    //generate base64 string of image

                   String encodedImage =Base64.encodeToString(byteImage_photo,Base64.DEFAULT);

  //send this encoded string to server

PostgreSQL, checking date relative to "today"

This should give you the current date minus 1 year:

select now() - interval '1 year';

Detect application heap size in Android

Debug.getNativeHeapSize() will do the trick, I should think. It's been there since 1.0, though.

The Debug class has lots of great methods for tracking allocations and other performance concerns. Also, if you need to detect a low-memory situation, check out Activity.onLowMemory().

Combating AngularJS executing controller twice

The app router specified navigation to MyController like so:

$routeProvider.when('/',
                   { templateUrl: 'pages/home.html',
                     controller: MyController });

But I also had this in home.html:

<div data-ng-controller="MyController">

This digested the controller twice. Removing the data-ng-controller attribute from the HTML resolved the issue. Alternatively, the controller: property could have been removed from the routing directive.

This problem also appears when using tabbed navigation. For example, app.js might contain:

  .state('tab.reports', {
    url: '/reports',
    views: {
      'tab-reports': {
        templateUrl: 'templates/tab-reports.html',
        controller: 'ReportsCtrl'
      }
    }
  })

The corresponding reports tab HTML might resemble:

<ion-view view-title="Reports">
  <ion-content ng-controller="ReportsCtrl">

This will also result in running the controller twice.

What is the difference between Left, Right, Outer and Inner Joins?

Simple Example: Let's say you have a Students table, and a Lockers table. In SQL, the first table you specify in a join, Students, is the LEFT table, and the second one, Lockers, is the RIGHT table.

Each student can be assigned to a locker, so there is a LockerNumber column in the Student table. More than one student could potentially be in a single locker, but especially at the beginning of the school year, you may have some incoming students without lockers and some lockers that have no students assigned.

For the sake of this example, let's say you have 100 students, 70 of which have lockers. You have a total of 50 lockers, 40 of which have at least 1 student and 10 lockers have no student.

INNER JOIN is equivalent to "show me all students with lockers".
Any students without lockers, or any lockers without students are missing.
Returns 70 rows

LEFT OUTER JOIN would be "show me all students, with their corresponding locker if they have one".
This might be a general student list, or could be used to identify students with no locker.
Returns 100 rows

RIGHT OUTER JOIN would be "show me all lockers, and the students assigned to them if there are any".
This could be used to identify lockers that have no students assigned, or lockers that have too many students.
Returns 80 rows (list of 70 students in the 40 lockers, plus the 10 lockers with no student)

FULL OUTER JOIN would be silly and probably not much use.
Something like "show me all students and all lockers, and match them up where you can"
Returns 110 rows (all 100 students, including those without lockers. Plus the 10 lockers with no student)

CROSS JOIN is also fairly silly in this scenario.
It doesn't use the linked lockernumber field in the students table, so you basically end up with a big giant list of every possible student-to-locker pairing, whether or not it actually exists.
Returns 5000 rows (100 students x 50 lockers). Could be useful (with filtering) as a starting point to match up the new students with the empty lockers.

Sleep function Visual Basic

Since you are asking about .NET, you should change the parameter from Long to Integer. .NET's Integer is 32-bit. (Classic VB's integer was only 16-bit.)

Declare Sub Sleep Lib "kernel32.dll" (ByVal Milliseconds As Integer)

Really though, the managed method isn't difficult...

System.Threading.Thread.CurrentThread.Sleep(5000)

Be careful when you do this. In a forms application, you block the message pump and what not, making your program to appear to have hanged. Rarely is sleep a good idea.

Location of WSDL.exe

It is included with .NET (not sure if only in the SDK).

Converting Columns into rows with their respective data in sql server

i solved the query this way

SELECT
    ca.ID, ca.[Name]
FROM [Emp2]
CROSS APPLY (
      Values
         ('ID' , cast(ID as varchar)),
         ('[Name]' , Name)

  ) as CA (ID, Name)

output look like

  ID     Name
------ --------------------------------------------------
ID     1
[Name] Joy
ID     2
[Name] jean
ID     4
[Name] paul

Center button under form in bootstrap

Try adding this class

class="pager"

<p class="pager" style="line-height: 70px;">
    <button type="submit" class="btn">Confirm</button>
</p>

I tried mine within a <div class=pager><button etc etc></div> which worked well

See http://getbootstrap.com/components/ look under Pagination -> Pager

This looks like the correct bootstrap class to center this, text-align: center; is meant for text not images and blocks etc.

How to save data in an android app

In my opinion db4o is the easiest way to go. Here you can find a tutorial: http://community.versant.com/documentation/reference/db4o-7.12/java/tutorial/

And here you can download the library:

http://www.db4o.com/community/download.aspx?file=db4o-8.0-java.zip

(Just put the db4o-8.0...-all-java5.jar in the lib directory into your project's libs folder. If there is no libs folder in you project create it)

As db4o is a object oriented database system you can directly save you objects into the database and later get them back.

asp.net validation to make sure textbox has integer values

You can use java script for this:-

<asp:TextBox ID="textbox1" runat="server" Width="150px" MaxLength="8" onkeypress="if(event.keyCode<48 || event.keyCode>57)event.returnValue=false;"></asp:TextBox>

Type converting slices of interfaces

In case you need more shorting your code, you can creating new type for helper

type Strings []string

func (ss Strings) ToInterfaceSlice() []interface{} {
    iface := make([]interface{}, len(ss))
    for i := range ss {
        iface[i] = ss[i]
    }
    return iface
}

then

a := []strings{"a", "b", "c", "d"}
sliceIFace := Strings(a).ToInterfaceSlice()

How can I split and parse a string in Python?

Python string parsing walkthrough

Split a string on space, get a list, show its type, print it out:

el@apollo:~/foo$ python
>>> mystring = "What does the fox say?"

>>> mylist = mystring.split(" ")

>>> print type(mylist)
<type 'list'>

>>> print mylist
['What', 'does', 'the', 'fox', 'say?']

If you have two delimiters next to each other, empty string is assumed:

el@apollo:~/foo$ python
>>> mystring = "its  so   fluffy   im gonna    DIE!!!"

>>> print mystring.split(" ")
['its', '', 'so', '', '', 'fluffy', '', '', 'im', 'gonna', '', '', '', 'DIE!!!']

Split a string on underscore and grab the 5th item in the list:

el@apollo:~/foo$ python
>>> mystring = "Time_to_fire_up_Kowalski's_Nuclear_reactor."

>>> mystring.split("_")[4]
"Kowalski's"

Collapse multiple spaces into one

el@apollo:~/foo$ python
>>> mystring = 'collapse    these       spaces'

>>> mycollapsedstring = ' '.join(mystring.split())

>>> print mycollapsedstring.split(' ')
['collapse', 'these', 'spaces']

When you pass no parameter to Python's split method, the documentation states: "runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace".

Hold onto your hats boys, parse on a regular expression:

el@apollo:~/foo$ python
>>> mystring = 'zzzzzzabczzzzzzdefzzzzzzzzzghizzzzzzzzzzzz'
>>> import re
>>> mylist = re.split("[a-m]+", mystring)
>>> print mylist
['zzzzzz', 'zzzzzz', 'zzzzzzzzz', 'zzzzzzzzzzzz']

The regular expression "[a-m]+" means the lowercase letters a through m that occur one or more times are matched as a delimiter. re is a library to be imported.

Or if you want to chomp the items one at a time:

el@apollo:~/foo$ python
>>> mystring = "theres coffee in that nebula"

>>> mytuple = mystring.partition(" ")

>>> print type(mytuple)
<type 'tuple'>

>>> print mytuple
('theres', ' ', 'coffee in that nebula')

>>> print mytuple[0]
theres

>>> print mytuple[2]
coffee in that nebula

Try catch statements in C

In C, you can "simulate" exceptions along with automatic "object reclamation" through manual use of if + goto for explicit error handling.

I often write C code like the following (boiled down to highlight error handling):

#include <assert.h>

typedef int errcode;

errcode init_or_fail( foo *f, goo *g, poo *p, loo *l )
{
    errcode ret = 0;

    if ( ( ret = foo_init( f ) ) )
        goto FAIL;

    if ( ( ret = goo_init( g ) ) )
        goto FAIL_F;

    if ( ( ret = poo_init( p ) ) )
        goto FAIL_G;

    if ( ( ret = loo_init( l ) ) )
        goto FAIL_P;

    assert( 0 == ret );
    goto END;

    /* error handling and return */

    /* Note that we finalize in opposite order of initialization because we are unwinding a *STACK* of initialized objects */

FAIL_P:
    poo_fini( p );

FAIL_G:
    goo_fini( g );

FAIL_F:
    foo_fini( f );

FAIL:
    assert( 0 != ret );

END:
    return ret;        
}

This is completely standard ANSI C, separates the error handling away from your mainline code, allows for (manual) stack unwinding of initialized objects much like C++ does, and it is completely obvious what is happening here. Because you are explicitly testing for failure at each point it does make it easier to insert specific logging or error handling at each place an error can occur.

If you don't mind a little macro magic, then you can make this more concise while doing other things like logging errors with stack traces. For example:

#include <assert.h>
#include <stdio.h>
#include <string.h>

#define TRY( X, LABEL ) do { if ( ( X ) ) { fprintf( stderr, "%s:%d: Statement '" #X "' failed! %d, %s\n", __FILE__, __LINE__, ret, strerror( ret ) ); goto LABEL; } while ( 0 )

typedef int errcode;

errcode init_or_fail( foo *f, goo *g, poo *p, loo *l )
{
    errcode ret = 0;

    TRY( ret = foo_init( f ), FAIL );
    TRY( ret = goo_init( g ), FAIL_F );
    TRY( ret = poo_init( p ), FAIL_G );
    TRY( ret = loo_init( l ), FAIL_P );

    assert( 0 == ret );
    goto END;

    /* error handling and return */

FAIL_P:
    poo_fini( p );

FAIL_G:
    goo_fini( g );

FAIL_F:
    foo_fini( f );

FAIL:
    assert( 0 != ret );

END:
    return ret;        
}

Of course, this isn't as elegant as C++ exceptions + destructors. For example, nesting multiple error handling stacks within one function this way isn't very clean. Instead, you'd probably want to break those out into self contained sub functions that similarly handle errors, initialize + finalize explicitly like this.

This also only works within a single function and won't keep jumping up the stack unless higher level callers implement similar explicit error handling logic, whereas a C++ exception will just keep jumping up the stack until it finds an appropriate handler. Nor does it allow you to throw an arbitrary type, but instead only an error code.

Systematically coding this way (i.e. - with a single entry and single exit point) also makes it very easy to insert pre and post ("finally") logic that will execute no matter what. You just put your "finally" logic after the END label.

How do I send an HTML Form in an Email .. not just MAILTO

I don't know that what you want to do is possible. From my understanding, sending an email from a web form requires a server side language to communicate with a mail server and send messages.

Are you running PHP or ASP.NET?

ASP.NET Example

PHP Example

Rotating a point about another point (2D)

First subtract the pivot point (cx,cy), then rotate it, then add the point again.

Untested:

POINT rotate_point(float cx,float cy,float angle,POINT p)
{
  float s = sin(angle);
  float c = cos(angle);

  // translate point back to origin:
  p.x -= cx;
  p.y -= cy;

  // rotate point
  float xnew = p.x * c - p.y * s;
  float ynew = p.x * s + p.y * c;

  // translate point back:
  p.x = xnew + cx;
  p.y = ynew + cy;
  return p;
}

Change Project Namespace in Visual Studio

Instead of Find & Replace, you can right click the namespace in code and Refactor -> Rename.

Thanks to @Jimmy for this.

SSIS how to set connection string dynamically from a config file

First add a variable to your SSIS package (Package Scope) - I used FileName, OleRootFilePath, OleProperties, OleProvider. The type for each variable is "string". Then I create a Configuration file (Select each variable - value) - populate the values in the configuration file - Eg: for OleProperties - Microsoft.ACE.OLEDB.12.0; for OleProperties - Excel 8.0;HDR=, OleRootFilePath - Your Excel file path, FileName - FileName

In the Connection manager - I then set the Properties-> Expressions-> Connection string expression dynamically eg:

"Provider=" + @[User::OleProvider] + "Data Source=" + @[User::OleRootFilePath]
+ @[User::FileName]  + ";Extended Properties=\"" + @[User::OleProperties] + "NO \""+";"

This way once you set the variables values and change it in your configuration file - the connection string will change dynamically - this helps especially in moving from development to production environments.

database vs. flat files

Unless you are loading the files into memory each time you boot, use a database. Simple as that.

That is assuming that your colleges already have the program to handle queries to the files. If not, then use a database.

Ternary operator in PowerShell

If you're just looking for a syntactically simple way to assign/return a string or numeric based on a boolean condition, you can use the multiplication operator like this:

"Condition is "+("true"*$condition)+("false"*!$condition)
(12.34*$condition)+(56.78*!$condition)

If you're only ever interested in the result when something is true, you can just omit the false part entirely (or vice versa), e.g. a simple scoring system:

$isTall = $true
$isDark = $false
$isHandsome = $true

$score = (2*$isTall)+(4*$isDark)+(10*$isHandsome)
"Score = $score"
# or
# "Score = $((2*$isTall)+(4*$isDark)+(10*$isHandsome))"

Note that the boolean value should not be the leading term in the multiplication, i.e. $condition*"true" etc. won't work.

How to split one string into multiple variables in bash shell?

If your solution doesn't have to be general, i.e. only needs to work for strings like your example, you could do:

var1=$(echo $STR | cut -f1 -d-)
var2=$(echo $STR | cut -f2 -d-)

I chose cut here because you could simply extend the code for a few more variables...

How can I install pip on Windows?

Working as of Feb 04 2014 :):

If you have tried installing pip through the Windows installer file from http://www.lfd.uci.edu/~gohlke/pythonlibs/#pip as suggested by @Colonel Panic, you might have installed the pip package manager successfully, but you might be unable to install any packages with pip. You might also have got the same SSL error as I got when I tried to install Beautiful Soup 4 if you look in the pip.log file:

Downloading/unpacking beautifulsoup4
  Getting page https://pypi.python.org/simple/beautifulsoup4/
  Could not fetch URL https://pypi.python.org/simple/beautifulsoup4/: **connection error: [Errno 1] _ssl.c:504: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed**
  Will skip URL https://pypi.python.org/simple/beautifulsoup4/ when looking for download links for beautifulsoup4

The problem is an issue with an old version of OpenSSL being incompatible with pip 1.3.1 and above versions. The easy workaround for now, is to install pip 1.2.1, which does not require SSL:

Installing Pip on Windows:

  1. Download pip 1.2.1 from https://pypi.python.org/packages/source/p/pip/pip-1.2.1.tar.gz
  2. Extract the pip-1.2.1.tar.gz file
  3. Change directory to the extracted folder: cd <path to extracted folder>/pip-1.2.1
  4. Run python setup.py install
  5. Now make sure C:\Python27\Scripts is in PATH because pip is installed in the C:\Python27\Scripts directory unlike C:\Python27\Lib\site-packages where Python packages are normally installed

Now try to install any package using pip.

For example, to install the requests package using pip, run this from cmd:

pip install requests

Whola! requests will be successfully installed and you will get a success message.

How do I find out what is hammering my SQL Server?

You can find some useful query here:

Investigating the Cause of SQL Server High CPU

For me this helped a lot:

SELECT s.session_id,
    r.status,
    r.blocking_session_id 'Blk by',
    r.wait_type,
    wait_resource,
    r.wait_time / (1000 * 60) 'Wait M',
    r.cpu_time,
    r.logical_reads,
    r.reads,
    r.writes,
    r.total_elapsed_time / (1000 * 60) 'Elaps M',
    Substring(st.TEXT,(r.statement_start_offset / 2) + 1,
    ((CASE r.statement_end_offset
WHEN -1
THEN Datalength(st.TEXT)
ELSE r.statement_end_offset
END - r.statement_start_offset) / 2) + 1) AS statement_text,
    Coalesce(Quotename(Db_name(st.dbid)) + N'.' + Quotename(Object_schema_name(st.objectid, st.dbid)) + N'.' +
    Quotename(Object_name(st.objectid, st.dbid)), '') AS command_text,
    r.command,
    s.login_name,
    s.host_name,
    s.program_name,
    s.last_request_end_time,
    s.login_time,
    r.open_transaction_count
FROM sys.dm_exec_sessions AS s
    JOIN sys.dm_exec_requests AS r
ON r.session_id = s.session_id
    CROSS APPLY sys.Dm_exec_sql_text(r.sql_handle) AS st
WHERE r.session_id != @@SPID
ORDER BY r.cpu_time desc

In the fields of status, wait_type and cpu_time you can find the most cpu consuming task that is running right now.

How to download Xcode DMG or XIP file?

You can find the DMGs or XIPs for Xcode and other development tools on https://developer.apple.com/download/more/ (requires Apple ID to login).

You must login to have a valid session before downloading anything below.

*(Newest on top. For each minor version (6.3, 5.1, etc.) only the latest revision is kept in the list.)

*With Xcode 12.2, Apple introduces the term “Release Candidate” (RC) which replaces “GM seed” and indicates this version is near final.

Xcode 12

  • 12.4 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later) (Latest as of 27-Jan-2021)

  • 12.3 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later)

  • 12.2

  • 12.1

  • 12.0.1 (Requires macOS 10.15.4 or later) (Latest as of 24-Sept-2020)

Xcode 11

Xcode 10 (unsupported for iTunes Connect)

  • 10.3 (Requires macOS 10.14.3 or later)
  • 10.2.1 (Requires macOS 10.14.3 or later)
  • 10.1 (Last version supporting macOS 10.13.6 High Sierra)
  • 10 (Subsequent versions were unsupported for iTunes Connect from March 2019)

Xcode 9

Xcode 8

Xcode 7

Xcode 6

Even Older Versions (unsupported for iTunes Connect)

How to undo last commit

Warning: Don't do this if you've already pushed

You want to do:

git reset HEAD~

If you don't want the changes and blow everything away:

git reset --hard HEAD~

Kubernetes service external ip pending

In case someone is using MicroK8s: You need a network load balancer.

MicroK8s comes with metallb, you can enable it like this:

microk8s enable metallb

<pending> should turn into an actual IP address then.

MySQL date format DD/MM/YYYY select query?

SELECT DATE_FORMAT(somedate, "%d/%m/%Y") AS formatted_date
..........
ORDER BY formatted_date DESC

How can I read a text file from the SD card in Android?

In response to

Don't hardcode /sdcard/

Sometimes we HAVE TO hardcode it as in some phone models the API method returns the internal phone memory.

Known types: HTC One X and Samsung S3.

Environment.getExternalStorageDirectory().getAbsolutePath() gives a different path - Android

CSS: fixed to bottom and centered

revised code by Daniel Kanis:

just change the following lines in CSS

.problem {text-align:center}
.enclose {position:fixed;bottom:0px;width:100%;}

and in html:

<p class="enclose problem">
Your footer text here.
</p>

Hour from DateTime? in 24 hours format

Using ToString("HH:mm") certainly gives you what you want as a string.

If you want the current hour/minute as numbers, string manipulation isn't necessary; you can use the TimeOfDay property:

TimeSpan timeOfDay = fechaHora.TimeOfDay;
int hour = timeOfDay.Hours;
int minute = timeOfDay.Minutes;

Count the number of occurrences of a string in a VARCHAR field?

try this:

 select TITLE,
        (length(DESCRIPTION )-length(replace(DESCRIPTION ,'value','')))/5 as COUNT 
  FROM <table> 


SQL Fiddle Demo

How to return temporary table from stored procedure

What version of SQL Server are you using? In SQL Server 2008 you can use Table Parameters and Table Types.

An alternative approach is to return a table variable from a user defined function but I am not a big fan of this method.

You can find an example here

Should I use encodeURI or encodeURIComponent for encoding URLs?

Here is a summary.

  1. escape() will not encode @ * _ + - . /

    Do not use it.

  2. encodeURI() will not encode A-Z a-z 0-9 ; , / ? : @ & = + $ - _ . ! ~ * ' ( ) #

    Use it when your input is a complete URL like 'https://searchexample.com/search?q=wiki'

  3. encodeURIComponent() will not encode A-Z a-z 0-9 - _ . ! ~ * ' ( ) Use it when your input is part of a complete URL e.g const queryStr = encodeURIComponent(someString)

Styling input buttons for iPad and iPhone

You may be looking for

-webkit-appearance: none;

What does .pack() do?

The pack method sizes the frame so that all its contents are at or above their preferred sizes. An alternative to pack is to establish a frame size explicitly by calling setSize or setBounds (which also sets the frame location). In general, using pack is preferable to calling setSize, since pack leaves the frame layout manager in charge of the frame size, and layout managers are good at adjusting to platform dependencies and other factors that affect component size.

From Java tutorial

You should also refer to Javadocs any time you need additional information on any Java API

What is the best way to get all the divisors of a number?

Old question, but here is my take:

def divs(n, m):
    if m == 1: return [1]
    if n % m == 0: return [m] + divs(n, m - 1)
    return divs(n, m - 1)

You can proxy with:

def divisorGenerator(n):
    for x in reversed(divs(n, n)):
        yield x

NOTE: For languages that support, this could be tail recursive.

Show two digits after decimal point in c++

Using header file stdio.h you can easily do it as usual like c. before using %.2lf(set a specific number after % specifier.) using printf().

It simply printf specific digits after decimal point.

#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
   double total=100;
   printf("%.2lf",total);//this prints 100.00 like as C
}

How can I implement a tree in Python?

anytree

I recommend https://pypi.python.org/pypi/anytree (I am the author)

Example

from anytree import Node, RenderTree

udo = Node("Udo")
marc = Node("Marc", parent=udo)
lian = Node("Lian", parent=marc)
dan = Node("Dan", parent=udo)
jet = Node("Jet", parent=dan)
jan = Node("Jan", parent=dan)
joe = Node("Joe", parent=dan)

print(udo)
Node('/Udo')
print(joe)
Node('/Udo/Dan/Joe')

for pre, fill, node in RenderTree(udo):
    print("%s%s" % (pre, node.name))
Udo
+-- Marc
¦   +-- Lian
+-- Dan
    +-- Jet
    +-- Jan
    +-- Joe

print(dan.children)
(Node('/Udo/Dan/Jet'), Node('/Udo/Dan/Jan'), Node('/Udo/Dan/Joe'))

Features

anytree has also a powerful API with:

  • simple tree creation
  • simple tree modification
  • pre-order tree iteration
  • post-order tree iteration
  • resolve relative and absolute node paths
  • walking from one node to an other.
  • tree rendering (see example above)
  • node attach/detach hookups

How to add two strings as if they were numbers?

MDN docs for parseInt
MDN docs for parseFloat

In parseInt radix is specified as ten so that we are in base 10. In nonstrict javascript a number prepended with 0 is treated as octal. This would obviously cause problems!

parseInt(num1, 10) + parseInt(num2, 10) //base10
parseFloat(num1) + parseFloat(num2)

Also see ChaosPandion's answer for a useful shortcut using a unary operator. I have set up a fiddle to show the different behaviors.

http://jsfiddle.net/EtX6G/

var ten = '10';
var zero_ten = '010';
var one = '1';
var body = document.getElementsByTagName('body')[0];

Append(parseInt(ten) + parseInt(one));
Append(parseInt(zero_ten) + parseInt(one));
Append(+ten + +one);
Append(+zero_ten + +one);

function Append(text) {
    body.appendChild(document.createTextNode(text));
    body.appendChild(document.createElement('br'));
}

Am I trying to connect to a TLS-enabled daemon without TLS?

You will need to do:

$boot2docker init
$boot2docker start

The following settings fixed the issue:

$export DOCKER_HOST=tcp://192.168.59.103:2376
$export DOCKER_CERT_PATH=/Users/{profileName}/.boot2docker/certs/boot2docker-vm
$export DOCKER_TLS_VERIFY=1

Ranges of floating point datatype in C?

Infinity, NaN and subnormals

These are important caveats that no other answer has mentioned so far.

First read this introduction to IEEE 754 and subnormal numbers: What is a subnormal floating point number?

Then, for single precision floats (32-bit):

  • IEEE 754 says that if the exponent is all ones (0xFF == 255), then it represents either NaN or Infinity.

    This is why the largest non-infinite number has exponent 0xFE == 254 and not 0xFF.

    Then with the bias, it becomes:

    254 - 127 == 127
    
  • FLT_MIN is the smallest normal number. But there are smaller subnormal ones! Those take up the -127 exponent slot.

All asserts of the following program pass on Ubuntu 18.04 amd64:

#include <assert.h>
#include <float.h>
#include <inttypes.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>

float float_from_bytes(
    uint32_t sign,
    uint32_t exponent,
    uint32_t fraction
) {
    uint32_t bytes;
    bytes = 0;
    bytes |= sign;
    bytes <<= 8;
    bytes |= exponent;
    bytes <<= 23;
    bytes |= fraction;
    return *(float*)&bytes;
}

int main(void) {
    /* All 1 exponent and non-0 fraction means NaN.
     * There are of course many possible representations,
     * and some have special semantics such as signalling vs not.
     */
    assert(isnan(float_from_bytes(0, 0xFF, 1)));
    assert(isnan(NAN));
    printf("nan                  = %e\n", NAN);

    /* All 1 exponent and 0 fraction means infinity. */
    assert(INFINITY == float_from_bytes(0, 0xFF, 0));
    assert(isinf(INFINITY));
    printf("infinity             = %e\n", INFINITY);

    /* ANSI C defines FLT_MAX as the largest non-infinite number. */
    assert(FLT_MAX == 0x1.FFFFFEp127f);
    /* Not 0xFF because that is infinite. */
    assert(FLT_MAX == float_from_bytes(0, 0xFE, 0x7FFFFF));
    assert(!isinf(FLT_MAX));
    assert(FLT_MAX < INFINITY);
    printf("largest non infinite = %e\n", FLT_MAX);

    /* ANSI C defines FLT_MIN as the smallest non-subnormal number. */
    assert(FLT_MIN == 0x1.0p-126f);
    assert(FLT_MIN == float_from_bytes(0, 1, 0));
    assert(isnormal(FLT_MIN));
    printf("smallest normal      = %e\n", FLT_MIN);

    /* The smallest non-zero subnormal number. */
    float smallest_subnormal = float_from_bytes(0, 0, 1);
    assert(smallest_subnormal == 0x0.000002p-126f);
    assert(0.0f < smallest_subnormal);
    assert(!isnormal(smallest_subnormal));
    printf("smallest subnormal   = %e\n", smallest_subnormal);

    return EXIT_SUCCESS;
}

GitHub upstream.

Compile and run with:

gcc -ggdb3 -O0 -std=c11 -Wall -Wextra -Wpedantic -Werror -o subnormal.out subnormal.c
./subnormal.out

Output:

nan                  = nan
infinity             = inf
largest non infinite = 3.402823e+38
smallest normal      = 1.175494e-38
smallest subnormal   = 1.401298e-45

How to select first and last TD in a row?

You could use the :first-child and :last-child pseudo-selectors:

tr td:first-child{
    color:red;
}
tr td:last-child {
    color:green
}

Or you can use other way like

// To first child 
tr td:nth-child(1){
    color:red;
}

// To last child 
tr td:nth-last-child(1){
    color:green;
}

Both way are perfectly working

ORA-00054: resource busy and acquire with NOWAIT specified or timeout expired

I had this error happen when I had 2 scripts I was running. I had:

  • A SQL*Plus session connected directly using a schema user account (account #1)
  • Another SQL*Plus session connected using a different schema user account (account #2), but connecting across a database link as the first account

I ran a table drop, then table creation as account #1. I ran a table update on account #2's session. Did not commit changes. Re-ran table drop/creation script as account #1. Got error on the drop table x command.

I solved it by running COMMIT; in the SQL*Plus session of account #2.

How to loop through a dataset in powershell?

The PowerShell string evaluation is calling ToString() on the DataSet. In order to evaluate any properties (or method calls), you have to force evaluation by enclosing the expression in $()

for($i=0;$i -lt $ds.Tables[1].Rows.Count;$i++)
{ 
  write-host "value is : $i $($ds.Tables[1].Rows[$i][0])"
}

Additionally foreach allows you to iterate through a collection or array without needing to figure out the length.

Rewritten (and edited for compile) -

foreach ($Row in $ds.Tables[1].Rows)
{ 
  write-host "value is : $($Row[0])"
}

Is it possible to append Series to rows of DataFrame without making a list first?

Convert the series to a dataframe and transpose it, then append normally.

srs = srs.to_frame().T
df = df.append(srs)

pull access denied repository does not exist or may require docker login

I solved this by inserting a language at the front of the docker image

FROM python:3.7-alpine

Proper MIME media type for PDF files

From Wikipedia Media type,

A media type is composed of a type, a subtype, and optional parameters. As an example, an HTML file might be designated text/html; charset=UTF-8.

Media type consists of top-level type name and sub-type name, which is further structured into so-called "trees".

top-level type name / subtype name [ ; parameters ]

top-level type name / [ tree. ] subtype name [ +suffix ] [ ; parameters ]

All media types should be registered using the IANA registration procedures. Currently the following trees are created: standard, vendor, personal or vanity, unregistered x.

Standard:

Media types in the standards tree do not use any tree facet (prefix).

type / media type name [+suffix]

Examples: "application/xhtml+xml", "image/png"

Vendor:

Vendor tree is used for media types associated with publicly available products. It uses vnd. facet.

type / vnd. media type name [+suffix] - used in the case of well-known producer

type / vnd. producer's name followed by media type name [+suffix] - producer's name must be approved by IANA

type / vnd. producer's name followed by product's name [+suffix] - producer's name must be approved by IANA

Personal or Vanity tree:

Personal or Vanity tree includes media types created experimentally or as part of products that are not distributed commercially. It uses prs. facet.

type / prs. media type name [+suffix]

Unregistered x. tree:

The "x." tree may be used for media types intended exclusively for use in private, local environments and only with the active agreement of the parties exchanging them. Types in this tree cannot be registered.

According to the previous version of RFC 6838 - obsoleted RFC 2048 (published in November 1996) it should rarely, if ever, be necessary to use unregistered experimental types, and as such use of both "x-" and "x." forms is discouraged. Previous versions of that RFC - RFC 1590 and RFC 1521 stated that the use of "x-" notation for the sub-type name may be used for unregistered and private sub-types, but this recommendation was obsoleted in November 1996.

type / x. media type name [+suffix]

So its clear that the standard type MIME type application/pdf is the appropriate one to use while you should avoid using the obsolete and unregistered x- media type as stated in RFC 2048 and RFC 6838.

Xcode - ld: library not found for -lPods

My problem had fixed by the following config:

Build Active Architecture Only: YES

How to delete multiple pandas (python) dataframes from memory to save RAM?

In python automatic garbage collection deallocates the variable (pandas DataFrame are also just another object in terms of python). There are different garbage collection strategies that can be tweaked (requires significant learning).

You can manually trigger the garbage collection using

import gc
gc.collect()

But frequent calls to garbage collection is discouraged as it is a costly operation and may affect performance.

Reference

How to use if - else structure in a batch file?

A little bit late and perhaps still good for complex if-conditions, because I would like to add a "done" parameter to keep a if-then-else structure:

set done=0
if %F%==1 if %C%==0 (set done=1 & echo found F=1 and C=0: %F% + %C%)
if %F%==2 if %C%==0 (set done=1 & echo found F=2 and C=0: %F% + %C%)
if %F%==3 if %C%==0 (set done=1 & echo found F=3 and C=0: %F% + %C%)
if %done%==0 (echo do something)

How can I use std::maps with user-defined types as key?

class key
{
    int m_value;
public:
    bool operator<(const key& src)const
    {
        return (this->m_value < src.m_value);
    }

};
int main()
{
    key key1;
    key key2;
    map<key,int> mymap;
    mymap.insert(pair<key,int>(key1,100));
    mymap.insert(pair<key,int>(key2,200));
    map<key,int>::iterator iter=mymap.begin();
    for(;iter!=mymap.end();++iter)
    {
        cout<<iter->second<<endl;
    }


}

Run javascript function when user finishes typing instead of on key up?

Why not just use onfocusout?

https://www.w3schools.com/jsreF/event_onfocusout.asp

If it's a form, they will always leave focus of every input field in order to click the submit button so you know no input will miss out on getting its onfocusout event handler called.

How can I encode a string to Base64 in Swift?

You could just do a simple extension like:

import UIKit

// MARK: - Mixed string utils and helpers
extension String {


    /**
    Encode a String to Base64

    :returns: 
    */
    func toBase64()->String{

        let data = self.dataUsingEncoding(NSUTF8StringEncoding)

        return data!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))

    }

}

iOS 7 and up

Two HTML tables side by side, centered on the page

The problem is that you need to give #inner a set width (anything but auto or inherit). The margin: 0 auto; trick only works if the inner element is narrower than its container element. Without being given a width, #inner is automatically expanding to the full width of #outer, which causes its contents to be flush left.

System.currentTimeMillis vs System.nanoTime

Yes, if such precision is required use System.nanoTime(), but be aware that you are then requiring a Java 5+ JVM.

On my XP systems, I see system time reported to at least 100 microseconds 278 nanoseconds using the following code:

private void test() {
    System.out.println("currentTimeMillis: "+System.currentTimeMillis());
    System.out.println("nanoTime         : "+System.nanoTime());
    System.out.println();

    testNano(false);                                                            // to sync with currentTimeMillis() timer tick
    for(int xa=0; xa<10; xa++) {
        testNano(true);
        }
    }

private void testNano(boolean shw) {
    long strMS=System.currentTimeMillis();
    long strNS=System.nanoTime();
    long curMS;
    while((curMS=System.currentTimeMillis()) == strMS) {
        if(shw) { System.out.println("Nano: "+(System.nanoTime()-strNS)); }
        }
    if(shw) { System.out.println("Nano: "+(System.nanoTime()-strNS)+", Milli: "+(curMS-strMS)); }
    }

jquery toggle slide from left to right and back

There is no such method as slideLeft() and slideRight() which looks like slideUp() and slideDown(), but you can simulate these effects using jQuery’s animate() function.

HTML Code:

<div class="text">Lorem ipsum.</div>

JQuery Code:

  $(document).ready(function(){
    var DivWidth = $(".text").width();
    $(".left").click(function(){
      $(".text").animate({
        width: 0
      });
    });
    $(".right").click(function(){
      $(".text").animate({
        width: DivWidth
      });
    });
  });

You can see an example here: How to slide toggle a DIV from Left to Right?

Showing all errors and warnings

PHP errors can be displayed by any of below methods:

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

For more details:

Displaying PHP errors

Remove object from a list of objects in python

If you know the array location you can can pass it into itself. If you are removing multiple items I suggest you remove them in reverse order.

#Setup array
array = [55,126,555,2,36]
#Remove 55 which is in position 0
array.remove(array[0])

Convert json data to a html table

You can use simple jQuery jPut plugin

http://plugins.jquery.com/jput/

<script>
$(document).ready(function(){

var json = [{"name": "name1","email":"[email protected]"},{"name": "name2","link":"[email protected]"}];
//while running this code the template will be appended in your div with json data
$("#tbody").jPut({
    jsonData:json,
    //ajax_url:"youfile.json",  if you want to call from a json file
    name:"tbody_template",
});

});
</script>   

<table jput="t_template">
 <tbody jput="tbody_template">
     <tr>
         <td>{{name}}</td>
         <td>{{email}}</td>
     </tr>
 </tbody>
</table>

<table>
 <tbody id="tbody">
 </tbody>
</table>

Difference between _self, _top, and _parent in the anchor tag target attribute

While these answers are good, IMHO I don't think they fully address the question.

The target attribute in an anchor tag tells the browser the target of the destination of the anchor. They were initially created in order to manipulate and direct anchors to the frame system of document. This was well before CSS came to the aid of HTML developers.

While target="_self" is default by browser and the most common target is target="_blank" which opens the anchor in a new window(which has been redirected to tabs by browser settings usually). The "_parent", "_top" and framename tags are left a mystery to those that aren't familiar with the days of iframe site building as the trend.

target="_self" This opens an anchor in the same frame. What is confusing is that because we generally don't write in frames anymore (and the frame and frameset tags are obsolete in HTML5) people assume this a same window function. Instead if this anchor was nested in frames it would open in a sandbox mode of sorts, meaning only in that frame.

target="_parent" Will open the in the next level up of a frame if they were nested to inside one another

target="_top" This breaks outside of all the frames it is nested in and opens the link as top document in the browser window.

target="framename This was originally deprecated but brought back in HTML5. This will target the exact frame in question. While the name was the proper method that method has been replaced with using the id identifying tag.

<!--Example:-->

<html>
<head>
</head>
<body>
<iframe src="url1" name="A"><p> This my first iframe</p></iframe>
<iframe src="url2" name="B"><p> This my second iframe</p></iframe>
<iframe src="url3" name="C"><p> This my third iframe</p></iframe>

<a href="url4" target="B"></a>
</body>
</html>