Programs & Examples On #Counter

A Counter is a container(/bag/multiset/etc.) that keeps track of how many times equivalent values are added.

How to count the number of words in a sentence, ignoring numbers, punctuation and whitespace?

import string 

sentence = "I     am having  a   very  nice  23!@$      day. "
# Remove all punctuations
sentence = sentence.translate(str.maketrans('', '', string.punctuation))
# Remove all numbers"
sentence = ''.join([word for word in sentence if not word.isdigit()])
count = 0;
for index in range(len(sentence)-1) :
    if sentence[index+1].isspace() and not sentence[index].isspace():
        count += 1 

HTML/Javascript Button Click Counter

After looking at the code you're having typos, here is the updated code

var clicks = 0; // should be var not int
    function clickME() {
        clicks += 1;
        document.getElementById("clicks").innerHTML = clicks; //getElementById() not getElementByID() Which you corrected in edit


Note: Don't use in-built handlers, as .click() is javascript function try giving different name like clickME()

Count characters in textarea

?? The accepted solution is flawed.

Here are two scenarios where the keyup event will not get fired:

  1. The user drags text into the textarea.
  2. The user copy-paste text in the textarea with a right click (contextual menu).

Use the HTML5 input event instead for a more robust solution:

<textarea maxlength='140'></textarea>

JavaScript (demo):

const textarea = document.querySelector("textarea");

textarea.addEventListener("input", event => {
    const target = event.currentTarget;
    const maxLength = target.getAttribute("maxlength");
    const currentLength = target.value.length;

    if (currentLength >= maxLength) {
        return console.log("You have reached the maximum number of characters.");

    console.log(`${maxLength - currentLength} chars left`);

And if you absolutely want to use jQuery:

$('textarea').on("input", function(){
    var maxlength = $(this).attr("maxlength");
    var currentLength = $(this).val().length;

    if( currentLength >= maxlength ){
        console.log("You have reached the maximum number of characters.");
        console.log(maxlength - currentLength + " chars left");

Counter in foreach loop in C#

The sequence being iterated in a foreach loop might not support indexing or know such a concept it just needs to implement a method called GetEnumerator that returns an object that as a minimum has the interface of IEnumerator though implmenting it is not required. If you know that what you iterate does support indexing and you need the index then I suggest to use a for loop instead.

An example class that can be used in foreach:

    class Foo {

        public iterator GetEnumerator() {
            return new iterator();

        public class iterator {
            public Bar Current {

            public bool MoveNext() {

Counter increment in Bash loop not working

Try to use


instead of


Get loop counter/index using for…of syntax in JavaScript

Here's a function eachWithIndex that works with anything iterable.

You could also write a similar function eachWithKey that works with objets using

// example generator (returns an iterator that can only be iterated once)
function* eachFromTo(start, end) { for (let i = start; i <= end; i++) yield i }

// convers an iterable to an array (potential infinite loop)
function eachToArray(iterable) {
    const result = []
    for (const val of iterable) result.push(val)
    return result

// yields every value and index of an iterable (array, generator, ...)
function* eachWithIndex(iterable) {
    const shared = new Array(2)
    shared[1] = 0
    for (shared[0] of iterable) {
        yield shared

console.log('iterate values and indexes from a generator')
for (const [val, i] of eachWithIndex(eachFromTo(10, 13))) console.log(val, i)

console.log('create an array')
const anArray = eachToArray(eachFromTo(10, 13))

console.log('iterate values and indexes from an array')
for (const [val, i] of eachWithIndex(anArray)) console.log(val, i)

The good thing with generators is that they are lazy and can take another generator's result as an argument.

How to sort Counter by value? - python

A rather nice addition to @MartijnPieters answer is to get back a dictionary sorted by occurrence since Collections.most_common only returns a tuple. I often couple this with a json output for handy log files:

from collections import Counter, OrderedDict

x = Counter({'a':5, 'b':3, 'c':7})
y = OrderedDict(x.most_common())

With the output:

OrderedDict([('c', 7), ('a', 5), ('b', 3)])
  "c": 7, 
  "a": 5, 
  "b": 3

Code for a simple JavaScript countdown timer?

I wrote this script some time ago:


var myCounter = new Countdown({  
    seconds:5,  // number of seconds to count down
    onUpdateStatus: function(sec){console.log(sec);}, // callback for each second
    onCounterEnd: function(){ alert('counter ended!');} // final action


function Countdown(options) {
  var timer,
  instance = this,
  seconds = options.seconds || 10,
  updateStatus = options.onUpdateStatus || function () {},
  counterEnd = options.onCounterEnd || function () {};

  function decrementCounter() {
    if (seconds === 0) {

  this.start = function () {
    timer = 0;
    seconds = options.seconds;
    timer = setInterval(decrementCounter, 1000);

  this.stop = function () {

How to count the frequency of the elements in an unordered list?

Yet another solution with another algorithm without using collections:

def countFreq(A):
   count=[0]*n                     # Create a new list initialized with '0'
   for i in range(n):
      count[A[i]]+= 1              # increase occurrence for value A[i]
   return [x for x in count if x]  # return non-zero count

jQuery counter to count up to a target number

CodePen Working Example

For more GitHub repo

<!DOCTYPE html>
    <title>Count Up Numbers Example</title>
    <script src="" integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>

    <style type="text/css">
        .rewards {
            background-color: #160922;

        .th-num-bold {
            font-family: "Arial" ;

        .ff-arial {
            font-family: "Arial" ;

        .scroll-wrap .scroll-exchange-fee .exchange_time {
            color: hsla(0,0%,100%,.7);
            font-size: 13px;

        .f14 {
            font-size: 14px;

        .flex {
            display: -webkit-box;
            display: -ms-flexbox;
            display: flex;

        .jcsb {
            -ms-flex-pack: justify!important;
            -webkit-box-pack: justify!important;
            justify-content: space-between!important;

        .aic {
            -ms-flex-align: center!important;
            -webkit-box-align: center!important;
            align-items: center!important;

        li {
            list-style: none;

        .pull-left {
            float: left!important;

        .rewards-wrap {
            height: 100%;

        .at-equity-wrap .rewards .calculate_container {
            -webkit-box-shadow: rgba(0,0,0,.03) 0 5px 10px 0;
            background: url(;
            background-repeat: no-repeat;
            background-size: 1440px 100%;
            box-shadow: 0 5px 10px 0 rgba(0,0,0,.03);
            margin: 0 auto;
            max-width: 1200px;
            overflow: hidden;
            position: relative;

        .rewards-pc-wrap .current-profit .point {
            color: #fff;
            font-size: 25px;

        .rewards-pc-wrap .current-profit .integer {
            color: #fff;
            font-size: 45px;

        .rewards-pc-wrap .current-profit .decimal {
            color: #fff;
            font-size: 25px;

        .rewards-pc-wrap .current-profit .unit {
            color: #fff;
            font-size: 24px;
            margin-right: 5px;
            margin-top: 18px;

        .rewards-pc-wrap .yesterday-profit .point {
            color: #fff;
            font-size: 25px;

        .rewards-pc-wrap .yesterday-profit .integer {
            color: #fff;
            font-size: 45px;

        .rewards-pc-wrap .yesterday-profit .decimal {
            color: #fff;
            font-size: 25px;

        .rewards-pc-wrap .yesterday-profit .unit {
            color: #fff;
            font-size: 24px;
            margin-right: 5px;
            margin-top: 18px;

        .rewards-pc-wrap .profit-rate-100 .point {
            color: #fff;
            font-size: 25px;

        .rewards-pc-wrap .profit-rate-100 .integer {
            color: #fff;
            font-size: 45px;

        .rewards-pc-wrap .profit-rate-100 .decimal {
            color: #fff;
            font-size: 25px;

        .rewards-pc-wrap .profit-rate-100 .unit {
            color: #fff;
            font-size: 24px;
            margin-right: 5px;
            margin-top: 18px;

        .rewards-pc-wrap .total-profit .point {
            color: #fff;
            font-size: 25px;

        .rewards-pc-wrap .total-profit .integer {
            color: #fff;
            font-size: 45px;

        .rewards-pc-wrap .total-profit .decimal {
            color: #fff;
            font-size: 25px;

        .rewards-pc-wrap .total-profit .unit {
            color: #fff;
            font-size: 24px;
            margin-right: 5px;
            margin-top: 18px;

        .rewards-pc-wrap {
            height: 400px;
            margin-left: 129px;
            padding-top: 100px;
            width: 630px;

        .itm-rv {
            -ms-flex: 1;
            -webkit-box-flex: 1;
            flex: 1;
            font-family: "Arial";

        .fb {
            font-weight: 700;

        .main-p {
            color: hsla(0,0%,100%,.7);
            font-size: 13px;
            margin-bottom: 8px;
            margin-top: 10px;

        .sub-p {
            color: hsla(0,0%,100%,.5);
            font-size: 12px;
            margin-top: 12px;

        .fb-r {
            font-weight: 300;

        .price-btc {
            color: hsla(0,0%,100%,.5);
            font-size: 13px;
            margin-top: 10px;

    <div class="at-equity-wrap">
        <div  class="rewards" >
            <div  class="calculate_container">
                <div  class="rewards-wrap">
                    <div class="flex jcc aic">
                        <div  class="rewards-pc-wrap slideInUp" id="nuBlock">
                            <div  class="flex jcsb aic">
                                <div  class="itm-rv" style="margin-right: 60px;">
                                    <div  class="current-profit th-num-bold fb"><span  class="unit pull-left">$</span> <span class="integer" id="cr_prft_int" >0</span> <span  class="point">.</span> <span class="decimal" id="cr_prft_dcml" >00</span></div>
                                    <p  class="main-p">Platform Rewards to Be Distributed Today</p>
                                    <p  class="sub-p fb-r">Total circulating KAT eligible for rewards:100,000,000</p>
                                <div  class="itm-rv">
                                    <div  class="profit-rate-100 th-num-bold"><span  class="unit pull-left">$</span> <span  class="integer" id="dly_prft_int" >0</span> <span  class="point">.</span><span  class="decimal" id="dly_prft_dcml" >00</span></div>
                                    <p  class="main-p">Daily Rewards of 1000 KAT</p>
                                    <div  class="profit-rate sub-p fb-r"><span >Daily KAT Rewards Rate</span> <span  class="integer">0</span> <span  class="decimal">.00</span> <span  class="unit">%</span></div>
                            <div  class="flex jcsb aic" style="margin-top: 40px;">
                                <div  class="itm-rv" style="margin-right: 60px;">
                                    <div  class="yesterday-profit th-num-bold fb'"><span  class="unit pull-left">$</span> <span  class="integer" id="ytd_prft_int" >0</span> <span  class="point">.</span><span  class="decimal" id="ytd_prft_dcml" >00</span></div>
                                    <div  class="price-btc fb-r">/ 0.00000000 BTC</div>
                                    <p  class="main-p fb-r">Platform Rewards Distributed Yesterday</p>
                                <div  class="itm-rv">
                                    <div  class="total-profit th-num-bold fb'"><span  class="unit pull-left">$</span> <span  class="integer" id="ttl_prft_int" >0</span> <span  class="point">.</span><span  class="decimal" id="ttl_prft_dcml" >00</span></div>
                                    <div  class="price-btc fb-r">/ 0.00000000 BTC</div>
                                    <p  class="main-p fb-r">Cumulative Platform Rewards Distributed</p>
<script type="text/javascript">

    $(document).on('ready', function(){

        }, 2000);


    unit = "$";

    var cr_data, dly_data, ytd_data, ttl_data;
    cr_data = dly_data = ytd_data = ttl_data = ["670.0000682", "670.002", "660.000068", "660.002", "650.000000063", "650.01", "640.00000006", "640.01", "630.0000000602", "630.01", "620.0000000622", "620.01", "610.00000016", "610.002", "600.00000015998", "600.002", "590.00000094", "590.002", "580.0000009", "580.002", "760.0000682", "760.002", "660.000068", "660.002", "560.000000063", "560.01", "460.00000006", "460.01", "360.0000000602", "360.01", "260.0000000622", "260.01", "160.00000016", "160.002", "060.00000015998", "060.002", "950.00000094", "950.002", "850.0000009", "850.002"];

    cr_start = 0;
    cr_stop = cr_data.length - 1;
    cr_nu = 20;

    function cr_countUp(){
            if(cr_start < cr_stop){
                cr_start += 1;
        }, cr_nu);

    dly_start = 0;
    dly_stop = dly_data.length - 1;
    dly_nu = 20;

    function dly_countUp(){
            if(dly_start < dly_stop){
                dly_start += 1;
        }, dly_nu);

    ytd_start = 0;
    ytd_stop = ytd_data.length - 1;
    ytd_nu = 20;

    function ytd_countUp(){
            if(ytd_start < ytd_stop){
                ytd_start += 1;
        }, ytd_nu);

    ttl_start = 0;
    ttl_stop = ttl_data.length - 1;
    ttl_nu = 20;

    function ttl_countUp(){
            if(ttl_start < ttl_stop){
                ttl_start += 1;
        }, ttl_nu);


Can a PDF file's print dialog be opened with Javascript?

I use named action instead of javascript because javascript often is disabled, and if it isn't it gives a warning.

My web application creates a postscript file that then is converted with ghostscript to a pdf. I want it to print automatically because the user has already clicked on print inside my application. With the information about named actions from @DSimon above, I researched how to solve this. It all boils down to insert the string /Type /Action /S /Named /N /Print at the right place in the pdf.

I was thinking of writing a small utility, but it has to parse the pdf to find the root node, insert /OpenAction with a reference an object with the action, and recalculate the byte-offsets in xref.

But then I found out about pdfmark which is an extension to postscript to express, in postscript syntax, idioms that are converted to pdf by Adobes distiller or by ghostscript.

Since I'm already using ghostscript, all I have to do is append the following to the end of my postscript file:

[ /_objdef {PrintAction} /type /dict /OBJ pdfmark
[ {PrintAction} << /Type /Action /S /Named /N /Print >> /PUT pdfmark
[ {Catalog} << /OpenAction {PrintAction} >> /PUT pdfmark

and ghostscript will create the action, link it, and calculate the xref offsets. (In postscript % is a comment and PrintAction is my name for the object)

By looking at the PDF I see that it has created this:

1 0 obj
<</Type /Catalog /Pages 3 0 R
/OpenAction  9 0 R
/Metadata 10 0 R

9 0 obj

1 0 is object 1, revision 0, and 9 0 is object 9, revision 0. In the pdf-trailer is says that it is object 1 that is the root node. As you can see there is a reference from object 1, /OpenAction to run object 9 revision 0.

With ghostscript it's possible to convert a pdf to postscript (pdf2ps), append the text above, and convert it back to pdf with ps2pdf. It should be noted that meta-information about the pdf is lost in this conversion. I haven't searched more into this.

Stripping non printable characters from a string in python

Yet another option in python 3:

re.sub(f'[^{re.escape(string.printable)}]', '', my_string)

When to use throws in a Java method declaration?

This is not an answer, but a comment, but I could not write a comment with a formatted code, so here is the comment.

Lets say there is

public static void main(String[] args) {
  try {
    // do nothing or throw a RuntimeException
    throw new RuntimeException("test");
  } catch (Exception e) {
    throw e;

The output is

Exception in thread "main" java.lang.RuntimeException: test
    at MyClass.main(

That method does not declare any "throws" Exceptions, but throws them! The trick is that the thrown exceptions are RuntimeExceptions (unchecked) that are not needed to be declared on the method. It is a bit misleading for the reader of the method, since all she sees is a "throw e;" statement but no declaration of the throws exception

Now, if we have

public static void main(String[] args) throws Exception {
  try {
    throw new Exception("test");
  } catch (Exception e) {
    throw e;

We MUST declare the "throws" exceptions in the method otherwise we get a compiler error.

checking memory_limit in PHP

very old post. but i'll just leave this here:

/* converts a number with byte unit (B / K / M / G) into an integer */
function unitToInt($s)
    return (int)preg_replace_callback('/(\-?\d+)(.?)/', function ($m) {
        return $m[1] * pow(1024, strpos('BKMG', $m[2]));
    }, strtoupper($s));

$mem_limit = unitToInt(ini_get('memory_limit'));

Keystore change passwords

If the keystore contains other key-entries with different password you have to change them also or you can isolate your key to different keystore using below command,

keytool -importkeystore  -srckeystore mystore.jck -destkeystore myotherstore.jks -srcstoretype jceks
-deststoretype jks -srcstorepass mystorepass -deststorepass myotherstorepass -srcalias myserverkey
-destalias myotherserverkey -srckeypass mykeypass -destkeypass myotherkeypass

nginx error:"location" directive is not allowed here in /etc/nginx/nginx.conf:76

Since your server already includes the sites-enabled folder ( notice the include /etc/nginx/sites-enabled/* line ), then you better use that.

  1. Create a file inside /etc/nginx/sites-available and call it whatever you want, I'll call it django since it's a djanog server

    sudo touch /etc/nginx/sites-available/django
  2. Then create a symlink that points to it

    sudo ln -s /etc/nginx/sites-available/django /etc/nginx/sites-enabled
  3. Then edit that file with whatever file editor you use, vim or nano or whatever and create the server inside it

    server {
        # hostname or ip or multiple separated by spaces
        server_name localhost; #change to your setting
        location / {
            root /home/techcee/scrapbook/local/lib/python2.7/site-packages/django/__init__.pyc/;
  4. Restart or reload nginx settings

    sudo service nginx reload

Note I believe that your configuration like this probably won't work yet because you need to pass it to a fastcgi server or something, but at least this is how you could create a valid server

Why use prefixes on member variables in C++ classes

I almost never use prefixes in front of my variable names. If you're using a decent enough IDE you should be able to refactor and find references easily. I use very clear names and am not afraid of having long variable names. I've never had trouble with scope either with this philosophy.

The only time I use a prefix would be on the signature line. I'll prefix parameters to a method with _ so I can program defensively around them.

Using @property versus getters and setters

The short answer is: properties wins hands down. Always.

There is sometimes a need for getters and setters, but even then, I would "hide" them to the outside world. There are plenty of ways to do this in Python (getattr, setattr, __getattribute__, etc..., but a very concise and clean one is:

def set_email(self, value):
    if '@' not in value:
        raise Exception("This doesn't look like an email address.")
    self._email = value

def get_email(self):
    return self._email

email = property(get_email, set_email)

Here's a brief article that introduces the topic of getters and setters in Python.

How to apply bold text style for an entire row using Apache POI?

This should work fine.

    Workbook wb = new XSSFWorkbook("myWorkbook.xlsx");
    Row row=sheet.getRow(0);
    CellStyle style=null;

    XSSFFont defaultFont= wb.createFont();

    XSSFFont font= wb.createFont();


If you do not create defaultFont all your workbook will be using the other one as default.

get user timezone

This will get you the timezone as a PHP variable. I wrote a function using jQuery and PHP. This is tested, and does work!

On the PHP page where you are want to have the timezone as a variable, have this snippet of code somewhere near the top of the page:

    $timezone = $_SESSION['time'];

This will read the session variable "time", which we are now about to create.

On the same page, in the <head> section, first of all you need to include jQuery:

<script type="text/javascript" src=""></script>

Also in the <head> section, paste this jQuery:

<script type="text/javascript">
    $(document).ready(function() {
        if("<?php echo $timezone; ?>".length==0){
            var visitortime = new Date();
            var visitortimezone = "GMT " + -visitortime.getTimezoneOffset()/60;
                type: "GET",
                url: "",
                data: 'time='+ visitortimezone,
                success: function(){

You may or may not have noticed, but you need to change the url to your actual domain.

One last thing. You are probably wondering what the heck timezone.php is. Well, it is simply this: (create a new file called timezone.php and point to it with the above url)

    $_SESSION['time'] = $_GET['time'];

If this works correctly, it will first load the page, execute the JavaScript, and reload the page. You will then be able to read the $timezone variable and use it to your pleasure! It returns the current UTC/GMT time zone offset (GMT -7) or whatever timezone you are in.

You can read more about this on my blog

Getting HTTP code in PHP using curl

use this hitCurl method for fetch all type of api response i.e. Get / Post

        function hitCurl($url,$param = [],$type = 'POST'){
        $ch = curl_init();
        if(strtoupper($type) == 'GET'){
            $param = http_build_query((array)$param);
            $url = "{$url}?{$param}";
                CURLOPT_POST => (strtoupper($type) == 'POST'),
                CURLOPT_POSTFIELDS => (array)$param,
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
        $resp = curl_exec($ch);
        $statusCode = curl_getinfo($ch,CURLINFO_HTTP_CODE);
        return [
            'statusCode' => $statusCode,
            'resp' => $resp

Demo function to test api

 function fetchApiData(){
        $url = '';
        $resp = $this->hitCurl($url,[
        $apiData = "Getting header code {$resp['statusCode']}";
        if($resp['statusCode'] == 200){
            $apiData = json_decode($resp['resp']);
        echo "<pre>";
        print_r ($apiData);
        echo "</pre>";

Replace Multiple String Elements in C#

If you are simply after a pretty solution and don't need to save a few nanoseconds, how about some LINQ sugar?

var input = "test1test2test3";
var replacements = new Dictionary<string, string> { { "1", "*" }, { "2", "_" }, { "3", "&" } };

var output = replacements.Aggregate(input, (current, replacement) => current.Replace(replacement.Key, replacement.Value));

Converting camel case to underscore case in ruby

You can use


Or just


Both options ways will yield "camel_cased_name". You can check more details it here.

Angular directives - when and how to use compile, controller, pre-link and post-link

Compile function

Each directive's compile function is only called once, when Angular bootstraps.

Officially, this is the place to perform (source) template manipulations that do not involve scope or data binding.

Primarily, this is done for optimisation purposes; consider the following markup:

<tr ng-repeat="raw in raws">

The <my-raw> directive will render a particular set of DOM markup. So we can either:

  • Allow ng-repeat to duplicate the source template (<my-raw>), and then modify the markup of each instance template (outside the compile function).
  • Modify the source template to involve the desired markup (in the compile function), and then allow ng-repeat to duplicate it.

If there are 1000 items in the raws collection, the latter option may be faster than the former one.


  • Manipulate markup so it serves as a template to instances (clones).

Do not

  • Attach event handlers.
  • Inspect child elements.
  • Set up observations on attributes.
  • Set up watches on the scope.

Uppercase first letter of variable

You can use text-transform: capitalize; for this work -


<input type="text" style="text-transform: capitalize;" />

JQuery -

$(document).ready(function (){
   var asdf = "WERTY UIOP";

Try This

Note: It's only change visual representation of the string. If you alert this string it's always show original value of the string.

How do I capture the output into a variable from an external process in PowerShell?

I use the following:

Function GetProgramOutput([string]$exe, [string]$arguments)
    $process = New-Object -TypeName System.Diagnostics.Process
    $process.StartInfo.FileName = $exe
    $process.StartInfo.Arguments = $arguments
    $process.StartInfo.UseShellExecute = $false
    $process.StartInfo.RedirectStandardOutput = $true
    $process.StartInfo.RedirectStandardError = $true
    $output = $process.StandardOutput.ReadToEnd()   
    $err = $process.StandardError.ReadToEnd()
$exe = "C:\Program Files\7-Zip\7z.exe"
$arguments = "i"
$runResult = (GetProgramOutput $exe $arguments)
$stdout = $runResult[-2]
$stderr = $runResult[-1]
[System.Console]::WriteLine("Standard out: " + $stdout)
[System.Console]::WriteLine("Standard error: " + $stderr)

Enable/Disable a dropdownbox in jquery



Java: Get first item from a collection

In Java 8 you have some many operators to use, for instance limit

 * Operator that limit the total number of items emitted through the pipeline
 * Shall print
 * [1]
 * @throws InterruptedException
public void limitStream() throws InterruptedException {
    List<Integer> list = Arrays.asList(1, 2, 3, 1, 4, 2, 3)

DBCC SHRINKFILE on log file not reducing size even after BACKUP LOG TO DISK

I resolved this problem by taking the full and transactional backup. Sometimes, the backup process is not completed and that's one of the reason the .ldf file is not getting shrink. Try this. It worked for me.

Model summary in pytorch

For visualization and summary of PyTorch models, tensorboardX can also can be utilized.

Calculate execution time of a SQL query?

I found this one more helpful and simple

DECLARE @StartTime datetime,@EndTime datetime   
--Your Query to be run goes here--  
SELECT DATEDIFF(ms,@StartTime,@EndTime) AS [Duration in milliseconds]   

Function not defined javascript

I just went through the same problem. And found out once you have a syntax or any type of error in you javascript, the whole file don't get loaded so you cannot use any of the other functions at all.

How to iterate for loop in reverse order in swift?

In Swift 4 and latter

    let count = 50//For example
    for i in (1...count).reversed() {

Rails select helper - Default selected value, how?

This should do it:

<%= :project_id, @project_select, :selected => params[:pid] %>

Simple way to compare 2 ArrayLists

Convert Lists to Collection and use removeAll

    Collection<String> listOne = new ArrayList(Arrays.asList("a","b", "c", "d", "e", "f", "g"));
    Collection<String> listTwo = new ArrayList(Arrays.asList("a","b",  "d", "e", "f", "gg", "h"));

    List<String> sourceList = new ArrayList<String>(listOne);
    List<String> destinationList = new ArrayList<String>(listTwo);

    sourceList.removeAll( listTwo );
    destinationList.removeAll( listOne );

    System.out.println( sourceList );
    System.out.println( destinationList );


[c, g]
[gg, h]


other way (more clear)

  Collection<String> list = new ArrayList(Arrays.asList("a","b", "c", "d", "e", "f", "g"));

    List<String> sourceList = new ArrayList<String>(list);
    List<String> destinationList = new ArrayList<String>(list);


    sourceList.removeAll( list );
    list.removeAll( destinationList );

    System.out.println( sourceList );
    System.out.println( list );



How to connect html pages to mysql database?

HTML are markup languages, basically they are set of tags like <html>, <body>, which is used to present a website using , and as a whole. All these, happen in the clients system or the user you will be browsing the website.

Now, Connecting to a database, happens on whole another level. It happens on server, which is where the website is hosted.

So, in order to connect to the database and perform various data related actions, you have to use server-side scripts, like , , etc.

Now, lets see a snippet of connection using MYSQLi Extension of PHP

$db = mysqli_connect('hostname','username','password','databasename');

This single line code, is enough to get you started, you can mix such code, combined with HTML tags to create a HTML page, which is show data based pages. For example:

    $db = mysqli_connect('hostname','username','password','databasename');
                $query = "SELECT * FROM `mytable`;";
                $result = mysqli_query($db, $query);
                while($row = mysqli_fetch_assoc($result)) {
                      // Display your datas on the page

In order to insert new data into the database, you can use phpMyAdmin or write a INSERT query and execute them.

Why XML-Serializable class need a parameterless constructor

During an object's de-serialization, the class responsible for de-serializing an object creates an instance of the serialized class and then proceeds to populate the serialized fields and properties only after acquiring an instance to populate.

You can make your constructor private or internal if you want, just so long as it's parameterless.

C++ for each, pulling from vector elements

For next examples assumed that you use C++11. Example with ranged-based for loops:

for (auto &attack : m_attack) // access by reference to avoid copying
    if (attack->m_num == input)

You should use const auto &attack depending on the behavior of makeDamage().

You can use std::for_each from standard library + lambdas:

std::for_each(m_attack.begin(), m_attack.end(),
        [](Attack * attack)
            if (attack->m_num == input)

If you are uncomfortable using std::for_each, you can loop over m_attack using iterators:

for (auto attack = m_attack.begin(); attack != m_attack.end(); ++attack)
    if (attack->m_num == input)

Use m_attack.cbegin() and m_attack.cend() to get const iterators.

(SC) DeleteService FAILED 1072

I had this error also, make sure the exe the service is pointing to is stopped. Also make sure you don't have any Windows dialog boxes behind your other windows. That is why mine wasn't deleting. There was a windows message behind it saying this service has been deleted or something similar.. just had to click ok, there it went.

Why do abstract classes in Java have constructors?

A constructor in Java doesn't actually "build" the object, it is used to initialize fields.

Imagine that your abstract class has fields x and y, and that you always want them to be initialized in a certain way, no matter what actual concrete subclass is eventually created. So you create a constructor and initialize these fields.

Now, if you have two different subclasses of your abstract class, when you instantiate them their constructors will be called, and then the parent constructor will be called and the fields will be initialized.

If you don't do anything, the default constructor of the parent will be called. However, you can use the super keyword to invoke specific constructor on the parent class.

Python Pandas User Warning: Sorting because non-concatenation axis is not aligned


concat and append currently sort the non-concatenation index (e.g. columns if you're adding rows) if the columns don't match. In pandas 0.23 this started generating a warning; pass the parameter sort=True to silence it. In the future the default will change to not sort, so it's best to specify either sort=True or False now, or better yet ensure that your non-concatenation indices match.

The warning is new in pandas 0.23.0:

In a future version of pandas pandas.concat() and DataFrame.append() will no longer sort the non-concatenation axis when it is not already aligned. The current behavior is the same as the previous (sorting), but now a warning is issued when sort is not specified and the non-concatenation axis is not aligned, link.

More information from linked very old github issue, comment by smcinerney :

When concat'ing DataFrames, the column names get alphanumerically sorted if there are any differences between them. If they're identical across DataFrames, they don't get sorted.

This sort is undocumented and unwanted. Certainly the default behavior should be no-sort.

After some time the parameter sort was implemented in pandas.concat and DataFrame.append:

sort : boolean, default None

Sort non-concatenation axis if it is not already aligned when join is 'outer'. The current default of sorting is deprecated and will change to not-sorting in a future version of pandas.

Explicitly pass sort=True to silence the warning and sort. Explicitly pass sort=False to silence the warning and not sort.

This has no effect when join='inner', which already preserves the order of the non-concatenation axis.

So if both DataFrames have the same columns in the same order, there is no warning and no sorting:

df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['a', 'b'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])

print (pd.concat([df1, df2]))
   a  b
0  1  0
1  2  8
0  4  7
1  5  3

df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['b', 'a'])

print (pd.concat([df1, df2]))
   b  a
0  0  1
1  8  2
0  7  4
1  3  5

But if the DataFrames have different columns, or the same columns in a different order, pandas returns a warning if no parameter sort is explicitly set (sort=None is the default value):

df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])

print (pd.concat([df1, df2]))

FutureWarning: Sorting because non-concatenation axis is not aligned.

   a  b
0  1  0
1  2  8
0  4  7
1  5  3

print (pd.concat([df1, df2], sort=True))
   a  b
0  1  0
1  2  8
0  4  7
1  5  3

print (pd.concat([df1, df2], sort=False))
   b  a
0  0  1
1  8  2
0  7  4
1  3  5

If the DataFrames have different columns, but the first columns are aligned - they will be correctly assigned to each other (columns a and b from df1 with a and b from df2 in the example below) because they exist in both. For other columns that exist in one but not both DataFrames, missing values are created.

Lastly, if you pass sort=True, columns are sorted alphanumerically. If sort=False and the second DafaFrame has columns that are not in the first, they are appended to the end with no sorting:

df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8], 'e':[5, 0]}, 
                    columns=['b', 'a','e'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3], 'c':[2, 8], 'd':[7, 0]}, 

print (pd.concat([df1, df2]))

FutureWarning: Sorting because non-concatenation axis is not aligned.

   a  b    c    d    e
0  1  0  NaN  NaN  5.0
1  2  8  NaN  NaN  0.0
0  4  7  2.0  7.0  NaN
1  5  3  8.0  0.0  NaN

print (pd.concat([df1, df2], sort=True))
   a  b    c    d    e
0  1  0  NaN  NaN  5.0
1  2  8  NaN  NaN  0.0
0  4  7  2.0  7.0  NaN
1  5  3  8.0  0.0  NaN

print (pd.concat([df1, df2], sort=False))

   b  a    e    c    d
0  0  1  5.0  NaN  NaN
1  8  2  0.0  NaN  NaN
0  7  4  NaN  2.0  7.0
1  3  5  NaN  8.0  0.0

In your code:

placement_by_video_summary = placement_by_video_summary.drop(placement_by_video_summary_new.index)
                                                       .append(placement_by_video_summary_new, sort=True)

how to use the Box-Cox power transformation in R

According to the Box-cox transformation formula in the paper Box,George E. P.; Cox,D.R.(1964). "An analysis of transformations", I think mlegge's post might need to be slightly edited.The transformed y should be (y^(lambda)-1)/lambda instead of y^(lambda). (Actually, y^(lambda) is called Tukey transformation, which is another distinct transformation formula.)
So, the code should be:

(trans <- bc$x[which.max(bc$y)])
[1] 0.4242424
# re-run with transformation
mnew <- lm(((y^trans-1)/trans) ~ x) # Instead of mnew <- lm(y^trans ~ x) 

More information

Please correct me if I misunderstood it.

Byte Array in Python

An alternative that also has the added benefit of easily logging its output:

hexs = "13 00 00 00 08 00"
key = bytearray.fromhex(hexs)

allows you to do easy substitutions like so:

hexs = "13 00 00 00 08 {:02X}".format(someByte)
key = bytearray.fromhex(hexs)

The Role Manager feature has not been enabled

If you got here because you're using the new ASP.NET Identity UserManager, what you're actually looking for is the RoleManager:

var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));

roleManager will give you access to see if the role exists, create, etc, plus it is created for the UserManager

Byte Array to Hex String

Using str.format:

>>> array_alpha = [ 133, 53, 234, 241 ]
>>> print ''.join('{:02x}'.format(x) for x in array_alpha)

or using format

>>> print ''.join(format(x, '02x') for x in array_alpha)

Note: In the format statements, the 02 means it will pad with up to 2 leading 0s if necessary. This is important since [0x1, 0x1, 0x1] i.e. (0x010101) would be formatted to "111" instead of "010101"

or using bytearray with binascii.hexlify:

>>> import binascii
>>> binascii.hexlify(bytearray(array_alpha))

Here is a benchmark of above methods in Python 3.6.1:

from timeit import timeit
import binascii

number = 10000

def using_str_format() -> str:
    return "".join("{:02x}".format(x) for x in test_obj)

def using_format() -> str:
    return "".join(format(x, "02x") for x in test_obj)

def using_hexlify() -> str:
    return binascii.hexlify(bytearray(test_obj)).decode('ascii')

def do_test():
    print("Testing with {}-byte {}:".format(len(test_obj), test_obj.__class__.__name__))
    if using_str_format() != using_format() != using_hexlify():
        raise RuntimeError("Results are not the same")

    print("Using str.format       -> " + str(timeit(using_str_format, number=number)))
    print("Using format           -> " + str(timeit(using_format, number=number)))
    print("Using binascii.hexlify -> " + str(timeit(using_hexlify, number=number)))

test_obj = bytes([i for i in range(255)])

test_obj = bytearray([i for i in range(255)])


Testing with 255-byte bytes:
Using str.format       -> 1.459474583090427
Using format           -> 1.5809937679100738
Using binascii.hexlify -> 0.014521426401399307
Testing with 255-byte bytearray:
Using str.format       -> 1.443447684109402
Using format           -> 1.5608712609513171
Using binascii.hexlify -> 0.014114164661833684

Methods using format do provide additional formatting options, as example separating numbers with spaces " ".join, commas ", ".join, upper-case printing "{:02X}".format(x)/format(x, "02X"), etc., but at a cost of great performance impact.

Is there possibility of sum of ArrayList without looping

The only alternative to using a loop is to use recursion.

You can define a method like

public static int sum(List<Integer> ints) {
   return ints.isEmpty() ? 0 : ints.get(0) + ints.subList(1, ints.length());

This is very inefficient compared to using a plain loop and can blow up if you have many elements in the list.

An alternative which avoid a stack overflow is to use.

public static int sum(List<Integer> ints) {
    int len = ints.size();
    if (len == 0) return 0;
    if (len == 1) return ints.get(0);
    return sum(ints.subList(0, len/2)) + sum(ints.subList(len/2, len));

This is just as inefficient, but will avoid a stack overflow.

The shortest way to write the same thing is

int sum = 0, a[] = {2, 4, 6, 8};

for(int i: a) {
    sum += i;

System.out.println("sum(a) = " + sum);


sum(a) = 20

Rails filtering array of objects by attribute value

You can filter using where

Job.includes(:attachments).where(file_type: ["logo", "image"])

Twitter Bootstrap Responsive Background-Image inside Div

I had the similar issue and i solved it using:

background:url(images/banner1.png) no-repeat center top scroll;
background-size: 100% auto;
padding-bottom: 50%;

... here i had to add the padding: 50% because it wasn't working for me otherwise. It allowed me to set the height of container, as per the size ratio of my banner image. and it is also responsive in my case.

How to access the ith column of a NumPy multidimensional array?

>>> test[:,0]
array([1, 3, 5])


>>> test[1,:]
array([3, 4])

lets you access rows. This is covered in Section 1.4 (Indexing) of the NumPy reference. This is quick, at least in my experience. It's certainly much quicker than accessing each element in a loop.

Is there a naming convention for git repositories?

lowercase-with-hyphens is the style I most often see on GitHub.*

lowercase_with_underscores is probably the second most popular style I see.

The former is my preference because it saves keystrokes.

* Anecdotal; I haven't collected any data.

How to stop/shut down an elasticsearch node?

If you just want to apply new config you don't need to shut it down.

$ sudo service elasticsearch restart

But if you want to shut it down anyway:

$ sudo service elasticsearch stop


$ sudo systemctl stop elasticsearch.service

$ sudo systemctl restart elasticsearch.service


docker restart <elasticsearch-container-name or id>

Detect change to selected date with bootstrap-datepicker

Based on Irvin Dominin example, I've created 2 examples supporting Paste and hit Enter.

This works in Chrome:

$(document).ready(function() {
      format: 'dd/mm/yyyy',
      assumeNearbyYear: true,
      autoclose: true,
      orientation: 'bottom right',
      todayHighlight: true,
      keyboardNavigation: false
    /* On 'paste' -> loses focus, hide calendar and trigger 'change' */
    .on('paste', function(e) {
    /* On 'enter' keypress -> loses focus and trigger 'change' */
    .on('keydown', function(e) {

      if (e.which === 13) {
    .change(function(e) {
      $('#stdout').append($('#date-daily').val() + ' change\n');

But not in IE, so I created another example for IE11:,js,console,output

$(document).ready(function() {
      format: 'dd/mm/yyyy',
      assumeNearbyYear: true,
      autoclose: true,
      orientation: 'bottom right',
      todayHighlight: true,
      keyboardNavigation: false
    // OnEnter -> lose focus
    .on('keydown', function(e) {
         if (e.which === 13){ 
    // onPaste -> hide and lose focus
    .on('keyup', function(e) {
         if (e.which === 86){ 
    .change(function(e) {
       $('#stdout').append($('#date-daily').val() + ' change\n');

If last example still doesn't work in IE11, you can try splitting the setup:

// DatePicker setup
    format: 'dd/mm/yyyy',
    assumeNearbyYear: true,      /* manually-entered dates with two-digit years, such as '5/1/15', will be parsed as '2015', not '15' */
    autoclose: true,             /* close the datepicker immediately when a date is selected */
    orientation: 'bottom rigth',
    todayHighlight: true,        /* today appears with a blue box */
    keyboardNavigation: false    /* select date only onClick. when true, is too difficult free typing  */

And the event handlers: (note I'm not using $('.datepicker').datepicker({)

   // Smoker DataPicker behaviour
    // OnEnter -> lose focus
    .on('keydown', function (e) {
        if (e.which === 13){ 
    // onPaste -> hide and lose focus
    .on('keyup', function (e) {
        if (e.which === 86){ 
    .change(function (e) {
        // do saomething

document.getElementById("test").style.display="hidden" not working

you can use something like this....div container

<script type="text/javascript">
function hide(){
<div id="test">
<form method="post" >

<table width="60%" border="0" cellspacing="2" cellpadding="2"  >
  <tr style="background:url(../images/nav.png) repeat-x; color:#fff; font-weight:bold" align="center">
    <td>Ample Id</td>

  <tr align="center" bgcolor="#E8F8FF" style="color:#006" >
    <td><input type="text" name="ampid" id="ampid" value="<?php echo $_POST['ampid'];?>" /></td>
   <td><input type="image" src="../images/btnFind.png" id="find" name="find" onclick="javascript:hide();"/></td>



Python error: TypeError: 'module' object is not callable for HeadFirst Python code

Your module and your class AthleteList have the same name. The line

import AthleteList

imports the module and creates a name AthleteList in your current scope that points to the module object. If you want to access the actual class, use


In particular, in the line

return(AthleteList(templ.pop(0), templ.pop(0), templ))

you are actually accessing the module object and not the class. Try

return(AthleteList.AthleteList(templ.pop(0), templ.pop(0), templ))

C# how to convert File.ReadLines into string array?

Change string[] lines = File.ReadLines("c:\\file.txt"); to IEnumerable<string> lines = File.ReadLines("c:\\file.txt"); The rest of your code should work fine.

Checking for #N/A in Excel cell from VBA code

First check for an error (N/A value) and then try the comparisation against cvErr(). You are comparing two different things, a value and an error. This may work, but not always. Simply casting the expression to an error may result in similar problems because it is not a real error only the value of an error which depends on the expression.

If IsError(ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value) Then
  If (ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value <> CVErr(xlErrNA)) Then
    'do something
  End If
End If

Eclipse Generate Javadoc Wizard: what is "Javadoc Command"?

Yes, presumably it wants the path to the javadoc command line tool that comes with the JDK (in the bin directory, same as java and javac).

Eclipse should be able to find it automatically; are you perhaps running it on a JRE? That would explain the request.

How does the "position: sticky;" property work?

Check if an ancestor element has overflow set (e.g. overflow:hidden); try toggling it. You may have to go up the DOM tree higher than you expect =).

This may affect your position:sticky on a descendant element.

Accessing elements of Python dictionary by index

mydict = {
'Apple': {'American':'16', 'Mexican':10, 'Chinese':5},
'Grapes':{'Arabian':'25','Indian':'20'} }

for n in mydict:

Sniff HTTP packets for GET and POST requests from an application

Put http.request.method == "POST" in the display filter of wireshark to only show POST requests. Click on the packet, then expand the Hypertext Transfer Protocol field. The POST data will be right there on top.

How do I kill an Activity when the Back button is pressed?

add this to your activity

public boolean onKeyDown(int keyCode, KeyEvent event)
    if ((keyCode == KeyEvent.KEYCODE_BACK))
    return super.onKeyDown(keyCode, event);

Adding calculated column(s) to a dataframe in pandas

For the second part of your question, you can also use shift, for example:

df['t-1'] = df['t'].shift(1)

t-1 would then contain the values from t one row above.

No numeric types to aggregate - change in groupby() behaviour?

I got this error generating a data frame consisting of timestamps and data:

df = pd.DataFrame({'data':value}, index=pd.DatetimeIndex(timestamp))

Adding the suggested solution works for me:

df = pd.DataFrame({'data':value}, index=pd.DatetimeIndex(timestamp), dtype=float))

Thanks Chang She!


2005-01-01 00:10:00  7.53
2005-01-01 00:20:00  7.54
2005-01-01 00:30:00  7.62
2005-01-01 00:40:00  7.68
2005-01-01 00:50:00  7.81
2005-01-01 01:00:00  7.95
2005-01-01 01:10:00  7.96
2005-01-01 01:20:00  7.95
2005-01-01 01:30:00  7.98
2005-01-01 01:40:00  8.06
2005-01-01 01:50:00  8.04
2005-01-01 02:00:00  8.06
2005-01-01 02:10:00  8.12
2005-01-01 02:20:00  8.12
2005-01-01 02:30:00  8.25
2005-01-01 02:40:00  8.27
2005-01-01 02:50:00  8.17
2005-01-01 03:00:00  8.21
2005-01-01 03:10:00  8.29
2005-01-01 03:20:00  8.31
2005-01-01 03:30:00  8.25
2005-01-01 03:40:00  8.19
2005-01-01 03:50:00  8.17
2005-01-01 04:00:00  8.18
2005-01-01 00:00:00  7.636000
2005-01-01 01:00:00  7.990000
2005-01-01 02:00:00  8.165000
2005-01-01 03:00:00  8.236667
2005-01-01 04:00:00  8.180000

Standard deviation of a list

pure python code:

from math import sqrt

def stddev(lst):
    mean = float(sum(lst)) / len(lst)
    return sqrt(float(reduce(lambda x, y: x + y, map(lambda x: (x - mean) ** 2, lst))) / len(lst))

Return sql rows where field contains ONLY non-alphanumeric characters

This will not work correctly, e.g. abcÑxyz will pass thru this as it has a,b,c... you need to work with Collate or check each byte.

Source file not compiled Dev C++

I was having this issue and fixed it by going to: C:\Dev-Cpp\libexec\gcc\mingw32\3.4.2 , then deleting collect2.exe

How to import an existing X.509 certificate and private key in Java keystore to use in SSL?

Previous answers point out correctly that you can only do this with the standard JDK tools by converting the JKS file into PKCS #12 format first. If you're interested, I put together a compact utility to import OpenSSL-derived keys into a JKS-formatted keystore without having to convert the keystore to PKCS #12 first:

You would use the linked utility like this:

$ openssl req -x509 -newkey rsa:2048 -keyout localhost.key -out localhost.csr -subj "/CN=localhost"

(sign the CSR, get back localhost.cer)

$ openssl rsa -in localhost.key -out localhost.rsa
Enter pass phrase for localhost.key:
writing RSA key
$ java -classpath . KeyImport -keyFile localhost.rsa -alias localhost -certificateFile localhost.cer -keystore localhost.jks -keystorePassword changeit -keystoreType JKS -keyPassword changeit

What is the best way to delete a component with CLI

Currently Angular CLI doesn't support an option to remove the component, you need to do it manually.

  1. Remove import references for every component from app.module
  2. Delete component folders.
  3. You also need to remove the component declaration from @NgModule declaration array in app.module.ts file

How to compile a Perl script to a Windows executable with Strawberry Perl?

There are three packagers, and two compilers:

free packager: PAR
commercial packagers: perl2exe, perlapp
compilers: B::C, B::CC

(Note: perlfaq3 is still wrong)

For strawberry you need perl-5.16 and B-C from git master (1.43), as B-C-1.42 does not support 5.16.

Capturing URL parameters in request.GET

This is not exactly what you asked for, but this snippet is helpful for managing query_strings in templates.

What is the difference between venv, pyvenv, pyenv, virtualenv, virtualenvwrapper, pipenv, etc?

Jan 2020 Update

@Flimm has explained all the differences very well. Generally, we want to know the difference between all tools because we want to decide what's best for us. So, the next question would be: which one to use? I suggest you choose one of the two official ways to manage virtual environments:

How can I get a resource content from a static context?

I load shader for openGL ES from static function.

Remember you must use lower case for your file and directory name, or else the operation will be failed

public class MyGLRenderer implements GLSurfaceView.Renderer {


    public static int loadShader() {
        //    Read file as input stream
        InputStream inputStream = MyGLRenderer.class.getResourceAsStream("/res/raw/vertex_shader.txt");

        //    Convert input stream to string
        Scanner s = new Scanner(inputStream).useDelimiter("\\A");
        String shaderCode = s.hasNext() ? : "";



Get index of clicked element in collection with jQuery


$(this).index() can be used to get the index of the clicked element if the elements are siblings.

<div id="container">
    <a href="#" class="link">1</a>
    <a href="#" class="link">2</a>
    <a href="#" class="link">3</a>
    <a href="#" class="link">4</a>

$('#container').on('click', 'a', function() {
<script src=""></script>
<div id="container">
  <a href="#" class="link">1</a>
  <a href="#" class="link">2</a>
  <a href="#" class="link">3</a>
  <a href="#" class="link">4</a>

Not siblings

If no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.

Pass the selector to the index(selector).



Find the index of the <a> element that is clicked.

    <td><a href="#" class="adwa">0001</a></td>
    <td><a href="#" class="adwa">0002</a></td>
    <td><a href="#" class="adwa">0003</a></td>
    <td><a href="#" class="adwa">0004</a></td>


$('#table').on('click', '.adwa', function() {
<script src=""></script>
<table id="table">
            <th>vendor id</th>
            <td><a href="#" class="adwa">0001</a></td>
            <td><a href="#" class="adwa">0002</a></td>
            <td><a href="#" class="adwa">0003</a></td>
            <td><a href="#" class="adwa">0004</a></td>

How do I check if a type is a subtype OR the type of an object?

If you're trying to do it in a Xamarin Forms PCL project, the above solutions using IsAssignableFrom gives an error:

Error: 'Type' does not contain a definition for 'IsAssignableFrom' and no extension method 'IsAssignableFrom' accepting a first argument of type 'Type' could be found (are you missing a using directive or an assembly reference?)

because IsAssignableFrom asks for a TypeInfo object. You can use the GetTypeInfo() method from System.Reflection:


Python "SyntaxError: Non-ASCII character '\xe2' in file"

I my case \xe2 was a which should be replaced by '.

In general I recommend to convert UTF-8 to ASCII using e.g.

However if you want to keep UTF-8 you can use

#-*- mode: python -*-
# -*- coding: utf-8 -*-

Extract a single (unsigned) integer from a string

I do not own the credit for this, but I just have to share it. This regex will get numbers from a string, including decimal points/places, as well as commas:


Cited from here:
php - regex - how to extract a number with decimal (dot and comma) from a string (e.g. 1,120.01)?

Where will log4net create this log file?

Log4net is saving into your project folder. Something like: \SolutionFolder\ProjectFolder\bin\SolutionConfiguration\logs\log-file.txt.


  • SolutionFolder is where you save your solution
  • ProjectFolder is the folder where your project lives into the solution and
  • SolutionConfiguration is the folder that contais all the binaries of your project (the default is Debug or Release)

Hope this helps!

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1922-1' for key 'IDX_STOCK_PRODUCT'

I just added an @ symbol and it started working. Like this: @$product->save();

How to get screen width and height

        *DisplayMetrics: A structure describing general information about a display, such as its size, density, and font scaling.
        * */

 DisplayMetrics metrics = getResources().getDisplayMetrics();

       int DeviceTotalWidth = metrics.widthPixels;
       int DeviceTotalHeight = metrics.heightPixels;

ASP.NET MVC: What is the purpose of @section?

You want to use sections when you want a bit of code/content to render in a placeholder that has been defined in a layout page.

In the specific example you linked, he has defined the RenderSection in the _Layout.cshtml. Any view that uses that layout can define an @section of the same name as defined in Layout, and it will replace the RenderSection call in the layout.

Perhaps you're wondering how we know Index.cshtml uses that layout? This is due to a bit of MVC/Razor convention. If you look at the dialog where he is adding the view, the box "Use layout or master page" is checked, and just below that it says "Leave empty if it is set in a Razor _viewstart file". It isn't shown, but inside that _ViewStart.cshtml file is code like:

    Layout = "~/Views/Shared/_Layout.cshtml";

The way viewstarts work is that any cshtml file within the same directory or child directories will run the ViewStart before it runs itself.

Which is what tells us that Index.cshtml uses Shared/_Layout.cshtml.

What do *args and **kwargs mean?

Also, we use them for managing inheritance.

class Super( object ):
   def __init__( self, this, that ):
       self.this = this
       self.that = that

class Sub( Super ):
   def __init__( self, myStuff, *args, **kw ):
       super( Sub, self ).__init__( *args, **kw )
       self.myStuff= myStuff

x= Super( 2.7, 3.1 )
y= Sub( "green", 7, 6 )

This way Sub doesn't really know (or care) what the superclass initialization is. Should you realize that you need to change the superclass, you can fix things without having to sweat the details in each subclass.

Is it correct to use DIV inside FORM?

Your question doesn't address what you want to put in the DIV tags, which is probably why you've received some incomplete/wrong answers. The truth is that you can, as Royi said, put DIV tags inside of your forms. You don't want to do this for labels, for instance, but if you have a form with a bunch of checkboxes that you want to lay out into three columns, then by all means, use DIV tags (or SPAN, HEADER, etc.) to accomplish the look and feel you're trying to achieve.

How do I restart my C# WinForm Application?

I wanted the new application start up after the old one shuts down.

Using process.WaitForExit() to wait for your own process to shutdown makes no sense. It will always time out.

So, my approach is to use Application.Exit() then wait, but allow events to be processed, for a period of time. Then start a new application with the same arguments as the old.

static void restartApp() {
    string commandLineArgs = getCommandLineArgs();
    string exePath = Application.ExecutablePath;
    try {
        wait_allowingEvents( 1000 );
    } catch( ArgumentException ex ) {
    Process.Start( exePath, commandLineArgs );

static string getCommandLineArgs() {
    Queue<string> args = new Queue<string>( Environment.GetCommandLineArgs() );
    args.Dequeue(); // args[0] is always exe path/filename
    return string.Join( " ", args.ToArray() );

static void wait_allowingEvents( int durationMS ) {
    DateTime start = DateTime.Now;
    do {
    } while( start.Subtract( DateTime.Now ).TotalMilliseconds > durationMS );

How can I prevent java.lang.NumberFormatException: For input string: "N/A"?

"N/A" is a string and cannot be converted to a number. Catch the exception and handle it. For example:

    String text = "N/A";
    int intVal = 0;
    try {
        intVal = Integer.parseInt(text);
    } catch (NumberFormatException e) {
        //Log it if needed
        intVal = //default fallback value;

Plot two graphs in same plot in R

tl;dr: You want to use curve (with add=TRUE) or lines.

I disagree with par(new=TRUE) because that will double-print tick-marks and axis labels. Eg

sine and parabola

The output of plot(sin); par(new=T); plot( function(x) x**2 ).

Look how messed up the vertical axis labels are! Since the ranges are different you would need to set ylim=c(lowest point between the two functions, highest point between the two functions), which is less easy than what I'm about to show you---and way less easy if you want to add not just two curves, but many.

What always confused me about plotting is the difference between curve and lines. (If you can't remember that these are the names of the two important plotting commands, just sing it.)

Here's the big difference between curve and lines.

curve will plot a function, like curve(sin). lines plots points with x and y values, like: lines( x=0:10, y=sin(0:10) ).

And here's a minor difference: curve needs to be called with add=TRUE for what you're trying to do, while lines already assumes you're adding to an existing plot.

id & sine

Here's the result of calling plot(0:2); curve(sin).

Behind the scenes, check out methods(plot). And check body( plot.function )[[5]]. When you call plot(sin) R figures out that sin is a function (not y values) and uses the plot.function method, which ends up calling curve. So curve is the tool meant to handle functions.

Custom Listview Adapter with filter Android

please check below code it will help you

            .setOnItemClickListener(new OnItemClickListener() {

                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {

                    int pos = position;
                    Intent intent = new Intent(getContext(),
                    intent.putExtra("model", list.get(position));
    return convertView;

public android.widget.Filter getFilter() {

    return new android.widget.Filter() {

        protected void publishResults(CharSequence constraint,
                FilterResults results) {

            ArrayList<UserListModel> updatelist = (ArrayList<UserListModel>) results.values;
            UserListCustomAdaptor newadaptor = new UserListCustomAdaptor(
                    getContext(), getCount(), updatelist);

            if (results.equals(constraint)) {
            if (results.count > 0) {
            } else {


        protected FilterResults performFiltering(CharSequence constraint) {

            FilterResults filterResults = new FilterResults();
            list = new ArrayList<UserListModel>();

            if (constraint != null && DrawerActivity.userlist != null) {

                constraint = constraint.toString().toLowerCase();
                int length = DrawerActivity.userlist.size();
                int i = 0;
                while (i < length) {

                    UserListModel modelobj = DrawerActivity.userlist.get(i);
                    String data = modelobj.getFirstName() + " "
                            + modelobj.getLastName();
                    if (data.toLowerCase().contains(constraint.toString())) {

                filterResults.values = list;
                filterResults.count = list.size();
            return filterResults;

public int getCount() {
    return list.size();

public UserListModel getItem(int position) {

    return list.get(position);

An "and" operator for an "if" statement in Bash

Try this:

if [ ${STATUS} -ne 100 -a "${STRING}" = "${VALUE}" ]


if [ ${STATUS} -ne 100 ] && [ "${STRING}" = "${VALUE}" ]

Laravel Eloquent ORM Transactions

You can do this:

DB::transaction(function() {

Everything inside the Closure executes within a transaction. If an exception occurs it will rollback automatically.

Java AES encryption and decryption

Try this, a simpler solution.

byte[] salt = "ThisIsASecretKey".getBytes();
Key key = new SecretKeySpec(salt, 0, 16, "AES");

Cipher cipher = Cipher.getInstance("AES");

How to create SPF record for multiple IPs?

The open SPF wizard from the previous answer is no longer available, neither the one from Microsoft.

Background color not showing in print preview

There's a style in the bootstrap css files under @media print{*,:after,:before ....} that has color and background styles labeled !important, which remove any background colors on any elements. Kill those two pieces of css and it will work.

Bootstrap is making the executing decision that you should never have any background color in prints, so you have to edit their css or have another !important style that is a higher precedence. Good job bootstrap...

Removing duplicate characters from a string

 mylist=["ABA", "CAA", "ADA"]
 for item in mylist:
     for char in item:
         if char not in buffer:

 ['AB', 'CA', 'AD']

HTTP Error 401.2 - Unauthorized You are not authorized to view this page due to invalid authentication headers

I had the same issue, and spent quite a bit of time trying to track down the solution. I had Anonymous Authentication set up at two different levels with two different users. Make sure that you're not overwriting your set up at a lower level.

Is it possible to run .APK/Android apps on iPad/iPhone devices?

There is another option not mentioned previously:

  • Pieceable Viewer has unfortunately stopped its service at December 31, 2012 but open-sourced its software. You need to compile your iOS application for the emulator and Pieceable's software will embed it in a webpage which hosts the application. This webpage can be used to run the iOS application. See Pieceable's for more details.

Get file size, image width and height before upload

So I started experimenting with the different things that FileReader API had to offer and could create an IMG tag with a DATA URL.

Drawback: It doesn't work on mobile phones, but it works fine on Google Chrome.

$('input').change(function() {_x000D_
    var fr = new FileReader;_x000D_
    fr.onload = function() {_x000D_
        var img = new Image;_x000D_
        img.onload = function() { _x000D_
//I loaded the image and have complete control over all attributes, like width and src, which is the purpose of filereader._x000D_
            $.ajax({url: img.src, async: false, success: function(result){_x000D_
              $("#result").html("READING IMAGE, PLEASE WAIT...")_x000D_
              $("#result").html("<img src='" + img.src + "' />");_x000D_
                console.log("Finished reading Image");_x000D_
        img.src = fr.result;_x000D_
<script src=""></script>_x000D_
<input type="file" accept="image/*" capture="camera">_x000D_
<div id='result'>Please choose a file to view it. <br/>(Tested successfully on Chrome - 100% SUCCESS RATE)</div>

(see this on a jsfiddle at
(see the original jsfiddle that i added upon to at

Bootstrap date time picker

In order to run the bootstrap date time picker you need to include Moment.js as well. Here is the working code sample in your case.

<!DOCTYPE html>_x000D_
    <html lang="en">_x000D_
      <meta charset="utf-8">_x000D_
      <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
      <link rel="stylesheet" href="">_x000D_
      <script src=""></script>_x000D_
      <script src=""></script>_x000D_
      <!-- <link rel="stylesheet" type="text/css" href="css/bootstrap-datetimepicker.css"> -->_x000D_
      <script type="text/javascript" src=""></script>_x000D_
      <link rel="stylesheet" type="text/css" href=""> _x000D_
      <link rel="stylesheet" type="text/css" href=""> _x000D_
      <script type="text/javascript" src=""></script>_x000D_
       <div class="container">_x000D_
          <div class="row">_x000D_
            <div class='col-sm-6'>_x000D_
                <div class="form-group">_x000D_
                    <div class='input-group date' id='datetimepicker1'>_x000D_
                        <input type='text' class="form-control" />_x000D_
                        <span class="input-group-addon">_x000D_
                            <span class="glyphicon glyphicon-calendar"></span>_x000D_
            <script type="text/javascript">_x000D_
                $(function () {_x000D_

How to add button inside input

The button isn't inside the input. Here:

input[type="text"] {
    width: 200px;
    height: 20px;
    padding-right: 50px;

input[type="submit"] {
    margin-left: -50px;
    height: 20px;
    width: 50px;


jQuery.css() - marginLeft vs. margin-left?

jQuery's underlying code passes these strings to the DOM, which allows you to specify the CSS property name or the DOM property name in a very similar way: = "10px";

is equivalent to:["margin-left"] = "10px";

Why has jQuery allowed for marginLeft as well as margin-left? It seems pointless and uses more resources to be converted to the CSS margin-left?

jQuery's not really doing anything special. It may alter or proxy some strings that you pass to .css(), but in reality there was no work put in from the jQuery team to allow either string to be passed. There's no extra resources used because the DOM does the work.

How can I access an internal class from an external assembly?

I see only one case that you would allow exposure to your internal members to another assembly and that is for testing purposes.

Saying that there is a way to allow "Friend" assemblies access to internals:

In the AssemblyInfo.cs file of the project you add a line for each assembly.

[assembly: InternalsVisibleTo("name of assembly here")]

this info is available here.

Hope this helps.

Resizing an Image without losing any quality

Here is a forum thread that provides a C# image resizing code sample. You could use one of the GD library binders to do resampling in C#.

Conversion from 12 hours time to 24 hours time in java

Using LocalTime in Java 8, LocalTime has many useful methods like getHour() or the getMinute() method,

For example,

LocalTime intime = LocalTime.parse(inputString, DateTimeFormatter.ofPattern("h:m a"));
String outtime = intime.format(DateTimeFormatter.ISO_LOCAL_TIME);

In some cases, First line alone can do the required parsing

Why is processing a sorted array faster than processing an unsorted array?

I tried the same code with MATLAB 2011b with my MacBook Pro (Intel i7, 64 bit, 2.4 GHz) for the following MATLAB code:

% Processing time with Sorted data vs unsorted data
% Generate data
arraySize = 32768
sum = 0;
% Generate random integer data from range 0 to 255
data = randi(256, arraySize, 1);

%Sort the data
data1= sort(data); % data1= data  when no sorting done

%Start a stopwatch timer to measure the execution time

for i=1:100000

    for j=1:arraySize

        if data1(j)>=128
            sum=sum + data1(j);


ExeTimeWithSorting = toc - tic;

The results for the above MATLAB code are as follows:

  a: Elapsed time (without sorting) = 3479.880861 seconds.
  b: Elapsed time (with sorting ) = 2377.873098 seconds.

The results of the C code as in @GManNickG I get:

  a: Elapsed time (without sorting) = 19.8761 sec.
  b: Elapsed time (with sorting ) = 7.37778 sec.

Based on this, it looks MATLAB is almost 175 times slower than the C implementation without sorting and 350 times slower with sorting. In other words, the effect (of branch prediction) is 1.46x for MATLAB implementation and 2.7x for the C implementation.

Convert a number into a Roman Numeral in javaScript

I know this is an old question but I'm pretty proud of this solution :) It only handles numbers less than 1000 but could easily be expanded to include however large you'd need by adding on to the 'numeralCodes' 2D array.

var numeralCodes = [["","I","II","III","IV","V","VI","VII","VIII","IX"],         // Ones_x000D_
                    ["","X","XX","XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"],   // Tens_x000D_
                    ["","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"]];        // Hundreds_x000D_
function convert(num) {_x000D_
  var numeral = "";_x000D_
  var digits = num.toString().split('').reverse();_x000D_
  for (var i=0; i < digits.length; i++){_x000D_
    numeral = numeralCodes[i][parseInt(digits[i])] + numeral;_x000D_
  return numeral;  _x000D_
<input id="text-input" type="text">_x000D_
<button id="convert-button" onClick="var n = parseInt(document.getElementById('text-input').value);document.getElementById('text-output').value = convert(n);">Convert!</button>_x000D_
<input id="text-output" style="display:block" type="text">

How do I convert from int to Long in Java?

As soon as there is only method Long.valueOf(long), cast from int to long will be done implicitly in case of using Long.valueOf(intValue).

The more clear way to do this is


jQuery UI - Close Dialog When Clicked Outside

The given example(s) use one dialog with id '#dialog', i needed a solution that close any dialog:

$.extend($.ui.dialog.prototype.options, {
    modal: true,
    open: function(object) {
        jQuery('.ui-widget-overlay').bind('click', function() {              
            var id = jQuery('id');

Thanks to my colleague Youri Arkesteijn for the suggestion of using prototype.

Visual Studio: LINK : fatal error LNK1181: cannot open input file

I had a similar problem in that I was getting LINK1181 errors on the .OBJ file that was part of the project itself (and there were only 2 .cxx files in the entire project).

Initially I had setup the project to generate an .EXE in Visual Studio, and then in the Property Pages -> Configuration Properties -> General -> Project Defaults -> Configuration Type, I changed the .EXE to .DLL. Suspecting that somehow Visual Studio 2008 was getting confused, I recreated the entire solution from scratch using .DLL mode right from the start. Problem went away after that. I imagine if you manually picked your way through the .vcproj and other related files you could figure out how to fix things without starting from scratch (but my program consisted of two .cpp files so it was easier to start over).

What are the basic rules and idioms for operator overloading?

Conversion Operators (also known as User Defined Conversions)

In C++ you can create conversion operators, operators that allow the compiler to convert between your types and other defined types. There are two types of conversion operators, implicit and explicit ones.

Implicit Conversion Operators (C++98/C++03 and C++11)

An implicit conversion operator allows the compiler to implicitly convert (like the conversion between int and long) the value of a user-defined type to some other type.

The following is a simple class with an implicit conversion operator:

class my_string {
  operator const char*() const {return data_;} // This is the conversion operator
  const char* data_;

Implicit conversion operators, like one-argument constructors, are user-defined conversions. Compilers will grant one user-defined conversion when trying to match a call to an overloaded function.

void f(const char*);

my_string str;
f(str); // same as f( str.operator const char*() )

At first this seems very helpful, but the problem with this is that the implicit conversion even kicks in when it isn’t expected to. In the following code, void f(const char*) will be called because my_string() is not an lvalue, so the first does not match:

void f(my_string&);
void f(const char*);


Beginners easily get this wrong and even experienced C++ programmers are sometimes surprised because the compiler picks an overload they didn’t suspect. These problems can be mitigated by explicit conversion operators.

Explicit Conversion Operators (C++11)

Unlike implicit conversion operators, explicit conversion operators will never kick in when you don't expect them to. The following is a simple class with an explicit conversion operator:

class my_string {
  explicit operator const char*() const {return data_;}
  const char* data_;

Notice the explicit. Now when you try to execute the unexpected code from the implicit conversion operators, you get a compiler error:

prog.cpp: In function ‘int main()’:
prog.cpp:15:18: error: no matching function for call to ‘f(my_string)’
prog.cpp:15:18: note: candidates are:
prog.cpp:11:10: note: void f(my_string&)
prog.cpp:11:10: note:   no known conversion for argument 1 from ‘my_string’ to ‘my_string&’
prog.cpp:12:10: note: void f(const char*)
prog.cpp:12:10: note:   no known conversion for argument 1 from ‘my_string’ to ‘const char*’

To invoke the explicit cast operator, you have to use static_cast, a C-style cast, or a constructor style cast ( i.e. T(value) ).

However, there is one exception to this: The compiler is allowed to implicitly convert to bool. In addition, the compiler is not allowed to do another implicit conversion after it converts to bool (a compiler is allowed to do 2 implicit conversions at a time, but only 1 user-defined conversion at max).

Because the compiler will not cast "past" bool, explicit conversion operators now remove the need for the Safe Bool idiom. For example, smart pointers before C++11 used the Safe Bool idiom to prevent conversions to integral types. In C++11, the smart pointers use an explicit operator instead because the compiler is not allowed to implicitly convert to an integral type after it explicitly converted a type to bool.

Continue to Overloading new and delete.

taking input of a string word by word

getline is storing the entire line at once, which is not what you want. A simple fix is to have three variables and use cin to get them all. C++ will parse automatically at the spaces.

#include <iostream>
using namespace std;

int main() {
    string a, b, c;
    cin >> a >> b >> c;
    //now you have your three words
    return 0;

I don't know what particular "operation" you're talking about, so I can't help you there, but if it's changing characters, read up on string and indices. The C++ documentation is great. As for using namespace std; versus std:: and other libraries, there's already been a lot said. Try these questions on StackOverflow to start.

How to compile python script to binary executable

Or use PyInstaller as an alternative to py2exe. Here is a good starting point. PyInstaller also lets you create executables for linux and mac...

Here is how one could fairly easily use PyInstaller to solve the issue at hand:


From the tool's documentation:

PyInstaller analyzes and:

  • Writes myscript.spec in the same folder as the script.
  • Creates a folder build in the same folder as the script if it does not exist.
  • Writes some log files and working files in the build folder.
  • Creates a folder dist in the same folder as the script if it does not exist.
  • Writes the myscript executable folder in the dist folder.

In the dist folder you find the bundled app you distribute to your users.

Difference between View and ViewGroup in Android

Viewgroup inherits properties of views and does more with other views and viewgroup.

See the Android API:

add id to dynamically created <div>

Use Jquery for append the value for creating dynamically


var user_image1='<img src="{@user_image}" class="img-thumbnail" alt="Thumbnail Image" 
style="width:125px; height:125px">';



<div id="userphoto">

Run MySQLDump without Locking Tables

As none of these approaches worked for me, I simply did a:

mysqldump [...] | grep -v "LOCK TABLE" | mysql [...]

It will exclude both LOCK TABLE <x> and UNLOCK TABLES commands.

Note: Hopefully your data doesn't contain that string in it!

Maximum size of a varchar(max) variable

As far as I can tell there is no upper limit in 2008.

In SQL Server 2005 the code in your question fails on the assignment to the @GGMMsg variable with

Attempting to grow LOB beyond maximum allowed size of 2,147,483,647 bytes.

the code below fails with

REPLICATE: The length of the result exceeds the length limit (2GB) of the target large type.

However it appears these limitations have quietly been lifted. On 2008


SET @y = REPLICATE(@y,92681);




I ran this on my 32 bit desktop machine so this 8GB string is way in excess of addressable memory


select internal_objects_alloc_page_count
from sys.dm_db_task_space_usage
WHERE session_id = @@spid



so I presume this all just gets stored in LOB pages in tempdb with no validation on length. The page count growth was all associated with the SET @y = REPLICATE(@y,92681); statement. The initial variable assignment to @y and the LEN calculation did not increase this.

The reason for mentioning this is because the page count is hugely more than I was expecting. Assuming an 8KB page then this works out at 16.36 GB which is obviously more or less double what would seem to be necessary. I speculate that this is likely due to the inefficiency of the string concatenation operation needing to copy the entire huge string and append a chunk on to the end rather than being able to add to the end of the existing string. Unfortunately at the moment the .WRITE method isn't supported for varchar(max) variables.


I've also tested the behaviour with concatenating nvarchar(max) + nvarchar(max) and nvarchar(max) + varchar(max). Both of these allow the 2GB limit to be exceeded. Trying to then store the results of this in a table then fails however with the error message Attempting to grow LOB beyond maximum allowed size of 2147483647 bytes. again. The script for that is below (may take a long time to run).

SET @y1 = @y1 + @y1;
SELECT LEN(@y1), DATALENGTH(@y1)  /*4294967294, 4294967292*/

SET @y2 = @y2 + @y2;
SELECT LEN(@y2), DATALENGTH(@y2)  /*2147483646, 4294967292*/

DECLARE @y3 NVARCHAR(MAX) = @y2 + @y1
SELECT LEN(@y3), DATALENGTH(@y3)   /*6442450940, 12884901880*/

/*This attempt fails*/
SELECT @y1 y1, @y2 y2, @y3 y3

Object of class DateTime could not be converted to string

It's kind of offtopic, but i come here from googling the same error. For me this error appeared when i was selecting datetime field from mssql database and than using it later in php-script. like this:

$SQL="SELECT Created
FROM test_table";

$stmt = sqlsrv_query($con, $SQL);
if( $stmt === false ) {
    die( print_r( sqlsrv_errors(), true));

$Row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC);

$SQL="INSERT INTO another_test_table (datetime_field) VALUES ('".$Row['Created']."')";
$stmt = sqlsrv_query($con, $SQL);
if( $stmt === false ) {
    die( print_r( sqlsrv_errors(), true));

the INSERT statement was giving error: Object of class DateTime could not be converted to string

I realized that you CAN'T just select the datetime from database:

SELECT Created FROM test_table

BUT you have to use CONVERT for this field:

SELECT CONVERT(varchar(24),Created) as Created FROM test_table

How to get HttpRequestMessage data

  System.IO.StreamReader reader = new System.IO.StreamReader(HttpContext.Current.Request.InputStream);
  reader.BaseStream.Position = 0;
  string requestFromPost = reader.ReadToEnd();

PHP post_max_size overrides upload_max_filesize


  • Sets max size of post data allowed. This setting also affects file upload
  • To upload large files, this value must be larger than upload_max_filesize
  • Generally speaking, memory_limit should be larger than post_max_size.
  • PHP Default: 8M


  • The maximum size of an uploaded file
  • PHP Default: 2M

memory_limit > post_max_size > upload_max_filesize

PHP Default: 128M > 8M > 2M

By default, post_max_size should be 4 times greater than upload_max_filesize.
In turn memory_limit should be 16 times greater than post_max_size

Javascript: best Singleton pattern

Why use a constructor and prototyping for a single object?

The above is equivalent to:

var earth= {
    someMethod: function () {
        if (console && console.log)
            console.log('some method');                             

return {
    Person: Constructors.Person,
    PlanetEarth: earth

javascript regex for special characters

You can use this to find and replace any special characters like in Worpress's slug

const regex = /[`~!@#$%^&*()-_+{}[\]\\|,.//?;':"]/g
let slug = label.replace(regex, '')

How to write subquery inside the OUTER JOIN Statement

I think you don't have to use sub query in this scenario.You can directly left outer join the DEPRMNT table .

While using Left Outer Join ,don't use columns in the RHS table of the join in the where condition, you ll get wrong output

how to set radio option checked onload with jQuery

This one will cause form.reset() failure:

$('input:radio[name=gender][value=Male]').attr('checked', true);

But this one works:


The requested resource does not support HTTP method 'GET'

In my case, the route signature was different from the method parameter. I had id, but I was accepting documentId as parameter, that caused the problem.

[Route("Documents/{id}")]   <--- caused the webapi error
[Route("Documents/{documentId}")] <-- solved
public Document Get(string documentId)

Count the number of commits on a Git branch

If you are using a UNIX system, you could do

git log|grep "Author"|wc -l

SQL update from one Table to another based on a ID match

For SQL Server 2008 + Using MERGE rather than the proprietary UPDATE ... FROM syntax has some appeal.

As well as being standard SQL and thus more portable it also will raise an error in the event of there being multiple joined rows on the source side (and thus multiple possible different values to use in the update) rather than having the final result be undeterministic.

MERGE INTO Sales_Import
   USING RetrieveAccountNumber
      ON Sales_Import.LeadID = RetrieveAccountNumber.LeadID
      SET AccountNumber = RetrieveAccountNumber.AccountNumber;

Unfortunately the choice of which to use may not come down purely to preferred style however. The implementation of MERGE in SQL Server has been afflicted with various bugs. Aaron Bertrand has compiled a list of the reported ones here.

How can I remove a child node in HTML using JavaScript?

You should be able to use the .RemoveNode method of the node or the .RemoveChild method of the parent node.

What is "Advanced" SQL?

I suppose subqueries and PIVOT would qualify, as well as multiple joins, unions and the like.

Laravel 5 How to switch from Production mode

What you could also have a look at is the exposed method Application->loadEnvironmentFrom($file)

I needed one application to run on multiple subdomains. So in bootstrap/app.php I added something like:

$envFile = '.env';
// change $envFile conditionally here

What is the difference between require_relative and require in Ruby?


Use require for installed gems

Use require_relative for local files

require uses your $LOAD_PATH to find the files.
require_relative uses the current location of the file using the statement


Require relies on you having installed (e.g. gem install [package]) a package somewhere on your system for that functionality.

When using require you can use the "./" format for a file in the current directory, e.g. require "./my_file" but that is not a common or recommended practice and you should use require_relative instead.


This simply means include the file 'relative to the location of the file with the require_relative statement'. I generally recommend that files should be "within" the current directory tree as opposed to "up", e.g. don't use

require_relative '../../../filename'

(up 3 directory levels) within the file system because that tends to create unnecessary and brittle dependencies. However in some cases if you are already 'deep' within a directory tree then "up and down" another directory tree branch may be necessary. More simply perhaps, don't use require_relative for files outside of this repository (assuming you are using git which is largely a de-facto standard at this point, late 2018).

Note that require_relative uses the current directory of the file with the require_relative statement (so not necessarily your current directory that you are using the command from). This keeps the require_relative path "stable" as it always be relative to the file requiring it in the same way.

ini_set("memory_limit") in PHP 5.3.3 is not working at all

Works for me, has nothing to do with PHP 5.3. Just like many such options it cannot be overriden via ini_set() when safe_mode is enabled. Check your updated php.ini (and better yet: change the memory_limit there too).

Activity <App Name> has leaked ServiceConnection <ServiceConnection Name>@438030a8 that was originally bound here

I have been reading about Android Service very recently and got a chance to deep dive on it. I have encountered a service leak, for my situation it happened because I had an unbound Service which was starting a bound Service, but in this my unbound Service is replaced by an Activity.

So when I was stopping my unbound Service by using stopSelf() the leak occurred, the reason was I was stopping the parent service without unbinding the bound service. Now the bound service is running and it doesn't know to whom does it belong.

The easy and straight forward fix is you should call unbindService(YOUR_SERVICE); in your onDestroy() function of your parent Activity/Service. This way the lifecycle will ensure that your bound services are stopped or cleaned up before your parent Activity/Services go down.

There is one other variation of this problem. Sometimes in your bound service you want certain functions to work only if the service is bound so we end up putting a bound flag in the onServiceConnected like:

public void onServiceConnected(ComponentName name, IBinder service) {
            bounded = true;
            // code here

This works fine till here but the problem comes when we treat onServiceDisconnected function as a callback for unbindService function call, this by documentation is only called when a service is killed or crashed. And you will never get this callback in the same thread. Hence, we end up doing something like:

public void onServiceDisconnected(ComponentName name) {
            bounded = false;

Which creates major bug in the code because our bound flag never gets reset to false and when this service is connected back again most of the times it is true. So in order to avoid this scenario you should set the bound to false the moment you are calling unbindService.

This is cover in more detail in Erik's blog.

Hope who ever came here got his curiosity satisfied.

Upload file to SFTP using PowerShell

I am able to sftp using PowerShell as below:

PS C:\Users\user\Desktop> sftp [email protected]                                                     
[email protected]'s password:
Connected to [email protected].
sftp> ls
sftp> cd testFolder
sftp> ls
sftp> put taj_mahal_1.jpeg
Uploading taj_mahal_1.jpeg to /home/user/testFolder/taj_mahal_1.jpeg
taj_mahal_1.jpeg                                                                      100%   11KB  35.6KB/s   00:00
sftp> ls
taj_mahal.jpeg      taj_mahal_1.jpeg

I do not have installed Posh-SSH or anything like that. I am using Windows 10 Pro PowerShell. No additional modules installed.

Refresh Part of Page (div)

Usefetch and innerHTML to load div content

let url=""

async function refresh() {
  btn.disabled = true;
  dynamicPart.innerHTML = "Loading..."
  dynamicPart.innerHTML = await(await fetch(url)).text();
<div id="staticPart">
  Here is static part of page

  <button id="btn" onclick="refresh()">
    Click here to start refreshing every 2s

<div id="dynamicPart">Dynamic part</div>

Android Studio cannot resolve R in imported project?

Had this error when importing project from Eclipse. The reason was some of the xml files had errors. Check ALL your XML files for errors. Including androidmanifest.xml, and values, themes, styles, layouts folders, etc. Warnings in xml are ok, but errors will generate this error.

Afterwards, do a Clean Project and rebuild.

How to launch an application from a browser?

The correct method is to register your custom URL Protocol in windows registry as follows:

@="Description here"
"URL Protocol"=""



@="\"C:\\Path To Your EXE\\ExeName.exe\" \"%1\""

Once the above keys and values are added, from the web page, just call "customurl:\\parameter1=xxx&parameter2=xxx" . You will receive the entire url as the argument in exe, which you need to process inside your exe. Change 'customurl' with the text of your choice.

Calculating powers of integers

base is the number that you want to power up, n is the power, we return 1 if n is 0, and we return the base if the n is 1, if the conditions are not met, we use the formula base*(powerN(base,n-1)) eg: 2 raised to to using this formula is : 2(base)*2(powerN(base,n-1)).

public int power(int base, int n){
   return n == 0 ? 1 : (n == 1 ? base : base*(power(base,n-1)));

Insert data into hive table

Although there is an accepted answer I would want to add that as of Hive 0.14, record level operations are allowed. The correct syntax and query would be:

INSERT INTO TABLE tweet_table VALUES ('data');

Carriage Return\Line feed in Java

Encapsulate your writer to provide char replacement, like this:

public class WindowsFileWriter extends Writer {

    private Writer writer;

    public WindowsFileWriter(File file) throws IOException {
        try {
            writer = new OutputStreamWriter(new FileOutputStream(file), "ISO-8859-15");
        } catch (UnsupportedEncodingException e) {
            writer = new FileWriter(logfile);

    public void write(char[] cbuf, int off, int len) throws IOException {
        writer.write(new String(cbuf, off, len).replace("\n", "\r\n"));

    public void flush() throws IOException {

    public void close() throws IOException {


How to sort a dataFrame in python pandas by two or more columns?

For large dataframes of numeric data, you may see a significant performance improvement via numpy.lexsort, which performs an indirect sort using a sequence of keys:

import pandas as pd
import numpy as np


df1 = pd.DataFrame(np.random.randint(1, 5, (10,2)), columns=['a','b'])
df1 = pd.concat([df1]*100000)

def pdsort(df1):
    return df1.sort_values(['a', 'b'], ascending=[True, False])

def lex(df1):
    arr = df1.values
    return pd.DataFrame(arr[np.lexsort((-arr[:, 1], arr[:, 0]))])

assert (pdsort(df1).values == lex(df1).values).all()

%timeit pdsort(df1)  # 193 ms per loop
%timeit lex(df1)     # 143 ms per loop

One peculiarity is that the defined sorting order with numpy.lexsort is reversed: (-'b', 'a') sorts by series a first. We negate series b to reflect we want this series in descending order.

Be aware that np.lexsort only sorts with numeric values, while pd.DataFrame.sort_values works with either string or numeric values. Using np.lexsort with strings will give: TypeError: bad operand type for unary -: 'str'.

How to place a div on the right side with absolute position

yourbox {
   position: absolute;
   left: 100%;
   top: 0;

left:100%; is the important issue here!

UITableView example for Swift

In Swift 4.1 and Xcode 9.4.1

  1. Add UITableViewDataSource, UITableViewDelegate delegated to your class.

  2. Create table view variable and array.

  3. In viewDidLoad create table view.

  4. Call table view delegates

  5. Call table view delegate functions based on your requirement.

import UIKit
// 1
class yourViewController: UIViewController , UITableViewDataSource, UITableViewDelegate { 

// 2
var yourTableView:UITableView = UITableView()
let myArray = ["row 1", "row 2", "row 3", "row 4"]

override func viewDidLoad() {

    // 3
    yourTableView.frame = CGRect(x: 10, y: 10, width: view.frame.width-20, height: view.frame.height-200)

    // 4
    yourTableView.dataSource = self
    yourTableView.delegate = self


// 5
// MARK - UITableView Delegates
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return myArray.count

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

var cell : UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: "cell")
    if cell == nil {
        cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
    if self. myArray.count > 0 {
        cell?.textLabel!.text = self. myArray[indexPath.row]
    cell?.textLabel?.numberOfLines = 0

    return cell!

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    return 50.0

If you are using storyboard, no need for Step 3.

But you need to create IBOutlet for your table view before Step 4.

Convert a hexadecimal string to an integer efficiently in C?

Try this to Convert from Decimal to Hex


    int main(void)
      int count=0,digit,n,i=0;
      int hex[5];
      printf("enter a number   ");


          case 10:
          case 11:
          case 12:
          case 13:
          case 14:
          case 15:
          case 16:



             case 10:
             case 11:
             case 12:
             case  13:
             case 14:
             case 15:


    return 0;

How to run a single test with Mocha?

If you are using npm test (using package.json scripts) use an extra -- to pass the param through to mocha

e.g. npm test -- --grep "my second test"

EDIT: Looks like --grep can be a little fussy (probably depending on the other arguments). You can:

Modify the package.json:

"test:mocha": "mocha --grep \"<DealsList />\" .",

Or alternatively use --bail which seems to be less fussy

npm test -- --bail

How to get the difference between two dictionaries in Python?

What about this? Not as pretty but explicit.

orig_dict = {'a' : 1, 'b' : 2}
new_dict = {'a' : 2, 'v' : 'hello', 'b' : 2}

updates = {}
for k2, v2 in new_dict.items():
    if k2 in orig_dict:    
        if v2 != orig_dict[k2]:
            updates.update({k2 : v2})
        updates.update({k2 : v2})

#test it
#value of 'a' was changed
#'v' is a completely new entry
assert all(k in updates for k in ['a', 'v'])

Remove lines that contain certain string

You could simply not include the line into the new file instead of doing replace.

for line in infile :
     if 'bad' not in line and 'naughty' not in line:

Creating a UIImage from a UIColor to use as a background image for UIButton

Xamarin.iOS solution

 public UIImage CreateImageFromColor()
     var imageSize = new CGSize(30, 30);
     var imageSizeRectF = new CGRect(0, 0, 30, 30);
     UIGraphics.BeginImageContextWithOptions(imageSize, false, 0);
     var context = UIGraphics.GetCurrentContext();
     var red = new CGColor(255, 0, 0);
     var image = UIGraphics.GetImageFromCurrentImageContext();
     return image;

Replace multiple whitespaces with single whitespace in JavaScript string

Something like this:

var s = "  a  b     c  ";_x000D_
  s.replace(/\s+/g, ' ')_x000D_

Making authenticated POST requests with Spring RestTemplate for Android

Ok found the answer. exchange() is the best way. Oddly the HttpEntity class doesn't have a setBody() method (it has getBody()), but it is still possible to set the request body, via the constructor.

// Create the request body as a MultiValueMap
MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();     

body.add("field", "value");

// Note the body object as first parameter!
HttpEntity<?> httpEntity = new HttpEntity<Object>(body, requestHeaders);

ResponseEntity<MyModel> response ="/api/url", HttpMethod.POST, httpEntity, MyModel.class);

operator << must take exactly one argument

If you define operator<< as a member function it will have a different decomposed syntax than if you used a non-member operator<<. A non-member operator<< is a binary operator, where a member operator<< is a unary operator.

// Declarations
struct MyObj;
std::ostream& operator<<(std::ostream& os, const MyObj& myObj);

struct MyObj
    // This is a member unary-operator, hence one argument
    MyObj& operator<<(std::ostream& os) { os << *this; return *this; }

    int value = 8;

// This is a non-member binary-operator, 2 arguments
std::ostream& operator<<(std::ostream& os, const MyObj& myObj)
    return os << myObj.value;

So.... how do you really call them? Operators are odd in some ways, I'll challenge you to write the operator<<(...) syntax in your head to make things make sense.

MyObj mo;

// Calling the unary operator
mo << std::cout;

// which decomposes to...

Or you could attempt to call the non-member binary operator:

MyObj mo;

// Calling the binary operator
std::cout << mo;

// which decomposes to...
operator<<(std::cout, mo);

You have no obligation to make these operators behave intuitively when you make them into member functions, you could define operator<<(int) to left shift some member variable if you wanted to, understand that people may be a bit caught off guard, no matter how many comments you may write.

Almost lastly, there may be times where both decompositions for an operator call are valid, you may get into trouble here and we'll defer that conversation.

Lastly, note how odd it might be to write a unary member operator that is supposed to look like a binary operator (as you can make member operators virtual..... also attempting to not devolve and run down this path....)

struct MyObj
    // Note that we now return the ostream
    std::ostream& operator<<(std::ostream& os) { os << *this; return os; }

    int value = 8;

This syntax will irritate many coders now....

MyObj mo;

mo << std::cout << "Words words words";

// this decomposes to...
mo.operator<<(std::cout) << "Words words words";

// ... or even further ...
operator<<(mo.operator<<(std::cout), "Words words words");

Note how the cout is the second argument in the chain here.... odd right?

HTML combo box with option to type an entry

This one is much smaller, doesn't require jquery and works better in safari.

Check the issues for the modification to add a downarrow.

Adding additional data to select options using jQuery

To me, it sounds like you want to create a new attribute? Do you want

<option value="2" value2="somethingElse">...

To do this, you can do

$(your selector).attr('value2', 'the value');

And then to retrieve it, you can use

$(your selector).attr('value2')

It's not going to be valid code, but I guess it does the job.

How to write unit testing for Angular / TypeScript for private methods with Jasmine

I agree with @toskv: I wouldn't recommend to do that:-)

But if you really want to test your private method, you can be aware that the corresponding code for the TypeScript correspond to a method of the constructor function prototype. This means that it can be used at runtime (whereas you will probably have some compilation errors).

For example:

export class FooBar {
  private _status: number;

  constructor( private foo : Bar ) {

  private initFooBar(data){ data );
    this._status =;

will be transpiled into:

(function(System) {(function(__moduleName){System.register([], function(exports_1, context_1) {
  "use strict";
  var __moduleName = context_1 &&;
  var FooBar;
  return {
    execute: function() {
      FooBar = (function () {
        function FooBar(foo) {
 = foo;
        FooBar.prototype.initFooBar = function (data) {
          this._status =;
        return FooBar;
      exports_1("FooBar", FooBar);

See this plunkr:

SQL Query - Change date format in query to DD/MM/YYYY

SELECT CONVERT(varchar(11),Getdate(),105)

MySQL Workbench: "Can't connect to MySQL server on' (10061)" error

If you have installed WAMP on your machine, please make sure that it is running. Do not EXIT the WAMP from tray menu since it will stop the MySQL Server.

Python - Module Not Found

you need a file named (two underscores on each side) in every folder in the hierarchy, so one in src/ and one in model/. This is what python looks for to know that it should access a particular folder. The files are meant to contain initialization instructions but even if you create them empty this will solve it.

How to import Angular Material in project?

Step 1

yarn add @angular/material @angular/cdk @angular/animations

Step 2 - Create a new file( /myApp/src/app/material.module.ts ) that includes all the material UI modules (there is no shortcut, you have to include individual modules one by one)

import { NgModule } from '@angular/core';

    import {
    } from '@angular/material';

      imports: [
      exports: [
    export class MaterialModule {}

Step 3 - Import and add that newly created module to your app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { MaterialModule } from './material.module'; // material module imported

  declarations: [
  imports: [
    MaterialModule // MAteria module added
  providers: [],
  bootstrap: [AppComponent]
export class AppModule { }

Javascript loading CSV file into an array

If your not overly worried about the size of the file then it may be easier for you to store the data as a JS object in another file and import it in your . Either synchronously or asynchronously using the syntax <script src="countries.js" async></script>. Saves on you needing to import the file and parse it.

However, i can see why you wouldnt want to rewrite 10000 entries so here's a basic object orientated csv parser i wrote.

function requestCSV(f,c){return new CSVAJAX(f,c);};
function CSVAJAX(filepath,callback)
    this.request = new XMLHttpRequest();
    this.request.timeout = 10000;"GET", filepath, true);
    this.request.parent = this;
    this.callback = callback;
    this.request.onload = function() 
        var d = this.response.split('\n'); /*1st separator*/
        var i = d.length;
            if(d[i] !== "")
                d[i] = d[i].split(','); /*2nd separator*/
        this.parent.response = d;
        if(typeof this.parent.callback !== "undefined")

Which can be used like this;

var foo = requestCSV("csvfile.csv",drawlines(lines)); 

The first parameter is the file, relative to the position of your html file in this case. The second parameter is an optional callback function the runs when the file has been completely loaded.

If your file has non-separating commmas then it wont get on with this, as it just creates 2d arrays by chopping at returns and commas. You might want to look into regexp if you need that functionality.

//THIS works 

"1234","ABCD" \n
"!@£$" \n

//Gives you 

//This DOESN'T!

"12,34","AB,CD" \n
"!@,£$" \n

//Gives you


If your not used to the OO methods; they create a new object (like a number, string, array) with their own local functions and variables via a 'constructor' function. Very handy in certain situations. This function could be used to load 10 different files with different callbacks all at the same time(depending on your level of csv love! )

X-Frame-Options on apache

  1. You can add to .htaccess, httpd.conf or VirtualHost section
  2. Header set X-Frame-Options SAMEORIGIN this is the best option

Allow from URI is not supported by all browsers. Reference: X-Frame-Options on MDN

Alter column, add default constraint

alter table TableName drop constraint DF_TableName_WhenEntered

alter table TableName add constraint DF_TableName_WhenEntered default getutcdate() for WhenEntered

How to pass arguments to Shell Script through docker run

Use the same

echo $1

Build the image using the existing Dockerfile:

docker build -t test .

Run the image with arguments abc or xyz or something else.

docker run -ti --rm test / abc

docker run -ti --rm test / xyz

What is Robocopy's "restartable" option?

Restartable mode (/Z) has to do with a partially-copied file. With this option, should the copy be interrupted while any particular file is partially copied, the next execution of robocopy can pick up where it left off rather than re-copying the entire file.

That option could be useful when copying very large files over a potentially unstable connection.

Backup mode (/B) has to do with how robocopy reads files from the source system. It allows the copying of files on which you might otherwise get an access denied error on either the file itself or while trying to copy the file's attributes/permissions. You do need to be running in an Administrator context or otherwise have backup rights to use this flag.

What is the difference between .py and .pyc files?

"A program doesn't run any faster when it is read from a ".pyc" or ".pyo" file than when it is read from a ".py" file; the only thing that's faster about ".pyc" or ".pyo" files is the speed with which they are loaded. "

Rewrite URL after redirecting 404 error htaccess

Try adding this rule to the top of your htaccess:

RewriteEngine On
RewriteRule ^404/?$ /pages/errors/404.php [L]

Then under that (or any other rules that you have):

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^ [L,R]

What is a deadlock?

Deadlocks does not just occur with locks, although that's the most frequent cause. In C++, you can create deadlock with two threads and no locks by just having each thread call join() on the std::thread object for the other.

Loading .sql files from within PHP

I have an environment where no mysql tool or phpmyadmin just my php application connecting to a mysql server on a different host but I need to run scripts exported by mysqldump or myadmin. To solve the problem I created a script multi_query as I mentioned here

It can process mysqldump output and phpmyadmin exports without mysql command line tool. I also made some logic to process multiple migration files based on timestamp stored in DB like Rails. I know it needs more error handling but currently does the work for me.

Check it out:

It's pure php and don't need any other tools. If you don't process user input with it only scripts made by developers or export tools you can use it safely.

TypeError: Image data can not convert to float

The error occurred when I unknowingly tried plotting the image path instead of the image.

My code :

import cv2 as cv
from matplotlib import pyplot as plt
import pytesseract
from resizeimage import resizeimage

img = cv.imread("D:\TemplateMatch\\fitting.png") ------>"THIS IS THE WRONG USAGE"

Correction: img = cv.imread("fitting.png") --->THIS IS THE RIGHT USAGE"

How to handle back button in activity

A simpler approach is to capture the Back button press and call moveTaskToBack(true) as follows:

public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        return true;
    return super.onKeyDown(keyCode, event);

Android 2.0 introduced a new onBackPressed method, and these recommendations on how to handle the Back button

Java properties UTF-8 encoding in Eclipse

I recommend you to use Attesoro ( Is simple and easy to use. And is made in java.

Sanitizing user input before adding it to the DOM in Javascript

Never use escape(). It's nothing to do with HTML-encoding. It's more like URL-encoding, but it's not even properly that. It's a bizarre non-standard encoding available only in JavaScript.

If you want an HTML encoder, you'll have to write it yourself as JavaScript doesn't give you one. For example:

function encodeHTML(s) {
    return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');

However whilst this is enough to put your user_id in places like the input value, it's not enough for id because IDs can only use a limited selection of characters. (And % isn't among them, so escape() or even encodeURIComponent() is no good.)

You could invent your own encoding scheme to put any characters in an ID, for example:

function encodeID(s) {
    if (s==='') return '_';
    return s.replace(/[^a-zA-Z0-9.-]/g, function(match) {
        return '_'+match[0].charCodeAt(0).toString(16)+'_';

But you've still got a problem if the same user_id occurs twice. And to be honest, the whole thing with throwing around HTML strings is usually a bad idea. Use DOM methods instead, and retain JavaScript references to each element, so you don't have to keep calling getElementById, or worrying about how arbitrary strings are inserted into IDs.


function addChut(user_id) {
    var log= document.createElement('div');
    log.className= 'log';
    var textarea= document.createElement('textarea');
    var input= document.createElement('input');
    input.value= user_id;
    input.readonly= True;
    var button= document.createElement('input');
    button.type= 'button';
    button.value= 'Message';

    var chut= document.createElement('div');
    chut.className= 'chut';

    button.onclick= function() {
        alert('Send '+textarea.value+' to '+user_id);

    return chut;

You could also use a convenience function or JS framework to cut down on the lengthiness of the create-set-appends calls there.


I'm using jQuery at the moment as a framework

OK, then consider the jQuery 1.4 creation shortcuts, eg.:

var log= $('<div>', {className: 'log'});
var input= $('<input>', {readOnly: true, val: user_id});

The problem I have right now is that I use JSONP to add elements and events to a page, and so I can not know whether the elements already exist or not before showing a message.

You can keep a lookup of user_id to element nodes (or wrapper objects) in JavaScript, to save putting that information in the DOM itself, where the characters that can go in an id are restricted.

var chut_lookup= {};

function getChut(user_id) {
    var key= '_map_'+user_id;
    if (key in chut_lookup)
        return chut_lookup[key];
    return chut_lookup[key]= addChut(user_id);

(The _map_ prefix is because JavaScript objects don't quite work as a mapping of arbitrary strings. The empty string and, in IE, some Object member names, confuse it.)

The "backspace" escape character '\b': unexpected behavior?

If you want a destructive backspace, you'll need something like

"\b \b"

i.e. a backspace, a space, and another backspace.

Use URI builder in Android or create URL with variables

Let's say that I want to create the following URL:

To build this with the Uri.Builder I would do the following.

Uri.Builder builder = new Uri.Builder();
    .appendQueryParameter("type", "1")
    .appendQueryParameter("sort", "relevance")
String myUrl =;

Is there a command line command for verifying what version of .NET is installed

You can write yourself a little console app and use System.Environment.Version to find out the version. Scott Hanselman gives a blog post about it.

Or look in the registry for the installed versions. HKLM\Software\Microsoft\NETFramework Setup\NDP

Font size of TextView in Android application changes on changing font size from native settings

Override getResources() in Activity.

Set TextView's size in sp as usual like android:textSize="32sp"

override fun getResources(): Resources {
    return super.getResources().apply {
        configuration.fontScale = 1F
        updateConfiguration(configuration, displayMetrics)

Dynamic LINQ OrderBy on IEnumerable<T> / IQueryable<T>

This answer is a response to the comments that need an example for the solution provided by @John Sheehan - Runscope

Please provide an example for the rest of us.

in DAL (Data Access Layer),

The IEnumerable version:

  public  IEnumerable<Order> GetOrders()
      // i use Dapper to return IEnumerable<T> using Query<T>
      //.. do stuff
      return  orders  // IEnumerable<Order>

The IQueryable version

  public IQueryable<Order> GetOrdersAsQuerable()
        IEnumerable<Order> qry= GetOrders();
        //use the built-in extension method  AsQueryable in  System.Linq namespace
        return qry.AsQueryable();            

Now you can use the IQueryable version to bind, for example GridView in and benefit for sorting (you can't sort using IEnumerable version)

I used Dapper as ORM and build IQueryable version and utilized sorting in GridView in so easy.

Android: View.setID(int id) programmatically - how to avoid ID conflicts?

public String TAG() {
    return this.getClass().getSimpleName();

private AtomicInteger lastFldId = null;

public int generateViewId(){

    if(lastFldId == null) {
        int maxFld = 0;
        String fldName = "";
        Field[] flds =; inst = new;

        for (int i = 0; i < flds.length; i++) {
            Field fld = flds[i];

            try {
                int value = fld.getInt(inst);

                if (value > maxFld) {
                    maxFld = value;
                    fldName = fld.getName();
            } catch (IllegalAccessException e) {
                Log.e(TAG(), "error getting value for \'"+ fld.getName() + "\' " + e.toString());
        Log.d(TAG(), "maxId="+maxFld +"  name="+fldName);
        lastFldId = new AtomicInteger(maxFld);

    return lastFldId.addAndGet(1);

Where can I find System.Web.Helpers, System.Web.WebPages, and System.Web.Razor?

You will find these assemblies in the Extensions group under Assemblies in Visual Studio 2010, 2012 & 2013 (Reference Manager)

what does "dead beef" mean?

It's a magic number used in various places because it also happens to be readable in English, making it stand out. There's a partial list on Wikipedia.

Call An Asynchronous Javascript Function Synchronously

There is one nice workaround at

It uses generators which are new to javascript. So it's currently not implemented by most browsers. I tested it in firefox, and for me it is nice way to wrap asynchronous function.

Here is example code from project GitHub

var { Deferred } = task;

spawn(function() {
    out.innerHTML = "reading...\n";
    try {
        var d = yield read("read.html");
    } catch (e) {
        e.stack.split(/\n/).forEach(function(line) { console.log(line) });
        out.innerHTML = "error: " + e;


function read(url, method) {
    method = method || "GET";
    var xhr = new XMLHttpRequest();
    var deferred = new Deferred();
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            if (xhr.status >= 400) {
                var e = new Error(xhr.statusText);
                e.status = xhr.status;
            } else {
                    responseText: xhr.responseText
    };, url, true);
    return deferred.promise;

How to set the focus for a particular field in a Bootstrap modal, once it appears

Bootstrap has added a loaded event.

capture the '' event on the modal

$('#mymodal').on('', function(e) {
  // do cool stuff here all day… no need to change bootstrap

How to set timeout on python's socket recv method?

The typical approach is to use select() to wait until data is available or until the timeout occurs. Only call recv() when data is actually available. To be safe, we also set the socket to non-blocking mode to guarantee that recv() will never block indefinitely. select() can also be used to wait on more than one socket at a time.

import select


ready =[mysocket], [], [], timeout_in_seconds)
if ready[0]:
    data = mysocket.recv(4096)

If you have a lot of open file descriptors, poll() is a more efficient alternative to select().

Another option is to set a timeout for all operations on the socket using socket.settimeout(), but I see that you've explicitly rejected that solution in another answer.

Have Excel formulas that return 0, make the result blank

If you’re willing to cause all zeroes in the worksheet to disappear, go into “Excel Options”, “Advanced” page, “Display options for this worksheet” section, and clear the “Show a zero in cells that have a zero value” checkbox.  (This is the navigation for Excel 2007; YMMV.)

Regarding your answer (2), you can save a couple of keystrokes by typing 0;-0; –– as far as I can tell, that’s equivalent to 0;-0;;@.  Conversely, if you want to be a little more general, you can use the format General;-General;.  No, that doesn’t automagically handle dates, but, as Barry points out, if you’re expecting a date value, you can use a format like d-mmm-yyyy;;.

$.browser is undefined error

The .browser call has been removed in jquery 1.9 have a look at for more details.

What does this square bracket and parenthesis bracket notation mean [first1,last1)?

A bracket - [ or ] - means that end of the range is inclusive -- it includes the element listed. A parenthesis - ( or ) - means that end is exclusive and doesn't contain the listed element. So for [first1, last1), the range starts with first1 (and includes it), but ends just before last1.

Assuming integers:

  • (0, 5) = 1, 2, 3, 4
  • (0, 5] = 1, 2, 3, 4, 5
  • [0, 5) = 0, 1, 2, 3, 4
  • [0, 5] = 0, 1, 2, 3, 4, 5

Comparison of C++ unit test frameworks

Boost Test Library is a very good choice especially if you're already using Boost.

// TODO: Include your class to test here.
#include <boost/test/unit_test.hpp>

    // To simplify this example test, let's suppose we'll test 'float'.
    // Some test are stupid, but all should pass.
    float x = 9.5f;

    BOOST_CHECK(x != 0.0f);
    BOOST_CHECK_EQUAL((int)x, 9);
    BOOST_CHECK_CLOSE(x, 9.5f, 0.0001f); // Checks differ no more then 0.0001%

It supports:

  • Automatic or manual tests registration
  • Many assertions
  • Automatic comparison of collections
  • Various output formats (including XML)
  • Fixtures / Templates...

PS: I wrote an article about it that may help you getting started: C++ Unit Testing Framework: A Boost Test Tutorial

How do I show a message in the foreach loop?

You are looking to see if a single value is in an array. Use in_array.

However note that case is important, as are any leading or trailing spaces. Use var_dump to find out the length of the strings too, and see if they fit.

Exit while loop by user hitting ENTER key

if repr(User) == repr(''):

How can I resolve the error: "The command [...] exited with code 1"?

Right click project -> Properties -> Build Events

Remove the text in Post-build event command line text block

Can I have an onclick effect in CSS?

You can use pseudo class :target to mimic on click event, let me give you an example.

#something {_x000D_
  display: none;_x000D_
#something:target {_x000D_
  display: block;_x000D_
<a href="#something">Show</a>_x000D_
<div id="something">Bingo!</div>

Here's how it looks like:

One thing to note, this is only limited to hyperlink, so if you need to use on other than hyperlink, such as a button, you might want to hack it a little bit, such as styling a hyperlink to look like a button.

Display last git commit comment

This command will get you the last commit message:

git log -1 --oneline --format=%s | sed 's/^.*: //'

outputs something similar to:

Create FUNDING.yml

You can change the -1 to any negative number to increase the range of commit messages retrieved

removing new line character from incoming stream using sed

To remove newlines, use tr:

tr -d '\n'

If you want to replace each newline with a single space:

tr '\n' ' '

The error ba: Event not found is coming from csh, and is due to csh trying to match !ba in your history list. You can escape the ! and write the command:

sed ':a;N;$\!ba;s/\n/ /g'  # Suitable for csh only!!

but sed is the wrong tool for this, and you would be better off using a shell that handles quoted strings more reasonably. That is, stop using csh and start using bash.

JavaScript - Replace all commas in a string

var mystring = "this,is,a,test"
mystring.replace(/,/g, "newchar");

Use the global(g) flag

Simple DEMO

How do I enable logging for Spring Security?

Assuming you're using Spring Boot, another option is to put the following in your

This is the same for most other Spring modules as well.

If you're not using Spring Boot, try setting the property in your logging configuration, e.g. logback.

Here is the application.yml version as well:

        security: DEBUG

PHP display current server path

You can also use the following alternative realpath.

Create a file called path.php

Put the following code inside by specifying the name of the created file.

    echo realpath('path.php'); 

A php file that you can move to all your folders to always have the absolute path from where the executed file is located.


continuous page numbering through section breaks

You can check out this post on SuperUser.

Word starts page numbering over for each new section by default.

I do it slightly differently than the post above that goes through the ribbon menus, but in both methods you have to go through the document to each section's beginning.

My method:

  • open up the footer (or header if that's where your page number is)
  • drag-select the page number
  • right-click on it
  • hit Format Page Numbers
  • click on the Continue from Previous Section radio button under Page numbering

I find this right-click method to be a little faster. Also, usually if I insert the page numbers first before I start making any new sections, this problem doesn't happen in the first place.

How do you get the current time of day?

MyEmail.Body = string.Format("The validation is done at {0:HH:mm:ss} Hrs.",DateTime.Now);

Can Use {0:HH:mm:ss}, {0:HH:mm:ss.fff}, {0:DD/mm/yyy HH:mm:ss}, etc...

How does one reorder columns in a data frame?

dplyr version 1.0.0 includes the relocate() function to easily reorder columns:

dat <- data.frame(Time=c(1,2), In=c(2,3), Out=c(3,4), Files=c(4,5))

library(dplyr) # from version 1.0.0 only

dat %>%
  relocate(Out, .before = In)


dat %>%
  relocate(Out, .after = Time)

What is ".NET Core"?

It is a sub-set of the .NET Framework, started with the Compact Framework edition. It progressed into Silverlight, Windows Store and Windows Phone. It focused on keeping the deployment small, suitable for quick downloads and devices with limited storage capabilities. And it is easier to bring up on non-Windows platforms, and surely this was the reason it was chosen as the open sourced edition. The "difficult" and "expensive" parts of the CLR and the base class libraries are omitted.

Otherwise, it is always easy to recognize when you target such a framework version, because lots of goodies will be missing. You'll be using a distinct set of reference assemblies that only expose what is supported by the runtime. It is stored on your machine in the C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETCore directory.

Update: after the .NET Core 2.0 release I've seen some representative numbers that gives a decent insight. They have been hard at work back-porting framework APIs to .NET Core over the past two years. .NET Core 1.0 originally supported 13,000 APIs. .NET Core 2.0 added 20,000 APIs, bringing the total to 32,000 and allowing about 70% of existing NuGet packages to be ported. There are a set of APIs that are too heavily wedded to Windows to be easy to port to Linux and MacOS. Covered by the recently released Windows Compatibility Pack, it adds another 20,000 APIs.

TypeError: $.browser is undefined

$.browser has been removed from JQuery 1.9. You can to use Modernizr project instead


To complete the @daniel.moura answer, here is a version which support IE 11 and +

var matched, browser;

jQuery.uaMatch = function( ua ) {
    ua = ua.toLowerCase();

    var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
        /(webkit)[ \/]([\w.]+)/.exec( ua ) ||
        /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
        /(msie)[\s?]([\w.]+)/.exec( ua ) ||       
        /(trident)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
        ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||

    return {
        browser: match[ 1 ] || "",
        version: match[ 2 ] || "0"

matched = jQuery.uaMatch( navigator.userAgent );
//IE 11+ fix (Trident) 
matched.browser = matched.browser == 'trident' ? 'msie' : matched.browser;
browser = {};

if ( matched.browser ) {
    browser[ matched.browser ] = true;
    browser.version = matched.version;

// Chrome is Webkit, but Webkit is also Safari.
if ( ) {
    browser.webkit = true;
} else if ( browser.webkit ) {
    browser.safari = true;

jQuery.browser = browser;
// log removed - adds an extra dependency

jQuery select child element by class with unknown path

$('#thisElement').find('.classToSelect') will find any descendents of #thisElement with class classToSelect.

How do I compile a Visual Studio project from the command-line?

To be honest I have to add my 2 cents.

You can do it with msbuild.exe. There are many version of the msbuild.exe.

C:\Windows\Microsoft.NET\Framework64\v2.0.50727\msbuild.exe C:\Windows\Microsoft.NET\Framework64\v3.5\msbuild.exe C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe
C:\Windows\Microsoft.NET\Framework\v2.0.50727\msbuild.exe C:\Windows\Microsoft.NET\Framework\v3.5\msbuild.exe C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe

Use version you need. Basically you have to use the last one.


So how to do it.

  1. Run the COMMAND window

  2. Input the path to msbuild.exe


  1. Input the path to the project solution like

"C:\Users\Clark.Kent\Documents\visual studio 2012\Projects\WpfApplication1\WpfApplication1.sln"

  1. Add any flags you need after the solution path.

  2. Press ENTER

Note you can get help about all possible flags like

C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe /help

Getting result of dynamic SQL into a variable for sql-server

DECLARE @sqlCommand nvarchar(1000)
DECLARE @city varchar(75)
DECLARE @cnt int
SET @city = 'London'
SET @sqlCommand = 'SELECT @cnt=COUNT(*) FROM customers WHERE City = @city'
EXECUTE sp_executesql @sqlCommand, N'@city nvarchar(75)', @city = @city

Get current language in CultureInfo

This is what i used:

var culture = System.Globalization.CultureInfo.CurrentCulture;

and it's working :)

How to Specify Eclipse Proxy Authentication Credentials?

If you have still problems, try deactivating ("Clear") SOCKS

see: "I believe the reason for this is because it uses the SOCKS proxy instead of the HTTP proxy if SOCKS is configured."

How to retrieve inserted id after inserting row in SQLite using Python?

All credits to @Martijn Pieters in the comments:

You can use the function last_insert_rowid():

The last_insert_rowid() function returns the ROWID of the last row insert from the database connection which invoked the function. The last_insert_rowid() SQL function is a wrapper around the sqlite3_last_insert_rowid() C/C++ interface function.

Creating a byte array from a stream

i was able to make it work on a single line:

byte [] byteArr= ((MemoryStream)localStream).ToArray();

as clarified by johnnyRose, Above code will only work for MemoryStream

Free Rest API to retrieve current datetime as string (timezone irrelevant)

TimezoneDb provides a free API:

GenoNames also has a RESTful API available to get the current time for a given location:

You can use Greenwich, UK if you'd like GMT.

How to calculate the width of a text string of a specific font and font-size?

Update Sept 2019

This answer is a much cleaner way to do it using new syntax.

Original Answer

Based on Glenn Howes' excellent answer, I created an extension to calculate the width of a string. If you're doing something like setting the width of a UISegmentedControl, this can set the width based on the segment's title string.

extension String {

    func widthOfString(usingFont font: UIFont) -> CGFloat {
        let fontAttributes = [NSAttributedString.Key.font: font]
        let size = self.size(withAttributes: fontAttributes)
        return size.width

    func heightOfString(usingFont font: UIFont) -> CGFloat {
        let fontAttributes = [NSAttributedString.Key.font: font]
        let size = self.size(withAttributes: fontAttributes)
        return size.height

    func sizeOfString(usingFont font: UIFont) -> CGSize {
        let fontAttributes = [NSAttributedString.Key.font: font]
        return self.size(withAttributes: fontAttributes)


    // Set width of segmentedControl
    let starString = "??"
    let starWidth = starString.widthOfString(usingFont: UIFont.systemFont(ofSize: 14)) + 16
    segmentedController.setWidth(starWidth, forSegmentAt: 3)

How can I detect browser type using jQuery?

You can get Browser type here:

    var browser_type = Object.keys($.browser)[0];

Eclipse Problems View not showing Errors anymore

I experienced that problem with a MapReduce project. I closed the error window and never came back after doing what the other answers suggested.

Click on the bottom left -> Other -> Problems

enter image description here

Remove all occurrences of char from string

Try using the overload that takes CharSequence arguments (eg, String) rather than char:

str = str.replace("X", "");

How to change default JRE for all Eclipse workspaces?

My answer will overlap with amphibient's while adding on to it.

Your JAVA_HOME variable is fine, but you also need to append the following to your Path variable :


This will allow your applications in your Windows environment to access your JDK. You should also restart your computer once you've added these environment variables before checking out if they work. In my case, even logging out and then back in didn't work : I had to completely restart.

If you want to check if the environment variables are set correctly, you can open up a command prompt and type >echo %JAVA_HOME and >echo %Path% to see if those variables are working correctly. While snooping around for solutions, I have also run into people claiming that they need to add quotations marks (") around the environment variables to make them work correctly ("%JAVA_HOME%"\bin) if your JAVA_HOME path includes spaces. I thought that this was my case at first, but after doing a full restart my variables seemed to work correctly without quotation marks despite the spaces.