Programs & Examples On #Rtp

The Real-time Transport Protocol (RTP) defines a standardized packet format for delivering audio and video over IP networks.

Streaming via RTSP or RTP in HTML5

There are three streaming protocols / technology in HTML5:

Live streaming, low latency - WebRTC - Websocket

VOD and Live streaming, high latency - HLS

1. WebRTC

In fact WebRTC is SRTP(secure RTP protocol). Thus we can say that video tag supports RTP(SRTP) indirectly via WebRTC.

Therefore to get RTP stream on your Chrome, Firefox or another HTML5 browser, you need a WebRTC server which will deliver the SRTP stream to browser.

2. Websocket

It is TCP based, but with lower latency than HLS. Again you need a Websocket server.

3. HLS

Most popular high-latency streaming protocol for VOD(pre-recorded video).

What is the difference between RTP or RTSP in a streaming server?

RTSP (actually RTP) can be used for streaming video, but also many other types of media including live presentations. Rtsp is just the protocol used to setup the RTP session.

For all the details you can check out my open source RTSP Server implementation on the following address:

Or my article @

It supports re-sourcing streams as well as the dynamic creation of streams, various RFC's are implemented and the library achieves better performance and less memory then FFMPEG and just about any other solutions in the transport layer and thus makes it a good candidate to use as a centralized point of access for most scenarios.

How to add checkboxes to JTABLE swing

1) JTable knows JCheckbox with built-in Boolean TableCellRenderers and TableCellEditor by default, then there is contraproductive declare something about that,

2) AbstractTableModel should be useful, where is in the JTable required to reduce/restrict/change nested and inherits methods by default implemented in the DefaultTableModel,

3) consider using DefaultTableModel, (if you are not sure about how to works) instead of AbstractTableModel,


could be generated from simple code:

import javax.swing.*;
import javax.swing.table.*;

public class TableCheckBox extends JFrame {

    private static final long serialVersionUID = 1L;
    private JTable table;

    public TableCheckBox() {
        Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
        Object[][] data = {
            {"Buy", "IBM", new Integer(1000), new Double(80.50), false},
            {"Sell", "MicroSoft", new Integer(2000), new Double(6.25), true},
            {"Sell", "Apple", new Integer(3000), new Double(7.35), true},
            {"Buy", "Nortel", new Integer(4000), new Double(20.00), false}
        DefaultTableModel model = new DefaultTableModel(data, columnNames);
        table = new JTable(model) {

            private static final long serialVersionUID = 1L;

            public Class getColumnClass(int column) {
            return getValueAt(0, column).getClass();
            public Class getColumnClass(int column) {
                switch (column) {
                    case 0:
                        return String.class;
                    case 1:
                        return String.class;
                    case 2:
                        return Integer.class;
                    case 3:
                        return Double.class;
                        return Boolean.class;
        JScrollPane scrollPane = new JScrollPane(table);

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                TableCheckBox frame = new TableCheckBox();
                frame.setLocation(150, 150);

Why isn't sizeof for a struct equal to the sum of sizeof of each member?

In addition to the other answers, a struct can (but usually doesn't) have virtual functions, in which case the size of the struct will also include the space for the vtbl.

Round up to Second Decimal Place in Python

Updated answer:
The problem with my original answer, as pointed out in the comments by @jpm, is the behavior at the boundaries. Python 3 makes this even more difficult since it uses "bankers" rounding instead of "old school" rounding. However, in looking into this issue I discovered an even better solution using the decimal library.

import decimal

def round_up(x, place=0):
    context = decimal.getcontext()
    # get the original setting so we can put it back when we're done
    original_rounding = context.rounding
    # change context to act like ceil()
    context.rounding = decimal.ROUND_CEILING

    rounded = round(decimal.Decimal(str(x)), place)
    context.rounding = original_rounding
    return float(rounded)

Or if you really just want a one-liner:

import decimal
decimal.getcontext().rounding = decimal.ROUND_CEILING

# here's the one-liner
float(round(decimal.Decimal(str(0.1111)), ndigits=2))
>> 0.12

# Note: this only affects the rounding of `Decimal`
round(0.1111, ndigits=2)
>> 0.11

Here are some examples:

round_up(0.022499999999999999, 2)
>> 0.03
round_up(0.1111111111111000, 2)
>> 0.12
round_up(0.1111111111111000, 3)
>> 0.112

>> 4.0

# @jpm - boundaries do what we want
round_up(0.1, 2)
>> 0.1
round_up(1.1, 2)
>> 1.1

# Note: this still rounds toward `inf`, not "away from zero"
round_up(2.049, 2)
>> 2.05
round_up(-2.0449, 2)
>> -2.04

We can use it to round to the left of the decimal as well:

round_up(11, -1)
>> 20

We don't multiply by 10, thereby avoiding the overflow mentioned in this answer.

round_up(1.01e308, -307)
>> 1.1e+308

Original Answer (Not recommended):
This depends on the behavior you want when considering positive and negative numbers, but if you want something that always rounds to a larger value (e.g. 2.0449 -> 2.05, -2.0449 -> -2.04) then you can do:

round(x + 0.005, 2)

or a little fancier:

def round_up(x, place):
    return round(x + 5 * 10**(-1 * (place + 1)), place)

This also seems to work as follows:

round(144, -1)
# 140
round_up(144, -1)
# 150
round_up(1e308, -307)
# 1.1e308

How to vertical align an inline-block in a line of text?

display: inline-block is your friend you just need all three parts of the construct - before, the "block", after - to be one, then you can vertically align them all to the middle:

Working Example

(it looks like your picture anyway ;))


p, div {
  display: inline-block; 
  vertical-align: middle;
p, div {
  display: inline !ie7; /* hack for IE7 and below */

table {
  background: #000; 
  color: #fff; 
  font-size: 16px; 
  font-weight: bold; margin: 0 10px;

td {
  padding: 5px; 
  text-align: center;


<p>some text</p> 
  <table summary="">
<p>continues afterwards</p>

OpenCV Python rotate image by X degrees around specific point

Quick tweak to @alex-rodrigues answer... deals with shape including the number of channels.

import cv2
import numpy as np

def rotateImage(image, angle):
    rot_mat = cv2.getRotationMatrix2D(center,angle,1.0)
    return cv2.warpAffine(image, rot_mat, image.shape[0:2],flags=cv2.INTER_LINEAR)

What's the difference between SoftReference and WeakReference in Java?

SoftReference is designed for caches. When it is found that a WeakReference references an otherwise unreachable object, then it will get cleared immediately. SoftReference may be left as is. Typically there is some algorithm relating to the amount of free memory and the time last used to determine whether it should be cleared. The current Sun algorithm is to clear the reference if it has not been used in as many seconds as there are megabytes of memory free on the Java heap (configurable, server HotSpot checks against maximum possible heap as set by -Xmx). SoftReferences will be cleared before OutOfMemoryError is thrown, unless otherwise reachable.

Write single CSV file using spark-csv

import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.fs._
import org.apache.spark.sql.{DataFrame,SaveMode,SparkSession}
import org.apache.spark.sql.functions._

I solved using below approach (hdfs rename file name):-

Step 1:- (Crate Data Frame and write to HDFS)

df.coalesce(1).write.format("csv").option("header", "false").mode(SaveMode.Overwrite).save("/hdfsfolder/blah/")

Step 2:- (Create Hadoop Config)

val hadoopConfig = new Configuration()
val hdfs = FileSystem.get(hadoopConfig)

Step3 :- (Get path in hdfs folder path)

val pathFiles = new Path("/hdfsfolder/blah/")

Step4:- (Get spark file names from hdfs folder)

val fileNames = hdfs.listFiles(pathFiles, false)

setp5:- (create scala mutable list to save all the file names and add it to the list)

    var fileNamesList = scala.collection.mutable.MutableList[String]()
    while (fileNames.hasNext) {
      fileNamesList +=

Step 6:- (filter _SUCESS file order from file names scala list)

    // get files name which are not _SUCCESS
    val partFileName = fileNamesList.filterNot(filenames => filenames == "_SUCCESS")

step 7:- (convert scala list to string and add desired file name to hdfs folder string and then apply rename)

val partFileSourcePath = new Path("/yourhdfsfolder/"+ partFileName.mkString(""))
    val desiredCsvTargetPath = new Path(/yourhdfsfolder/+ "op_"+ ".csv")
    hdfs.rename(partFileSourcePath , desiredCsvTargetPath)

Using Enum values as String literals

You can use however you often don't need to do this.

Mode mode =
System.out.println("The mode is "+mode);

How prevent CPU usage 100% because of worker process in iis

There are a lot of reasons that you can be seeing w3wp.exe high CPU usage. I have selected six common causes to cover.

  1. High error rates within your ASP.NET web application
  2. Increase in web traffic causing high CPU
  3. Problems with application dependencies
  4. Garbage collection
  5. Requests getting blocked or hung somewhere in the ASP.NET pipeline
  6. Inefficient .NET code that needs to be optimized

How do I read input character-by-character in Java?

In java 5 new feature added that is Scanner method who gives the chance to read input character by character in java.

for instance; for use Scanner method import java.util.Scanner; after in main method:define

Scanner myScanner = new Scanner(; //for read character

char anything=myScanner.findInLine(".").charAt(0);

you anything store single character, if you want more read more character declare more object like anything1,anything2... more example for your answer please check in your hand(copy/paste)

     import java.util.Scanner;
     class ReverseWord  {

    public static void main(String args[]){
    Scanner myScanner=new Scanner(;
    char c1,c2,c3,c4;

    c1 = myScanner.findInLine(".").charAt(0);
        c2 = myScanner.findInLine(".").charAt(0);
    c3 = myScanner.findInLine(".").charAt(0);
    c4 = myScanner.findInLine(".").charAt(0);



Angular ng-if="" with multiple arguments

Yes, it's possible. for example checkout:

<div class="singleMatch" ng-if=" | date:'ddMMyyyy' === &&  match.team1.code === main.team1code && match.team2.code === main.team2code">
    //Do something here

Bootstrap 3, 4 and 5 .container-fluid with grid adding unwanted padding

I think I had the same requirement as Tim, but none of the answers provide for a 'viewport edge-to-edge columns with normal internal gutters' solution. Or another way to put it: how can I get my first and last columns to break into the container padding and flow to the edge of the viewport, while still maintaining normal gutters between the columns.

full width rows

From what I can tell, there is no neat and clean solution. This is what works for me, but it is well outside anything that would be supported by Bootstrap. But it works for now (Bootstrap 3.3.5 & 4.0-alpha).

Sample HTML:

<div class="container">
  <div class="row full-width-row">
      <div class="col-sm-4 col-md-3">…</div>
      <div class="col-sm-4 col-md-3">…</div>
      <div class="col-sm-4 col-md-3">…</div>
      <div class="col-sm-4 col-md-3">…</div>


.full-width-row {
  overflow-x: hidden;

.full-width-row > div {
  margin-left: -15px;
  margin-right: -15px;

The trick is to nest a div in between the row and the columns to generate the extra -15px margin to push into the container padding. The extra negative margin creates horizontal scroll (into whitespace) on small viewports. Adding overflow-x: hidden to the .row is required to suppress it.

This works the same for .container-fluid as .container.

Formatting Decimal places in R

Background: Some answers suggested on this page (e.g., signif, options(digits=...)) do not guarantee that a certain number of decimals are displayed for an arbitrary number. I presume this is a design feature in R whereby good scientific practice involves showing a certain number of digits based on principles of "significant figures". However, in many domains (e.g., APA style, business reports) formatting requirements dictate that a certain number of decimal places are displayed. This is often done for consistency and standardisation purposes rather than being concerned with significant figures.


The following code shows exactly two decimal places for the number x.

format(round(x, 2), nsmall = 2)

For example:

format(round(1.20, 2), nsmall = 2)
# [1] "1.20"
format(round(1, 2), nsmall = 2)
# [1] "1.00"
format(round(1.1234, 2), nsmall = 2)
# [1] "1.12"

A more general function is as follows where x is the number and k is the number of decimals to show. trimws removes any leading white space which can be useful if you have a vector of numbers.

specify_decimal <- function(x, k) trimws(format(round(x, k), nsmall=k))


specify_decimal(1234, 5)
# [1] "1234.00000"
specify_decimal(0.1234, 5)
# [1] "0.12340"

"Uncaught TypeError: undefined is not a function" - Beginner Backbone.js Application

Uncaught TypeError: undefined is not a function example_app.js:7

This error message tells the whole story. On this line, you are trying to execute a function. However, whatever is being executed is not a function! Instead, it's undefined.

So what's on example_app.js line 7? Looks like this:

var tasks = new ExampleApp.Collections.Tasks(data.tasks);

There is only one function being run on that line. We found the problem! ExampleApp.Collections.Tasks is undefined.

So lets look at where that is declared:

var Tasks = Backbone.Collection.extend({
    model: Task,
    url: '/tasks'

If that's all the code for this collection, then the root cause is right here. You assign the constructor to global variable, called Tasks. But you never add it to the ExampleApp.Collections object, a place you later expect it to be.

Change that to this, and I bet you'd be good.

ExampleApp.Collections.Tasks = Backbone.Collection.extend({
    model: Task,
    url: '/tasks'

See how important the proper names and line numbers are in figuring this out? Never ever regard errors as binary (it works or it doesn't). Instead read the error, in most cases the error message itself gives you the critical clues you need to trace through to find the real issue.

In Javascript, when you execute a function, it's evaluated like:

expression.that('returns').aFunctionObject(); // js
execute -> expression.that('returns').aFunctionObject // what the JS engine does

That expression can be complex. So when you see undefined is not a function it means that expression did not return a function object. So you have to figure out why what you are trying to execute isn't a function.

And in this case, it was because you didn't put something where you thought you did.

Understanding generators in Python

Performance difference:

macOS Big Sur 11.1
MacBook Pro (13-inch, M1, 2020)
Chip Apple M1
Memory 8gb


import random
import psutil # pip install psutil
import os
from datetime import datetime

def memory_usage_psutil():
    # return the memory usage in MB
    process = psutil.Process(os.getpid())
    mem = process.memory_info().rss / float(2 ** 20)
    return '{:.2f} MB'.format(mem)

names = ['John', 'Milovan', 'Adam', 'Steve', 'Rick', 'Thomas']
majors = ['Math', 'Engineering', 'CompSci', 'Arts', 'Business']

print('Memory (Before): {}'.format(memory_usage_psutil()))

def people_list(num_people):
    result = []
    for i in range(num_people):
        person = {
            'id': i,
            'name': random.choice(names),
            'major': random.choice(majors)
    return result

t1 =
people = people_list(1000000)
t2 =

print('Memory (After) : {}'.format(memory_usage_psutil()))
print('Took {} Seconds'.format(t2 - t1))


Memory (Before): 50.38 MB
Memory (After) : 1140.41 MB
Took 0:00:01.056423 Seconds
  • Function which returns a list of 1 million results.
  • At the bottom I'm printing out the memory usage and the total time.
  • Base memory usage was around 50.38 megabytes and this memory after is after I created that list of 1 million records so you can see here that it jumped up by nearly 1140.41 megabytes and it took 1,1 seconds.


import random
import psutil # pip install psutil
import os
from datetime import datetime

def memory_usage_psutil():
    # return the memory usage in MB
    process = psutil.Process(os.getpid())
    mem = process.memory_info().rss / float(2 ** 20)
    return '{:.2f} MB'.format(mem)

names = ['John', 'Milovan', 'Adam', 'Steve', 'Rick', 'Thomas']
majors = ['Math', 'Engineering', 'CompSci', 'Arts', 'Business']

print('Memory (Before): {}'.format(memory_usage_psutil()))

def people_generator(num_people):
    for i in range(num_people):
        person = {
            'id': i,
            'name': random.choice(names),
            'major': random.choice(majors)
        yield person

t1 =
people = people_generator(1000000)
t2 =

print('Memory (After) : {}'.format(memory_usage_psutil()))
print('Took {} Seconds'.format(t2 - t1))


Memory (Before): 50.52 MB
Memory (After) : 50.73 MB
Took 0:00:00.000008 Seconds
  • After I ran this that the memory is almost exactly the same and that's because the generator hasn't actually done anything yet it's not holding those million values in memory it's waiting for me to grab the next one.

  • Basically it didn't take any time because as soon as it gets to the first yield statement it stops.

  • I think that it is generator a little bit more readable and it also gives you big performance boosts not only with execution time but with memory.

  • As well and you can still use all of the comprehensions and this generator expression here so you don't lose anything in that area. So those are a few reasons why you would use generators and also some of the advantages that come along with that.

enter image description here

AngularJS ng-style with a conditional expression

I am doing like below for multiple and independent conditions and it works like charm:

<div ng-style="{{valueFromJS}} === 'Hello' ? {'color': 'red'} : {'color': ''} && valueFromNG-Repeat === '{{dayOfToday}}' ? {'font-weight': 'bold'} : {'font-weight': 'normal'}"></div>

How to re import an updated package while in Python Interpreter?

No matter how many times you import a module, you'll get the same copy of the module from sys.modules - which was loaded at first import mymodule

I am answering this late, as each of the above/previous answer has a bit of the answer, so I am attempting to sum it all up in a single answer.

Using built-in function:

For Python 2.x - Use the built-in reload(mymodule) function.

For Python 3.x - Use the imp.reload(mymodule).

For Python 3.4 - In Python 3.4 imp has been deprecated in favor of importlib i.e. importlib.reload(mymodule)

Few caveats:

  • It is generally not very useful to reload built-in or dynamically loaded modules. Reloading sys, __main__, builtins and other key modules is not recommended.
  • In many cases extension modules are not designed to be initialized more than once, and may fail in arbitrary ways when reloaded. If a module imports objects from another module using from ... import ..., calling reload() for the other module does not redefine the objects imported from it — one way around this is to re-execute the from statement, another is to use import and qualified names ( instead.
  • If a module instantiates instances of a class, reloading the module that defines the class does not affect the method definitions of the instances — they continue to use the old class definition. The same is true for derived classes.

External packages:

reimport - Reimport currently supports Python 2.4 through 2.7.

xreload- This works by executing the module in a scratch namespace, and then patching classes, methods and functions in place. This avoids the need to patch instances. New objects are copied into the target namespace.

livecoding - Code reloading allows a running application to change its behaviour in response to changes in the Python scripts it uses. When the library detects a Python script has been modified, it reloads that script and replaces the objects it had previously made available for use with newly reloaded versions. As a tool, it allows a programmer to avoid interruption to their workflow and a corresponding loss of focus. It enables them to remain in a state of flow. Where previously they might have needed to restart the application in order to put changed code into effect, those changes can be applied immediately.

"webxml attribute is required" error in Maven

Make sure to run mvn install before you compile your war.

Overflow:hidden dots at the end

Most of solutions use static width here. But it can be sometimes wrong for some reasons.

Example: I had table with many columns. Most of them are narrow (static width). But the main column should be as wide as possible (depends on screen size).


<table style="width: 100%">
    <td style="width: 60px;">narrow</td>
      <span class="cutwrap" data-cutwrap="dynamic column can have really long text which can be wrapped on two rows, but we just need not wrapped texts using as much space as possible">
        dynamic column can have really long text which can be wrapped on two rows
        but we just need not wrapped texts using as much space as possible


.cutwrap {
  position: relative;
  overflow: hidden;
  display: block;
  width: 100%;
  height: 18px;
  white-space: normal;
  color: transparent !important;
.cutwrap::selection {
  color: transparent !important;
.cutwrap:before {
  content: attr(data-cutwrap);
  position: absolute;
  left: 0;
  right: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #333;
/* different styles for links */
a.cutwrap:before {
  text-decoration: underline;
  color: #05c;

Docker Repository Does Not Have a Release File on Running apt-get update on Ubuntu

I saw an interesting post from Ikraider here that solved my issue :

Website instructions are wrong, here is what works in 16.04:

curl -s | sudo apt-key add
apt-key fingerprint 58118E89F3A912897C070ADBF76221572C52609D
sudo add-apt-repository "deb ubuntu-$(lsb_release -cs) main"
sudo apt-get update
sudo apt-get install docker-engine=1.13.0-0~ubuntu-xenial

How to suppress "error TS2533: Object is possibly 'null' or 'undefined'"?

In ReactJS, I check in the constructor if the variables are null, if they are I treat it like an exception and manage the exception appropriately. If the variables are not null, code carries on and compiler does not complain anymore after that point:

private variable1: any;
private variable2: any;

constructor(props: IProps) {

    // i.e. here I am trying to access an HTML element
    // which might be null if there is a typo in the name
    this.variable1 = document.querySelector('element1');
    this.variable2 = document.querySelector('element2');

    // check if objects are null
    if(!this.variable1 || !this.variable2) {
        // Manage the 'exception', show the user a message, etc.
    } else {
        // Interpreter should not complain from this point on
        // in any part of the file
        this.variable1.disabled = true; // i.e. this line should not show the error

Select specific row from mysql table

You can use LIMIT 2,1 instead of WHERE row_number() = 3.

As the documentation explains, the first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return.

Keep in mind that it's an 0-based index. So, if you want the line number n, the first argument should be n-1. The second argument will always be 1, because you just want one row. For example, if you want the line number 56 of a table customer:

SELECT * FROM customer LIMIT 55,1

Android Studio doesn't recognize my device

Click Revoke USB debugging authorization in Developer option and try it again.

ExtJs Gridpanel store refresh

  callback: function(){

How to comment out a block of Python code in Vim

CtrlK for comment (Visual Mode):

vnoremap <silent> <C-k> :s#^#\##<cr>:noh<cr>

CtrlU for uncomment (Visual Mode):

vnoremap <silent> <C-u> :s#^\###<cr>:noh<cr>

Copy array items into another array

With JavaScript ES6, you can use the ... operator as a spread operator which will essentially convert the array into values. Then, you can do something like this:

const myArray = [1,2,3,4,5];
const moreData = [6,7,8,9,10];

const newArray = [

While the syntax is concise, I do not know how this works internally and what the performance implications are on large arrays.

What is the difference between "screen" and "only screen" in media queries?

The following is from Adobe docs.

The media queries specification also provides the keyword only, which is intended to hide media queries from older browsers. Like not, the keyword must come at the beginning of the declaration. For example:

media="only screen and (min-width: 401px) and (max-width: 600px)"

Browsers that don't recognize media queries expect a comma-separated list of media types, and the specification says they should truncate each value immediately before the first nonalphanumeric character that isn't a hyphen. So, an old browser should interpret the preceding example as this:


Because there is no such media type as only, the stylesheet is ignored. Similarly, an old browser should interpret

media="screen and (min-width: 401px) and (max-width: 600px)"



In other words, it should apply the style rules to all screen devices, even though it doesn't know what the media queries mean.

Unfortunately, IE 6–8 failed to implement the specification correctly.

Instead of applying the styles to all screen devices, it ignores the style sheet altogether.

In spite of this behavior, it's still recommended to prefix media queries with only if you want to hide the styles from other, less common browsers.

So, using

media="only screen and (min-width: 401px)"


media="screen and (min-width: 401px)"

will have the same effect in IE6-8: both will prevent those styles from being used. They will, however, still be downloaded.

Also, in browsers that support CSS3 media queries, both versions will load the styles if the viewport width is larger than 401px and the media type is screen.

I'm not entirely sure which browsers that don't support CSS3 media queries would need the only version

media="only screen and (min-width: 401px)" 

as opposed to

media="screen and (min-width: 401px)"

to make sure it is not interpreted as


It would be a good test for someone with access to a device lab.

Create component to specific module with Angular-CLI

Go to module level/we can also be in the root level and type below commands

ng g component "path to your component"/NEW_COMPONENT_NAME -m "MODULE_NAME"

Example :

ng g component common/signup/payment-processing/OnlinePayment -m pre-login.module

How to install JSON.NET using NuGet?

You can do this a couple of ways.

Via the "Solution Explorer"

  1. Simply right-click the "References" folder and select "Manage NuGet Packages..."
  2. Once that window comes up click on the option labeled "Online" in the left most part of the dialog.
  3. Then in the search bar in the upper right type ""
  4. Click "Install" and you're done.

Via the "Package Manager Console"

  1. Open the console. "View" > "Other Windows" > "Package Manager Console"
  2. Then type the following:
    Install-Package Newtonsoft.Json

For more info on how to use the "Package Manager Console" check out the nuget docs.

ldap_bind: Invalid Credentials (49)

I don't see an obvious problem with the above.

It's possible your ldap.conf is being overridden, but the command-line options will take precedence, ldapsearch will ignore BINDDN in the main ldap.conf, so the only parameter that could be wrong is the URI. (The order is ETCDIR/ldap.conf then ~/ldaprc or ~/.ldaprc and then ldaprc in the current directory, though there environment variables which can influence this too, see man ldapconf.)

Try an explicit URI:

ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base -H ldap://localhost

or prevent defaults with:

LDAPNOINIT=1 ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base

If that doesn't work, then some troubleshooting (you'll probably need the full path to the slapd binary for these):

  • make sure your slapd.conf is being used and is correct (as root)

    slapd -T test -f slapd.conf -d 65535

    You may have a left-over or default slapd.d configuration directory which takes preference over your slapd.conf (unless you specify your config explicitly with -f, slapd.conf is officially deprecated in OpenLDAP-2.4). If you don't get several pages of output then your binaries were built without debug support.

  • stop OpenLDAP, then manually start slapd in a separate terminal/console with debug enabled (as root, ^C to quit)

    slapd -h ldap://localhost -d 481

    then retry the search and see if you can spot the problem (there will be a lot of schema noise in the start of the output unfortunately). (Note: running slapd without the -u/-g options can change file ownerships which can cause problems, you should usually use those options, probably -u ldap -g ldap )

  • if debug is enabled, then try also

    ldapsearch -v -d 63 -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base

Finding out the name of the original repository you cloned from in Git

I stumbled on this question trying to get the organization/repo string from a git host like github or gitlab.

This is working for me:

git config --get remote.origin.url | sed -e 's/^git@.*:\([[:graph:]]*\).git/\1/'

It uses sed to replace the output of the git config command with just the organization and repo name.

Something like github/scientist would be matched by the character class [[:graph:]] in the regular expression.

The \1 tells sed to replace everything with just the matched characters.

TypeError: 'module' object is not callable

A simple way to solve this problem is export thePYTHONPATH variable enviroment. For example, for Python 2.6 in Debian/GNU Linux:

export PYTHONPATH=/usr/lib/python2.6`

In other operating systems, you would first find the location of this module or the file.

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

Even I had same problem, The reason was mysql service was not getting configured properly, when I installed it through 'MySQL installer'. Also it was not starting, when I tried to start the service manually.

So in my case it seemed be a Bug with the 'MySQL Installer', as editing the install path to a different one when the 'Developer default' was selected, the problem occurs.

Solution (Not exactly a solution):

  • Uninstalled the MySQL all products (completely)
  • Reinstalled, this time also I have selected 'Developer default', but didn't make any changes to the path or any thing. So the path was just 'C:\Program Files\MySQL' (the default one)
  • And just clicked Next Next...
  • Done, this time MySql was running fine.

Javascript: Load an Image from url and display

Are you after something like this:

    <title>Z Test</title>

<div id="img_home"></div>

<button onclick="addimage()" type="button">Add an image</button>

function addimage() {
    var img = new Image();
    img.src = ""

change figure size and figure format in matplotlib

The first part (setting the output size explictly) isn't too hard:

import matplotlib.pyplot as plt
list1 = [3,4,5,6,9,12]
list2 = [8,12,14,15,17,20]
fig = plt.figure(figsize=(4,3))
ax = fig.add_subplot(111)
ax.plot(list1, list2)
fig.savefig('fig1.png', dpi = 300)

But after a quick google search on matplotlib + tiff, I'm not convinced that matplotlib can make tiff plots. There is some mention of the GDK backend being able to do it.

One option would be to convert the output with a tool like imagemagick's convert.

(Another option is to wait around here until a real matplotlib expert shows up and proves me wrong ;-)

Fastest way to remove non-numeric characters from a VARCHAR in SQL Server

replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(string,'a',''),'b',''),'c',''),'d',''),'e',''),'f',''),'g',''),'h',''),'i',''),'j',''),'k',''),'l',''),'m',''),'n',''),'o',''),'p',''),'q',''),'r',''),'s',''),'t',''),'u',''),'v',''),'w',''),'x',''),'y',''),'z',''),'A',''),'B',''),'C',''),'D',''),'E',''),'F',''),'G',''),'H',''),'I',''),'J',''),'K',''),'L',''),'M',''),'N',''),'O',''),'P',''),'Q',''),'R',''),'S',''),'T',''),'U',''),'V',''),'W',''),'X',''),'Y',''),'Z','')*1 AS string,


What is the difference between cache and persist?

Cache() and persist() both the methods are used to improve performance of spark computation. These methods help to save intermediate results so they can be reused in subsequent stages.

The only difference between cache() and persist() is ,using Cache technique we can save intermediate results in memory only when needed while in Persist() we can save the intermediate results in 5 storage levels(MEMORY_ONLY, MEMORY_AND_DISK, MEMORY_ONLY_SER, MEMORY_AND_DISK_SER, DISK_ONLY).

Implementing autocomplete

I have created a module for anuglar2 autocomplete In this module you can use array, or url npm link : ang2-autocomplete

using mailto to send email with an attachment

this is not possible in "mailto" function.

please go with server side coding(C#).make sure open vs in administrative permission.

Microsoft.Office.Interop.Outlook.Application oApp = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.MailItem oMsg = (Microsoft.Office.Interop.Outlook.MailItem)oApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);

oMsg.Subject = "emailSubject";
oMsg.BodyFormat = Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatHTML;
oMsg.BCC = "emailBcc";
oMsg.To = "emailRecipient";

string body = "emailMessage";

oMsg.HTMLBody = "body";              
oMsg.Attachments.Add(Convert.ToString(@"/my_location_virtual_path/myfile.txt"), Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing);

oMsg.Display(false); //In order to displ

error C2065: 'cout' : undeclared identifier

Are you sure it's compiling as C++? Check your file name (it should end in .cpp). Check your project settings.

There's simply nothing wrong with your program, and cout is in namespace std. Your installation of VS 2010 Beta 2 is defective, and I don't think it's just your installation.

I don't think VS 2010 is ready for C++ yet. The standard "Hello, World" program didn't work on Beta 1. I just tried creating a test Win32 console application, and the generated test.cpp file didn't have a main() function.

I've got a really, really bad feeling about VS 2010.


Access requires parentheses in the FROM clause for queries which include more than one join. Try it this way ...

    INNER JOIN tbl_netpay
    ON tbl_employee.emp_id = tbl_netpay.emp_id)
    INNER JOIN tbl_gross
    ON tbl_employee.emp_id = tbl_gross.emp_ID)
    INNER JOIN tbl_tax
    ON tbl_employee.emp_id = tbl_tax.emp_ID;

If possible, use the Access query designer to set up your joins. The designer will add parentheses as required to keep the db engine happy.

What is a Java String's default initial value?

That depends. Is it just a variable (in a method)? Or a class-member?

If it's just a variable you'll get an error that no value has been set when trying to read from it without first assinging it a value.

If it's a class-member it will be initialized to null by the VM.

Telegram Bot - how to get a group chat id?

You can get Chat ID in this way.

On private chat with your bot, send a random message. You will search this message later.


Then, on your browser make a request with that url :

The request returns a json response, in json text search your random message and get chat id in that object.

PHP: How to generate a random, unique, alphanumeric string for use in a secret link?

This is a simple function that allows you to generate random strings containing Letters and Numbers (alphanumeric). You can also limit the string length. These random strings can be used for various purposes, including: Referral Code, Promotional Code, Coupon Code. Function relies on following PHP functions: base_convert, sha1, uniqid, mt_rand

function random_code($length)
  return substr(base_convert(sha1(uniqid(mt_rand())), 16, 36), 0, $length);

echo random_code(6);

/*sample output
* a7d9e8
* 3klo93

How to obtain image size using standard Python class (without using external library)?

While it's possible to call open(filename, 'rb') and check through the binary image headers for the dimensions, it seems much more useful to install PIL and spend your time writing great new software! You gain greater file format support and the reliability that comes from widespread usage. From the PIL documentation, it appears that the code you would need to complete your task would be:

from PIL import Image
im ='filename.png')
print 'width: %d - height: %d' % im.size # returns (width, height) tuple

As for writing code yourself, I'm not aware of a module in the Python standard library that will do what you want. You'll have to open() the image in binary mode and start decoding it yourself. You can read about the formats at:

How to stop/cancel 'git log' command in terminal?

You can hit the key q (for quit) and it should take you to the prompt.

Please see this link.

Why does calling sumr on a stream with 50 tuples not complete

sumr is implemented in terms of foldRight:

 final def sumr(implicit A: Monoid[A]): A = F.foldRight(self, 

foldRight is not always tail recursive, so you can overflow the stack if the collection is too long. See Why foldRight and reduceRight are NOT tail recursive? for some more discussion of when this is or isn't true.

File opens instead of downloading in internet explorer in a href link

This is not a code issue. It is your default IE settings

To change the "always open" setting:

  1. In Windows Explorer, click on the "Tools" menu, choose "Folder options"
  2. In the window that appears, click on the "File Types" tab, and scroll through the list until you find the file extension you want to change (they're in alphabetical order). For example, if Internet Explorer always tries to open .zip files, scroll through the list until you find the entry for "zip".
  3. Click on the file type, then the "Advanced" button.
  4. Check the "Confirm after download" box, then click OK > Close.

EDIT: If you ask me , instead of making any changes in the code i would add the following text "Internet Explorer users: To download file, "Rightclick" the link and hit "Save target as" to download the file."

EDIT 2: THIS solution will work perfectly for you. Its a solution i just copied from the other answer. Im not trying to pass it off as my own

Content-Type: application/octet-stream
Content-Disposition: attachment;filename=\"\"

However you must make sure that you specify the type of file(s) you allow. You have mentioned in your post that you want this for any type of file. This will be an issue.

For ex. If your site has images and if the end user clicks these images then they will be downloaded on his computer instead of opening in a new page. Got the point. So you need to specify the file extensions.

What is the difference between rb and r+b modes in file objects

r+ is used for reading, and writing mode. b is for binary. r+b mode is open the binary file in read or write mode.
You can read more here.

Can you "compile" PHP code and upload a binary-ish file, which will just be run by the byte code interpreter?

phc allows you to compile PHP programs into shared libraries, which can be uploaded to the server. The PHP program is compiled into binaries. It's done in such a way as to support evals, includes, and the entire PHP standard library.

python dict to numpy structured array

Similarly to the approved answer. If you want to create an array from dictionary keys:

np.array( tuple(dict.keys()) )

If you want to create an array from dictionary values:

np.array( tuple(dict.values()) )

What does "O(1) access time" mean?

O(1) means Random Access. In any Random Access Memory, the time taken to access any element at any location is the same. Here time can be any integer, but the only thing to remember is time taken to retrieve the element at (n-1)th or nth location will be same(ie constant).

Whereas O(n) is dependent on the size of n.

Android Studio: “Execution failed for task ':app:mergeDebugResources'” if project is created on drive C:

In my case, I created a folder audio in res directory. That caused the problem! Deleting the folder fixed it. Hope it might help someone.

How do I create a timeline chart which shows multiple events? Eg. Metallica Band members timeline on wiki

A Stacked bar chart should suffice:

Setup data as follows

Name    Start       End         Duration (End - Start)
Fred    1/01/1981   1/06/1985    1612   
Bill    1/07/1985   1/11/2000    5602  
Joe     1/01/1980   1/12/2001    8005  
Jim     1/03/1999   1/01/2000    306  
  1. Plot Start and Duration as a stacked bar chart
  2. Set the X-Axis minimum to the desired start date
  3. Set the Fill Colour of thestart range to no fill
  4. Set the Fill of individual bars to suit

(example prepared in Excel 2010)

enter image description here

What is the difference between Cloud, Grid and Cluster?

There's some pretty good answers here but I want to elaborate on all topics:

Cloud: shailesh's answer is awesome, nothing to add there! Basically, An application that's served seamlessly over the network can be considered a Cloud application. Cloud isn't a new invention and it's very similar to Grid computing, but it's more of a buzzword with the spike of recent popularity.

Grid: Grid is defined as a large collection as machines connected by a private network and offers a set of services to users, it acts as a sort of supercomputer by sharing processing power across the machines. Source: Tenenbaum, Andrew.

Cluster: A cluster is different from those two. Clusters are two or more computers who share a network connection that acts as a heart-beat. Clusters are configurable in Active-Active or Active-Passive ways. Active-Active being that each computer runs it's own set of services (Say, one runs a SQL instance, the other runs a web server) and they share some resources such as storage. If one of the computers in a cluster goes down the service fails over to the other node and almost seamlessly starts running there. Active-Passive is similar, but only one machine runs these services and only takes over once there's a failure.

Laravel-5 how to populate select box from database with id value and name value

Try this one. Without using controller

{{ Form::select('apartment_id', \App\Apartment::all()->pluck('apartment_name', 'apartment_id')->toArray(), null,['class'=>'select2 form-control', 'multiple'=>'multiple','required','id' => 'apartment_id']) }}

Adding files to a GitHub repository

The general idea is to add, commit and push your files to the GitHub repo.

First you need to clone your GitHub repo.
Then, you would git add all the files from your other folder: one trick is to specify an alternate working tree when git add'ing your files.

git --work-tree=yourSrcFolder add .

(done from the root directory of your cloned Git repo, then git commit -m "a msg", and git push origin master)

That way, you keep separate your initial source folder, from your Git working tree.

Note that since early December 2012, you can create new files directly from GitHub:

Create new File

ProTip™: You can pre-fill the filename field using just the URL.
Typing ?filename=yournewfile.txt at the end of the URL will pre-fill the filename field with the name yournewfile.txt.


How to install a plugin in Jenkins manually

The answers given work, with added plugins.

If you want to replace/update a built-in plugin like the credentials plugin, that has dependencies, then you have to use the frontend. To automate I use:

 curl -i -F [email protected] http://jenkinshost/jenkins/pluginManager/uploadPlugin

How to mount a single file in a volume


If you experience a directory being created in place of the file you are trying to mount, you have probably failed to supply a valid and absolute path. This is a common mistake with a silent and confusing failure mode.

File volumes are done this way in docker (absolute path example (can use env variables), and you need to mention the file name) :

      - /src/docker/myapp/upload:/var/www/html/upload
      - /src/docker/myapp/upload/config.php:/var/www/html/config.php

You can also do:

      - ${PWD}/upload:/var/www/html/upload
      - ${PWD}/upload/config.php:/var/www/html/config.php

If you fire the docker-compose from /src/docker/myapp folder

Python Prime number checker

You need to stop iterating once you know a number isn't prime. Add a break once you find prime to exit the while loop.

Making only minimal changes to your code to make it work:

while num > a :
  if num%a==0 & a!=num:
    print('not prime')
  i += 1
else: # loop not exited via break

Your algorithm is equivalent to:

for a in range(a, num):
    if a % num == 0:
        print('not prime')
else: # loop not exited via break

If you throw it into a function you can dispense with break and for-else:

def is_prime(n):
    for i in range(3, n):
        if n % i == 0:
            return False
    return True

Even if you are going to brute-force for prime like this you only need to iterate up to the square root of n. Also, you can skip testing the even numbers after two.

With these suggestions:

import math
def is_prime(n):
    if n % 2 == 0 and n > 2: 
        return False
    for i in range(3, int(math.sqrt(n)) + 1, 2):
        if n % i == 0:
            return False
    return True

Note that this code does not properly handle 0, 1, and negative numbers.

We make this simpler by using all with a generator expression to replace the for-loop.

import math
def is_prime(n):
    if n % 2 == 0 and n > 2: 
        return False
    return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))

How to start/stop/restart a thread in Java?

Once a thread stops you cannot restart it. However, there is nothing stopping you from creating and starting a new thread.

Option 1: Create a new thread rather than trying to restart.

Option 2: Instead of letting the thread stop, have it wait and then when it receives notification you can allow it to do work again. This way the thread never stops and will never need to be restarted.

Edit based on comment:

To "kill" the thread you can do something like the following.

yourThread.setIsTerminating(true); // tell the thread to stop
yourThread.join(); // wait for the thread to stop

why I can't get value of label with jquery and javascript?

Label's aren't form elements. They don't have a value. They have innerHTML and textContent.


// or


var telefon = document.getElementById('telefon');

If you are starting with your form element, check out the labels list of it. That is,

var el = $('#myformelement');
var label = $( el.prop('labels') );
// label.html();
// el.val();
// blah blah blah you get the idea

Get difference between two dates in months using Java

You can use Joda time library for Java. It would be much easier to calculate time-diff between dates with it.

Sample snippet for time-diff:

Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();

mongod command not recognized when trying to connect to a mongodb server

1.To begin using MongoDB, Open CMD with admin privilege and type : "C:\Program Files\MongoDB\Server\4.2\bin\mongo.exe"

2.To create data directory(open another cmd terminal) cd C:
md "\data\db" 3. To start your mongo DB database, type in cmd the following lines: "C:\Program Files\MongoDB\Server\4.2\bin\mongod.exe" --dbpath="c:\data\db" (The --dbpath option points to your database directory.) [you can also do step 2 and 3 first and then step 1]


How to run cron once, daily at 10pm

The syntax for crontab

* * * * * 

Minute(0-59) Hour(0-24) Day_of_month(1-31) Month(1-12) Day_of_week(0-6) Command_to_execute

Your syntax

* 22 * * * test > /dev/null

your job will Execute every minute at 22:00 hrs all week, month and year.

adding an option (0-59) at the minute place will run it once at 22:00 hrs all week, month and year.

0 22 * * * command_to_execute 


Python how to exit main function

use sys module

import sys

How do I enable saving of filled-in fields on a PDF form?

In Acrobat XI, (Close Form Editing if open) File > Save As Other > Reader Extended PDF > Enable Additional Features

How to get evaluated attributes inside a custom directive

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

myApp .directive('myDirective', function ($timeout) {
    return function (scope, element, attr) {
            element.val("value = "+attr.value);


function MyCtrl($scope) {


Use $timeout because directive call after dom load so your changes doesn`'t apply

Restore LogCat window within Android Studio

In my case the window was also missing and "View -> ToolWindows -> Logcat (Alt + 6)" did not even exist. Pressing ALT+6 also had absolutely no effect whatsoever.

I fixed it this way:

  1. connect a device
  2. start ADB via Terminal ("> adb usb")
  3. stop it again (ctrl + c)
  4. close the Terminal window in the bottom left window next to the Event Log (via the red X)

After closing the terminal the Logcat window appeared in the tab list and the menu entry appeared in the "View -> ToolWindows" category.

enter image description here

How add items(Text & Value) to ComboBox & read them in SelectedIndexChanged (SelectedValue = null)

        combo1.DisplayMember = "Text";
        combo1.ValueMember = "Value";   
        combo1.Items.Add(new { Text = "someText"), Value = "someValue") });
        dynamic item = combo1.Items[combo1.SelectedIndex];
        var itemValue = item.Value;
        var itemText = item.Text;

Unfortunatly "combo1.SelectedValue" does not work, i did not want to bind my combobox with any source, so i came up with this solution. Maybe it will help someone.

How to calculate sum of a formula field in crystal Reports?

You can try like this:


It will work without creating a summarize field in formulae.

Add animated Gif image in Iphone UIImageView

Here is the best solution to use Gif Image. Add SDWebImage from Github in your project.

#import "UIImage+GIF.h"

_imageViewAnimatedGif.image= [UIImage sd_animatedGIFNamed:@"thumbnail"];

Cannot find module cv2 when using OpenCV

I had the same problem, just couldn't figure it out with opencv2 and opencv3 installed into /opt/opencv and opencv3 respectively. Turned out that bloody anaconda install of opencv in my home directory was first on path and mangled opencv. Removed it and started using /opt/opencv3/lib as defined in /etc/ Worked perfectly first go. Do you have anaconda installed? Could be the issue.

HTML table with 100% width, with vertical scroll inside tbody

In modern browsers, you can simply use css:

th {
  position: sticky;
  top: 0;
  z-index: 2;

Unresolved Import Issues with PyDev and Eclipse

Here is what worked for me (sugested by soulBit):

1) Restart using restart from the file menu
2) Once it started again, manually close and open it.

This is the simplest solution ever and it completely removes the annoying thing.

How to compare strings

You need to use strcmp.

if (strcmp(string,"add") == 0){

Two submit buttons in one form

An even better solution consists of using button tags to submit the form:

    <button type="submit" name="action" value="update">Update</button>
    <button type="submit" name="action" value="delete">Delete</button>

The HTML inside the button (e.g. ..>Update<.. is what is seen by the user; because there is HTML provided, the value is not user-visible; it is only sent to server. This way there is no inconvenience with internationalization and multiple display languages (in the former solution, the label of the button is also the value sent to the server).

How to use new PasswordEncoder from Spring Security

Having just gone round the internet to read up on this and the options in Spring I'd second Luke's answer, use BCrypt (it's mentioned in the source code at Spring).

The best resource I found to explain why to hash/salt and why use BCrypt is a good choice is here: Salted Password Hashing - Doing it Right.

Writing files in Node.js

You can write to files with streams.

Just do it like this:

const fs = require('fs');

const stream = fs.createWriteStream('./test.txt');
stream.write("Example text");

How to update values using pymongo?

With my pymongo version: 3.2.2 I had do the following

from bson.objectid import ObjectId
import pymongo

client = pymongo.MongoClient("localhost", 27017)
db = client.mydbname

  '_id': ObjectId(p['_id']['$oid'])
  '$set': {
    'd.a': existing + 1
}, upsert=False)

Using sendmail from bash script for multiple recipients

to use sendmail from the shell script

subject="mail subject"
body="Hello World"
from="[email protected]"
to="[email protected],[email protected]"
echo -e "Subject:${subject}\n${body}" | sendmail -f "${from}" -t "${to}"

How to directly move camera to current location in Google Maps Android API v2?

make sure you have these permissions:

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

Then make some activity and register a LocationListener

package com.example.location;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;

public class LocationActivity extends SherlockFragmentActivity implements LocationListener     {
private GoogleMap map;
private LocationManager locationManager;
private static final long MIN_TIME = 400;
private static final float MIN_DISTANCE = 1000;

protected void onCreate(Bundle savedInstanceState) {
    map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(;

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, this); //You can also use LocationManager.GPS_PROVIDER and LocationManager.PASSIVE_PROVIDER        

public void onLocationChanged(Location location) {
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 10);

public void onStatusChanged(String provider, int status, Bundle extras) { }

public void onProviderEnabled(String provider) { }

public void onProviderDisabled(String provider) { }


<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android=""

Submit a form in a popup, and then close the popup

Here's how I ended up doing this:

        <div id="divform">
            <form action="/system/wpacert" method="post" enctype="multipart/form-data" name="certform">
                <div>Certificate 1: <input type="file" name="cert1"/></div>
                <div>Certificate 2: <input type="file" name="cert2"/></div>

                <div><input type="button" value="Upload" onclick="closeSelf();"/></div>
        <div  id="closelink" style="display:none">
            <a href="javascript:window.close()">Click Here to Close this Page</a>

function closeSelf(){


Where hide() and unhide() set the style.display to 'none' and 'block' respectively.

Not exactly what I had in mind, but this will have to do for the time being. Works on IE, Safari, FF and Chrome.

How to convert const char* to char* in C?

You can cast it by doing (char *)Identifier_Of_Const_char

But as there is probabbly a reason that the api doesn't accept const cahr *, you should do this only, if you are sure, the function doesn't try to assign any value in range of your const char* which you casted to a non const one.

Unknown lifecycle phase "mvn". You must specify a valid lifecycle phase or a goal in the format <plugin-prefix>:<goal> or <plugin-group-id>

Sometimes this error comes because it's simply the wrong folder. :-(

It shall be the folder which contains the pom.xml.

Responsive font size in CSS

I've been playing around with ways to overcome this issue, and believe I have found a solution:

If you can write your application for Internet Explorer 9 (and later) and all other modern browsers that support CSS calc(), rem units, and vmin units. You can use this to achieve scalable text without media queries:

body {
  font-size: calc(0.75em + 1vmin);

Here it is in action:

How to allow CORS in react.js?

It is better to add CORS enabling code on Server Side. To enable CORS in NodeJS and ExpressJs based application following code should be included-

var app = express();

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

MongoDB and "joins"

If you use mongoose, you can just use(assuming you're using subdocuments and population):

Profile.findById profileId
  .select 'friends'
  .exec (err, profile) ->
    if err or not profile
      handleError err, profile, res
      Status.find { profile: { $in: profile.friends } }, (err, statuses) ->
        if err
          handleErr err, statuses, res
          res.json createJSON statuses

It retrieves Statuses which belong to one of Profile (profileId) friends. Friends is array of references to other Profiles. Profile schema with friends defined:

schema = new mongoose.Schema
  # ...

  friends: [
    type: mongoose.Schema.Types.ObjectId
    ref: 'Profile'
    unique: true
    index: true

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

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

INSERT INTO TABLE from comma separated varchar-list

Something like this should work:

INSERT INTO #IMEIS (imei) VALUES ('val1'), ('val2'), ...


Apparently this syntax is only available starting on SQL Server 2008.

Remove directory which is not empty

//without use of any third party lib

const fs = require('fs');
var FOLDER_PATH = "./dirname";
var files = fs.readdirSync(FOLDER_PATH);
files.forEach(element => {
    fs.unlinkSync(FOLDER_PATH + "/" + element);

ASP.NET MVC: Custom Validation by DataAnnotation

A bit late to answer, but for who is searching. You can easily do this by using an extra property with the data annotation:

public string foo { get; set; }
public string bar { get; set; }

[MinLength(20, ErrorMessage = "too short")]
public string foobar 
        return foo + bar;

That's all that is too it really. If you really want to display in a specific place the validation error as well, you can add this in your view:

@Html.ValidationMessage("foobar", "your combined text is too short")

doing this in the view can come in handy if you want to do localization.

Hope this helps!

How to update the constant height constraint of a UIView programmatically?

Create an IBOutlet of NSLayoutConstraint of yourView and update the constant value accordingly the condition specifies.

//Connect them from Interface 
@IBOutlet viewHeight: NSLayoutConstraint! 
@IBOutlet view: UIView!

private func updateViewHeight(height:Int){
   guard let aView = view, aViewHeight = viewHeight else{
   aViewHeight.constant = height

Express-js can't GET my static files, why?

to serve static files (css,images,js files)just two steps:

  1. pass the directory of css files to built in middleware express.static

    var express = require('express');
    var app = express();
    /*public is folder in my project directory contains three folders
    //css  =>folder contains css file
    //image=>folder contains images
    //js   =>folder contains javascript files
    app.use(express.static( 'public/css'));
  2. to access css files or images just type in url http://localhost:port/filename.css ex:http://localhost:8081/bootstrap.css

note: to link css files to html just type<link href="file_name.css" rel="stylesheet">

if i write this code

var express = require('express');
var app = express();
app.use('/css',express.static( 'public/css'));

to access the static files just type in url:localhost:port/css/filename.css ex:http://localhost:8081/css/bootstrap.css

note to link css files with html just add the following line

<link href="css/file_name.css" rel="stylesheet">    

File upload progress bar with jQuery

This solved my problem

var url = "http://localhost/tech1/index.php?route=app/upload/ajax"; 

  xhr: function() {
    var xhr = new window.XMLHttpRequest();

    xhr.upload.addEventListener("progress", function(evt) {
      if (evt.lengthComputable) {
        var percentComplete = evt.loaded /;
        percentComplete = parseInt(percentComplete * 100);
var $link = $('.'+ids);
          var $img = $link.find('i'); 
    }, false);

    return xhr;
  url: url,
  type: "POST",
  data: JSON.stringify(uploaddata),
  contentType: "application/json",
  dataType: "json",
  success: function(result) {

Check if value exists in Postgres array

Simpler with the ANY construct:

SELECT value_variable = ANY ('{1,2,3}'::int[])

The right operand of ANY (between parentheses) can either be a set (result of a subquery, for instance) or an array. There are several ways to use it:

Important difference: Array operators (<@, @>, && et al.) expect array types as operands and support GIN or GiST indices in the standard distribution of PostgreSQL, while the ANY construct expects an element type as left operand and does not support these indices. Example:

None of this works for NULL elements. To test for NULL:

How to access single elements in a table in R

Maybe not so perfect as above ones, but I guess this is what you were looking for.

data[1:1,3:3]    #works with positive integers
data[1:1, -3:-3] #does not work, gives the entire 1st row without the 3rd element
data[i:i,j:j]    #given that i and j are positive integers

Here indexing will work from 1, i.e,

data[1:1,1:1]    #means the top-leftmost element

How to configure slf4j-simple

This is a sample which you can place on the classpath (uncomment the properties you wish to use):

# SLF4J's SimpleLogger configuration file
# Simple implementation of Logger that sends all enabled log messages, for all defined loggers, to System.err.

# Default logging detail level for all instances of SimpleLogger.
# Must be one of ("trace", "debug", "info", "warn", or "error").
# If not specified, defaults to "info".

# Logging detail level for a SimpleLogger instance named "xxxxx".
# Must be one of ("trace", "debug", "info", "warn", or "error").
# If not specified, the default logging detail level is used.

# Set to true if you want the current date and time to be included in output messages.
# Default is false, and will output the number of milliseconds elapsed since startup.

# The date and time format to be used in the output messages.
# The pattern describing the date and time format is the same that is used in java.text.SimpleDateFormat.
# If the format is not specified or is invalid, the default format is used.
# The default format is yyyy-MM-dd HH:mm:ss:SSS Z.
#org.slf4j.simpleLogger.dateTimeFormat=yyyy-MM-dd HH:mm:ss:SSS Z

# Set to true if you want to output the current thread name.
# Defaults to true.

# Set to true if you want the Logger instance name to be included in output messages.
# Defaults to true.

# Set to true if you want the last component of the name to be included in output messages.
# Defaults to false.

"Uncaught Error: [$injector:unpr]" with angular after deployment

If you have separated files for angular app\resources\directives and other stuff then you can just disable minification of your angular app bundle like this (use new Bundle() instead of ScriptBundle() in your bundle config file):

new Bundle("~/bundles/angular/SomeBundleName").Include(

And angular app would appear in bundle unmodified.

Apache: The requested URL / was not found on this server. Apache

In httpd.conf file you need to remove #

#LoadModule rewrite_module modules/

after removing # line will look like this:

LoadModule rewrite_module modules/

And Apache restart

How do I install a color theme for IntelliJ IDEA 7.0.x

Interesting I never spent too much time adjusting the colours in IntelliJ although tried once.

See link below with an already defined colour scheme you can import.

Where can I download IntelliJ IDEA 10 Color Schemes?

Download the jar file, file import the jar where you will see a what to import ;)

enter image description here

Setting environment variables for accessing in PHP when using Apache

Unbelievable, but on httpd 2.2 on centos 6.4 this works.

Export env vars in /etc/sysconfig/httpd

export mydocroot=/var/www/html

Then simply do this...

<VirtualHost *:80>
  DocumentRoot ${mydocroot}

Then finally....

service httpd restart;

JQuery - File attributes

To get the filenames, use:

var files = document.getElementById('inputElementID').files;

Using jQuery (since you already are) you can adapt this to the following:

        var files = this.files;
        for (i=0;i<files.length;i++){
            console.log(files[i].fileName + ' (' + files[i].fileSize + ').');
        return false;

JS Fiddle demo.

How can I rename a conda environment?

Based upon dwanderson's helpful comment, I was able to do this in a Bash one-liner:

conda create --name envpython2 --file <(conda list -n env1 -e )

My badly named env was "env1" and the new one I wish to clone from it is "envpython2".

increase font size of hyperlink text html

There is a way simpler way. You put the href in a paragraph just created for that href. For example:

HREF name

C# Clear Session

The other big difference is Abandon does not remove items immediately, but when it does then cleanup it does a loop over session items to check for STA COM objects it needs to handle specially. And this can be a problem.

Under high load it's possible for two (or more) requests to make it to the server for the same session (that is two requests with the same session cookie). Their execution will be serialized, but since Abandon doesn't clear out the items synchronously but rather sets a flag it's possible for both requests to run, and both requests to schedule a work item to clear out session "later". Both these work items can then run at the same time, and both are checking the session objects, and both are clearing out the array of objects, and what happens when you have two things iterating over a list and changing it?? Boom! And since this happens in a queueuserworkitem callback and is NOT done in a try/catch (thanks MS), it will bring down your entire app domain. Been there.

When do you use the "this" keyword?

There are several usages of this keyword in C#.

  1. To qualify members hidden by similar name
  2. To have an object pass itself as a parameter to other methods
  3. To have an object return itself from a method
  4. To declare indexers
  5. To declare extension methods
  6. To pass parameters between constructors
  7. To internally reassign value type (struct) value.
  8. To invoke an extension method on the current instance
  9. To cast itself to another type
  10. To chain constructors defined in the same class

You can avoid the first usage by not having member and local variables with the same name in scope, for example by following common naming conventions and using properties (Pascal case) instead of fields (camel case) to avoid colliding with local variables (also camel case). In C# 3.0 fields can be converted to properties easily by using auto-implemented properties.

What is a simple C or C++ TCP server and client example?

Although many year ago, clsocket seems a really nice small cross-platform (Windows, Linux, Mac OSX):

What's the difference between the 'ref' and 'out' keywords?

ref tells the compiler that the object is initialized before entering the function, while out tells the compiler that the object will be initialized inside the function.

So while ref is two-ways, out is out-only.

How to test a variable is null in python

    if val is None: # The variable
        print('It is None')
except NameError:
    print ("This variable is not defined")
    print ("It is defined and has a value")

How do you run a script on login in *nix?

From wikipedia Bash

When Bash starts, it executes the commands in a variety of different scripts.

When Bash is invoked as an interactive login shell, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable.

When a login shell exits, Bash reads and executes commands from the file ~/.bash_logout, if it exists.

When an interactive shell that is not a login shell is started, Bash reads and executes commands from ~/.bashrc, if that file exists. This may be inhibited by using the --norc option. The --rcfile file option will force Bash to read and execute commands from file instead of ~/.bashrc.

How do I run a class in a WAR from the command line?

If you're using Maven, just follow the maven-war-plugin documentation about "How do I create a JAR containing the classes in my webapp?": add <attachClasses>true</attachClasses> to the <configuration> of the plugin:


The you will have 2 products in the target/ folder:

  • The project.war itself
  • The project-classes.jar which contains all the compiled classes in a jar

Then you will be able to execute a main class using classic method: java -cp target/project-classes.jar 'com.mycompany.MainClass' param1 param2

How to append one DataTable to another DataTable

You could let your DataAdapter do the work. DataAdapter.Fill(DataTable) will append your new rows to any existing rows in DataTable.

How to retrieve field names from temporary table (SQL Server 2008)

select * 
where table_name like '#MyTempTable%'

Stop MySQL service windows

to stop the service:

sc stop mysql56

and to start it:

sc start mysql56

you might need to change the mysql56 to whatever your version is.

"Line contains NULL byte" in CSV reader (Python)

I've recently fixed this issue and in my instance it was a file that was compressed that I was trying to read. Check the file format first. Then check that the contents are what the extension refers to.

Bootstrap date and time picker

If you are still interested in a javascript api to select both date and time data, have a look at these projects which are forks of bootstrap datepicker:

The first fork is a big refactor on the parsing/formatting codebase and besides providing all views to select date/time using mouse/touch, it also has a mask option (by default) which lets the user to quickly type the date/time based on a pre-specified format.

What's the difference between a Python module and a Python package?

A late answer, yet another definition:

A package is represented by an imported top-entity which could either be a self-contained module, or the special module as the top-entity from a set of modules within a sub directory structure.

So physically a package is a distribution unit, which provides one or more modules.

How do I parse JSON in Android?

I've coded up a simple example for you and annotated the source. The example shows how to grab live json and parse into a JSONObject for detail extraction:

    // Create a new HTTP Client
    DefaultHttpClient defaultClient = new DefaultHttpClient();
    // Setup the get request
    HttpGet httpGetRequest = new HttpGet("http://example.json");

    // Execute the request in the client
    HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
    // Grab the response
    BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
    String json = reader.readLine();

    // Instantiate a JSON object from the request response
    JSONObject jsonObject = new JSONObject(json);

} catch(Exception e){
    // In your production code handle any errors and catch the individual exceptions

Once you have your JSONObject refer to the SDK for details on how to extract the data you require.

Print a file's last modified date in Bash

Best is

date -r filename +"%Y-%m-%d %H:%M:%S"

VBA Check if variable is empty

To check if a Variant is Null, you need to do it like:

Isnull(myvar) = True


Not Isnull(myvar)

Where to put the file

Actually there are 3 places where can be placed:

  1. Under gradle user home directory defined by the GRADLE_USER_HOME environment variable, which if not set defaults to USER_HOME/.gradle
  2. The sub-project directory (myProject2 in your case)
  3. The root project directory (under myProject)

Gradle looks for in all these places while giving precedence to properties definition based on the order above. So for example, for a property defined in gradle user home directory (#1) and the sub-project (#2) its value will be taken from gradle user home directory (#1).

You can find more details about it in gradle documentation here.


I think that parse_str is what you're looking for, something like this should do the trick for you:

parse_str($_SERVER['QUERY_STRING'], $vars);

Then the $vars array will hold all the passed arguments.

Redeploy alternatives to JRebel

DCEVM supports enhanced class redefinitions and is available for current JDK7 and JDK8.

HotswapAgent is an free JRebel alternative and supports DCEVM in various Frameworks.

Difference between jar and war in Java

Jar:- jar contain only .class war:- war contain html, js, css and .class also jsp and servlets pages

javascript regex for password containing at least 8 characters, 1 number, 1 upper and 1 lowercase

Using individual regular expressions to test the different parts would be considerably easier than trying to get one single regular expression to cover all of them. It also makes it easier to add or remove validation criteria.

Note, also, that your usage of .filter() was incorrect; it will always return a jQuery object (which is considered truthy in JavaScript). Personally, I'd use an .each() loop to iterate over all of the inputs, and report individual pass/fail statuses. Something like the below:

$(".buttonClick").click(function () {

    $("input[type=text]").each(function () {
        var validated =  true;
        if(this.value.length < 8)
            validated = false;
            validated = false;
            validated = false;
            validated = false;
            validated = false;
        $('div').text(validated ? "pass" : "fail");
        // use DOM traversal to select the correct div for this input above

Working demo

Regular expression to match numbers with or without commas and decimals in text

This regex:


Matched every number in the string:

1 1.0 0.1 1.001 1,000 1,000,000 1000.1 1,000.1 1,323,444,000 1,999 1,222,455,666.0 1,244

Failed to resolve:

Add the following code on build.gragle (project) for adding Google maven repository

allprojects {
    repositories {
        maven {
            url ''
            name 'Google'

Use placeholders in yaml

With Yglu Structural Templating, your example can be written:

foo: !()
  !? $.propname: 
     type: number 
     default: !? $.default

  !apply .foo: 
    propname: "some_prop"
    default: "some default"

Disclaimer: I am the author or Yglu.

Java8: sum values from specific field of the objects in a list

You can also collect with an appropriate summing collector like Collectors#summingInt(ToIntFunction)

Returns a Collector that produces the sum of a integer-valued function applied to the input elements. If no elements are present, the result is 0.

For example

Stream<Obj> filtered = -> o.field > 10);
int sum = filtered.collect(Collectors.summingInt(o -> o.field));

jQuery convert line breaks to br (nl2br equivalent)

Another way to insert text from a textarea in the DOM keeping the line breaks is to use the Node.innerText property that represents the rendered text content of a node and its descendants.

As a getter, it approximates the text the user would get if they highlighted the contents of the element with the cursor and then copied to the clipboard.

The property became standard in 2016 and is well supported by modern browsers. Can I Use: 97% global coverage when I posted this answer.


I think you should understand what delayed expansion is. The existing answers don't explain it (sufficiently) IMHO.

Typing SET /? explains the thing reasonably well:

Delayed environment variable expansion is useful for getting around the limitations of the current expansion which happens when a line of text is read, not when it is executed. The following example demonstrates the problem with immediate variable expansion:

set VAR=before
if "%VAR%" == "before" (
    set VAR=after
    if "%VAR%" == "after" @echo If you see this, it worked

would never display the message, since the %VAR% in BOTH IF statements is substituted when the first IF statement is read, since it logically includes the body of the IF, which is a compound statement. So the IF inside the compound statement is really comparing "before" with "after" which will never be equal. Similarly, the following example will not work as expected:

set LIST=
for %i in (*) do set LIST=%LIST% %i
echo %LIST%

in that it will NOT build up a list of files in the current directory, but instead will just set the LIST variable to the last file found. Again, this is because the %LIST% is expanded just once when the FOR statement is read, and at that time the LIST variable is empty. So the actual FOR loop we are executing is:

for %i in (*) do set LIST= %i

which just keeps setting LIST to the last file found.

Delayed environment variable expansion allows you to use a different character (the exclamation mark) to expand environment variables at execution time. If delayed variable expansion is enabled, the above examples could be written as follows to work as intended:

set VAR=before
if "%VAR%" == "before" (
    set VAR=after
    if "!VAR!" == "after" @echo If you see this, it worked

set LIST=
for %i in (*) do set LIST=!LIST! %i
echo %LIST%

Another example is this batch file:

@echo off
setlocal enabledelayedexpansion
set b=z1
for %%a in (x1 y1) do (
 set b=%%a
 echo !b:1=2!

This prints x2 and y2: every 1 gets replaced by a 2.

Without setlocal enabledelayedexpansion, exclamation marks are just that, so it will echo !b:1=2! twice.

Because normal environment variables are expanded when a (block) statement is read, expanding %b:1=2% uses the value b has before the loop: z2 (but y2 when not set).

Login failed for user 'DOMAIN\MACHINENAME$'

A colleague had the same error and it was due to a little configuration error in IIS.
The wrong Application Pool was assigned for the web application.

Indeed we use a custom Application Pool with a specific Identity to meet our needs.

In his local IIS Manager -> Sites -> Default Web Site -> Our Web App Name -> Basic Settings... The Application Pool was "DefaultAppPool" instead of our custom Application Pool.

Setting the correct application pool solved the problem.

how to pass this element to javascript onclick function and add a class to that clicked element

<!DOCTYPE html>
<script src=""></script> 
<script type="text/javascript" src="jquery-2.1.0.js"></script> 
<script type="text/javascript" >
function openOnImageClick(event)
//alert("Jai Sh Raam");
// document.getElementById("images").src = "fruits.jpg";
var target = || event.srcElement; // IE

 var img = document.createElement('img');
 img.setAttribute('src', target.src);
  img.setAttribute('width', '200');
   img.setAttribute('height', '150');



<h1>Screen Shot View</h1>
<p>Click the Tiger to display the Image</p>

<div id="images" >

<img src="tiger.jpg" width="100" height="50" alt="unfinished bingo card" onclick="openOnImageClick(event)" />
<img src="sabaLogo1.jpg" width="100" height="50" alt="unfinished bingo card" onclick="openOnImageClick(event)" />


How to get Javascript Select box's selected text

Just use

$('#SelectBoxId option:selected').text(); For Getting text as listed

$('#SelectBoxId').val(); For Getting selected Index value

How to I say Is Not Null in VBA

you can do like follows. Remember, IsNull is a function which returns TRUE if the parameter passed to it is null, and false otherwise.

Not IsNull(Fields!W_O_Count.Value)

position fixed header in html

Well! As I saw my question now, I realized that I didn't want to mention fixed margin value because of the dynamic height of header.

Here is what I have been using for such scenarios.

Calculate the header height using jQuery and apply that as a top margin value.

var divHeight = $('#header-wrap').height(); 
$('#container').css('margin-top', divHeight+'px');


What is the correct way to write HTML using Javascript?

  1. DOM methods, as outlined by Tom.

  2. innerHTML, as mentioned by iHunger.

DOM methods are highly preferable to strings for setting attributes and content. If you ever find yourself writing innerHTML= '<a href="'+path+'">'+text+'</a>' you're actually creating new cross-site-scripting security holes on the client side, which is a bit sad if you've spent any time securing your server-side.

DOM methods are traditionally described as ‘slow’ compared to innerHTML. But this isn't really the whole story. What is slow is inserting a lot of child nodes:

 for (var i= 0; i<1000; i++)
     div.parentNode.insertBefore(document.createElement('div'), div);

This translates to a load of work for the DOM finding the right place in its nodelist to insert the element, moving the other child nodes up, inserting the new node, updating the pointers, and so on.

Setting an existing attribute's value, or a text node's data, on the other hand, is very fast; you just change a string pointer and that's it. This is going to be much faster than serialising the parent with innerHTML, changing it, and parsing it back in (and won't lose your unserialisable data like event handlers, JS references and form values).

There are techniques to do DOM manipulations without so much slow childNodes walking. In particular, be aware of the possibilities of cloneNode, and using DocumentFragment. But sometimes innerHTML really is quicker. You can still get the best of both worlds by using innerHTML to write your basic structure with placeholders for attribute values and text content, which you then fill in afterwards using DOM. This saves you having to write your own escapehtml() function to get around the escaping/security problems mentioned above.

Reverse Y-Axis in PyPlot

There is a new API that makes this even simpler.




How to open a file / browse dialog using javascript?

Create input element.

Missing from these answers is how to get a file dialog without a input element on the page.

The function to show the input file dialog.

function openFileDialog (accept, callback) {  // this function must be called from  a user
                                              // activation event (ie an onclick event)
    // Create an input element
    var inputElement = document.createElement("input");

    // Set its type to file
    inputElement.type = "file";

    // Set accept to the file types you want the user to select. 
    // Include both the file extension and the mime type
    inputElement.accept = accept;

    // set onchange event to call callback when user has selected file
    inputElement.addEventListener("change", callback)
    // dispatch a click event to open the file dialog
    inputElement.dispatchEvent(new MouseEvent("click")); 

NOTE the function must be part of a user activation such as a click event. Attempting to open the file dialog without user activation will fail.

NOTE input.accept is not used in Edge


Calling above function when user clicks an anchor element.

// wait for window to load
window.addEventListener("load", windowLoad);

// open a dialog function
function openFileDialog (accept, multy = false, callback) { 
    var inputElement = document.createElement("input");
    inputElement.type = "file";
    inputElement.accept = accept; // Note Edge does not support this attribute
    if (multy) {
        inputElement.multiple = multy;
    if (typeof callback === "function") {
         inputElement.addEventListener("change", callback);
    inputElement.dispatchEvent(new MouseEvent("click")); 

// onload event
function windowLoad () {
    // add user click event to userbutton
    userButton.addEventListener("click", openDialogClick);

// userButton click event
function openDialogClick () {
    // open file dialog for text files
    openFileDialog(".txt,text/plain", true, fileDialogChanged);

// file dialog onchange event handler
function fileDialogChanged (event) {
    [...this.files].forEach(file => {
        var div = document.createElement("div");
        div.className = "fileList common";
        div.textContent =;
.common {
    font-family: sans-serif;
    padding: 2px;
    margin : 2px;
    border-radius: 4px;
.fileList {
    background: #229;
    color: white;
#userButton {
    background: #999;
    color: #000;
    width: 8em;
    text-align: center;
    cursor: pointer;

#userButton:hover {
   background : #4A4;
   color : white;
<a id = "userButton" class = "common" title = "Click to open file selection dialog">Open file dialog</a>
<div id = "userSelectedFiles" class = "common"></div>

Warning the above snippet is written in ES6.

Setting focus to a textbox control

create a textbox:

 <TextBox Name="tb">

focus() ---> it is used to set input focus to the textbox control


How to get CPU temperature?

I know this post is old, but just wanted to add a comment if somebody should be looking at this post and trying to find a solution for this problem.

You can indeed read the CPU temperature very easily in C# by using a WMI approach.

To get a Celsius value, I have created a wrapper that converts the value returned by WMI and wraps it into an easy to use object.

Please remember to add a reference to the System.Management.dll in Visual Studio.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;

namespace RCoding.Common.Diagnostics.SystemInfo
    public class Temperature
        public double CurrentValue { get; set; }
        public string InstanceName { get; set; }
        public static List<Temperature> Temperatures
                List<Temperature> result = new List<Temperature>();
                ManagementObjectSearcher searcher = new ManagementObjectSearcher(@"root\WMI", "SELECT * FROM MSAcpi_ThermalZoneTemperature");
                foreach (ManagementObject obj in searcher.Get())
                    Double temp = Convert.ToDouble(obj["CurrentTemperature"].ToString());
                    temp = (temp - 2732) / 10.0;
                    result.Add(new Temperature { CurrentValue = temp, InstanceName = obj["InstanceName"].ToString() });
                return result;


Update 25.06.2010:

(Just saw that a link was posted to the same kind of solution above... Anyway, I will leave this piece of code if somebody should want to use it :-) )

Importing variables from another file?

from file1 import *  

will import all objects and methods in file1

How to make a Bootstrap accordion collapse when clicking the header div?

I've noticed a couple of minor flaws in grim's jsfiddle.

To get the pointer to change to a hand for the whole of the panel use:

.panel-heading {
   cursor: pointer;

I've removed the <a> tag (a style issue) and kept data-toggle="collapse" data-parent="#accordion" data-target="#collapse..." on panel-heading throughout.

I've added a CSS method for displaying chevron, using font-awesome.css in my jsfiddle:

How to insert array of data into mysql using php

I've a PHP library which helps to insert array into MySQL Database. By using this you can create update and delete. Your array key value should be same as the table column value. Just using a single line code for the create operation

DB::create($db, 'YOUR_TABLE_NAME', $dataArray);

where $db is your Database connection.

Similarly, You can use this for update and delete. Select operation will be available soon. Github link to download :

Open Jquery modal dialog on click event


$(document).ready(function () {
    $('#dialog_link').click(function () {
        return false;

there is a open arg in the last part

Generate full SQL script from EF 5 Code First Migrations

To add to Matt wilson's answer I had a bunch of code-first entity classes but no database as I hadn't taken a backup. So I did the following on my Entity Framework project:

Open Package Manager console in Visual Studio and type the following:



Give your migration a name such as 'Initial' and then create the migration. Finally type the following:


Update-Database -Script -SourceMigration:0

The final command will create your database tables from your entity classes (provided your entity classes are well formed).

What is the maximum length of a table name in Oracle?

In the 10g database I'm dealing with, I know table names are maxed at 30 characters. Couldn't tell you what the column name length is (but I know it's > 30).

When and why to 'return false' in JavaScript?

I think a better question is, why in a case where you're evaluating a boolean set of return values, would you NOT use true/false? I mean, you could probably have true/null, true/-1, other misc. Javascript "falsy" values to substitute, but why would you do that?

Cross field validation with Hibernate Validator (JSR 303)

If you’re using the Spring Framework then you can use the Spring Expression Language (SpEL) for that. I’ve wrote a small library that provides JSR-303 validator based on SpEL – it makes cross-field validations a breeze! Take a look at

This will validate length and equality of the password fields.

@SpELAssert(value = "pass.equals(passVerify)",
            message = "{validator.passwords_not_same}")
public class MyBean {

    @Size(min = 6, max = 50)
    private String pass;

    private String passVerify;

You can also easily modify this to validate the password fields only when not both empty.

@SpELAssert(value = "pass.equals(passVerify)",
            applyIf = "pass || passVerify",
            message = "{validator.passwords_not_same}")
public class MyBean {

    @Size(min = 6, max = 50)
    private String pass;

    private String passVerify;

Blue and Purple Default links, how to remove?

You need to override the color:

a { color:red } /* Globally */

/* Each state */

a:visited { text-decoration: none; color:red; }
a:hover { text-decoration: none; color:blue; }
a:focus { text-decoration: none; color:yellow; }
a:hover, a:active { text-decoration: none; color:black }

Folder structure for a Node.js project

More example from my project architecture you can see here:

+-- Dockerfile
+-- config
¦   +-- production.json
+-- package.json
+-- schema
¦   +--
¦   +-- db.sql
+-- scripts
¦   +-- 
+-- src
¦   +-- app -> Containes API routes
¦   +-- db -> DB Models (ORM)
¦   +-- server.js -> the Server initlializer.
+-- test

Basically, the logical app separated to DB and APP folders inside the SRC dir.

Call Python function from JavaScript code

Communicating through processes


Python: This python code block should return random temperatures.


import random, time
while True:
    time.sleep(random.random() * 5)  # wait 0 to 5 seconds
    temperature = (random.random() * 20) - 5  # -5 to 15
    print(temperature, flush=True, end='')

Javascript (Nodejs): Here we will need to spawn a new child process to run our python code and then get the printed output.

// temperature-listener.js

const { spawn } = require('child_process');
const temperatures = []; // Store readings

const sensor = spawn('python', ['']);
sensor.stdout.on('data', function(data) {

    // convert Buffer object to Float

Inserting into Oracle and retrieving the generated sequence ID

There are no auto incrementing features in Oracle for a column. You need to create a SEQUENCE object. You can use the sequence like:

insert into table(batch_id, ...) values(my_sequence.nextval, ...) return the next number. To find out the last created sequence nr (in your session), you would use:


This site has several complete examples on how to use sequences.

load jquery after the page is fully loaded

If you're trying to avoid loading jquery until your content has been loaded, the best way is to simply put the reference to it in the bottom of your page, like many other answers have said.

General tips on Jquery usage:

  1. Use a CDN. This way, your site can use the cached version a user likely has on their computer. The // at the beginning allows it to be called (and use the same resource) whether it's http or https. Example:

    <script src="//"></script>

Using a CDN has a couple of big benefits: it makes it more likely that users have it cached from another site, so there will be no download (and no render-blocking). Further, CDNs use the closest, fastest connection available, meaning that if they do need to load it, it will probably be faster than connecting to your server. More info from Google.

  1. Put scripts at the bottom. Move as much of your js to the bottom of the page as possible. I use php to include a file with all my JS resources below the footer.

  2. If you're using a template system, you may need to have javascript spread throughout the html output. If you're using jquery in scripts that get called as the page renders, this will cause errors. To have your scripts wait until jquery is loaded, put them into

    window.onload() = function () { //... your js that isn't called by user interaction ... }

This will prevent errors but still run before user interaction and without timers.

Of course, if jquery is cached, it won't matter too much where you put it, except to page speed tools that will tell you you're blocking rendering.

Android Endless List

Here is a solution that also makes it easy to show a loading view in the end of the ListView while it's loading.

You can see the classes here: - Helper to make it possible to use the features without extending from SimpleListViewWithLoadingIndicator. - Listener that starts loading data when the user is about to reach the bottom of the ListView. - The EndlessListView. You can use this class directly or extend from it.

How to use cURL in Java?

Using standard java libs, I suggest looking at the HttpUrlConnection class

It can handle most of what curl can do with setting up the connection. What you do with the stream is up to you.

List View Filter Android

Add an EditText on top of your listview in its .xml layout file. And in your activity/fragment..

lv = (ListView) findViewById(;
    inputSearch = (EditText) findViewById(;

// Adding items to listview
adapter = new ArrayAdapter<String>(this, R.layout.list_item,,    products);
inputSearch.addTextChangedListener(new TextWatcher() {

    public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
        // When user changed the Text

    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }

    public void afterTextChanged(Editable arg0) {}

The basic here is to add an OnTextChangeListener to your edit text and inside its callback method apply filter to your listview's adapter.


To get filter to your custom BaseAdapter you"ll need to implement Filterable interface.

class CustomAdapter extends BaseAdapter implements Filterable {

    public View getView(){
    public Integer getCount()

    public Filter getFilter() {

        Filter filter = new Filter() {

            protected void publishResults(CharSequence constraint, FilterResults results) {

                arrayListNames = (List<String>) results.values;

            protected FilterResults performFiltering(CharSequence constraint) {

                FilterResults results = new FilterResults();
                ArrayList<String> FilteredArrayNames = new ArrayList<String>();

                // perform your search here using the searchConstraint String.

                constraint = constraint.toString().toLowerCase();
                for (int i = 0; i < mDatabaseOfNames.size(); i++) {
                    String dataNames = mDatabaseOfNames.get(i);
                    if (dataNames.toLowerCase().startsWith(constraint.toString()))  {

                results.count = FilteredArrayNames.size();
                results.values = FilteredArrayNames;
                Log.e("VALUES", results.values.toString());

                return results;

        return filter;

Inside performFiltering() you need to do actual comparison of the search query to values in your database. It will pass its result to publishResults() method.

How to drop columns using Rails migration

rails g migration RemoveXColumnFromY column_name:data_type

X = column name
Y = table name


Changed RemoveXColumnToY to RemoveXColumnFromY as per comments - provides more clarity for what the migration is actually doing.

How to do logging in React Native?

Just console.log('debug');

And run it you can see the log in the terminal/cd prompt .

Convert a Unix timestamp to time in JavaScript

shortest one-liner solution to format seconds as hh:mm:ss: variant:

console.log(new Date(1549312452 * 1000).toISOString().slice(0, 19).replace('T', ' '));_x000D_
// "2019-02-04 20:34:12"

If input value is blank, assign a value of "empty" with Javascript

You can do this:

var getValue  = function (input, defaultValue) {
    return input.value || defaultValue;

How can I insert a line break into a <Text> component in React Native?

this is a nice question , you can do this in multiple ways First

        Hi this is first line  {\n}  hi this is second line 

which means you can use {\n} backslash n to break the line


         Hi this is first line
             hi this is second line 

which means you can use another <View> component inside first <View> and wrap it around <Text> component

Happy Coding

How to read file from res/raw by name

With the help of the given links I was able to solve the problem myself. The correct way is to get the resource ID with

                             "raw", getPackageName());

To get it as a InputStream

InputStream ins = getResources().openRawResource(
            "raw", getPackageName()));

Java associative-array

Java doesn't have associative arrays, the closest thing you can get is the Map interface

Here's a sample from that page.

import java.util.*;

public class Freq {
    public static void main(String[] args) {
        Map<String, Integer> m = new HashMap<String, Integer>();

        // Initialize frequency table from command line
        for (String a : args) {
            Integer freq = m.get(a);
            m.put(a, (freq == null) ? 1 : freq + 1);

        System.out.println(m.size() + " distinct words:");

If run with:

java Freq if it is to be it is up to me to delegate

You'll get:

8 distinct words:
{to=3, delegate=1, be=1, it=2, up=1, if=1, me=1, is=2}

When should you use a class vs a struct in C++?

Structs (PODs, more generally) are handy when you're providing a C-compatible interface with a C++ implementation, since they're portable across language borders and linker formats.

If that's not a concern to you, then I suppose the use of the "struct" instead of "class" is a good communicator of intent (as @ZeroSignal said above). Structs also have more predictable copying semantics, so they're useful for data you intend to write to external media or send across the wire.

Structs are also handy for various metaprogramming tasks, like traits templates that just expose a bunch of dependent typedefs:

template <typename T> struct type_traits {
  typedef T type;
  typedef T::iterator_type iterator_type;

...But that's really just taking advantage of struct's default protection level being public...

How to Generate Unique Public and Private Key via RSA

What I ended up doing is create a new KeyContainer name based off of the current DateTime (DateTime.Now.Ticks.ToString()) whenever I need to create a new key and save the container name and public key to the database. Also, whenever I create a new key I would do the following:

public static string ConvertToNewKey(string oldPrivateKey)

    // get the current container name from the database...

    rsa.PersistKeyInCsp = false;
    rsa = null;

    string privateKey = AssignNewKey(true); // create the new public key and container name and write them to the database...

       // re-encrypt existing data to use the new keys and write to database...

    return privateKey;
public static string AssignNewKey(bool ReturnPrivateKey){
     string containerName = DateTime.Now.Ticks.ToString();
     // create the new key...
     // saves container name and public key to database...
     // and returns Private Key XML.

before creating the new key.

Guid.NewGuid() vs. new Guid()

new Guid() makes an "empty" all-0 guid (00000000-0000-0000-0000-000000000000 is not very useful).

Guid.NewGuid() makes an actual guid with a unique value, what you probably want.

How to run a makefile in Windows?

I tried all of above. What helps me:

  1. Download the mingw-get.
  2. Setup it.
  3. Add something like this C:\MinGW\bin to environment variables.
  4. Launch (!important) git bash. Power shell, developer vs cmd, system cmd etc did'nt help.
  5. Type mingw-get into command line.
  6. After type mingw-get install mingw32-make.
  7. Copy and paste all files from C:\MinGW\bin to folder where your Makefile is. Done! Now You might be able to use make-commands in this folder.

XmlSerializer giving FileNotFoundException at constructor

In Visual Studio project properties ("Build" page, if I recall it right) there is an option saying "generate serialization assembly". Try turning it on for a project that generates [Containing Assembly of MyType].

What is correct media query for IPad Pro?

For those who want to target an iPad Pro 11" the device-width is 834px, device-height is 1194px and the device-pixel-ratio is 2. Source: screen.width, screen.height and devicePixelRatio reported by Safari on iOS Simulator.

Exact media query for portrait: (device-height: 1194px) and (device-width: 834px) and (-webkit-device-pixel-ratio: 2) and (orientation: portrait)

How can I avoid Java code in JSP files, using JSP 2?

If we use the following things in a Java web application, Java code can be eliminated from the foreground of the JSP file.

  1. Use the MVC architecture for a web application

  2. Use JSP Tags

a. Standard Tags

b. Custom Tags

  1. Expression Language

Adding Counter in shell script

Here's how you might implement a counter:

while true; do
  if /home/hadoop/latest/bin/hadoop fs -ls /apps/hdtech/bds/quality-rt/dt=$DATE_YEST_FORMAT2 then
       echo "Files Present" | mailx -s "File Present"  -r [email protected] [email protected]
       exit 0
  elif [[ "$counter" -gt 20 ]]; then
       echo "Counter: $counter times reached; Exiting loop!"
       exit 1
       echo "Counter: $counter time(s); Sleeping for another half an hour" | mailx -s "Time to Sleep Now"  -r [email protected] [email protected]
       sleep 1800

Some Explanations:

  • counter=$((counter+1)) - this is how you can increment a counter. The $ for counter is optional inside the double parentheses in this case.
  • elif [[ "$counter" -gt 20 ]]; then - this checks whether $counter is not greater than 20. If so, it outputs the appropriate message and breaks out of your while loop.

Removing address bar from browser (to view on Android)

Finally I Try with this. Its worked for me..

  public void onCreate(Bundle savedInstanceState) {


    //webview use to call own site
    webview =(WebView)findViewById(;

    webview.setWebViewClient(new WebViewClient());       
    webview .getSettings().setJavaScriptEnabled(true);
    webview .getSettings().setDomStorageEnabled(true);     

and your entire main.xml(res/layout) look should like this:

<WebView  xmlns:android=""

don't go to add layouts.

xsd:boolean element type accept "true" but not "True". How can I make it accept it?

If you're on Linux, or have cygwin available on Windows, you can run the input XML through a simple sed script that will replace <Active>True</Active> with <Active>true</Active>, like so:

cat <your XML file> | sed 'sX<Active>True</Active>X<Active>true</Active>X' | xmllint --schema -

If you're not, you can still use a non-validating xslt pocessor (xalan, saxon etc.) to run a simple xslt transformation on the input, and only then pipe it to xmllint.

What the xsl should contain something like below, for the example you listed above (the xslt processor should be 2.0 capable):

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="" version="2.0">
    <xsl:output method="xml" indent="yes"/>
    <xsl:template match="/">
    <xsl:for-each select="XML">
        <xsl:for-each select="Active">
            <xsl:value-of select=" replace(current(), 'True','true')"/>

Can CSS detect the number of children an element has?

No, there is nothing like this in CSS. You can, however, use JavaScript to calculate the number of children and apply styles.

SQL Server Profiler - How to filter trace to only display events from one database?

Under Trace properties > Events Selection tab > select show all columns. Now under column filters, you should see the database name. Enter the database name for the Like section and you should see traces only for that database.

A 'for' loop to iterate over an enum in Java

If you don't care about the order this should work:

Set<Direction> directions = EnumSet.allOf(Direction.class);
for(Direction direction : directions) {
    // do stuff

Bash script to check running process

I tried your version on BASH version 3.2.29, worked fine. However, you could do something like the above suggested, an example here:


RESULT=`ps -ef | grep $1 | grep -v 'grep' | grep -v $0`
result=$(echo $ps_out | grep "$1")

if [[ "$result" != "" ]];then
    echo "Running"
    echo "Not Running"

Counting duplicates in Excel

This can be done using pivot tables. See this youtube video for a walkthrough: Quickly Count Duplicates in Excel List With Pivot Table.

To count the number of times each item is duplicated in an Excel list, you can use a pivot table, instead of manually creating a list with formulas.

HTML iframe - disable scroll

Unfortunately I do not believe it's possible in fully-conforming HTML5 with just HTML and CSS properties. Fortunately however, most browsers do still support the scrolling property (which was removed from the HTML5 specification).

overflow isn't a solution for HTML5 as the only modern browser which wrongly supports this is Firefox.

A current solution would be to combine the two:

<iframe src="" scrolling="no"></iframe>
iframe {
  overflow: hidden;

But this could be rendered obsolete as browsers update. You may want to check this for a JavaScript solution:

Edit: I've checked and scrolling="no" will work in IE10, Chrome 25 and Opera 12.12.

Count the number of items in my array list

Using Java 8 stream API:

 String[] keys = new String[0];

// A map for keys and their count
Map<String, Long> keyCountMap =
collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
int uniqueItemIdCount= keyCountMap.size();

How to change an input button image using CSS?

I think the following is the best solution:


.edit-button {
    background-image: url(edit.png);
    background-size: 100%;
    width: 24px;
    height: 24px;


<input class="edit-button" type="image" src="transparent.png" />

How to use onClick() or onSelect() on option tag in a JSP page?

If you need to change the value of another field, you can use this:

<input type="hidden" id="mainvalue" name="mainvalue" value="0">
<select onChange="document.getElementById('mainvalue').value = this.value;">
<option value="0">option 1</option>
<option value="1">option 2</option>

Why can't I define a static method in a Java interface?

Why can't I define a static method in a Java interface?

All methods in an interface are explicitly abstract and hence you cannot define them as static because static methods cannot be abstract.

Best way to remove items from a collection

There is another approach you can take depending on how you're using your collection. If you're downloading the assignments one time (e.g., when the app runs), you could translate the collection on the fly into a hashtable where:

shortname => SPRoleAssignment

If you do this, then when you want to remove an item by short name, all you need to do is remove the item from the hashtable by key.

Unfortunately, if you're loading these SPRoleAssignments a lot, that obviously isn't going to be any more cost efficient in terms of time. The suggestions other people made about using Linq would be good if you're using a new version of the .NET Framework, but otherwise, you'll have to stick to the method you're using.

How can I exclude all "permission denied" messages from "find"?

While above approaches do not address the case for Mac OS X because Mac Os X does not support -readable switch this is how you can avoid 'Permission denied' errors in your output. This might help someone.

find / -type f -name "your_pattern" 2>/dev/null.

If you're using some other command with find, for example, to find the size of files of certain pattern in a directory 2>/dev/null would still work as shown below.

find . -type f -name "your_pattern" -exec du -ch {} + 2>/dev/null | grep total$.

This will return the total size of the files of a given pattern. Note the 2>/dev/null at the end of find command.

Windows equivalent of $export

There is not an equivalent statement for export in Windows Command Prompt. In Windows the environment is copied so when you exit from the session (from a called command prompt or from an executable that set a variable) the variable in Windows get lost. You can set it in user registry or in machine registry via setx but you won't see it if you not start a new command prompt.

How to override a JavaScript function

var origParseFloat = parseFloat;
parseFloat = function(str) {
     alert("And I'm in your floats!");
     return origParseFloat(str);

Allow Access-Control-Allow-Origin header using HTML5 fetch API

I know this is an older post, but I found what worked for me to fix this error was using the IP address of my server instead of using the domain name within my fetch request. So for example:

#(original) var request = new Request('');
#use IP instead
var request = new Request('');

fetch(request).then(function(response) {
    // Convert to JSON
    return response.json();
}).then(function(j) {
    // Yay, `j` is a JavaScript object
}).catch(function(error) {
    console.log('Request failed', error)

How to escape a JSON string to have it in a URL?

Answer given by Delan is perfect. Just adding to it - incase someone wants to name the parameters or pass multiple JSON strings separately - the below code could help!


var valuesToPass = new Array(encodeURIComponent(VALUE_1), encodeURIComponent(VALUE_2), encodeURIComponent(VALUE_3), encodeURIComponent(VALUE_4));

data = {elements:JSON.stringify(valuesToPass)}



Hope this helps!

JQuery show and hide div on mouse click (animate)

That .toggle() method was removed from jQuery in version 1.9. You can do this instead:

$(document).ready(function() {
    $('#showmenu').click(function() {


...but as with the code in your question that would slide up or down. To slide left or right you can do the following:

$(document).ready(function() {
    $('#showmenu').click(function() {


Noting that this requires jQuery-UI's slide effect, but you added that tag to your question so I assume that is OK.

How to remove .html from URL?

Good question, but it seems to have confused people. The answers are almost equally divided between those who thought Dave (the OP) was saving his HTML pages without the .html extension, and those who thought he was saving them as normal (with .html), but wanting the URL to show up without. While the question could have been worded a little better, I think it’s clear what he meant. If he was saving pages without .html, his two question (‘how to remove .html') and (how to ‘redirect any url with .html’) would be exactly the same question! So that interpretation doesn’t make much sense. Also, his first comment (about avoiding an infinite loop) and his own answer seem to confirm this.

So let’s start by rephrasing the question and breaking down the task. We want to accomplish two things:

  1. Visibly remove the .html if it’s part of the requested URL (e.g. /page.html)
  2. Point the cropped URL (e.g. /page) back to the actual file (/page.html).

There’s nothing difficult about doing either of these things. (We could achieve the second one simply by enabling MultiViews.) The challenge here is doing them both without creating an infinite loop.

Dave’s own answer got the job done, but it’s pretty convoluted and not at all portable. (Sorry Dave.) Lukasz Habrzyk seems to have cleaned up Anmol’s answer, and finally Amit Verma improved on them both. However, none of them explained how their solutions solved the fundamental problem—how to avoid an infinite loop. As I understand it, they work because THE_REQUEST variable holds the original request from the browser. As such, the condition (RewriteCond %{THE_REQUEST}) only gets triggered once. Since it doesn’t get triggered upon a rewrite, you avoid the infinite loop scenario. But then you're dealing with the full HTTP request—GET, HTTP and all—which partly explains some of the uglier regex examples on this page.

I’m going to offer one more approach, which I think is easier to understand. I hope this helps future readers understand the code they’re using, rather than just copying and pasting code they barely understand and hoping for the best.

RewriteEngine on

# Remove .html (or htm) from visible URL (permanent redirect)
RewriteCond %{REQUEST_URI} ^/(.+)\.html?$ [nocase]
RewriteRule ^ /%1 [L,R=301]

# Quietly point back to the HTML file (temporary/undefined redirect):
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^ %{REQUEST_URI}.html [END]

Let’s break it down…

The first rule is pretty simple. The condition matches any URL ending in .html (or .htm) and redirects to the URL without the filename extension. It's a permanent redirect to indicate that the cropped URL is the canonical one.

The second rule is simple too. The first condition will only pass if the requested filename is not a valid directory (!-d). The second will only pass if the filename refers to a valid file (-f) with the .html extension added. If both conditions pass, the rewrite rule simply adds ‘.html’ to the filename. And then the magic happens… [END]. Yep, that’s all it takes to prevent an infinite loop. The Apache RewriteRule Flags documentation explains it:

Using the [END] flag terminates not only the current round of rewrite processing (like [L]) but also prevents any subsequent rewrite processing from occurring in per-directory (htaccess) context.

How to convert string to datetime format in pandas python?

Use to_datetime, there is no need for a format string the parser is man/woman enough to handle it:

In [51]:

0   2012-03-28 14:15:00
1   2012-03-28 14:17:28
2   2012-03-28 14:50:50
Name: I_DATE, dtype: datetime64[ns]

To access the date/day/time component use the dt accessor:

In [54]:

0    2012-03-28
1    2012-03-28
2    2012-03-28
dtype: object

In [56]:    

0    14:15:00
1    14:17:28
2    14:50:50
dtype: object

You can use strings to filter as an example:

In [59]:
df = pd.DataFrame({'date':pd.date_range(start = dt.datetime(2015,1,1), end =})
df[(df['date'] > '2015-02-04') & (df['date'] < '2015-02-10')]

35 2015-02-05
36 2015-02-06
37 2015-02-07
38 2015-02-08
39 2015-02-09

fatal error C1083: Cannot open include file: 'xyz.h': No such file or directory?

Add the "code" folder to the project properties within Visual Studio

Project->Properties->Configuration Properties->C/C++->Additional Include Directories

How can I make a jQuery UI 'draggable()' div draggable for touchscreen?

jQuery ui 1.9 is going to take care of this for you. Heres a demo of the pre:

Just grab the jquery.mouse.ui.js out, stick it under the jQuery ui file you're loading, and that's all you should have to do! Works for sortable as well.

This code is working great for me, but if your getting errors, an updated version of jquery.mouse.ui.js can be found here:

Jquery-ui sortable doesn't work on touch devices based on Android or IOS