Programs & Examples On #Scope id

Remove rows with all or some NAs (missing values) in data.frame

Assuming dat as your dataframe, the expected output can be achieved using

1.rowSums

> dat[!rowSums((is.na(dat))),]
             gene hsap mmul mmus rnor cfam
2 ENSG00000199674    0   2    2    2    2
6 ENSG00000221312    0   1    2    3    2

2.lapply

> dat[!Reduce('|',lapply(dat,is.na)),]
             gene hsap mmul mmus rnor cfam
2 ENSG00000199674    0   2    2    2    2
6 ENSG00000221312    0   1    2    3    2

How to use a decimal range() step value?

Python's range() can only do integers, not floating point. In your specific case, you can use a list comprehension instead:

[x * 0.1 for x in range(0, 10)]

(Replace the call to range with that expression.)

For the more general case, you may want to write a custom function or generator.

Converting Decimal to Binary Java

public static void main(String h[])
{
    Scanner sc=new Scanner(System.in);
    int decimal=sc.nextInt();

    String binary="";

    if(decimal<=0)
    {
        System.out.println("Please Enter more than 0");

    }
    else
    {
        while(decimal>0)
        {

            binary=(decimal%2)+binary;
            decimal=decimal/2;

        }
        System.out.println("binary is:"+binary);

    }

}

Authenticated HTTP proxy with Java

For Java 1.8 and higher you must set

-Djdk.http.auth.tunneling.disabledSchemes=

to make proxies with Basic Authorization working with https along with Authenticator as mentioned in accepted answer

Select first 4 rows of a data.frame in R

In case someone is interested in dplyr solution, it's very intuitive:

dt <- dt %>%
  slice(1:4)

Simple http post example in Objective-C?

Thanks a lot it worked , please note I did a typo in php as it should be mysqli_query( $con2, $sql )

HTML favicon won't show on google chrome

A common issue where the favicon will not show up when expected is cache, if your .htaccess for example reads: ExpiresByType image/x-icon "access plus 1 month"

Then simply add a random value to your favicon reference: <link rel="shortcut icon" href="https://example.com/favicon.ico?r=31241" type="image/x-icon" />

Works every time for me even with heavy caching.

How can I get the content of CKEditor using JQuery?

First of all you should include ckeditor and jquery connector script in your page,

then create a textarea

<textarea name="content" class="editor" id="ms_editor"></textarea>

attach ckeditor to the text area, in my project I use something like this:

$('textarea.editor').ckeditor(function() {
        }, { toolbar : [
            ['Cut','Copy','Paste','PasteText','PasteFromWord','-','Print', 'SpellChecker', 'Scayt'],
            ['Undo','Redo'],
            ['Bold','Italic','Underline','Strike','-','Subscript','Superscript'],
            ['NumberedList','BulletedList','-','Outdent','Indent','Blockquote'],
            ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
            ['Link','Unlink','Anchor', 'Image', 'Smiley'],
            ['Table','HorizontalRule','SpecialChar'],
            ['Styles','BGColor']
        ], toolbarCanCollapse:false, height: '300px', scayt_sLang: 'pt_PT', uiColor : '#EBEBEB' } );

on submit get the content using:

var content = $( 'textarea.editor' ).val();

That's it! :)

How to set up gradle and android studio to do release build?

  1. open the Build Variants pane, typically found along the lower left side of the window:

Build Variants

  1. set debug to release
  2. shift+f10 run!!

then, Android Studio will execute assembleRelease task and install xx-release.apk to your device.

HTML5: Slider with two inputs possible?

Sure you can simply use two sliders overlaying each other and add a bit of javascript (actually not more than 5 lines) that the selectors are not exceeding the min/max values (like in @Garys) solution.

Attached you'll find a short snippet adapted from a current project including some CSS3 styling to show what you can do (webkit only). I also added some labels to display the selected values.

It uses JQuery but a vanillajs version is no magic though.

@Update: The code below was just a proof of concept. Due to many requests I've added a possible solution for Mozilla Firefox (without changing the original code). You may want to refractor the code below before using it.

_x000D_
_x000D_
    (function() {

        function addSeparator(nStr) {
            nStr += '';
            var x = nStr.split('.');
            var x1 = x[0];
            var x2 = x.length > 1 ? '.' + x[1] : '';
            var rgx = /(\d+)(\d{3})/;
            while (rgx.test(x1)) {
                x1 = x1.replace(rgx, '$1' + '.' + '$2');
            }
            return x1 + x2;
        }

        function rangeInputChangeEventHandler(e){
            var rangeGroup = $(this).attr('name'),
                minBtn = $(this).parent().children('.min'),
                maxBtn = $(this).parent().children('.max'),
                range_min = $(this).parent().children('.range_min'),
                range_max = $(this).parent().children('.range_max'),
                minVal = parseInt($(minBtn).val()),
                maxVal = parseInt($(maxBtn).val()),
                origin = $(this).context.className;

            if(origin === 'min' && minVal > maxVal-5){
                $(minBtn).val(maxVal-5);
            }
            var minVal = parseInt($(minBtn).val());
            $(range_min).html(addSeparator(minVal*1000) + ' €');


            if(origin === 'max' && maxVal-5 < minVal){
                $(maxBtn).val(5+ minVal);
            }
            var maxVal = parseInt($(maxBtn).val());
            $(range_max).html(addSeparator(maxVal*1000) + ' €');
        }

     $('input[type="range"]').on( 'input', rangeInputChangeEventHandler);
})();
_x000D_
body{
font-family: sans-serif;
font-size:14px;
}
input[type='range'] {
  width: 210px;
  height: 30px;
  overflow: hidden;
  cursor: pointer;
    outline: none;
}
input[type='range'],
input[type='range']::-webkit-slider-runnable-track,
input[type='range']::-webkit-slider-thumb {
  -webkit-appearance: none;
    background: none;
}
input[type='range']::-webkit-slider-runnable-track {
  width: 200px;
  height: 1px;
  background: #003D7C;
}

input[type='range']:nth-child(2)::-webkit-slider-runnable-track{
  background: none;
}

input[type='range']::-webkit-slider-thumb {
  position: relative;
  height: 15px;
  width: 15px;
  margin-top: -7px;
  background: #fff;
  border: 1px solid #003D7C;
  border-radius: 25px;
  z-index: 1;
}


input[type='range']:nth-child(1)::-webkit-slider-thumb{
  z-index: 2;
}

.rangeslider{
    position: relative;
    height: 60px;
    width: 210px;
    display: inline-block;
    margin-top: -5px;
    margin-left: 20px;
}
.rangeslider input{
    position: absolute;
}
.rangeslider{
    position: absolute;
}

.rangeslider span{
    position: absolute;
    margin-top: 30px;
    left: 0;
}

.rangeslider .right{
   position: relative;
   float: right;
   margin-right: -5px;
}


/* Proof of concept for Firefox */
@-moz-document url-prefix() {
  .rangeslider::before{
    content:'';
    width:100%;
    height:2px;
    background: #003D7C;
    display:block;
    position: relative;
    top:16px;
  }

  input[type='range']:nth-child(1){
    position:absolute;
    top:35px !important;
    overflow:visible !important;
    height:0;
  }

  input[type='range']:nth-child(2){
    position:absolute;
    top:35px !important;
    overflow:visible !important;
    height:0;
  }
input[type='range']::-moz-range-thumb {
  position: relative;
  height: 15px;
  width: 15px;
  margin-top: -7px;
  background: #fff;
  border: 1px solid #003D7C;
  border-radius: 25px;
  z-index: 1;
}

  input[type='range']:nth-child(1)::-moz-range-thumb {
      transform: translateY(-20px);    
  }
  input[type='range']:nth-child(2)::-moz-range-thumb {
      transform: translateY(-20px);    
  }
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="rangeslider">
                                <input class="min" name="range_1" type="range" min="1" max="100" value="10" />
                                <input class="max" name="range_1" type="range" min="1" max="100" value="90" />
                                <span class="range_min light left">10.000 €</span>
                                <span class="range_max light right">90.000 €</span>
                            </div>
_x000D_
_x000D_
_x000D_

Implement touch using Python?

Here's some code that uses ctypes (only tested on Linux):

from ctypes import *
libc = CDLL("libc.so.6")

#  struct timespec {
#             time_t tv_sec;        /* seconds */
#             long   tv_nsec;       /* nanoseconds */
#         };
# int futimens(int fd, const struct timespec times[2]);

class c_timespec(Structure):
    _fields_ = [('tv_sec', c_long), ('tv_nsec', c_long)]

class c_utimbuf(Structure):
    _fields_ = [('atime', c_timespec), ('mtime', c_timespec)]

utimens = CFUNCTYPE(c_int, c_char_p, POINTER(c_utimbuf))
futimens = CFUNCTYPE(c_int, c_char_p, POINTER(c_utimbuf)) 

# from /usr/include/i386-linux-gnu/bits/stat.h
UTIME_NOW  = ((1l << 30) - 1l)
UTIME_OMIT = ((1l << 30) - 2l)
now  = c_timespec(0,UTIME_NOW)
omit = c_timespec(0,UTIME_OMIT)

# wrappers
def update_atime(fileno):
        assert(isinstance(fileno, int))
        libc.futimens(fileno, byref(c_utimbuf(now, omit)))
def update_mtime(fileno):
        assert(isinstance(fileno, int))
        libc.futimens(fileno, byref(c_utimbuf(omit, now)))

# usage example:
#
# f = open("/tmp/test")
# update_mtime(f.fileno())

Specified argument was out of the range of valid values. Parameter name: site

Instead of installing the bloated IIS, I get mine resolved by installing Internet Information Services Hostable Web Core from the Windows Features

How should the ViewModel close the form?

public partial class MyWindow: Window
{
    public ApplicationSelection()
    {
      InitializeComponent();

      MyViewModel viewModel = new MyViewModel();

      DataContext = viewModel;

      viewModel.RequestClose += () => { Close(); };

    }
}

public class MyViewModel
{

  //...Your code...

  public event Action RequestClose;

  public virtual void Close()
  {
    if (RequestClose != null)
    {
      RequestClose();
    }
  }

  public void SomeFunction()
  {
     //...Do something...
     Close();
  }
}

How to list npm user-installed packages?

Node_modules contains user-installed packages so change the directory to node_modules and list the items. Core Modules are defined in node's source in the lib/ folder.

Example:

     example@example:~/:~/node_modules$ ls
     express  maxmind-native  node-whois  socket.io  ua-parser-js
     geoip    mongoskin       pdfkit      tail       zeromq
     maxmind  nodemailer      request     ua-parser  zmq

How to require a controller in an angularjs directive

There is a good stackoverflow answer here by Mark Rajcok:

AngularJS directive controllers requiring parent directive controllers?

with a link to this very clear jsFiddle: http://jsfiddle.net/mrajcok/StXFK/

<div ng-controller="MyCtrl">
    <div screen>
        <div component>
            <div widget>
                <button ng-click="widgetIt()">Woo Hoo</button>
            </div>
        </div>
    </div>
</div>

JavaScript

var myApp = angular.module('myApp',[])

.directive('screen', function() {
    return {
        scope: true,
        controller: function() {
            this.doSomethingScreeny = function() {
                alert("screeny!");
            }
        }
    }
})

.directive('component', function() {
    return {
        scope: true,
        require: '^screen',
        controller: function($scope) {
            this.componentFunction = function() {
                $scope.screenCtrl.doSomethingScreeny();
            }
        },
        link: function(scope, element, attrs, screenCtrl) {
            scope.screenCtrl = screenCtrl
        }
    }
})

.directive('widget', function() {
    return {
        scope: true,
        require: "^component",
        link: function(scope, element, attrs, componentCtrl) {
            scope.widgetIt = function() {
                componentCtrl.componentFunction();
            };
        }
    }
})


//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});

function MyCtrl($scope) {
    $scope.name = 'Superhero';
}

What is the "proper" way to cast Hibernate Query.list() to List<Type>?

Just just using Transformers It did not work for me I was getting type cast exception.

sqlQuery.setResultTransformer(Transformers.aliasToBean(MYEngityName.class)) did notwork because I was getting Array of Object in the return list element not the fixed MYEngityName type of list element.

It worked for me when I make following changes When I have added sqlQuery.addScalar(-) each selected column and its type and for specific String type column we dont have to map its type. like addScalar("langCode");

And I have join MYEngityName with NextEnity we cant just select * in the Query it will give array of Object in the return list.

Below code sample :

session = ht.getSessionFactory().openSession();
                String sql = new StringBuffer("Select txnId,nft.mId,count,retryReason,langCode FROM  MYEngityName nft INNER JOIN NextEntity m on nft.mId  =  m.id where nft.txnId < ").append(lastTxnId)
                       .append(StringUtils.isNotBlank(regionalCountryOfService)? " And  m.countryOfService in ( "+ regionalCountryOfService +" )" :"")
                       .append(" order by nft.txnId desc").toString();
                SQLQuery sqlQuery = session.createSQLQuery(sql);
                sqlQuery.setResultTransformer(Transformers.aliasToBean(MYEngityName.class));
                sqlQuery.addScalar("txnId",Hibernate.LONG)
                        .addScalar("merchantId",Hibernate.INTEGER)
                        .addScalar("count",Hibernate.BYTE)
                        .addScalar("retryReason")
                        .addScalar("langCode");
                sqlQuery.setMaxResults(maxLimit);
                return sqlQuery.list();

It might help some one. in this way work for me.

Package Manager Console Enable-Migrations CommandNotFoundException only in a specific VS project

downgrade to 6.2 helped me.
.NET Framework version 4.6.1
Project in old format(non .NET Standard)
Visual Studio should be open with Admin rights for initial migration.
I guess EF with version above 6.2 require latest .NET Framework.

If statement in select (ORACLE)

In one line, answer is as below;

[ CASE WHEN COLUMN_NAME = 'VALUE' THEN 'SHOW_THIS' ELSE 'SHOW_OTHER' END as ALIAS ]

How to call a .NET Webservice from Android using KSOAP2?

It's very simple. You are getting the result into an Object which is a primitive one.

Your code:

Object result = (Object)envelope.getResponse();

Correct code:

SoapObject result=(SoapObject)envelope.getResponse();

//To get the data.
String resultData=result.getProperty(0).toString();
// 0 is the first object of data.

I think this should definitely work.

sort csv by column

import operator
sortedlist = sorted(reader, key=operator.itemgetter(3), reverse=True)

or use lambda

sortedlist = sorted(reader, key=lambda row: row[3], reverse=True)

VBA Runtime Error 1004 "Application-defined or Object-defined error" when Selecting Range

Some operations in Excel are limited by available Memory. If you repeat the same process over and over it could produce a memory overflow and excel will not be able to repeat it anymore. This happened to me while trying to create several sheets in the same workbook.

Eclipse won't compile/run java file

  • Make a project to put the files in.
    • File -> New -> Java Project
    • Make note of where that project was created (where your "workspace" is)
  • Move your java files into the src folder which is immediately inside the project's folder.
    • Find the project INSIDE Eclipse's Package Explorer (Window -> Show View -> Package Explorer)
    • Double-click on the project, then double-click on the 'src' folder, and finally double-click on one of the java files inside the 'src' folder (they should look familiar!)
  • Now you can run the files as expected.

Note the hollow 'J' in the image. That indicates that the file is not part of a project.

Hollow J means it is not part of a project

HTTP Basic Authentication credentials passed in URL and encryption

Not necessarily true. It will be encrypted on the wire however it still lands in the logs plain text

Django REST Framework: adding additional field to ModelSerializer

With the last version of Django Rest Framework, you need to create a method in your model with the name of the field you want to add. No need for @property and source='field' raise an error.

class Foo(models.Model):
    . . .
    def foo(self):
        return 'stuff'
    . . .

class FooSerializer(ModelSerializer):
    foo = serializers.ReadOnlyField()

    class Meta:
        model = Foo
        fields = ('foo',)

Image library for Python 3

As of March 30, 2012, I have tried and failed to get the sloonz fork on GitHub to open images. I got it to compile ok, but it didn't actually work. I also tried building gohlke's library, and it compiled also but failed to open any images. Someone mentioned PythonMagick above, but it only compiles on Windows. See PythonMagick on the wxPython wiki.

PIL was last updated in 2009, and while it's website says they are working on a Python 3 port, it's been 3 years, and the mailing list has gone cold.

To solve my Python 3 image manipulation problem, I am using subprocess.call() to execute ImageMagick shell commands. This method works.

See the subprocess module documentation.

Executing set of SQL queries using batch file?

Different ways:

  1. Using SQL Server Agent (If local instance)
    schedule a job in sql server agent with a new step having type as "T-SQL" then run the job.

  2. Using SQLCMD
    To use SQLCMD refer http://technet.microsoft.com/en-us/library/ms162773.aspx

  3. Using SQLPS
    To use SQLPS refer http://technet.microsoft.com/en-us/library/cc280450.aspx

Windows service with timer

Here's a working example in which the execution of the service is started in the OnTimedEvent of the Timer which is implemented as delegate in the ServiceBase class and the Timer logic is encapsulated in a method called SetupProcessingTimer():

public partial class MyServiceProject: ServiceBase
{

private Timer _timer;

public MyServiceProject()
{
    InitializeComponent();
}

private void SetupProcessingTimer()
{
    _timer = new Timer();
    _timer.AutoReset = true;
    double interval = Settings.Default.Interval;
    _timer.Interval = interval * 60000;
    _timer.Enabled = true;
    _timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
}

private void OnTimedEvent(object source, ElapsedEventArgs e)
{
    // begin your service work
    MakeSomething();
}

protected override void OnStart(string[] args)
{
    SetupProcessingTimer();
}

...
}

The Interval is defined in app.config in minutes:

<userSettings>
    <MyProject.Properties.Settings>
        <setting name="Interval" serializeAs="String">
            <value>1</value>
        </setting>
    </MyProject.Properties.Settings>
</userSettings>

How to terminate a Python script

I've just found out that when writing a multithreadded app, raise SystemExit and sys.exit() both kills only the running thread. On the other hand, os._exit() exits the whole process. This was discussed in "Why does sys.exit() not exit when called inside a thread in Python?".

The example below has 2 threads. Kenny and Cartman. Cartman is supposed to live forever, but Kenny is called recursively and should die after 3 seconds. (recursive calling is not the best way, but I had other reasons)

If we also want Cartman to die when Kenny dies, Kenny should go away with os._exit, otherwise, only Kenny will die and Cartman will live forever.

import threading
import time
import sys
import os

def kenny(num=0):
    if num > 3:
        # print("Kenny dies now...")
        # raise SystemExit #Kenny will die, but Cartman will live forever
        # sys.exit(1) #Same as above

        print("Kenny dies and also kills Cartman!")
        os._exit(1)
    while True:
        print("Kenny lives: {0}".format(num))
        time.sleep(1)
        num += 1
        kenny(num)

def cartman():
    i = 0
    while True:
        print("Cartman lives: {0}".format(i))
        i += 1
        time.sleep(1)

if __name__ == '__main__':
    daemon_kenny = threading.Thread(name='kenny', target=kenny)
    daemon_cartman = threading.Thread(name='cartman', target=cartman)
    daemon_kenny.setDaemon(True)
    daemon_cartman.setDaemon(True)

    daemon_kenny.start()
    daemon_cartman.start()
    daemon_kenny.join()
    daemon_cartman.join()

How do I programmatically force an onchange event on an input?

If you add all your events with this snippet of code:

//put this somewhere in your JavaScript:
HTMLElement.prototype.addEvent = function(event, callback){
  if(!this.events)this.events = {};
  if(!this.events[event]){
    this.events[event] = [];
    var element = this;
    this['on'+event] = function(e){
      var events = element.events[event];
      for(var i=0;i<events.length;i++){
        events[i](e||event);
      }
    }
  }
  this.events[event].push(callback);
}
//use like this:
element.addEvent('change', function(e){...});

then you can just use element.on<EVENTNAME>() where <EVENTNAME> is the name of your event, and that will call all events with <EVENTNAME>

npm ERR! code UNABLE_TO_GET_ISSUER_CERT_LOCALLY

A quick solution from the internet search was npm config set strict-ssl false, luckily it worked. But as a part of my work environment, I am restricted to set the strict-ssl flag to false.

Later I found a safe and working solution,

npm config set registry http://registry.npmjs.org/  

this worked perfectly and I got a success message Happy Hacking! by not setting the strict-ssl flag to false.

Cannot connect to MySQL Workbench on mac. Can't connect to MySQL server on '127.0.0.1' (61) Mac Macintosh

brew services start mysql defualt set --bind-address=127.0.0.1 with /usr/local/Cellar/mysql/5.6.27/homebrew.mxcl.mysql.plist,so replace --bind-address=127.0.0.1 with --bind-address=* or --bind-address=0.0.0.0

search in java ArrayList

I did something close to that, the compiler is seeing that your return statement is in an If() statement. If you wish to resolve this error, simply create a new local variable called customerId before the If statement, then assign a value inside of the if statement. After the if statement, call your return statement, and return cstomerId. Like this:

Customer findCustomerByid(int id)
{
    boolean exist=false;

    if(this.customers.isEmpty()) {
        return null;
    }

    for(int i=0;i<this.customers.size();i++) {
        if(this.customers.get(i).getId() == id) {
            exist=true;
            break;
        }

        int customerId;

        if(exist) {
            customerId = this.customers.get(id);
        } else {
            customerId = this.customers.get(id);
        }
    }
    return customerId;
}

How to properly apply a lambda function into a pandas data frame column

You need to add else in your lambda function. Because you are telling what to do in case your condition(here x < 90) is met, but you are not telling what to do in case the condition is not met.

sample['PR'] = sample['PR'].apply(lambda x: 'NaN' if x < 90 else x) 

Random alpha-numeric string in JavaScript?

for 32 characters:

for(var c = ''; c.length < 32;) c += Math.random().toString(36).substr(2, 1)

Multiple Python versions on the same machine?

I think it is totally independent. Just install them, then you have the commands e.g. /usr/bin/python2.5 and /usr/bin/python2.6. Link /usr/bin/python to the one you want to use as default.

All the libraries are in separate folders (named after the version) anyway.

If you want to compile the versions manually, this is from the readme file of the Python source code:

Installing multiple versions

On Unix and Mac systems if you intend to install multiple versions of Python using the same installation prefix (--prefix argument to the configure script) you must take care that your primary python executable is not overwritten by the installation of a different version. All files and directories installed using "make altinstall" contain the major and minor version and can thus live side-by-side. "make install" also creates ${prefix}/bin/python3 which refers to ${prefix}/bin/pythonX.Y. If you intend to install multiple versions using the same prefix you must decide which version (if any) is your "primary" version. Install that version using "make install". Install all other versions using "make altinstall".

For example, if you want to install Python 2.5, 2.6 and 3.0 with 2.6 being the primary version, you would execute "make install" in your 2.6 build directory and "make altinstall" in the others.

Required attribute HTML5

A small note on custom attributes: HTML5 allows all kind of custom attributes, as long as they are prefixed with the particle data-, i.e. data-my-attribute="true".

I am getting an "Invalid Host header" message when connecting to webpack-dev-server remotely

If you have not ejected from CRA yet, you can't easily modify your webpack config. The config file is hidden in node_modules/react_scripts/config/webpackDevServer.config.js. You are discouraged to change that config.

Instead, you can just set the environment variable DANGEROUSLY_DISABLE_HOST_CHECK to true to disable the host check:

DANGEROUSLY_DISABLE_HOST_CHECK=true yarn start  
# or the equivalent npm command

How do I format date in jQuery datetimepicker?

This works for me. Since it "extends" datepicker we can still use dateFormat:'dd/mm/yy'.

$(function() {
    $('.jqueryui-marker-datepicker').datetimepicker({
        showSecond: true,
        dateFormat: 'dd/mm/yy',
      timeFormat: 'hh:mm:ss',
      stepHour: 2,
      stepMinute: 10,
      stepSecond: 10

     });
});

How to validate domain credentials?

using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices.AccountManagement;

class WindowsCred
{
    private const string SPLIT_1 = "\\";

    public static bool ValidateW(string UserName, string Password)
    {
        bool valid = false;
        string Domain = "";

        if (UserName.IndexOf("\\") != -1)
        {
            string[] arrT = UserName.Split(SPLIT_1[0]);
            Domain = arrT[0];
            UserName = arrT[1];
        }

        if (Domain.Length == 0)
        {
            Domain = System.Environment.MachineName;
        }

        using (PrincipalContext context = new PrincipalContext(ContextType.Domain, Domain)) 
        {
            valid = context.ValidateCredentials(UserName, Password);
        }

        return valid;
    }
}

Kashif Mushtaq Ottawa, Canada

Getting "unixtime" in Java

Java 8 added a new API for working with dates and times. With Java 8 you can use

import java.time.Instant
...
long unixTimestamp = Instant.now().getEpochSecond();

Instant.now() returns an Instant that represents the current system time. With getEpochSecond() you get the epoch seconds (unix time) from the Instant.

"The operation is not valid for the state of the transaction" error and transaction scope

After doing some research, it seems I cannot have two connections opened to the same database with the TransactionScope block. I needed to modify my code to look like this:

public void MyAddUpdateMethod()
{
    using (TransactionScope Scope = new TransactionScope(TransactionScopeOption.RequiresNew))
    {
        using(SQLServer Sql = new SQLServer(this.m_connstring))
        {
            //do my first add update statement            
        }

        //removed the method call from the first sql server using statement
        bool DoesRecordExist = this.SelectStatementCall(id)
    }
}

public bool SelectStatementCall(System.Guid id)
{
    using(SQLServer Sql = new SQLServer(this.m_connstring))
    {
        //create parameters
    }
}

How to convert WebResponse.GetResponseStream return into a string?

You can create a StreamReader around the stream, then call StreamReader.ReadToEnd().

StreamReader responseReader = new StreamReader(request.GetResponse().GetResponseStream());
var responseData = responseReader.ReadToEnd();

How can I change Mac OS's default Java VM returned from /usr/libexec/java_home

Oracle's uninstallation instructions for Java 7 worked for me.

Excerpt:

Uninstalling the JDK To uninstall the JDK, you must have Administrator privileges and execute the remove command either as root or by using the sudo(8) tool.

Navigate to /Library/Java/JavaVirtualMachines and remove the directory whose name matches the following format:*

/Library/Java/JavaVirtualMachines/jdk<major>.<minor>.<macro[_update]>.jdk

For example, to uninstall 7u6:

% rm -rf jdk1.7.0_06.jdk

What is a vertical tab?

It was used during the typewriter era to move down a page to the next vertical stop, typically spaced 6 lines apart (much the same way horizontal tabs move along a line by 8 characters).

In modern day settings, the vt is of very little, if any, significance.

Convert .pem to .crt and .key

To extract the key and cert from a pem file:

Extract key

openssl pkey -in foo.pem -out foo.key

Another method of extracting the key...

openssl rsa -in foo.pem -out foo.key

Extract all the certs, including the CA Chain

openssl crl2pkcs7 -nocrl -certfile foo.pem | openssl pkcs7 -print_certs -out foo.cert

Extract the textually first cert as DER

openssl x509 -in foo.pem -outform DER -out first-cert.der

How to update column with null value

Another possible reason for the empty string, rather than a true null is that the field is an index or is part of an index. This happened to me: using phpMyAdmin, I edited the structure of a field in one of my tables to allow NULLs by checking the "Null" checkbox then hitting the "Save" button. "Table pricing has been altered successfully" was displayed so I assumed that the change happened -- it didn't. After doing an UPDATE to set all of those fields to NULL, they were, instead, set to empty strings, so I took a look at the table structure again and saw that the "Null" column for that field was set to 'no'. That's when I realized that the field was part of the Primary key!

How to change the text of a button in jQuery?

_x000D_
_x000D_
$(document).ready(function(){_x000D_
    $(":button").click(function(){_x000D_
        $("p").toggle();_x000D_
_x000D_
    if (this.value=="Add") this.value = "Save";_x000D_
    else this.value = "Add";_x000D_
_x000D_
  });_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<input type='button' value='Add' id='btnAddProfile'>_x000D_
_x000D_
<p>This is a paragraph with little content.</p>_x000D_
<p>This is another small paragraph.</p>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Why do I get a C malloc assertion failure?

My alternative solution to using Valgrind:

I'm very happy because I just helped my friend debug a program. His program had this exact problem (malloc() causing abort), with the same error message from GDB.

I compiled his program using Address Sanitizer with

gcc -Wall -g3 -fsanitize=address -o new new.c
              ^^^^^^^^^^^^^^^^^^

And then ran gdb new. When the program gets terminated by SIGABRT caused in a subsequent malloc(), a whole lot of useful information is printed:

=================================================================
==407==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x6060000000b4 at pc 0x7ffffe49ed1a bp 0x7ffffffedc20 sp 0x7ffffffed3c8
WRITE of size 104 at 0x6060000000b4 thread T0
    #0 0x7ffffe49ed19  (/usr/lib/x86_64-linux-gnu/libasan.so.4+0x5ed19)
    #1 0x8001dab in CreatHT2 /home/wsl/Desktop/hash/new.c:59
    #2 0x80031cf in main /home/wsl/Desktop/hash/new.c:209
    #3 0x7ffffe061b96 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x21b96)
    #4 0x8001679 in _start (/mnt/d/Desktop/hash/new+0x1679)

0x6060000000b4 is located 0 bytes to the right of 52-byte region [0x606000000080,0x6060000000b4)
allocated by thread T0 here:
    #0 0x7ffffe51eb50 in __interceptor_malloc (/usr/lib/x86_64-linux-gnu/libasan.so.4+0xdeb50)
    #1 0x8001d56 in CreatHT2 /home/wsl/Desktop/hash/new.c:55
    #2 0x80031cf in main /home/wsl/Desktop/hash/new.c:209
    #3 0x7ffffe061b96 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x21b96)

Let's take a look at the output, especially the stack trace:

The first part says there's a invalid write operation at new.c:59. That line reads

memset(len,0,sizeof(int*)*p);
             ^^^^^^^^^^^^

The second part says the memory that the bad write happened on is created at new.c:55. That line reads

if(!(len=(int*)malloc(sizeof(int)*p))){
                      ^^^^^^^^^^^

That's it. It only took me less than half a minute to locate the bug that confused my friend for a few hours. He managed to locate the failure, but it's a subsequent malloc() call that failed, without being able to spot this error in previous code.

Sum up: Try the -fsanitize=address of GCC or Clang. It can be very helpful when debugging memory issues.

Authenticate Jenkins CI for Github private repository

If you need Jenkins to access more then 1 project you will need to:
1. add public key to one github user account
2. add this user as Owner (to access all projects) or as a Collaborator in every project.

Many public keys for one system user will not work because GitHub will find first matched deploy key and will send back error like "ERROR: Permission to user/repo2 denied to user/repo1"

http://help.github.com/ssh-issues/

How do I create 7-Zip archives with .NET?

Install the NuGet package called SevenZipSharp.Interop

Then:

SevenZipBase.SetLibraryPath(@".\x86\7z.dll");
var compressor = new SevenZip.SevenZipCompressor();
var filesToCompress = Directory.GetFiles(@"D:\data\");
compressor.CompressFiles(@"C:\archive\abc.7z", filesToCompress);

Callback function for JSONP with jQuery AJAX

This is what I do on mine

$(document).ready(function() {
  if ($('#userForm').valid()) {
    var formData = $("#userForm").serializeArray();
    $.ajax({
      url: 'http://www.example.com/user/' + $('#Id').val() + '?callback=?',
      type: "GET",
      data: formData,
      dataType: "jsonp",
      jsonpCallback: "localJsonpCallback"
    });
  });

function localJsonpCallback(json) {
  if (!json.Error) {
    $('#resultForm').submit();
  } else {
    $('#loading').hide();
    $('#userForm').show();
    alert(json.Message);
  }
}

Access to the path is denied

I encountered this problem while developing on my local workstation.

After several unsuccessful iisreset invocations, I remedied this situation by rebooting my machine.

In retrospect, an open file handle may have been causing issues.

How to delete duplicates on a MySQL table?

Another easy way... using UPDATE IGNORE:

U have to use an index on one or more columns (type index). Create a new temporary reference column (not part of the index). In this column, you mark the uniques in by updating it with ignore clause. Step by step:

Add a temporary reference column to mark the uniques:

ALTER TABLE `yourtable` ADD `unique` VARCHAR(3) NOT NULL AFTER `lastcolname`;

=> this will add a column to your table.

Update the table, try to mark everything as unique, but ignore possible errors due to to duplicate key issue (records will be skipped):

UPDATE IGNORE `yourtable` SET `unique` = 'Yes' WHERE 1;

=> you will find your duplicate records will not be marked as unique = 'Yes', in other words only one of each set of duplicate records will be marked as unique.

Delete everything that's not unique:

DELETE * FROM `yourtable` WHERE `unique` <> 'Yes';

=> This will remove all duplicate records.

Drop the column...

ALTER TABLE `yourtable` DROP `unique`;

How to create/make rounded corner buttons in WPF?

despite the fact years have gone, i thing it's interesting to think about different way to approach it.

The way to recreate all the button template is an excellent way if you want to change everything but it's demoralizing for the beginner or if you just want to round corner of the button. It's true you don't have to change everything but at least you will must change events...

The way to modify "border" design in the button.resources is excellent too, if you are a beginner but it can be very boring to change all your buttons if you want to raise your design with more parameters.

There is a solution with a foot in both camps:

Put this code in window/page resources:

<Style TargetType="Border" x:Key="RoundMe">
    <Setter Property="CornerRadius" Value="4"/>
</Style>

Then for the buttons:

  <Button.Resources>
        <Style TargetType="Border" BasedOn="{StaticResource RoundMe}"/>
    </Button.Resources>

HTML5 Canvas background image

Theres a few ways you can do this. You can either add a background to the canvas you are currently working on, which if the canvas isn't going to be redrawn every loop is fine. Otherwise you can make a second canvas underneath your main canvas and draw the background to it. The final way is to just use a standard <img> element placed under the canvas. To draw a background onto the canvas element you can do something like the following:

Live Demo

var canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d");

canvas.width = 903;
canvas.height = 657;


var background = new Image();
background.src = "http://www.samskirrow.com/background.png";

// Make sure the image is loaded first otherwise nothing will draw.
background.onload = function(){
    ctx.drawImage(background,0,0);   
}

// Draw whatever else over top of it on the canvas.

How to reformat JSON in Notepad++?

You can use http://www.jsonlint.com/ to edit your json online if you don't have Notepad++.

List of All Folders and Sub-folders

You can use find

find . -type d > output.txt

or tree

tree -d > output.txt

tree, If not installed on your system.

If you are using ubuntu

sudo apt-get install tree

If you are using mac os.

brew install tree

If you can decode JWT, how are they secure?

You can go to jwt.io, paste your token and read the contents. This is jarring for a lot of people initially.

The short answer is that JWT doesn't concern itself with encryption. It cares about validation. That is to say, it can always get the answer for "Have the contents of this token been manipulated"? This means user manipulation of the JWT token is futile because the server will know and disregard the token. The server adds a signature based on the payload when issuing a token to the client. Later on it verifies the payload and matching signature.

The logical question is what is the motivation for not concerning itself with encrypted contents?

  1. The simplest reason is because it assumes this is a solved problem for the most part. If dealing with a client like the web browser for example, you can store the JWT tokens in a cookie that is secure (is not transmitted via HTTP, only via HTTPS) and httpOnly (can't be read by Javascript) and talks to the server over an encrypted channel (HTTPS). Once you know you have a secure channel between the server and client you can securely exchange JWT or whatever else you want.

  2. This keeps thing simple. A simple implementation makes adoption easier but it also lets each layer do what it does best (let HTTPS handle encryption).

  3. JWT isn't meant to store sensitive data. Once the server receives the JWT token and validates it, it is free to lookup the user ID in its own database for additional information for that user (like permissions, postal address, etc). This keeps JWT small in size and avoids inadvertent information leakage because everyone knows not to keep sensitive data in JWT.

It's not too different from how cookies themselves work. Cookies often contain unencrypted payloads. If you are using HTTPS then everything is good. If you aren't then it's advisable to encrypt sensitive cookies themselves. Not doing so will mean that a man-in-the-middle attack is possible--a proxy server or ISP reads the cookies and then replays them later on pretending to be you. For similar reasons, JWT should always be exchanged over a secure layer like HTTPS.

How to check if a Unix .tar.gz file is a valid file without uncompressing?

> use the -O option. [...] If the tar file is corrupt, the process will abort with an error.

Sometimes yes, but sometimes not. Let's see an example of a corrupted file:

echo Pete > my_name
tar -cf my_data.tar my_name 

# // Simulate a corruption
sed < my_data.tar 's/Pete/Fool/' > my_data_now.tar
# // "my_data_now.tar" is the corrupted file

tar -xvf my_data_now.tar -O

It shows:

my_name
Fool  

Even if you execute

echo $?

tar said that there was no error:

0

but the file was corrupted, it has now "Fool" instead of "Pete".

Get POST data in C#/ASP.NET

I'm a little surprised that this question has been asked so many times before, but the most reuseable and friendly solution hasn't been documented.

I often have webpages using AngularJS, and when I click on a Save button, I'll "POST" this data back to my .aspx page or .ashx handler to save this back to the database. The data will be in the form of a JSON record.

On the server, to turn the raw posted data back into a C# class, here's what I would do.

First, define a C# class which will contain the posted data.

Supposing my webpage is posting JSON data like this:

{
    "UserID" : 1,
    "FirstName" : "Mike",
    "LastName" : "Mike",
    "Address1" : "10 Really Street",
    "Address2" : "London"
}

Then I'd define a C# class like this...

public class JSONRequest
{
    public int UserID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }
}

(These classes can be nested, but the structure must match the format of the JSON data. So, if you're posting a JSON User record, with a list of Order records within it, your C# class should also contain a List<> of Order records.)

Now, in my .aspx.cs or .ashx file, I just need to do this, and leave JSON.Net to do the hard work...

    protected void Page_Load(object sender, EventArgs e)
    {
        string jsonString = "";
        HttpContext.Current.Request.InputStream.Position = 0;
        using (StreamReader inputStream = new StreamReader(this.Request.InputStream))
        {
            jsonString = inputStream.ReadToEnd();
        }
        JSONRequest oneQuestion = JsonConvert.DeserializeObject<JSONRequest>(jsonString);

And that's it. You now have a JSONRequest class containing the various fields which were POSTed to your server.

Is there a way to get the source code from an APK file?

Apktool for reverse engineering 3rd party, closed, binary Android apps.

It can decode resources to nearly original form and rebuild them after making some modifications.

It makes possible to debug smali code step by step. Also it makes working with an app easier because of project-like file structure and automation of some repetitive tasks like building apk, etc.

http://ibotpeaches.github.io/Apktool/

Android EditText Hint

You can use the concept of selector. onFocus removes the hint.

android:hint="Email"

So when TextView has focus, or has user input (i.e. not empty) the hint will not display.

How to open SharePoint files in Chrome/Firefox

You can use web-based protocol handlers for the links as per https://sharepoint.stackexchange.com/questions/70178/how-does-sharepoint-2013-enable-editing-of-documents-for-chrome-and-fire-fox

Basically, just prepend ms-word:ofe|u| to the links to your SharePoint hosted Word documents.

How can I include css files using node, express, and ejs?

In your app or server.js file include this line:

app.use(express.static('public'));

In your index.ejs, following line will help you:

<link rel="stylesheet" type="text/css" href="/css/style.css" />

I hope this helps, it did for me!

How to download a file using a Java REST service and a data stream

See example here: Input and Output binary streams using JERSEY?

Pseudo code would be something like this (there are a few other similar options in above mentioned post):

@Path("file/")
@GET
@Produces({"application/pdf"})
public StreamingOutput getFileContent() throws Exception {
     public void write(OutputStream output) throws IOException, WebApplicationException {
        try {
          //
          // 1. Get Stream to file from first server
          //
          while(<read stream from first server>) {
              output.write(<bytes read from first server>)
          }
        } catch (Exception e) {
            throw new WebApplicationException(e);
        } finally {
              // close input stream
        }
    }
}

Java 8 Lambda filter by Lists

Something like:

clients.stream.filter(c->{
   users.stream.filter(u->u.getName().equals(c.getName()).count()>0
}).collect(Collectors.toList());

This is however not an awfully efficient way to do it. Unless the collections are very small, you will be better of building a set of user names and using that in the condition.

WCF ServiceHost access rights

I am working on Windows Vista. Even i faced the same problem but when i tried to run VS 2008 with administrative privileges, the issue resolved and my service was up and running. :)

How to make a GridLayout fit screen size

Do you know View.getViewTreeObserver().addOnGlobalLayoutListener()

By this you can calculate the sizes.

I achieve your UI effect by GridView:

GridView g;
g.setNumColumns(2);
g.setStretchMode(GridView.STRETCH_SPACING_UNIFORM);

How do I resolve "Run-time error '429': ActiveX component can't create object"?

The file msrdo20.dll is missing from the installation.

According to the Support Statement for Visual Basic 6.0 on Windows Vista, Windows Server 2008 and Windows 7 this file should be distributed with the application.

I'm not sure why it isn't, but my solution is to place the file somewhere on the machine, and register it using regsvr32 in the command line, eg:

regsvr32 c:\windows\system32\msrdo20.dll

In an ideal world you would package this up with the redistributable.

How to compile the finished C# project and then run outside Visual Studio?

On your project folder, open up the bin\Debug subfolder and you'll see the compiled result.

Convert a SQL Server datetime to a shorter date format

The original DateTime field : [_Date_Time]

The converted to Shortdate : 'Short_Date'

CONVERT(date, [_Date_Time]) AS 'Short_Date'

Changing the color of an hr element

It's simple and my favorite.

<hr style="background-color: #dd3333" />

Make an image follow mouse pointer

Here's my code (not optimized but a full working example):

<head>
<style>
#divtoshow {position:absolute;display:none;color:white;background-color:black}
#onme {width:150px;height:80px;background-color:yellow;cursor:pointer}
</style>
<script type="text/javascript">
var divName = 'divtoshow'; // div that is to follow the mouse (must be position:absolute)
var offX = 15;          // X offset from mouse position
var offY = 15;          // Y offset from mouse position

function mouseX(evt) {if (!evt) evt = window.event; if (evt.pageX) return evt.pageX; else if (evt.clientX)return evt.clientX + (document.documentElement.scrollLeft ?  document.documentElement.scrollLeft : document.body.scrollLeft); else return 0;}
function mouseY(evt) {if (!evt) evt = window.event; if (evt.pageY) return evt.pageY; else if (evt.clientY)return evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop); else return 0;}

function follow(evt) {
    var obj = document.getElementById(divName).style;
    obj.left = (parseInt(mouseX(evt))+offX) + 'px';
    obj.top = (parseInt(mouseY(evt))+offY) + 'px'; 
    }
document.onmousemove = follow;
</script>
</head>
<body>
<div id="divtoshow">test</div>
<br><br>
<div id='onme' onMouseover='document.getElementById(divName).style.display="block"' onMouseout='document.getElementById(divName).style.display="none"'>Mouse over this</div>
</body>

"dd/mm/yyyy" date format in excel through vba

I got it

Cells(1, 1).Value = StartDate
Cells(1, 1).NumberFormat = "dd/mm/yyyy"

Basically, I need to set the cell format, instead of setting the date.

How to serve an image using nodejs

2016 Update

Examples with Express and without Express that actually work

This question is over 5 years old but every answer has some problems.

TL;DR

Scroll down for examples to serve an image with:

  1. express.static
  2. express
  3. connect
  4. http
  5. net

All of the examples are also on GitHub: https://github.com/rsp/node-static-http-servers

Test results are available on Travis: https://travis-ci.org/rsp/node-static-http-servers

Introduction

After over 5 years since this question was asked there is only one correct answer by generalhenry but even though that answer has no problems with the code, it seems to have some problems with reception. It was commented that it "doesn't explain much other than how to rely on someone else to get the job done" and the fact how many people have voted this comment up clearly shows that a lot of things need clarification.

First of all, a good answer to "How to serve images using Node.js" is not implementing a static file server from scratch and doing it badly. A good answer is using a module like Express that does the job correctly.

Answering comments that say that using Express "doesn't explain much other than how to rely on someone else to get the job done" it should be noted, that using the http module already relies on someone else to get the job done. If someone doesn't want to rely on anyone to get the job done then at least raw TCP sockets should be used instead - which I do in one of my examples below.

A more serious problem is that all of the answers here that use the http module are broken. They introduce race conditions, insecure path resolution that will lead to path traversal vulnerability, blocking I/O that will completely fail to serve any concurrent requests at all and other subtle problems - they are completely broken as examples of what the question asks about, and yet they already use the abstraction that is provided by the http module instead of using TCP sockets so they don't even do everything from scratch as they claim.

If the question was "How to implement static file server from scratch, as a learning exercise" then by all means answers how to do that should be posted - but even then we should expect them to at least be correct. Also, it is not unreasonable to assume that someone who wants to serve an image might want to serve more images in the future so one could argue that writing a specific custom static file server that can serve only one single file with hard-coded path is somewhat shortsighted. It seems hard to imagine that anyone who searches for an answer on how to serve an image would be content with a solution that serves just a single image instead of a general solution to serve any image.

In short, the question is how to serve an image and an answer to that is to use an appropriate module to do that in a secure, preformant and reliable way that is readable, maintainable and future-proof while using the best practice of professional Node development. But I agree that a great addition to such an answer would be showing a way to implement the same functionality manually but sadly every attempt to do that has failed so far. And that is why I wrote some new examples.

After this short introduction, here are my five examples doing the job on 5 different levels of abstraction.

Minimum functionality

Every example serves files from the public directory and supports the minumum functionality of:

  • MIME types for most common files
  • serves HTML, JS, CSS, plain text and images
  • serves index.html as a default directory index
  • responds with error codes for missing files
  • no path traversal vulnerabilities
  • no race conditions while reading files

I tested every version on Node versions 4, 5, 6 and 7.

express.static

This version uses the express.static built-in middleware of the express module.

This example has the most functionality and the least amount of code.

var path = require('path');
var express = require('express');
var app = express();

var dir = path.join(__dirname, 'public');

app.use(express.static(dir));

app.listen(3000, function () {
    console.log('Listening on http://localhost:3000/');
});

express

This version uses the express module but without the express.static middleware. Serving static files is implemented as a single route handler using streams.

This example has simple path traversal countermeasures and supports a limited set of most common MIME types.

var path = require('path');
var express = require('express');
var app = express();
var fs = require('fs');

var dir = path.join(__dirname, 'public');

var mime = {
    html: 'text/html',
    txt: 'text/plain',
    css: 'text/css',
    gif: 'image/gif',
    jpg: 'image/jpeg',
    png: 'image/png',
    svg: 'image/svg+xml',
    js: 'application/javascript'
};

app.get('*', function (req, res) {
    var file = path.join(dir, req.path.replace(/\/$/, '/index.html'));
    if (file.indexOf(dir + path.sep) !== 0) {
        return res.status(403).end('Forbidden');
    }
    var type = mime[path.extname(file).slice(1)] || 'text/plain';
    var s = fs.createReadStream(file);
    s.on('open', function () {
        res.set('Content-Type', type);
        s.pipe(res);
    });
    s.on('error', function () {
        res.set('Content-Type', 'text/plain');
        res.status(404).end('Not found');
    });
});

app.listen(3000, function () {
    console.log('Listening on http://localhost:3000/');
});

connect

This version uses the connect module which is a one level of abstraction lower than express.

This example has similar functionality to the express version but using slightly lower-lever APIs.

var path = require('path');
var connect = require('connect');
var app = connect();
var fs = require('fs');

var dir = path.join(__dirname, 'public');

var mime = {
    html: 'text/html',
    txt: 'text/plain',
    css: 'text/css',
    gif: 'image/gif',
    jpg: 'image/jpeg',
    png: 'image/png',
    svg: 'image/svg+xml',
    js: 'application/javascript'
};

app.use(function (req, res) {
    var reqpath = req.url.toString().split('?')[0];
    if (req.method !== 'GET') {
        res.statusCode = 501;
        res.setHeader('Content-Type', 'text/plain');
        return res.end('Method not implemented');
    }
    var file = path.join(dir, reqpath.replace(/\/$/, '/index.html'));
    if (file.indexOf(dir + path.sep) !== 0) {
        res.statusCode = 403;
        res.setHeader('Content-Type', 'text/plain');
        return res.end('Forbidden');
    }
    var type = mime[path.extname(file).slice(1)] || 'text/plain';
    var s = fs.createReadStream(file);
    s.on('open', function () {
        res.setHeader('Content-Type', type);
        s.pipe(res);
    });
    s.on('error', function () {
        res.setHeader('Content-Type', 'text/plain');
        res.statusCode = 404;
        res.end('Not found');
    });
});

app.listen(3000, function () {
    console.log('Listening on http://localhost:3000/');
});

http

This version uses the http module which is the lowest-level API for HTTP in Node.

This example has similar functionality to the connect version but using even more lower-level APIs.

var path = require('path');
var http = require('http');
var fs = require('fs');

var dir = path.join(__dirname, 'public');

var mime = {
    html: 'text/html',
    txt: 'text/plain',
    css: 'text/css',
    gif: 'image/gif',
    jpg: 'image/jpeg',
    png: 'image/png',
    svg: 'image/svg+xml',
    js: 'application/javascript'
};

var server = http.createServer(function (req, res) {
    var reqpath = req.url.toString().split('?')[0];
    if (req.method !== 'GET') {
        res.statusCode = 501;
        res.setHeader('Content-Type', 'text/plain');
        return res.end('Method not implemented');
    }
    var file = path.join(dir, reqpath.replace(/\/$/, '/index.html'));
    if (file.indexOf(dir + path.sep) !== 0) {
        res.statusCode = 403;
        res.setHeader('Content-Type', 'text/plain');
        return res.end('Forbidden');
    }
    var type = mime[path.extname(file).slice(1)] || 'text/plain';
    var s = fs.createReadStream(file);
    s.on('open', function () {
        res.setHeader('Content-Type', type);
        s.pipe(res);
    });
    s.on('error', function () {
        res.setHeader('Content-Type', 'text/plain');
        res.statusCode = 404;
        res.end('Not found');
    });
});

server.listen(3000, function () {
    console.log('Listening on http://localhost:3000/');
});

net

This version uses the net module which is the lowest-level API for TCP sockets in Node.

This example has some of the functionality of the http version but the minimal and incomplete HTTP protocol has been implemented from scratch. Since it doesn't support chunked encoding it loads the files into memory before serving them to know the size before sending a response because statting the files and then loading would introduce a race condition.

var path = require('path');
var net = require('net');
var fs = require('fs');

var dir = path.join(__dirname, 'public');

var mime = {
    html: 'text/html',
    txt: 'text/plain',
    css: 'text/css',
    gif: 'image/gif',
    jpg: 'image/jpeg',
    png: 'image/png',
    svg: 'image/svg+xml',
    js: 'application/javascript'
};

var server = net.createServer(function (con) {
    var input = '';
    con.on('data', function (data) {
        input += data;
        if (input.match(/\n\r?\n\r?/)) {
            var line = input.split(/\n/)[0].split(' ');
            var method = line[0], url = line[1], pro = line[2];
            var reqpath = url.toString().split('?')[0];
            if (method !== 'GET') {
                var body = 'Method not implemented';
                con.write('HTTP/1.1 501 Not Implemented\n');
                con.write('Content-Type: text/plain\n');
                con.write('Content-Length: '+body.length+'\n\n');
                con.write(body);
                con.destroy();
                return;
            }
            var file = path.join(dir, reqpath.replace(/\/$/, '/index.html'));
            if (file.indexOf(dir + path.sep) !== 0) {
                var body = 'Forbidden';
                con.write('HTTP/1.1 403 Forbidden\n');
                con.write('Content-Type: text/plain\n');
                con.write('Content-Length: '+body.length+'\n\n');
                con.write(body);
                con.destroy();
                return;
            }
            var type = mime[path.extname(file).slice(1)] || 'text/plain';
            var s = fs.readFile(file, function (err, data) {
                if (err) {
                    var body = 'Not Found';
                    con.write('HTTP/1.1 404 Not Found\n');
                    con.write('Content-Type: text/plain\n');
                    con.write('Content-Length: '+body.length+'\n\n');
                    con.write(body);
                    con.destroy();
                } else {
                    con.write('HTTP/1.1 200 OK\n');
                    con.write('Content-Type: '+type+'\n');
                    con.write('Content-Length: '+data.byteLength+'\n\n');
                    con.write(data);
                    con.destroy();
                }
            });
        }
    });
});

server.listen(3000, function () {
    console.log('Listening on http://localhost:3000/');
});

Download examples

I posted all of the examples on GitHub with more explanation.

Examples with express.static, express, connect, http and net:

Other project using only express.static:

Tests

Test results are available on Travis:

Everything is tested on Node versions 4, 5, 6, and 7.

See also

Other related answers:

Could not load file or assembly ... An attempt was made to load a program with an incorrect format (System.BadImageFormatException)

If you use LibreOffice from your program via cli .net integration like me, I got the same error. I use the older version of LibreOffice on the production environment on my PC I installed a newer version that was in conflict. Just uninstall LibreOffice. I found the solution here .NET CLI: Could not load file or assembly 'cli_cppuhelper'

How to backup Sql Database Programmatically in C#

You can use the following queries to Backup and Restore, you must change the path for your backup

Database name=[data]

Backup:

BACKUP DATABASE [data] TO  DISK = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Backup\data.bak' WITH NOFORMAT, NOINIT,  NAME = N'data-Full Database Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10
GO

Restore:

RESTORE DATABASE [data] FROM  DISK = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Backup\data.bak' WITH  FILE = 1,  NOUNLOAD,  REPLACE,  STATS = 10
GO

Hidden features of Windows batch files

Arrays in batch-files.

Set a value:

set count=1
set var%count%=42

Extract a value at the command-line:

call echo %var%count%%

Extract a value in a batch-file:

call echo %%var%count%%%

Note the extra strafing % signs.

The technique may look a little hairy, but it's quite useful. The above will print the contents of var1 (i.e. 42) as we explained. We could also replace the echo command with a set if we wanted to set some other variable to the value in var1. Meaning the following is a valid assignment at the command line:

call set x=%var%count%%

Then to see the value of va1:

echo %x%

ImportError: No module named enum

Depending on your rights, you need sudo at beginning.

What does jQuery.fn mean?

In jQuery, the fn property is just an alias to the prototype property.

The jQuery identifier (or $) is just a constructor function, and all instances created with it, inherit from the constructor's prototype.

A simple constructor function:

function Test() {
  this.a = 'a';
}
Test.prototype.b = 'b';

var test = new Test(); 
test.a; // "a", own property
test.b; // "b", inherited property

A simple structure that resembles the architecture of jQuery:

(function() {
  var foo = function(arg) { // core constructor
    // ensure to use the `new` operator
    if (!(this instanceof foo))
      return new foo(arg);
    // store an argument for this example
    this.myArg = arg;
    //..
  };

  // create `fn` alias to `prototype` property
  foo.fn = foo.prototype = {
    init: function () {/*...*/}
    //...
  };

  // expose the library
  window.foo = foo;
})();

// Extension:

foo.fn.myPlugin = function () {
  alert(this.myArg);
  return this; // return `this` for chainability
};

foo("bar").myPlugin(); // alerts "bar"

cannot convert data (type interface {}) to type string: need type assertion

Type Assertion

This is known as type assertion in golang, and it is a common practice.

Here is the explanation from a tour of go:

A type assertion provides access to an interface value's underlying concrete value.

t := i.(T)

This statement asserts that the interface value i holds the concrete type T and assigns the underlying T value to the variable t.

If i does not hold a T, the statement will trigger a panic.

To test whether an interface value holds a specific type, a type assertion can return two values: the underlying value and a boolean value that reports whether the assertion succeeded.

t, ok := i.(T)

If i holds a T, then t will be the underlying value and ok will be true.

If not, ok will be false and t will be the zero value of type T, and no panic occurs.

NOTE: value i should be interface type.

Pitfalls

Even if i is an interface type, []i is not interface type. As a result, in order to convert []i to its value type, we have to do it individually:

// var items []i
for _, item := range items {
    value, ok := item.(T)
    dosomethingWith(value)
}

Performance

As for performance, it can be slower than direct access to the actual value as show in this stackoverflow answer.

What exactly should be set in PYTHONPATH?

You don't have to set either of them. PYTHONPATH can be set to point to additional directories with private libraries in them. If PYTHONHOME is not set, Python defaults to using the directory where python.exe was found, so that dir should be in PATH.

What is the use of the @Temporal annotation in Hibernate?

Temporal types are the set of time-based types that can be used in persistent state mappings.

The list of supported temporal types includes the three java.sql types java.sql.Date, java.sql.Time, and java.sql.Timestamp, and it includes the two java.util types java.util.Date and java.util.Calendar.

The java.sql types are completely hassle-free. They act just like any other simple mapping type and do not need any special consideration.

The two java.util types need additional metadata, however, to indicate which of the JDBC java.sql types to use when communicating with the JDBC driver. This is done by annotating them with the @Temporal annotation and specifying the JDBC type as a value of the TemporalType enumerated type.

There are three enumerated values of DATE, TIME, and TIMESTAMP to represent each of the java.sql types.

PHP 5.4 Call-time pass-by-reference - Easy fix available?

PHP and references are somewhat unintuitive. If used appropriately references in the right places can provide large performance improvements or avoid very ugly workarounds and unusual code.

The following will produce an error:

 function f(&$v){$v = true;}
 f(&$v);

 function f($v){$v = true;}
 f(&$v);

None of these have to fail as they could follow the rules below but have no doubt been removed or disabled to prevent a lot of legacy confusion.

If they did work, both involve a redundant conversion to reference and the second also involves a redundant conversion back to a scoped contained variable.

The second one used to be possible allowing a reference to be passed to code that wasn't intended to work with references. This is extremely ugly for maintainability.

This will do nothing:

 function f($v){$v = true;}
 $r = &$v;
 f($r);

More specifically, it turns the reference back into a normal variable as you have not asked for a reference.

This will work:

 function f(&$v){$v = true;}
 f($v);

This sees that you are passing a non-reference but want a reference so turns it into a reference.

What this means is that you can't pass a reference to a function where a reference is not explicitly asked for making it one of the few areas where PHP is strict on passing types or in this case more of a meta type.

If you need more dynamic behaviour this will work:

 function f(&$v){$v = true;}
 $v = array(false,false,false);
 $r = &$v[1];
 f($r);

Here it sees that you want a reference and already have a reference so leaves it alone. It may also chain the reference but I doubt this.

How to set x axis values in matplotlib python?

The scaling on your example figure is a bit strange but you can force it by plotting the index of each x-value and then setting the ticks to the data points:

import matplotlib.pyplot as plt
x = [0.00001,0.001,0.01,0.1,0.5,1,5]
# create an index for each tick position
xi = list(range(len(x)))
y = [0.945,0.885,0.893,0.9,0.996,1.25,1.19]
plt.ylim(0.8,1.4)
# plot the index for the x-values
plt.plot(xi, y, marker='o', linestyle='--', color='r', label='Square') 
plt.xlabel('x')
plt.ylabel('y') 
plt.xticks(xi, x)
plt.title('compare')
plt.legend() 
plt.show()

React onClick function fires on render

JSX is used with ReactJS as it is very similar to HTML and it gives programmers feel of using HTML whereas it ultimately transpiles to a javascript file.

Writing a for-loop and specifying function as {this.props.removeTaskFunction(todo)} will execute the functions whenever the loop is triggered .

To stop this behaviour we need to return the function to onClick.

The fat arrow function has a hidden return statement along with the bind property. Thus it returns the function to OnClick as Javascript can return functions too !!!!!

Use -

onClick={() => { this.props.removeTaskFunction(todo) }}

which means-

var onClick = function() {
  return this.props.removeTaskFunction(todo);
}.bind(this);

Android: How to bind spinner to custom object list?

If you don't need a separated class, i mean just a simple adapter mapped on your object. Here is my code based on ArrayAdapter functions provided.

And because you might need to add item after adapter creation (eg database item asynchronous loading).

Simple but efficient.

editCategorySpinner = view.findViewById(R.id.discovery_edit_category_spinner);

// Drop down layout style - list view with radio button         
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

// attaching data adapter to spinner, as you can see i have no data at this moment
editCategorySpinner.setAdapter(dataAdapter);
final ArrayAdapter<Category> dataAdapter = new ArrayAdapter<Category>

(getActivity(), android.R.layout.simple_spinner_item, new ArrayList<Category>(0)) {


        // And the "magic" goes here
        // This is for the "passive" state of the spinner
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // I created a dynamic TextView here, but you can reference your own  custom layout for each spinner item
            TextView label = (TextView) super.getView(position, convertView, parent);
            label.setTextColor(Color.BLACK);
            // Then you can get the current item using the values array (Users array) and the current position
            // You can NOW reference each method you has created in your bean object (User class)
            Category item = getItem(position);
            label.setText(item.getName());

            // And finally return your dynamic (or custom) view for each spinner item
            return label;
        }

        // And here is when the "chooser" is popped up
        // Normally is the same view, but you can customize it if you want
        @Override
        public View getDropDownView(int position, View convertView,
                                    ViewGroup parent) {
            TextView label = (TextView) super.getDropDownView(position, convertView, parent);
            label.setTextColor(Color.BLACK);
            Category item = getItem(position);
            label.setText(item.getName());

            return label;
        }
    };

And then you can use this code (i couldn't put Category[] in adapter constructor because data are loaded separatly).

Note that adapter.addAll(items) refresh spinner by calling notifyDataSetChanged() in internal.

categoryRepository.getAll().observe(this, new Observer<List<Category>>() {

            @Override
            public void onChanged(@Nullable final List<Category> items) {
                dataAdapter.addAll(items);
            }
});

How Can I Set the Default Value of a Timestamp Column to the Current Timestamp with Laravel Migrations?

Use Paulo Freitas suggestion instead.


Until Laravel fixes this, you can run a standard database query after the Schema::create have been run.

    Schema::create("users", function($table){
        $table->increments('id');
        $table->string('email', 255);
        $table->string('given_name', 100);
        $table->string('family_name', 100);
        $table->timestamp('joined');
        $table->enum('gender', ['male', 'female', 'unisex'])->default('unisex');
        $table->string('timezone', 30)->default('UTC');
        $table->text('about');
    });
    DB::statement("ALTER TABLE ".DB::getTablePrefix()."users CHANGE joined joined TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL");

It worked wonders for me.

How to add multiple values to a dictionary key in python?

How about

a["abc"] = [1, 2]

This will result in:

>>> a
{'abc': [1, 2]}

Is that what you were looking for?

How do you declare an interface in C++?

You can also consider contract classes implemented with the NVI (Non Virtual Interface Pattern). For instance:

struct Contract1 : boost::noncopyable
{
    virtual ~Contract1();
    void f(Parameters p) {
        assert(checkFPreconditions(p)&&"Contract1::f, pre-condition failure");
        // + class invariants.
        do_f(p);
        // Check post-conditions + class invariants.
    }
private:
    virtual void do_f(Parameters p) = 0;
};
...
class Concrete : public Contract1, public Contract2
{
private:
    virtual void do_f(Parameters p); // From contract 1.
    virtual void do_g(Parameters p); // From contract 2.
};

Parse strings to double with comma and point

try this... it works for me.

double vdouble = 0;
string sparam = "2,1";

if ( !Double.TryParse( sparam, NumberStyles.Float, CultureInfo.InvariantCulture, out vdouble ) )
{
    if ( sparam.IndexOf( '.' ) != -1 )
    {
        sparam = sparam.Replace( '.', ',' );
    }
    else
    {
        sparam = sparam.Replace( ',', '.' );
    }

    if ( !Double.TryParse( sparam, NumberStyles.Float, CultureInfo.InvariantCulture, out vdouble ) )
    {
        vdouble = 0;
    }
}

phpMyAdmin Error: The mbstring extension is missing. Please check your PHP configuration

You can try this

sudo apt-get install phpmyadmin php-mbstring php-gettext
sudo ln -s /usr/share/phpmyadmin/ /var/www/html/phpmyadmin
service apache2 restart

CSS: Background image and padding

Use CSS background-clip:

background-clip: content-box;

The background will be painted within the content box.

Write string to text file and ensure it always overwrites the existing content.

If your code doesn't require the file to be truncated first, you can use the FileMode.OpenOrCreate to open the filestream, which will create the file if it doesn't exist or open it if it does. You can use the stream to point at the front and start overwriting the existing file?

I'm assuming your using a streams here, there are other ways to write a file.

Launch Pycharm from command line (terminal)

Edit (April 2020): It seems that launcher script creation is now managed in Toolbox App settings. See the Toolbox App announcement for more details.

--

  1. Open Application Pycharm
  2. Find tools in menu bar
  3. Click Create Command-line Launcher
  4. Checking the launcher executable file which has been created in /usr/local/bin/charm
  5. Open project or file just type $ charm YOUR_FOLDER_OR_FILE

Maybe this is what you need.

Where is the Keytool application?

here: C:\Program Files\Java\jre7\bin it is an exe keytool.exe

Use LINQ to get items in one List<>, that are not in another List<>

first, extract ids from the collection where condition

List<int> indexes_Yes = this.Contenido.Where(x => x.key == 'TEST').Select(x => x.Id).ToList();

second, use "compare" estament to select ids diffent to the selection

List<int> indexes_No = this.Contenido.Where(x => !indexes_Yes.Contains(x.Id)).Select(x => x.Id).ToList();

Obviously you can use x.key != "TEST", but is only a example

How to mock a final class with mockito

Give this a try:

Mockito.mock(SomeMockableType.class,AdditionalAnswers.delegatesTo(someInstanceThatIsNotMockableOrSpyable));

It worked for me. "SomeMockableType.class" is the parent class of what you want to mock or spy, and someInstanceThatIsNotMockableOrSpyable is the actual class that you want to mock or spy.

For more details have a look here

Delete all local git branches

if you want to delete test branch then

Step1

  • go to other branch
  • git branch -d branch_name

enter image description here

More Detail in depth

How to uninstall downloaded Xcode simulator?

Slightly off topic but could be very useful as it could be the basis for other tasks you might want to do with simulators.

I like to keep my simulator list to a minimum, and since there is no multi-select in the "Devices and Simulators" it is a pain to delete them all.

So I boot all the sims that I want to use then, remove all the simulators that I don't have booted.

Delete all the shutdown simulators:

xcrun simctl list | grep -w "Shutdown"  | grep -o "([-A-Z0-9]*)" | sed 's/[\(\)]//g' | xargs -I uuid xcrun simctl delete  uuid

If you need individual simulators back, just add them back to the list in "Devices and Simulators" with the plus button.

enter image description here

Simple Digit Recognition OCR in OpenCV-Python

OCR which stands for Optical Character Recognition is a computer vision technique used to identify the different types of handwritten digits that are used in common mathematics. To perform OCR in OpenCV we will use the KNN algorithm which detects the nearest k neighbors of a particular data point and then classifies that data point based on the class type detected for n neighbors.

Data Used


This data contains 5000 handwritten digits where there are 500 digits for every type of digit. Each digit is of 20×20 pixel dimensions. We will split the data such that 250 digits are for training and 250 digits are for testing for every class.

Below is the implementation.




import numpy as np
import cv2
   
      
# Read the image
image = cv2.imread('digits.png')
  
# gray scale conversion
gray_img = cv2.cvtColor(image,
                        cv2.COLOR_BGR2GRAY)
  
# We will divide the image
# into 5000 small dimensions 
# of size 20x20
divisions = list(np.hsplit(i,100) for i in np.vsplit(gray_img,50))
  
# Convert into Numpy array
# of size (50,100,20,20)
NP_array = np.array(divisions)
   
# Preparing train_data
# and test_data.
# Size will be (2500,20x20)
train_data = NP_array[:,:50].reshape(-1,400).astype(np.float32)
  
# Size will be (2500,20x20)
test_data = NP_array[:,50:100].reshape(-1,400).astype(np.float32)
  
# Create 10 different labels 
# for each type of digit
k = np.arange(10)
train_labels = np.repeat(k,250)[:,np.newaxis]
test_labels = np.repeat(k,250)[:,np.newaxis]
   
# Initiate kNN classifier
knn = cv2.ml.KNearest_create()
  
# perform training of data
knn.train(train_data,
          cv2.ml.ROW_SAMPLE, 
          train_labels)
   
# obtain the output from the
# classifier by specifying the
# number of neighbors.
ret, output ,neighbours,
distance = knn.findNearest(test_data, k = 3)
   
# Check the performance and
# accuracy of the classifier.
# Compare the output with test_labels
# to find out how many are wrong.
matched = output==test_labels
correct_OP = np.count_nonzero(matched)
   
#Calculate the accuracy.
accuracy = (correct_OP*100.0)/(output.size)
   
# Display accuracy.
print(accuracy)


Output

91.64


Well, I decided to workout myself on my question to solve the above problem. What I wanted is to implement a simple OCR using KNearest or SVM features in OpenCV. And below is what I did and how. (it is just for learning how to use KNearest for simple OCR purposes).

1) My first question was about letter_recognition.data file that comes with OpenCV samples. I wanted to know what is inside that file.

It contains a letter, along with 16 features of that letter.

And this SOF helped me to find it. These 16 features are explained in the paper Letter Recognition Using Holland-Style Adaptive Classifiers. (Although I didn't understand some of the features at the end)

2) Since I knew, without understanding all those features, it is difficult to do that method. I tried some other papers, but all were a little difficult for a beginner.

So I just decided to take all the pixel values as my features. (I was not worried about accuracy or performance, I just wanted it to work, at least with the least accuracy)

I took the below image for my training data:

enter image description here

(I know the amount of training data is less. But, since all letters are of the same font and size, I decided to try on this).

To prepare the data for training, I made a small code in OpenCV. It does the following things:

  1. It loads the image.
  2. Selects the digits (obviously by contour finding and applying constraints on area and height of letters to avoid false detections).
  3. Draws the bounding rectangle around one letter and wait for key press manually. This time we press the digit key ourselves corresponding to the letter in the box.
  4. Once the corresponding digit key is pressed, it resizes this box to 10x10 and saves all 100 pixel values in an array (here, samples) and corresponding manually entered digit in another array(here, responses).
  5. Then save both the arrays in separate .txt files.

At the end of the manual classification of digits, all the digits in the training data (train.png) are labeled manually by ourselves, image will look like below:

enter image description here

Below is the code I used for the above purpose (of course, not so clean):

import sys

import numpy as np
import cv2

im = cv2.imread('pitrain.png')
im3 = im.copy()

gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),0)
thresh = cv2.adaptiveThreshold(blur,255,1,1,11,2)

#################      Now finding Contours         ###################

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

samples =  np.empty((0,100))
responses = []
keys = [i for i in range(48,58)]

for cnt in contours:
    if cv2.contourArea(cnt)>50:
        [x,y,w,h] = cv2.boundingRect(cnt)
        
        if  h>28:
            cv2.rectangle(im,(x,y),(x+w,y+h),(0,0,255),2)
            roi = thresh[y:y+h,x:x+w]
            roismall = cv2.resize(roi,(10,10))
            cv2.imshow('norm',im)
            key = cv2.waitKey(0)

            if key == 27:  # (escape to quit)
                sys.exit()
            elif key in keys:
                responses.append(int(chr(key)))
                sample = roismall.reshape((1,100))
                samples = np.append(samples,sample,0)

responses = np.array(responses,np.float32)
responses = responses.reshape((responses.size,1))
print "training complete"

np.savetxt('generalsamples.data',samples)
np.savetxt('generalresponses.data',responses)

Now we enter in to training and testing part.

For the testing part, I used the below image, which has the same type of letters I used for the training phase.

enter image description here

For training we do as follows:

  1. Load the .txt files we already saved earlier
  2. create an instance of the classifier we are using (it is KNearest in this case)
  3. Then we use KNearest.train function to train the data

For testing purposes, we do as follows:

  1. We load the image used for testing
  2. process the image as earlier and extract each digit using contour methods
  3. Draw a bounding box for it, then resize it to 10x10, and store its pixel values in an array as done earlier.
  4. Then we use KNearest.find_nearest() function to find the nearest item to the one we gave. ( If lucky, it recognizes the correct digit.)

I included last two steps (training and testing) in single code below:

import cv2
import numpy as np

#######   training part    ############### 
samples = np.loadtxt('generalsamples.data',np.float32)
responses = np.loadtxt('generalresponses.data',np.float32)
responses = responses.reshape((responses.size,1))

model = cv2.KNearest()
model.train(samples,responses)

############################# testing part  #########################

im = cv2.imread('pi.png')
out = np.zeros(im.shape,np.uint8)
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray,255,1,1,11,2)

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

for cnt in contours:
    if cv2.contourArea(cnt)>50:
        [x,y,w,h] = cv2.boundingRect(cnt)
        if  h>28:
            cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2)
            roi = thresh[y:y+h,x:x+w]
            roismall = cv2.resize(roi,(10,10))
            roismall = roismall.reshape((1,100))
            roismall = np.float32(roismall)
            retval, results, neigh_resp, dists = model.find_nearest(roismall, k = 1)
            string = str(int((results[0][0])))
            cv2.putText(out,string,(x,y+h),0,1,(0,255,0))

cv2.imshow('im',im)
cv2.imshow('out',out)
cv2.waitKey(0)

And it worked, below is the result I got:

enter image description here


Here it worked with 100% accuracy. I assume this is because all the digits are of the same kind and the same size.

But anyway, this is a good start to go for beginners (I hope so).

How should I unit test multithreaded code?

Another way to (kinda) test threaded code, and very complex systems in general is through Fuzz Testing. It's not great, and it won't find everything, but its likely to be useful and its simple to do.

Quote:

Fuzz testing or fuzzing is a software testing technique that provides random data("fuzz") to the inputs of a program. If the program fails (for example, by crashing, or by failing built-in code assertions), the defects can be noted. The great advantage of fuzz testing is that the test design is extremely simple, and free of preconceptions about system behavior.

...

Fuzz testing is often used in large software development projects that employ black box testing. These projects usually have a budget to develop test tools, and fuzz testing is one of the techniques which offers a high benefit to cost ratio.

...

However, fuzz testing is not a substitute for exhaustive testing or formal methods: it can only provide a random sample of the system's behavior, and in many cases passing a fuzz test may only demonstrate that a piece of software handles exceptions without crashing, rather than behaving correctly. Thus, fuzz testing can only be regarded as a bug-finding tool rather than an assurance of quality.

How do I check if a string is unicode or ascii?

In Python 3, all strings are sequences of Unicode characters. There is a bytes type that holds raw bytes.

In Python 2, a string may be of type str or of type unicode. You can tell which using code something like this:

def whatisthis(s):
    if isinstance(s, str):
        print "ordinary string"
    elif isinstance(s, unicode):
        print "unicode string"
    else:
        print "not a string"

This does not distinguish "Unicode or ASCII"; it only distinguishes Python types. A Unicode string may consist of purely characters in the ASCII range, and a bytestring may contain ASCII, encoded Unicode, or even non-textual data.

batch script - run command on each file in directory

I am doing similar thing to compile all the c files in a directory.
for iterating files in different directory try this.

set codedirectory=C:\Users\code
for /r  %codedirectory% %%i in (*.c) do 
( some GCC commands )

Image Processing: Algorithm Improvement for 'Coca-Cola Can' Recognition

Looking at shape

Take a gander at the shape of the red portion of the can/bottle. Notice how the can tapers off slightly at the very top whereas the bottle label is straight. You can distinguish between these two by comparing the width of the red portion across the length of it.

Looking at highlights

One way to distinguish between bottles and cans is the material. A bottle is made of plastic whereas a can is made of aluminum metal. In sufficiently well-lit situations, looking at the specularity would be one way of telling a bottle label from a can label.

As far as I can tell, that is how a human would tell the difference between the two types of labels. If the lighting conditions are poor, there is bound to be some uncertainty in distinguishing the two anyways. In that case, you would have to be able to detect the presence of the transparent/translucent bottle itself.

Removing duplicate objects with Underscore for Javascript

here's my solution (coffeescript) :

_.mixin
  deepUniq: (coll) ->
    result = []
    remove_first_el_duplicates = (coll2) ->

      rest = _.rest(coll2)
      first = _.first(coll2)
      result.push first
      equalsFirst = (el) -> _.isEqual(el,first)

      newColl = _.reject rest, equalsFirst

      unless _.isEmpty newColl
        remove_first_el_duplicates newColl

    remove_first_el_duplicates(coll)
    result

example:

_.deepUniq([ {a:1,b:12}, [ 2, 1, 2, 1 ], [ 1, 2, 1, 2 ],[ 2, 1, 2, 1 ], {a:1,b:12} ]) 
//=> [ { a: 1, b: 12 }, [ 2, 1, 2, 1 ], [ 1, 2, 1, 2 ] ]

"A connection attempt failed because the connected party did not properly respond after a period of time" using WebClient

Is the URL that this code is making accessible in the browser?

http://" + Request.ServerVariables["HTTP_HOST"] + Request.ApplicationPath + "/PageDetails.aspx?ModuleID=" + ID

First thing you need to verify is that the URL you are making is correct. Then check in the browser to see if it is browsing. then use Fiddler tool to check what is passing over the network. It may be that URL that is being called through code is wrongly escaped.

Then check for firewall related issues.

Change the project theme in Android Studio?

In the AndroidManifest.xml, under the application tag, you can set the theme of your choice. To customize the theme, press Ctrl + Click on android:theme = "@style/AppTheme" in the Android manifest file. It will open styles.xml file where you can change the parent attribute of the style tag.

At parent= in styles.xml you can browse all available styles by using auto-complete inside the "". E.g. try parent="Theme." with your cursor right after the . and then pressing Ctrl + Space.

You can also preview themes in the preview window in Android Studio.

enter image description here

Angular2 If ngModel is used within a form tag, either the name attribute must be set or the form

Both attributes are needed and also recheck all the form elements has "name" attribute. if you are using form submit concept, other wise just use div tag instead of form element.

<input [(ngModel)]="firstname" name="something">

How to remove rows with any zero value

I would probably go with Joran's suggestion of replacing 0's with NAs and then using the built in functions you mentioned. If you can't/don't want to do that, one approach is to use any() to find rows that contain 0's and subset those out:

set.seed(42)
#Fake data
x <- data.frame(a = sample(0:2, 5, TRUE), b = sample(0:2, 5, TRUE))
> x
  a b
1 2 1
2 2 2
3 0 0
4 2 1
5 1 2
#Subset out any rows with a 0 in them
#Note the negation with ! around the apply function
x[!(apply(x, 1, function(y) any(y == 0))),]
  a b
1 2 1
2 2 2
4 2 1
5 1 2

To implement Joran's method, something like this should get you started:

x[x==0] <- NA

Programmatically find the number of cores on a machine

you can use WMI in .net too but you're then dependent on the wmi service running etc. Sometimes it works locally, but then fail when the same code is run on servers. I believe that's a namespace issue, related to the "names" whose values you're reading.

PHP - Failed to open stream : No such file or directory

Samba Shares

If you have a Linux test server and you work from a Windows Client, the Samba share interferes with the chmod command. So, even if you use:

chmod -R 777 myfolder

on the Linux side it is fully possible that the Unix Group\www-data still doesn't have write access. One working solution if your share is set up that Windows admins are mapped to root: From Windows, open the Permissions, disable Inheritance for your folder with copy, and then grant full access for www-data.

How to strip HTML tags from a string in SQL Server?

Here is a version that doesn't require an UDF and works even if the HTML contains tags without matching closing tags.

TRY_CAST(REPLACE(REPLACE(REPLACE([HtmlCol], '>', '/> '), '</', '<'), '--/>', '-->') AS XML).value('.', 'NVARCHAR(MAX)')

CSS Inset Borders

It's an old trick, but I still find the easiest way to do this is to use outline-offset with a negative value (example below uses -6px). Here's a fiddle of it—I've made the outer border red and the outline white to differentiate the two:

.outline-offset {
width:300px;
height:200px;
background:#333c4b;
border:2px solid red;
outline:2px #fff solid;
outline-offset:-6px;
}

<div class="outline-offset"></div>

How to use ng-repeat without an html element

You might want to flatten the data within your controller:

function MyCtrl ($scope) {
  $scope.myData = [[1,2,3], [4,5,6], [7,8,9]];
  $scope.flattened = function () {
    var flat = [];
    $scope.myData.forEach(function (item) {
      flat.concat(item);
    }
    return flat;
  }
}

And then in the HTML:

<table>
  <tbody>
    <tr ng-repeat="item in flattened()"><td>{{item}}</td></tr>
  </tbody>
</table>

preventDefault() on an <a> tag

This is a non-JQuery solution I just tested and it works.

<html lang="en">
<head>
<script type="text/javascript">
addEventListener("load",function(){
    var links= document.getElementsByTagName("a");
    for (var i=0;i<links.length;i++){
        links[i].addEventListener("click",function(e){
        alert("NOPE!, I won't take you there haha");
        //prevent event action
        e.preventDefault();
        })
    }
}); 

</script>
</head>
<body>
<div>
<ul>
    <li><a href="http://www.google.com">Google</a></li>
    <li><a href="http://www.facebook.com">Facebook</a></li>
    <p id="p1">Paragraph</p>
</ul>
</div>
<p>By Jefrey Bulla</p>
</body>
</html>

Getting windbg without the whole WDK?

WinDbg is now available separately via MS Store. It's called "Preview" but I tested it to analyse some memory dumps and it works fine.

If you're on Windows 10 - launch MS Store, type "WinDbg" in the search box and voi-la - you have it. The download is approx. 100mb. It will downlaod required symbols automatically.

Center-align a HTML table

table
{ 
margin-left: auto;
margin-right: auto;
}

This will definitely work. Cheers

Set value of textarea in jQuery

Have you tried val?

$("textarea#ExampleMessage").val(result.exampleMessage);

How to get element's width/height within directives and component?

You can use ElementRef as shown below,

DEMO : https://plnkr.co/edit/XZwXEh9PZEEVJpe0BlYq?p=preview check browser's console.

import { Directive,Input,Outpu,ElementRef,Renderer} from '@angular/core';

@Directive({
  selector:"[move]",
  host:{
    '(click)':"show()"
  }
})

export class GetEleDirective{

  constructor(private el:ElementRef){

  }
  show(){
    console.log(this.el.nativeElement);

    console.log('height---' + this.el.nativeElement.offsetHeight);  //<<<===here
    console.log('width---' + this.el.nativeElement.offsetWidth);    //<<<===here
  }
}

Same way you can use it within component itself wherever you need it.

How to set a Fragment tag by code?

I know it's been 6 years ago but if anyone is facing the same problem do like I've done:

Create a custom Fragment Class with a tag field:

public class MyFragment extends Fragment {
 private String _myTag;
 public void setMyTag(String value)
 {
   if("".equals(value))
     return;
   _myTag = value;
 }
 //other code goes here
}

Before adding the fragment to the sectionPagerAdapter set the tag just like that:

 MyFragment mfrag= new MyFragment();
 mfrag.setMyTag("TAG_GOES_HERE");
 sectionPagerAdapter.AddFragment(mfrag);

When should I use a struct rather than a class in C#?

I was just dealing with Windows Communication Foundation [WCF] Named Pipe and I did notice that it does make sense to use Structs in order to ensure that exchange of data is of value type instead of reference type.

In TensorFlow, what is the difference between Session.run() and Tensor.eval()?

Tensorflow 2.x Compatible Answer: Converting mrry's code to Tensorflow 2.x (>= 2.0) for the benefit of the community.

!pip install tensorflow==2.1
import tensorflow as tf

tf.compat.v1.disable_eager_execution()    

t = tf.constant(42.0)
sess = tf.compat.v1.Session()
with sess.as_default():   # or `with sess:` to close on exit
    assert sess is tf.compat.v1.get_default_session()
    assert t.eval() == sess.run(t)

#The most important difference is that you can use sess.run() to fetch the values of many tensors in the same step:

t = tf.constant(42.0)
u = tf.constant(37.0)
tu = tf.multiply(t, u)
ut = tf.multiply(u, t)
with sess.as_default():
   tu.eval()  # runs one step
   ut.eval()  # runs one step
   sess.run([tu, ut])  # evaluates both tensors in a single step

angular2: how to copy object into another object

As suggested before, the clean way of deep copying objects having nested objects inside is by using lodash's cloneDeep method.

For Angular, you can do it like this:

Install lodash with yarn add lodash or npm install lodash.

In your component, import cloneDeep and use it:

import * as cloneDeep from 'lodash/cloneDeep';
...
clonedObject = cloneDeep(originalObject);

It's only 18kb added to your build, well worth for the benefits.

I've also written an article here, if you need more insight on why using lodash's cloneDeep.

Expected block end YAML error

This error also occurs if you use four-space instead of two-space indentation.

e.g., the following would throw the error:

fields:
    - metadata: {}
        name: colName
        nullable: true

whereas changing indentation to two-spaces would fix it:

fields:
  - metadata: {}
    name: colName
    nullable: true

wamp server mysql user id and password

Hit enter as there is no password. Enter the following commands:

mysql> SET PASSWORD for 'root'@'localhost' = password('enteryourpassword');
mysql> SET PASSWORD for 'root'@'127.0.0.1' = password('enteryourpassword');
mysql> SET PASSWORD for 'root'@'::1' = password('enteryourpassword');

That’s it, I keep the passwords the same to keep things simple. If you want to check the user’s table to see that the info has been updated just enter the additional commands as shown below. This is a good option to check that you have indeed entered the same password for all hosts.

How to convert wstring into string?

In case anyone else is interested: I needed a class that could be used interchangeably wherever either a string or wstring was expected. The following class convertible_string, based on dk123's solution, can be initialized with either a string, char const*, wstring or wchar_t const* and can be assigned to by or implicitly converted to either a string or wstring (so can be passed into a functions that take either).

class convertible_string
{
public:
    // default ctor
    convertible_string()
    {}

    /* conversion ctors */
    convertible_string(std::string const& value) : value_(value)
    {}
    convertible_string(char const* val_array) : value_(val_array)
    {}
    convertible_string(std::wstring const& wvalue) : value_(ws2s(wvalue))
    {}
    convertible_string(wchar_t const* wval_array) : value_(ws2s(std::wstring(wval_array)))
    {}

    /* assignment operators */
    convertible_string& operator=(std::string const& value)
    {
        value_ = value;
        return *this;
    }
    convertible_string& operator=(std::wstring const& wvalue)
    {
        value_ = ws2s(wvalue);
        return *this;
    }

    /* implicit conversion operators */
    operator std::string() const { return value_; }
    operator std::wstring() const { return s2ws(value_); }
private:
    std::string value_;
};

Getting A File's Mime Type In Java

I was just wondering how most people fetch a mime type from a file in Java?

I've published my SimpleMagic Java package which allows content-type (mime-type) determination from files and byte arrays. It is designed to read and run the Unix file(1) command magic files that are a part of most ~Unix OS configurations.

I tried Apache Tika but it is huge with tons of dependencies, URLConnection doesn't use the bytes of the files, and MimetypesFileTypeMap also just looks at files names.

With SimpleMagic you can do something like:

// create a magic utility using the internal magic file
ContentInfoUtil util = new ContentInfoUtil();
// if you want to use a different config file(s), you can load them by hand:
// ContentInfoUtil util = new ContentInfoUtil("/etc/magic");
...
ContentInfo info = util.findMatch("/tmp/upload.tmp");
// or
ContentInfo info = util.findMatch(inputStream);
// or
ContentInfo info = util.findMatch(contentByteArray);

// null if no match
if (info != null) {
   String mimeType = info.getMimeType();
}

Unexpected token < in first line of HTML

Your page references a Javascript file at /Client/public/core.js.

This file probably can't be found, producing either the website's frontpage or an HTML error page instead. This is a pretty common issue for eg. websites running on an Apache server where paths are redirected by default to index.php.

If that's the case, make sure you replace /Client/public/core.js in your script tag <script type="text/javascript" src="/Client/public/core.js"></script> with the correct file path or put the missing file core.js at location /Client/public/ to fix your error!

If you do already find a file named core.js at /Client/public/ and the browser still produces a HTML page instead, check the permissions for folder and file. Either of these might be lacking the proper permissions.

How to switch activity without animation in Android?

You can create a style,

 <style name="noAnimTheme" parent="android:Theme">
   <item name="android:windowAnimationStyle">@null</item>
</style>

and set it as theme for your activity in the manifest:

   <activity android:name=".ui.ArticlesActivity" android:theme="@style/noAnimTheme">
    </activity>

You can also define a style to specify custom entry and exit animations. http://developer.android.com/reference/android/R.attr.html#windowEnterAnimation

How can I inspect element in an Android browser?

Chrome on Android makes it possible to use the Chrome developer tools on the desktop to inspect the HTML that was loaded from the Chrome application on the Android device.

See: https://developers.google.com/chrome-developer-tools/docs/remote-debugging

How can I add the sqlite3 module to Python?

Normally, it is included. However, as @ngn999 said, if your python has been built from source manually, you'll have to add it.

Here is an example of a script that will setup an encapsulated version (virtual environment) of Python3 in your user directory with an encapsulated version of sqlite3.

INSTALL_BASE_PATH="$HOME/local"
cd ~
mkdir build
cd build
[ -f Python-3.6.2.tgz ] || wget https://www.python.org/ftp/python/3.6.2/Python-3.6.2.tgz
tar -zxvf Python-3.6.2.tgz

[ -f sqlite-autoconf-3240000.tar.gz ] || wget https://www.sqlite.org/2018/sqlite-autoconf-3240000.tar.gz
tar -zxvf sqlite-autoconf-3240000.tar.gz

cd sqlite-autoconf-3240000
./configure --prefix=${INSTALL_BASE_PATH}
make
make install

cd ../Python-3.6.2
LD_RUN_PATH=${INSTALL_BASE_PATH}/lib configure
LDFLAGS="-L ${INSTALL_BASE_PATH}/lib"
CPPFLAGS="-I ${INSTALL_BASE_PATH}/include"
LD_RUN_PATH=${INSTALL_BASE_PATH}/lib make
./configure --prefix=${INSTALL_BASE_PATH}
make
make install

cd ~
LINE_TO_ADD="export PATH=${INSTALL_BASE_PATH}/bin:\$PATH"
if grep -q -v "${LINE_TO_ADD}" $HOME/.bash_profile; then echo "${LINE_TO_ADD}" >> $HOME/.bash_profile; fi
source $HOME/.bash_profile

Why do this? You might want a modular python environment that you can completely destroy and rebuild without affecting your managed package installation. This would give you an independent development environment. In this case, the solution is to install sqlite3 modularly too.

String strip() for JavaScript?

Use this:

if(typeof(String.prototype.trim) === "undefined")
{
    String.prototype.trim = function() 
    {
        return String(this).replace(/^\s+|\s+$/g, '');
    };
}

The trim function will now be available as a first-class function on your strings. For example:

" dog".trim() === "dog" //true

EDIT: Took J-P's suggestion to combine the regex patterns into one. Also added the global modifier per Christoph's suggestion.

Took Matthew Crumley's idea about sniffing on the trim function prior to recreating it. This is done in case the version of JavaScript used on the client is more recent and therefore has its own, native trim function.

Python unicode equal comparison failed

You may use the == operator to compare unicode objects for equality.

>>> s1 = u'Hello'
>>> s2 = unicode("Hello")
>>> type(s1), type(s2)
(<type 'unicode'>, <type 'unicode'>)
>>> s1==s2
True
>>> 
>>> s3='Hello'.decode('utf-8')
>>> type(s3)
<type 'unicode'>
>>> s1==s3
True
>>> 

But, your error message indicates that you aren't comparing unicode objects. You are probably comparing a unicode object to a str object, like so:

>>> u'Hello' == 'Hello'
True
>>> u'Hello' == '\x81\x01'
__main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
False

See how I have attempted to compare a unicode object against a string which does not represent a valid UTF8 encoding.

Your program, I suppose, is comparing unicode objects with str objects, and the contents of a str object is not a valid UTF8 encoding. This seems likely the result of you (the programmer) not knowing which variable holds unicide, which variable holds UTF8 and which variable holds the bytes read in from a file.

I recommend http://nedbatchelder.com/text/unipain.html, especially the advice to create a "Unicode Sandwich."

document.getElementByID is not a function

I've modified your script to work with jQuery, if you wish to do so.

$(document).ready(function(){
    //To add a task when the user hits the return key
    $('#task-text').keydown(function(evt){
          if(evt.keyCode == 13)
          {
             add_task($(this), evt);
          }
    });
    //To add a task when the user clicks on the submit button
    $("#add-task").click(function(evt){
        add_task($("#task-text"),evt);
    });
});

function add_task(textBox, evt){
  evt.preventDefault();
  var taskText = textBox.val();
  $("<li />").text(taskText).appendTo("#tasks");
  textBox.val("");
};

Event when window.location.href changes

I use this script in my extension "Grab Any Media" and work fine ( like youtube case )

var oldHref = document.location.href;

window.onload = function() {

    var
         bodyList = document.querySelector("body")

        ,observer = new MutationObserver(function(mutations) {

            mutations.forEach(function(mutation) {

                if (oldHref != document.location.href) {

                    oldHref = document.location.href;

                    /* Changed ! your code here */

                }

            });

        });

    var config = {
        childList: true,
        subtree: true
    };

    observer.observe(bodyList, config);

};

How can I exclude $(this) from a jQuery selector?

You can also use the jQuery .siblings() method:

HTML

<div class="content">
  <a href="#">A</a>
  <a href="#">B</a>
  <a href="#">C</a>
</div>

Javascript

$(".content").on('click', 'a', function(e) {
  e.preventDefault();
  $(this).siblings().hide('slow');
});

Working demo: http://jsfiddle.net/wTm5f/

Execute Insert command and return inserted Id in Sql

USE AdventureWorks2012;
GO
IF OBJECT_ID(N't6', N'U') IS NOT NULL 
    DROP TABLE t6;
GO
IF OBJECT_ID(N't7', N'U') IS NOT NULL 
    DROP TABLE t7;
GO
CREATE TABLE t6(id int IDENTITY);
CREATE TABLE t7(id int IDENTITY(100,1));
GO
CREATE TRIGGER t6ins ON t6 FOR INSERT 
AS
BEGIN
   INSERT t7 DEFAULT VALUES
END;
GO
--End of trigger definition

SELECT id FROM t6;
--IDs empty.

SELECT id FROM t7;
--ID is empty.

--Do the following in Session 1
INSERT t6 DEFAULT VALUES;
SELECT @@IDENTITY;
/*Returns the value 100. This was inserted by the trigger.*/

SELECT SCOPE_IDENTITY();
/* Returns the value 1. This was inserted by the 
INSERT statement two statements before this query.*/

SELECT IDENT_CURRENT('t7');
/* Returns value inserted into t7, that is in the trigger.*/

SELECT IDENT_CURRENT('t6');
/* Returns value inserted into t6. This was the INSERT statement four statements before this query.*/

-- Do the following in Session 2.
SELECT @@IDENTITY;
/* Returns NULL because there has been no INSERT action 
up to this point in this session.*/

SELECT SCOPE_IDENTITY();
/* Returns NULL because there has been no INSERT action 
up to this point in this scope in this session.*/

SELECT IDENT_CURRENT('t7');
/* Returns the last value inserted into t7.*/

How do I size a UITextView to its content?

Using UITextViewDelegate is the easiest way:

func textViewDidChange(_ textView: UITextView) {
    textView.sizeToFit()
    textviewHeight.constant = textView.contentSize.height
}

Use IntelliJ to generate class diagram

Try Ctrl+Alt+U

Also check if the UML plugin is activated (settings -> plugin, settings can be opened by Ctrl+Alt+S

How to do a newline in output

I would like to share my experience with \n
I came to notice that "\n" works as-

puts "\n\n" // to provide 2 new lines

but not

p "\n\n"

also puts '\n\n'
Doesn't works.

Hope will work for you!!

Which characters are valid in CSS class names/selectors?

Read the W3C spec. (this is CSS 2.1, find the appropriate version for your assumption of browsers)

edit: relevant paragraph follows:

In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-z0-9] and ISO 10646 characters U+00A1 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, or a hyphen followed by a digit. Identifiers can also contain escaped characters and any ISO 10646 character as a numeric code (see next item). For instance, the identifier "B&W?" may be written as "B\&W\?" or "B\26 W\3F".

edit 2: as @mipadi points out in Triptych's answer, there's this caveat, also in the same webpage:

In CSS, identifiers may begin with '-' (dash) or '_' (underscore). Keywords and property names beginning with '-' or '_' are reserved for vendor-specific extensions. Such vendor-specific extensions should have one of the following formats:

'-' + vendor identifier + '-' + meaningful name 
'_' + vendor identifier + '-' + meaningful name

Example(s):

For example, if XYZ organization added a property to describe the color of the border on the East side of the display, they might call it -xyz-border-east-color.

Other known examples:

 -moz-box-sizing
 -moz-border-radius
 -wap-accesskey

An initial dash or underscore is guaranteed never to be used in a property or keyword by any current or future level of CSS. Thus typical CSS implementations may not recognize such properties and may ignore them according to the rules for handling parsing errors. However, because the initial dash or underscore is part of the grammar, CSS 2.1 implementers should always be able to use a CSS-conforming parser, whether or not they support any vendor-specific extensions.

Authors should avoid vendor-specific extensions

What is a JavaBean exactly?

Java Beans are used for a less code and more work approach...

Java Beans are used throughout Java EE as a universal contract for runtime discovery and access. For example, JavaServer Pages (JSP) uses Java Beans as data transfer objects between pages or between servlets and JSPs. Java EE's JavaBeans Activation Framework uses Java Beans for integrating support for MIME data types into Java EE. The Java EE Management API uses JavaBeans as the foundation for the instrumentation of resources to be managed in a Java EE environment.

About Serialization:

In object serialization an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object.

After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.

How to import a .cer certificate into a java keystore?

Importing .cer certificate file downloaded from browser (open the url and dig for details) into cacerts keystore in java_home\jre\lib\security worked for me, as opposed to attemps to generate and use my own keystore.

  1. Go to your java_home\jre\lib\security
  2. (Windows) Open admin command line there using cmd and CTRL+SHIFT+ENTER
  3. Run keytool to import certificate:
    • (Replace yourAliasName and path\to\certificate.cer respectively)

 ..\..\bin\keytool -import -trustcacerts -keystore cacerts -storepass changeit -noprompt -alias yourAliasName -file path\to\certificate.cer

This way you don't have to specify any additional JVM options and the certificate should be recognized by the JRE.

Android fade in and fade out with ImageView

you can do it by two simple point and change in your code

1.In your xml in anim folder of your project, Set the fade in and fade out duration time not equal

2.In you java class before the start of fade out animation, set second imageView visibility Gone then after fade out animation started set second imageView visibility which you want to fade in visible

fadeout.xml

<alpha
    android:duration="4000"
    android:fromAlpha="1.0"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:toAlpha="0.0" />

fadein.xml

<alpha
    android:duration="6000"
    android:fromAlpha="0.0"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:toAlpha="1.0" />

In you java class

Animation animFadeOut = AnimationUtils.loadAnimation(this, R.anim.fade_out);
    ImageView iv = (ImageView) findViewById(R.id.imageView1);
    ImageView iv2 = (ImageView) findViewById(R.id.imageView2);
    iv.setVisibility(View.VISIBLE);
    iv2.setVisibility(View.GONE);
    animFadeOut.reset();
    iv.clearAnimation();
    iv.startAnimation(animFadeOut);

    Animation animFadeIn = AnimationUtils.loadAnimation(this, R.anim.fade_in);
    iv2.setVisibility(View.VISIBLE);
    animFadeIn.reset();
    iv2.clearAnimation();
    iv2.startAnimation(animFadeIn);

Check if date is a valid one

var date = moment('2016-10-19', 'DD-MM-YYYY', true);

You should add a third argument when invoking moment that enforces strict parsing. Here is the relevant portion of the moment documentation http://momentjs.com/docs/#/parsing/string-format/ It is near the end of the section.

laravel Unable to prepare route ... for serialization. Uses Closure

check that your web.php file has this extension

use Illuminate\Support\Facades\Route;

my problem gone fixed by this way.

PHP - Getting the index of a element from a array

function Index($index) {
    $Count = count($YOUR_ARRAY);
    if ($index <= $Count) {
        $Keys = array_keys($YOUR_ARRAY);
        $Value = array_values($YOUR_ARRAY);
        return $Keys[$index] . ' = ' . $Value[$index];
    } else {
        return "Out of the ring";
    }
}

echo 'Index : ' . Index(0);

Replace the ( $YOUR_ARRAY )

Psexec "run as (remote) admin"

Use psexec -s

The s switch will cause it to run under system account which is the same as running an elevated admin prompt. just used it to enable WinRM remotely.

css selector to match an element without attribute x

For a more cross-browser solution you could style all inputs the way you want the non-typed, text, and password then another style the overrides that style for radios, checkboxes, etc.

input { border:solid 1px red; }

input[type=radio], 
input[type=checkbox], 
input[type=submit], 
input[type=reset], 
input[type=file] 
      { border:none; }

- Or -

could whatever part of your code that is generating the non-typed inputs give them a class like .no-type or simply not output at all? Additionally this type of selection could be done with jQuery.

Find value in an array

If you want find one value from array, use Array#find:

arr = [1,2,6,4,9] 
arr.find {|e| e % 3 == 0}   #=>  6

See also:

arr.select {|e| e % 3 == 0} #=> [ 6, 9 ]
e.include? 6              #=> true

To find if a value exists in an Array you can also use #in? when using ActiveSupport. #in? works for any object that responds to #include?:

arr = [1, 6]
6.in? arr                 #=> true

Going to a specific line number using Less in Unix

With n being the line number:

  • ng: Jump to line number n. Default is the start of the file.
  • nG: Jump to line number n. Default is the end of the file.

So to go to line number 320123, you would type 320123g.

Copy-pasted straight from Wikipedia.

is there any IE8 only css hack?

So a recent question prompted me to notice a selector set hack for excluding IE 8 only.

.selector, #excludeIE8::before {} will cause IE 8 to throw out the entire selector set, while 5-7 and 9-11 will read it just fine. Any of the :: selectors (::first-line, ::before, ::first-letter, ::selection) will work, I've merely chosen ::before so the line reads accurately. Note that the goal of the fake ::before selector is to be fake, so be sure to change it to something else if you actually have an element with the ID excludeIE8

Interestingly enough, in modern browsers (FF 45-52, GC 49-57, Edge 25/13) a bad :: selector eats the entire selector set (dabblet demo). It seems that the last Windows version of Safari (and LTE IE 7, lol) doesn't have this behavior while still understanding ::before. Additionally, I can't find anything in the spec to indicate that this is intended behavior, and since it would cause breakage on any selector set containing: ::future-legitimate-pseudoelement... I'm inclined to say this is a bug- and one that'll nibble our rears in the future.


However, if you only want something at the property level (rather than the rule level), Ziga above had the best solution via appending  \9 (the space is key; do NOT copypaste that inline as it uses an nbsp):

/*property-level hacks:*/
/*Standards, Edge*/
prop:val;
/*lte ie 11*/
prop:val\9;
/*lte ie 8*/
prop:val \9;
/*lte ie 7*/
*prop:val;
/*lte ie 6*/
_prop:val;

/*other direction...*/
/*gte ie 8, NOT Edge*/
prop:val\0;

Side note, I feel like a dirty necromancer- but I wanted somewhere to document the exclude-IE8-only selector set hack I found today, and this seemed to be the most fitting place.

What is the full path to the Packages folder for Sublime text 2 on Mac OS Lion

You can browse package folder below method.

  1. Use Sublime Text 2 menu : Preferences\Browse Packages
  2. In Windows 7 : C:\Users\%username%\AppData\Roaming\Sublime Text 2\Packages (equals %appdata%\Sublime Text 2\Packages)

MATLAB, Filling in the area between two sets of data, lines in one figure

You can accomplish this using the function FILL to create filled polygons under the sections of your plots. You will want to plot the lines and polygons in the order you want them to be stacked on the screen, starting with the bottom-most one. Here's an example with some sample data:

x = 1:100;             %# X range
y1 = rand(1,100)+1.5;  %# One set of data ranging from 1.5 to 2.5
y2 = rand(1,100)+0.5;  %# Another set of data ranging from 0.5 to 1.5
baseLine = 0.2;        %# Baseline value for filling under the curves
index = 30:70;         %# Indices of points to fill under

plot(x,y1,'b');                              %# Plot the first line
hold on;                                     %# Add to the plot
h1 = fill(x(index([1 1:end end])),...        %# Plot the first filled polygon
          [baseLine y1(index) baseLine],...
          'b','EdgeColor','none');
plot(x,y2,'g');                              %# Plot the second line
h2 = fill(x(index([1 1:end end])),...        %# Plot the second filled polygon
          [baseLine y2(index) baseLine],...
          'g','EdgeColor','none');
plot(x(index),baseLine.*ones(size(index)),'r');  %# Plot the red line

And here's the resulting figure:

enter image description here

You can also change the stacking order of the objects in the figure after you've plotted them by modifying the order of handles in the 'Children' property of the axes object. For example, this code reverses the stacking order, hiding the green polygon behind the blue polygon:

kids = get(gca,'Children');        %# Get the child object handles
set(gca,'Children',flipud(kids));  %# Set them to the reverse order

Finally, if you don't know exactly what order you want to stack your polygons ahead of time (i.e. either one could be the smaller polygon, which you probably want on top), then you could adjust the 'FaceAlpha' property so that one or both polygons will appear partially transparent and show the other beneath it. For example, the following will make the green polygon partially transparent:

set(h2,'FaceAlpha',0.5);

Repeat-until or equivalent loop in Python

REPEAT
    ...
UNTIL cond

Is equivalent to

while True:
    ...
    if cond:
        break

What is the difference between match_parent and fill_parent?

Both, FILL_PARENT and MATCH_PARENT are the same properties. FILL_PARENT was deprecated in API level 8.

Java NIO: What does IOException: Broken pipe mean?

You should assume the socket was closed on the other end. Wrap your code with a try catch block for IOException.

You can use isConnected() to determine if the SocketChannel is connected or not, but that might change before your write() invocation finishes. Try calling it in your catch block to see if in fact this is why you are getting the IOException.

Querying a linked sql server

SELECT * FROM [server].[database].[schema].[table]

This works for me. SSMS intellisense may still underline this as a syntax error, but it should work if your linked server is configured and your query is otherwise correct.

How to fill Matrix with zeros in OpenCV?

You can choose filling zero data or create zero Mat.

  1. Filling zero data with setTo():

    img.setTo(Scalar::all(0));
    
  2. Create zero data with zeros():

    img = zeros(img.size(), img.type());
    

The img changes address of memory.

Open PDF in new browser full window

var pdf = MyPdf.pdf;
window.open(pdf);

This will open the pdf document in a full window from JavaScript

A function to open windows would look like this:

function openPDF(pdf){
  window.open(pdf);
  return false;
}

SQL, How to Concatenate results?

Small update on Marc we will have additional " , " at the end. i used stuff function to remove extra semicolon .

       SELECT STUFF((  SELECT ',' + ModuleValue AS ModuleValue
                           FROM ModuleValue WHERE ModuleID=@ModuleID
                      FOR XML PATH('') 
                     ), 1, 1, '' )

How to add a list item to an existing unordered list?

jQuery comes with the following options which could fulfil your need in this case:

append is used to add an element at the end of the parent div specified in the selector:

$('ul.tabs').append('<li>An element</li>');

prepend is used to add an element at the top/start of the parent div specified in the selector:

$('ul.tabs').prepend('<li>An element</li>');

insertAfter lets you insert an element of your selection next after an element you specify. Your created element will then be put in the DOM after the specified selector closing tag:

$('<li>An element</li>').insertAfter('ul.tabs>li:last');
will result in:
<li><a href="/user/edit"><span class="tab">Edit</span></a></li>
<li>An element</li>

insertBefore will do the opposite of the above:

$('<li>An element</li>').insertBefore('ul.tabs>li:last');
will result in:
<li>An element</li>
<li><a href="/user/edit"><span class="tab">Edit</span></a></li>

How to get the hours difference between two date objects?

Try using getTime (mdn doc) :

var diff = Math.abs(date1.getTime() - date2.getTime()) / 3600000;
if (diff < 18) { /* do something */ }

Using Math.abs() we don't know which date is the smallest. This code is probably more relevant :

var diff = (date1 - date2) / 3600000;
if (diff < 18) { array.push(date1); }

Creating Dynamic button with click event in JavaScript

<!DOCTYPE html>
<html>
<body>

<p>Click the button to make a BUTTON element with text.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    var btn = document.createElement("BUTTON");
    var t = document.createTextNode("CLICK ME");

    btn.setAttribute("style","color:red;font-size:23px");

    btn.appendChild(t);
    document.body.appendChild(btn);

    btn.setAttribute("onclick", alert("clicked"));

}
</script>

</body>
</html>

How to create json by JavaScript for loop?

var sels = //Here is your array of SELECTs
var json = { };

for(var i = 0, l = sels.length; i < l; i++) {
  json[sels[i].id] = sels[i].value;
}

SQL select max(date) and corresponding value

There's no easy way to do this, but something like this will work:

SELECT ET.TrainingID, 
  ET.CompletedDate, 
  ET.Notes
FROM 
HR_EmployeeTrainings ET
inner join
(
  select TrainingID, Max(CompletedDate) as CompletedDate
  FROM HR_EmployeeTrainings
  WHERE (ET.AvantiRecID IS NULL OR ET.AvantiRecID = @avantiRecID)
  GROUP BY AvantiRecID, TrainingID  
) ET2 
  on ET.TrainingID = ET2.TrainingID
  and ET.CompletedDate = ET2.CompletedDate

Passing an array as an argument to a function in C

When passing an array as a parameter, this

void arraytest(int a[])

means exactly the same as

void arraytest(int *a)

so you are modifying the values in main.

For historical reasons, arrays are not first class citizens and cannot be passed by value.

Unable to create/open lock file: /data/mongod.lock errno:13 Permission denied

On a Fedora 18 with Mongo 2.2.4 instance I was able to get around a similar error by disabling SELinux by calling setenforce 0 as root.

BTW, this was a corporate environment, not an Amazon EC2 instance, but the symptoms were similar.

Changing plot scale by a factor in matplotlib

Instead of changing the ticks, why not change the units instead? Make a separate array X of x-values whose units are in nm. This way, when you plot the data it is already in the correct format! Just make sure you add a xlabel to indicate the units (which should always be done anyways).

from pylab import *

# Generate random test data in your range
N = 200
epsilon = 10**(-9.0)
X = epsilon*(50*random(N) + 1)
Y = random(N)

# X2 now has the "units" of nanometers by scaling X
X2 = (1/epsilon) * X

subplot(121)
scatter(X,Y)
xlim(epsilon,50*epsilon)
xlabel("meters")

subplot(122)
scatter(X2,Y)
xlim(1, 50)
xlabel("nanometers")

show()

enter image description here

make a phone call click on a button

For those using AppCompact...Try this

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.net.Uri;

public class MainActivity extends AppCompatActivity {



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button startBtn = (Button) findViewById(R.id.db);
        startBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                makeCall();
            }
        });

    }

    protected void makeCall() {
        EditText num = (EditText)findViewById(R.id.Dail);
        String phone = num.getText().toString();
        String d = "tel:" + phone ;
        Log.i("Make call", "");
        Intent phoneIntent = new Intent(Intent.ACTION_CALL);
        phoneIntent.setData(Uri.parse(d));
        try {
            startActivity(phoneIntent);
            finish();
            Log.i("Finished making a call", "");
        } catch (android.content.ActivityNotFoundException ex) {
            Toast.makeText(this, "Call faild, please try again later.", Toast.LENGTH_SHORT).show();
        }
    }

}

Then add this to your manifest,,,

 <uses-permission android:name="android.permission.CALL_PHONE" />

How do I select which GPU to run a job on?

In case of someone else is doing it in Python and it is not working, try to set it before do the imports of pycuda and tensorflow.

I.e.:

import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
...
import pycuda.autoinit
import tensorflow as tf
...

As saw here.

What does \u003C mean?

That is a unicode character code that, when parsed by JavaScript as a string, is converted into its corresponding character (JavaScript automatically converts any occurrences of \uXXXX into the corresponding Unicode character). For example, your example would be:

Browse Interests{{/i}}</a>\n        </li>\n  {{#logged_in}}\n

As you can see, \u003C changes into < (less-than sign) and \u003E changes into > (greater-than sign).

In addition to the link posted by Raynos, this page from the Unicode website lists a lot of characters (so many that they decided to annoyingly group them) and this page has a (kind of) nice index.

How to center canvas in html5

To center the canvas element horizontally, you must specify it as a block level and leave its left and right margin properties to the browser:

canvas{
    margin-right: auto;
    margin-left: auto;
    display: block;
}

If you wanted to center it vertically, the canvas element needs to be absolutely positioned:

canvas{
    position: absolute;
    top: 50%;
    transform: translate(0, -50%);              
}

If you wanted to center it horizontally and vertically, do:

canvas{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);               
}

For more info visit: https://www.w3.org/Style/Examples/007/center.en.html

Clicking submit button of an HTML form by a Javascript code

document.getElementById('loginSubmit').submit();

or, use the same code as the onclick handler:

changeAction('submitInput','loginForm');
document.forms['loginForm'].submit();

(Though that onclick handler is kind of stupidly-written: document.forms['loginForm'] could be replaced with this.)

ESRI : Failed to parse source map

Further to just simply turning off Source Maps in Chrome - I've done a little digging and found that using Web Essentials to create the source maps seems to be the issue.

For whatever reason, if I use an external compiler (Koala) I can successfully create working source maps in Chrome (no errors). Whereas if I use Web Essentials, the source maps fail to parse.

Hope this helps someone.

How to Set Focus on JTextField?

public void actionPerformed(ActionEvent arg0)
{
    if (arg0.getSource()==clearButton)
    {
        enterText.setText(null);
        enterText.grabFocus();  //Places flashing cursor on text box        
    }       
}

How to step through Python code to help debug issues?

If you come from Java/C# background I guess your best bet would be to use Eclipse with Pydev. This gives you a fully functional IDE with debugger built in. I use it with django as well.

What is the "N+1 selects problem" in ORM (Object-Relational Mapping)?

Without going into tech stack implementation details, architecturally speaking there are at least two solutions to N + 1 Problem:

  • Have Only 1 - big query - with Joins. This makes a lot of information be transported from the database to the application layer, especially if there are multiple child records. The typical result of a database is a set of rows, not graph of objects (there are solutions to that with different DB systems)
  • Have Two(or more for more children needed to be joined) Queries - 1 for the parent and after you have them - query by IDs the children and map them. This will minimize data transfer between the DB and APP layers.

Linq to SQL how to do "where [column] in (list of values)"

Here is how I do it by using HashSet

        HashSet<String> hs = new HashSet<string>(new String[] { "Pluto", "Earth", "Neptune" });
        String[] arr =
        {
            "Pluto",
            "Earth",
            "Neptune",
            "Jupiter",
            "Saturn",
            "Mercury",
            "Pluto",
            "Earth",
            "Neptune",
            "Jupiter",
            "Saturn",
            "Mercury",
            // etc.
        };
        ICollection<String> coll = arr;

        String[] arrStrFiltered = coll.Where(str => hs.Contains(str)).ToArray();

HashSet is basically almost to O(1) so your complexity remains O(n).

OWIN Security - How to Implement OAuth2 Refresh Tokens

Freddy's answer helped me a lot to get this working. For the sake of completeness here's how you could implement hashing of the token:

private string ComputeHash(Guid input)
{
    byte[] source = input.ToByteArray();

    var encoder = new SHA256Managed();
    byte[] encoded = encoder.ComputeHash(source);

    return Convert.ToBase64String(encoded);
}

In CreateAsync:

var guid = Guid.NewGuid();
...
_refreshTokens.TryAdd(ComputeHash(guid), refreshTokenTicket);
context.SetToken(guid.ToString());

ReceiveAsync:

public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
{
    Guid token;

    if (Guid.TryParse(context.Token, out token))
    {
        AuthenticationTicket ticket;

        if (_refreshTokens.TryRemove(ComputeHash(token), out ticket))
        {
            context.SetTicket(ticket);
        }
    }
}

How can I develop for iPhone using a Windows development machine?

You can use WinChain

Quoting the project page:

It's the easiest way to build the iPhone toolchain on a Windows XP/Vista computer, which in turn, can take Objective-C source code that you write using their UIKit Headers (included with winChain) and compile it into an application that you can use on your iPhone.

Execute jar file with multiple classpath libraries from command prompt

a possible solution could be

create a batch file

there do a loop on lib directory for all files inside it and set each file unside lib on classpath

then after that run the jar

source for loop in batch file for info on loops

Python regex findall

Try this :

   for match in re.finditer(r"\[P[^\]]*\](.*?)\[/P\]", subject):
        # match start: match.start()
        # match end (exclusive): match.end()
        # matched text: match.group()

Java Enum Methods - return opposite direction enum

Create an abstract method, and have each of your enumeration values override it. Since you know the opposite while you're creating it, there's no need to dynamically generate or create it.

It doesn't read nicely though; perhaps a switch would be more manageable?

public enum Direction {
    NORTH(1) {
        @Override
        public Direction getOppositeDirection() {
            return Direction.SOUTH;
        }
    },
    SOUTH(-1) {
        @Override
        public Direction getOppositeDirection() {
            return Direction.NORTH;
        }
    },
    EAST(-2) {
        @Override
        public Direction getOppositeDirection() {
            return Direction.WEST;
        }
    },
    WEST(2) {
        @Override
        public Direction getOppositeDirection() {
            return Direction.EAST;
        }
    };

    Direction(int code){
        this.code=code;
    }
    protected int code;

    public int getCode() {
        return this.code;
    }

    public abstract Direction getOppositeDirection();
}

How to prevent a click on a '#' link from jumping to top of page?

In jQuery, when you handle the click event, return false to stop the link from responding the usual way prevent the default action, which is to visit the href attribute, from taking place (per PoweRoy's comment and Erik's answer):

$('a.someclass').click(function(e)
{
    // Special stuff to do when this link is clicked...

    // Cancel the default action
    e.preventDefault();
});

PHP include relative path

function relativepath($to){
    $a=explode("/",$_SERVER["PHP_SELF"] );
    $index= array_search("$to",$a);
    $str=""; 
    for ($i = 0; $i < count($a)-$index-2; $i++) {
        $str.= "../";
    }
    return $str;
    }

Here is the best solution i made about that, you just need to specify at which level you want to stop, but the problem is that you have to use this folder name one time.

Python 3 - Encode/Decode vs Bytes/Str

To add to Lennart Regebro's answer There is even the third way that can be used:

encoded3 = str.encode(original, 'utf-8')
print(encoded3)

Anyway, it is actually exactly the same as the first approach. It may also look that the second way is a syntactic sugar for the third approach.


A programming language is a means to express abstract ideas formally, to be executed by the machine. A programming language is considered good if it contains constructs that one needs. Python is a hybrid language -- i.e. more natural and more versatile than pure OO or pure procedural languages. Sometimes functions are more appropriate than the object methods, sometimes the reverse is true. It depends on mental picture of the solved problem.

Anyway, the feature mentioned in the question is probably a by-product of the language implementation/design. In my opinion, this is a nice example that show the alternative thinking about technically the same thing.

In other words, calling an object method means thinking in terms "let the object gives me the wanted result". Calling a function as the alternative means "let the outer code processes the passed argument and extracts the wanted value".

The first approach emphasizes the ability of the object to do the task on its own, the second approach emphasizes the ability of an separate algoritm to extract the data. Sometimes, the separate code may be that much special that it is not wise to add it as a general method to the class of the object.

How can I use interface as a C# generic type constraint?

I know this is a bit late but for those that are interested you can use a runtime check.

typeof(T).IsInterface

What does "use strict" do in JavaScript, and what is the reasoning behind it?

I would like to offer a somewhat more founded answer complementing the other answers. I was hoping to edit the most popular answer, but failed. I tried to make it as comprehensive and complete as I could.

You can refer to the MDN documentation for more information.

"use strict" a directive introduced in ECMAScript 5.

Directives are similar to statements, yet different.

  • use strict does not contain key words: The directive is a simple expression statement, which consists of a special string literal (in single or double quotes). JavaScript engines, that do not implement ECMAScript 5, merely see an expression statement without side effects. It is expected that future versions of ECMAScript standards introduce use as a real key word; the quotes would thereby become obsolete.
  • use strict can be used only at the beginning of a script or of a function, i.e. it must precede every other (real) statement. It does not have to be the first instruction in a script of function: it can be preceded by other statement expressions that consist of string literals ( and JavaScript implementations can treat them as implementation specific directives). String literals statements, which follow a first real statement (in a script or function) are simple expression statements. Interpreters must not interpret them as directives and they have no effect.

The use strict directive indicates that the following code (in a script or a function) is strict code. The code in the highest level of a script (code that is not in a function) is considered strict code when the script contains a use strict directive. The content of a function is considered strict code when the function itself is defined in a strict code or when the function contains a use strict directive. Code that is passed to an eval() method is considered strict code when eval() was called from a strict code or contains the use strict directive itself.

The strict mode of ECMAScript 5 is a restricted subset of the JavaScript language, which eliminates relevant deficits of the language and features more stringent error checking and higher security. The following lists the differences between strict mode and normal mode (of which the first three are particularly important):

  • You cannot use the with-statement in strict mode.
  • In strict mode all variables have to be declared: if you assign a value to an identifier that has not been declared as variable, function, function parameter, catch-clause parameter or property of the global Object, then you will get a ReferenceError. In normal mode the identifier is implicitly declared as a global variable (as a property of the global Object)
  • In strict mode the keyword this has the value undefined in functions that were invoked as functions (not as methods). (In normal mode this always points to the global Object). This difference can be used to test if an implementation supports the strict mode:
var hasStrictMode = (function() { "use strict"; return this===undefined }());
  • Also when a function is invoked with call() or apply in strict mode, then this is exactly the value of the first argument of the call()or apply() invocation. (In normal mode null and undefined are replaced by the global Object and values, which are not objects, are cast into objects.)

  • In strict mode you will get a TypeError, when you try to assign to readonly properties or to define new properties for a non extensible object. (In normal mode both simply fail without error message.)

  • In strict mode, when passing code to eval(), you cannot declare or define variables or functions in the scope of the caller (as you can do it in normal mode). Instead, a new scope is created for eval() and the variables and functions are within that scope. That scope is destroyed after eval() finishes execution.
  • In strict mode the arguments-object of a function contains a static copy of the values, which are passed to that function. In normal mode the arguments-object has a somewhat "magical" behaviour: The elements of the array and the named function parameters reference both the same value.
  • In strict mode you will get a SyntaxError when the delete operator is followed by a non qualified identifier (a variable, function or function parameter). In normal mode the delete expression would do nothing and is evaluated to false.
  • In strict mode you will get a TypeError when you try to delete a non configurable property. (In normal mode the attempt simply fails and the delete expression is evaluated to false).
  • In strict mode it is considered a syntactical error when you try to define several properties with the same name for an object literal. (In normal mode there is no error.)
  • In strict mode it is considered a syntactical error when a function declaration has multiple parameters with the same name. (In normal mode there is no error.)
  • In strict mode octal literals are not allowed (these are literals that start with 0x. (In normal mode some implementations do allow octal literals.)
  • In strict mode the identifiers eval and arguments are treated like keywords. You cannot change their value, cannot assign a value to them, and you cannot use them as names for variables, functions, function parameters or identifiers of a catch block.
  • In strict mode are more restrictions on the possibilities to examine the call stack. arguments.caller and arguments.callee cause a TypeError in a function in strict mode. Furthermore, some caller- and arguments properties of functions in strict mode cause a TypeError when you try to read them.

Fastest way to remove first char in a String

You could profile it, if you really cared. Write a loop of many iterations and see what happens. Chances are, however, that this is not the bottleneck in your application, and TrimStart seems the most semantically correct. Strive to write code readably before optimizing.

Encrypt & Decrypt using PyCrypto AES 256

from Crypto import Random
from Crypto.Cipher import AES
import base64

BLOCK_SIZE=16
def trans(key):
     return md5.new(key).digest()

def encrypt(message, passphrase):
    passphrase = trans(passphrase)
    IV = Random.new().read(BLOCK_SIZE)
    aes = AES.new(passphrase, AES.MODE_CFB, IV)
    return base64.b64encode(IV + aes.encrypt(message))

def decrypt(encrypted, passphrase):
    passphrase = trans(passphrase)
    encrypted = base64.b64decode(encrypted)
    IV = encrypted[:BLOCK_SIZE]
    aes = AES.new(passphrase, AES.MODE_CFB, IV)
    return aes.decrypt(encrypted[BLOCK_SIZE:])

Uninstall old versions of Ruby gems

Way to clean out any old versions of gems.

sudo gem cleanup

If you just want to see a list of what would be removed you can use:

sudo gem cleanup -d

You can also cleanup just a specific gem by specifying its name:

sudo gem cleanup gemname

for remove specific version like 1.1.9 only

gem uninstall gemname --version 1.1.9

If you still facing some exception to install gem, like:

invalid gem: package is corrupt, exception while verifying: undefined method `size' for nil:NilClass (NoMethodError) in /home/rails/.rvm/gems/ruby-2.1.1@project/cache/nokogiri-1.6.6.2.gem

the, you can remove it from cache:

rm /home/rails/.rvm/gems/ruby-2.1.1@project/cache/nokogiri-1.6.6.2.gem

For more detail:

http://blog.grepruby.com/2015/04/way-to-clean-up-gem-or-remove-old.html

Convert an integer to a byte array

I agree with Brainstorm's approach: assuming that you're passing a machine-friendly binary representation, use the encoding/binary library. The OP suggests that binary.Write() might have some overhead. Looking at the source for the implementation of Write(), I see that it does some runtime decisions for maximum flexibility.

func Write(w io.Writer, order ByteOrder, data interface{}) error {
    // Fast path for basic types.
    var b [8]byte
    var bs []byte
    switch v := data.(type) {
    case *int8:
        bs = b[:1]
        b[0] = byte(*v)
    case int8:
        bs = b[:1]
        b[0] = byte(v)
    case *uint8:
        bs = b[:1]
        b[0] = *v
    ...

Right? Write() takes in a very generic data third argument, and that's imposing some overhead as the Go runtime then is forced into encoding type information. Since Write() is doing some runtime decisions here that you simply don't need in your situation, maybe you can just directly call the encoding functions and see if it performs better.

Something like this:

package main

import (
    "encoding/binary"
    "fmt"
)

func main() {
    bs := make([]byte, 4)
    binary.LittleEndian.PutUint32(bs, 31415926)
    fmt.Println(bs)
}

Let us know how this performs.

Otherwise, if you're just trying to get an ASCII representation of the integer, you can get the string representation (probably with strconv.Itoa) and cast that string to the []byte type.

package main

import (
    "fmt"
    "strconv"
)

func main() {
    bs := []byte(strconv.Itoa(31415926))
    fmt.Println(bs)
}

How to create streams from string in Node.Js?

Heres a tidy solution in TypeScript:

import { Readable } from 'stream'

class ReadableString extends Readable {
    private sent = false

    constructor(
        private str: string
    ) {
        super();
    }

    _read() {
        if (!this.sent) {
            this.push(Buffer.from(this.str));
            this.sent = true
        }
        else {
            this.push(null)
        }
    }
}

const stringStream = new ReadableString('string to be streamed...')