Programs & Examples On #Calibre

calibre is a free and open source e-book library management application.

JavaScript data grid for millions of rows

best approach i could think of is by loading the chunk of data in json format for every scroll or some limit before the scrolling ends. json can be easily converted to objects and hence table rows can be constructed easily unobtrusively

Laravel Advanced Wheres how to pass variable into function?

You can pass variables using this...

$status =1;
 $info = JOBS::where(function($query) use ($status){        

How to set initial value and auto increment in MySQL?

First you need to add column for auto increment

alter table users add column id int(5) NOT NULL AUTO_INCREMENT FIRST

This query for add column at first. Now you have to reset auto increment initial value. So use this query

alter table users AUTO_INCREMENT=1001

Now your table started with 1001

PHP mail not working for some reason

I'm using this for a while now, don't know if this is still up to date with the actual PHP versions. You can use this in a one file setup, or just split it up in two files like contact.php and index.php

contact.php | Code

error_reporting(E_ALL ^ E_NOTICE); 

if(isset($_POST['submitted'])) {

if(trim($_POST['contactName']) === '') {
    $nameError =  '<span style="margin-left:40px;">You have missed your name.</span>'; 
    $hasError = true;
} else {
    $name = trim($_POST['contactName']);

if(trim($_POST['topic']) === '') {
    $topicError = '<span style="margin-left:40px;">You have missed the topic.</span>'; 
    $hasError = true;
} else {
    $topic = trim($_POST['topic']);

$telefon = trim($_POST['phone']);
$company = trim($_POST['company']);

if(trim($_POST['email']) === '')  {
    $emailError = '<span style="margin-left:40px;">You have missed your email adress.</span>';
    $hasError = true;
} else if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*@[a-z0-9.-]+\.[a-z]{2,4}$/i", trim($_POST['email']))) {
    $emailError = '<span style="margin-left:40px;">You have missspelled your email adress.</span>';
    $hasError = true;
} else {
    $email = trim($_POST['email']);

if(trim($_POST['comments']) === '') {
    $commentError = '<span style="margin-left:40px;">You have missed the comment section.</span>';
    $hasError = true;
} else {
    if(function_exists('stripslashes')) {
        $comments = utf8_encode(stripslashes(trim($_POST['comments'])));
    } else {
        $comments = trim($_POST['comments']);

if(!isset($hasError)) {

    $emailTo = '[email protected]';
    $subject = ' - '.$name.' - '.$betreff;
    $sendCopy = trim($_POST['sendCopy']);
    $body = "\n\n This is an email from \n\nCompany : $company\n\nName : $name \n\nEmail-Adress : $email \n\nPhone-No.. : $phone \n\nTopic : $topic\n\nMessage of the sender: $comments\n\n";
    $headers = "From: $email\r\nReply-To: $email\r\nReturn-Path: $email\r\n";

    mail($emailTo, $subject, $body, $headers);

    $emailSent = true;


.formblock{display:block;padding:5px;margin:8px; margin-left:40px;}
.failed{ margin-left:20px;font-size:18px;color:#C00;}
.alert{border:2px #fc0;padding:8px;text-transform:uppercase;font-weight:bold;}




index.php | FORM CODE

<?php header('Content-Type: text/html;charset=UTF-8'); ?>
<!DOCTYPE html>
<html lang="de">
<script type="text/javascript" src="js/jquery.js"></script>

<form action="contact.php" method="post">

<?php if(isset($emailSent) && $emailSent == true) { ?>

<span class="okay">Thank you for your interest. Your email has been send !</span>



<?php } else { ?>

<?php if(isset($hasError) || isset($captchaError) ) { ?>

<span class="failed">Email not been send. Please check the contact form.</span>



<?php } ?>

<label class="text label">Company</label>


<input type="text" size="30" name="company" id="company" value="<?php if(isset($_POST['company'])) echo $_POST['comnpany'];?>" class="formblock" placeholder="Your Company">

<label class="text label">Your Name <strong class="error">*</strong></label>


<?php if($nameError != '') { ?>

<span class="error"><?php echo $nameError;?></span>

<?php } ?>

<input type="text" size="30" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" class="formblock" placeholder="Your Name">

<label class="text label">- Betreff - Anliegen - <strong class="error">*</strong></label>


<?php if($topicError != '') { ?>

<span class="error"><?php echo $betrError;?></span>

<?php } ?>

<input type="text" size="30" name="topic" id="topic" value="<?php if(isset($_POST['topic'])) echo $_POST['topic'];?>" class="formblock" placeholder="Your Topic">

<label class="text label">Phone-No.</label>


<input type="text" size="30" name="phone" id="phone" value="<?php if(isset($_POST['phone'])) echo $_POST['phone'];?>" class="formblock" placeholder="12345 678910">

<label class="text label">Email-Adress<strong class="error">*</strong></label>


<?php if($emailError != '') { ?>

<span class="error"><?php echo $emailError;?></span>

<?php } ?>

<input type="text" size="30" name="email" id="email" value="<?php if(isset($_POST['email']))  echo $_POST['email'];?>" class="formblock" placeholder="[email protected]">

<label class="text label">Your Message<strong class="error">*</strong></label>


<?php if($commentError != '') { ?>

<span class="error"><?php echo $commentError;?></span>

<?php } ?>

<textarea name="comments" id="commentsText" class="formblock text" placeholder="Leave your message here..."><?php if(isset($_POST['comments'])) { if(function_exists('stripslashes')) { echo stripslashes($_POST['comments']); } else { echo $_POST['comments']; } } ?></textarea>

<button class="formblock" name="submit" type="submit">Send Email</button>
<input type="hidden" name="submitted" id="submitted" value="true">
<?php } ?>



<script type="text/javascript">


$(document).ready(function() {

$('form#contact-us').submit(function() {

$('form#contact-us .error').remove();
var hasError = false;

$('.requiredField').each(function() {

if($.trim($(this).val()) == '') {
var labelText = $(this).prev('label').text();

$(this).parent().append('<br><br><span style="margin-left:20px;">You have missed '+labelText+'.</span>.');

hasError = true;

} else if($(this).hasClass('email')) {

var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
if(!emailReg.test($.trim($(this).val()))) {

var labelText = $(this).prev('label').text();

$(this).parent().append('<br><br><span style="margin-left:20px;">You have entered a wrong '+labelText+' adress.</span>.');

hasError = true;
if(!hasError) {

var formInput = $(this).serialize();

$.post($(this).attr('action'),formInput, function(data){

$('form#contact-us').slideUp("fast", function() {                  
$(this).before('<br><br><strong>Thank You!</strong>Your Email has been send successfuly.');



return false;   





How should I pass multiple parameters to an ASP.Net Web API GET?

What does this record marking mean? If this is used only for logging purposes, I would use GET and disable all caching, since you want to log every query for this resources. If record marking has another purpose, POST is the way to go. User should know, that his actions effect the system and POST method is a warning.

Can you have a <span> within a <span>?

Yes. You can have a span within a span. Your problem stems from something else.

How to set background image in Java?

function SetBack(dir) {

How to create cross-domain request?

In fact, there is nothing to do in Angular2 regarding cross domain requests. CORS is something natively supported by browsers. This link could help you to understand how it works:

To be short, in the case of cross domain request, the browser automatically adds an Origin header in the request. There are two cases:

  • Simple requests. This use case applies if we use HTTP GET, HEAD and POST methods. In the case of POST methods, only content types with the following values are supported: text/plain, application/x-www-form-urlencoded and multipart/form-data.
  • Preflighted requests. When the "simple requests" use case doesn't apply, a first request (with the HTTP OPTIONS method) is made to check what can be done in the context of cross-domain requests.

So in fact most of work must be done on the server side to return the CORS headers. The main one is the Access-Control-Allow-Origin one.

200 OK HTTP/1.1
Access-Control-Allow-Origin: *

To debug such issues, you can use developer tools within browsers (Network tab).

Regarding Angular2, simply use the Http object like any other requests (same domain for example):

return this.http.get('')
           .map(res => res.json()).subscribe(

How to git commit a single file/directory

For git 1.9.5 on Windows 7: "my Notes" (double quotes) corrected this issue. In my case putting the file(s) before or after the -m 'message'. made no difference; using single quotes was the problem.

How to check if smtp is working from commandline (Linux)

Syntax for establishing a raw network connection using telnet is this:

telnet {domain_name} {port_number}

So telnet to your smtp server like

telnet 25

And copy and paste the below

mail from:<[email protected]>
rcpt to:<[email protected]>
From: [email protected]
Subject: test mail from command line

this is test number 1
sent from linux box

Note : Do not forgot the "." at the end which represents the end of the message. The "quit" line exits ends the session.

How to add a RequiredFieldValidator to DropDownList control?

For the most part you treat it as if you are validating any other kind of control but use the InitialValue property of the required field validator.

<asp:RequiredFieldValidator ID="rfv1" runat="server" ControlToValidate="your-dropdownlist" InitialValue="Please select" ErrorMessage="Please select something" />

Basically what it's saying is that validation will succeed if any other value than the 1 set in InitialValue is selected in the dropdownlist.

If databinding you will need to insert the "Please select" value afterwards as follows

this.ddl1.Items.Insert(0, "Please select");

Node.js - EJS - including a partial

In Express 4.x I used the following to load ejs:

  var path = require('path');

  // Set the default templating engine to ejs
  app.set('view engine', 'ejs');
  app.set('views', path.join(__dirname, 'views'));

  // The views/index.ejs exists in the app directory
  app.get('/hello', function (req, res) {
    res.render('index', {title: 'title'});

Then you just need two files to make it work - views/index.ejs:

<%- include partials/navigation.ejs %>

And the views/partials/navigation.ejs:

<ul><li class="active">...</li>...</ul>

You can also tell Express to use ejs for html templates:

var path = require('path');
var EJS  = require('ejs');

app.engine('html', EJS.renderFile);

// Set the default templating engine to ejs
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

// The views/index.html exists in the app directory
app.get('/hello', function (req, res) {
  res.render('index.html', {title: 'title'});

Finally you can also use the ejs layout module:

var EJSLayout = require('express-ejs-layouts');

This will use the views/layout.ejs as your layout.

undefined reference to `std::ios_base::Init::Init()'

Most of these linker errors occur because of missing libraries.

I added the libstdc++.6.dylib in my Project->Targets->Build Phases-> Link Binary With Libraries.

That solved it for me on Xcode 6.3.2 for iOS 8.3


Hot deploy on JBoss - how do I make JBoss "see" the change?

Solution for Netbeans 8.02 and 8.1 IDE and JBOSS EAP 6.4:

  1. From the services tab of Netbeans, add JBOSS server to your "servers" node.
  2. If you are using MAVEN, netbeans compiles files and maven copies files to ./target directory. You need to create a symbolic link from .\target to JBOSS_HOME\standalone\deployments. Under windows, an example command would be

    cd %JBOSS_HOME%\standalone\deployments mklink /d MyWebApplication.war %PROJECTS_HOME%\MyWebApplication\target\MyWebApplication-1.0.0

    The above creates a symbolic link from %JBOSS_HOME%\standalone\deployments\MyWebApplication.war to \target\MyWebApplication-1.0.0 which is where maven transfers all files after compilation, or after a jsp, html or any other file changes.

  3. Last think to do is to create a CentralManagement.war.dodeploy file in %JBOSS_HOME%\standalone\deployments. This file will tell JBOSS to deploy the war "file" as a web application

APT command line interface-like yes/no input?

As a programming noob, I found a bunch of the above answers overly complex, especially if the goal is to have a simple function that you can pass various yes/no questions to, forcing the user to select yes or no. After scouring this page and several others, and borrowing all of the various good ideas, I ended up with the following:

def yes_no(question_to_be_answered):
    while True:
        choice = input(question_to_be_answered).lower()
        if choice[:1] == 'y': 
            return True
        elif choice[:1] == 'n':
            return False
            print("Please respond with 'Yes' or 'No'\n")

#See it in Practice below 

musical_taste = yes_no('Do you like Pine Coladas?')
if musical_taste == True:
    print('and getting caught in the rain')
elif musical_taste == False:
    print('You clearly have no taste in music')

How to get the number of columns in a matrix?

While size(A,2) is correct, I find it's much more readable to first define

rows = @(x) size(x,1); 
cols = @(x) size(x,2);

and then use, for example, like this:

howManyColumns_in_A = cols(A)
howManyRows_in_A    = rows(A)

It might appear as a small saving, but size(.., 1) and size(.., 2) must be some of the most commonly used functions, and they are not optimally readable as-is.

Use Font Awesome Icons in CSS

#content h2:before {
    content: "\f055";
    font-family: FontAwesome;

Example Link:

Get Icon code from:

SQLite equivalent to ISNULL(), NVL(), IFNULL() or COALESCE()

Use IS NULL or IS NOT NULL in WHERE-clause instead of ISNULL() method:

SELECT myField1
FROM myTable1

How to use parameters with HttpPost

Generally speaking an HTTP POST assumes the content of the body contains a series of key/value pairs that are created (most usually) by a form on the HTML side. You don't set the values using setHeader, as that won't place them in the content body.

So with your second test, the problem that you have here is that your client is not creating multiple key/value pairs, it only created one and that got mapped by default to the first argument in your method.

There are a couple of options you can use. First, you could change your method to accept only one input parameter, and then pass in a JSON string as you do in your second test. Once inside the method, you then parse the JSON string into an object that would allow access to the fields.

Another option is to define a class that represents the fields of the input types and make that the only input parameter. For example

class MyInput
    String str1;
    String str2;

    public MyInput() { }
      //  getters, setters

public void create(MyInput in){
System.out.println("value 1 = " + in.getStr1());
System.out.println("value 2 = " + in.getStr2());

Depending on the REST framework you are using it should handle the de-serialization of the JSON for you.

The last option is to construct a POST body that looks like:


then add some additional annotations to your server method:

public void create(@QueryParam("str1") String str1, 
                  @QueryParam("str2") String str2)

@QueryParam doesn't care if the field is in a form post or in the URL (like a GET query).

If you want to continue using individual arguments on the input then the key is generate the client request to provide named query parameters, either in the URL (for a GET) or in the body of the POST.

Ignore python multiple return value

This seems like the best choice to me:

val1, val2, ignored1, ignored2 = some_function()

It's not cryptic or ugly (like the func()[index] method), and clearly states your purpose.

How do I get the current time zone of MySQL?

Use LPAD(TIME_FORMAT(TIMEDIFF(NOW(), UTC_TIMESTAMP),’%H:%i’),6,’+') to get a value in MySQL's timezone format that you can conveniently use with CONVERT_TZ(). Note that the timezone offset you get is only valid at the moment in time where the expression is evaluated since the offset may change over time if you have daylight savings time. Yet the expression is useful together with NOW() to store the offset with the local time, which disambiguates what NOW() yields. (In DST timezones, NOW() jumps back one hour once a year, thus has some duplicate values for distinct points in time).

Customize Bootstrap checkboxes

As others have said, the style you're after is actually just the Mac OS checkbox style, so it will look radically different on other devices.

In fact both screenshots you linked show what checkboxes look like on Mac OS in Chrome, the grey one is shown at non-100% zoom levels.

Float to String format specifier

Use ToString() with this format:

12345.678901.ToString("0.0000"); // outputs 12345.6789
12345.0.ToString("0.0000"); // outputs 12345.0000

Put as much zero as necessary at the end of the format.

Getting attributes of a class

Try the inspect module. getmembers and the various tests should be helpful.


For example,

class MyClass(object):
    a = '12'
    b = '34'
    def myfunc(self):
        return self.a

>>> import inspect
>>> inspect.getmembers(MyClass, lambda a:not(inspect.isroutine(a)))
[('__class__', type),
  <dictproxy {'__dict__': <attribute '__dict__' of 'MyClass' objects>,
   '__doc__': None,
   '__module__': '__main__',
   '__weakref__': <attribute '__weakref__' of 'MyClass' objects>,
   'a': '34',
   'b': '12',
   'myfunc': <function __main__.myfunc>}>),
 ('__doc__', None),
 ('__module__', '__main__'),
 ('__weakref__', <attribute '__weakref__' of 'MyClass' objects>),
 ('a', '34'),
 ('b', '12')]

Now, the special methods and attributes get on my nerves- those can be dealt with in a number of ways, the easiest of which is just to filter based on name.

>>> attributes = inspect.getmembers(MyClass, lambda a:not(inspect.isroutine(a)))
>>> [a for a in attributes if not(a[0].startswith('__') and a[0].endswith('__'))]
[('a', '34'), ('b', '12')]

...and the more complicated of which can include special attribute name checks or even metaclasses ;)

Predicate Delegates in C#

Leading on from Andrew's answer with regards to c#2 and c#3 ... you can also do them inline for a one off search function (see below).

using System;
using System.Collections.Generic;

class Program
    static void Main()
        List<int> list = new List<int> { 1, 2, 3 };

        List<int> newList = list.FindAll(delegate(int arg)
                               return arg> 2;

Hope this helps.

how to overcome ERROR 1045 (28000): Access denied for user 'ODBC'@'localhost' (using password: NO) permanently

I tried this and it worked:

C:\cd MySQL installed path\MySQL -uyourusername -pyourpassword

How do I Sort a Multidimensional Array in PHP

Here is a php4/php5 class that will sort one or more fields:

// a sorter class
//  php4 and php5 compatible
class Sorter {

  var $sort_fields;
  var $backwards = false;
  var $numeric = false;

  function sort() {
    $args = func_get_args();
    $array = $args[0];
    if (!$array) return array();
    $this->sort_fields = array_slice($args, 1);
    if (!$this->sort_fields) return $array();

    if ($this->numeric) {
      usort($array, array($this, 'numericCompare'));
    } else {
      usort($array, array($this, 'stringCompare'));
    return $array;

  function numericCompare($a, $b) {
    foreach($this->sort_fields as $sort_field) {
      if ($a[$sort_field] == $b[$sort_field]) {
      return ($a[$sort_field] < $b[$sort_field]) ? ($this->backwards ? 1 : -1) : ($this->backwards ? -1 : 1);
    return 0;

  function stringCompare($a, $b) {
    foreach($this->sort_fields as $sort_field) {
      $cmp_result = strcasecmp($a[$sort_field], $b[$sort_field]);
      if ($cmp_result == 0) continue;

      return ($this->backwards ? -$cmp_result : $cmp_result);
    return 0;

// usage examples

// some starting data
$start_data = array(
  array('first_name' => 'John', 'last_name' => 'Smith', 'age' => 10),
  array('first_name' => 'Joe', 'last_name' => 'Smith', 'age' => 11),
  array('first_name' => 'Jake', 'last_name' => 'Xample', 'age' => 9),

// sort by last_name, then first_name
$sorter = new Sorter();
print_r($sorter->sort($start_data, 'last_name', 'first_name'));

// sort by first_name, then last_name
$sorter = new Sorter();
print_r($sorter->sort($start_data, 'first_name', 'last_name'));

// sort by last_name, then first_name (backwards)
$sorter = new Sorter();
$sorter->backwards = true;
print_r($sorter->sort($start_data, 'last_name', 'first_name'));

// sort numerically by age
$sorter = new Sorter();
$sorter->numeric = true;
print_r($sorter->sort($start_data, 'age'));

Firebase Permission Denied

Go to the "Database" option you mentioned.

  1. There on the Blue Header you'll find a dropdown which says Cloud Firestore Beta
  2. Change it to "Realtime database"
  3. Go to Rules and set .write .read both to true

Copied from here.

running php script (php function) in linux bash

just run in linux terminal to get phpinfo .

   php -r 'phpinfo();'

and to run file like index.php

    php -f index.php

How to remove commits from a pull request

If you're removing a commit and don't want to keep its changes @ferit has a good solution.

If you want to add that commit to the current branch, but doesn't make sense to be part of the current pr, you can do the following instead:

  1. use git rebase -i HEAD~n
  2. Swap the commit you want to remove to the bottom (most recent) position
  3. Save and exit
  4. use git reset HEAD^ --soft to uncommit the changes and get them back in a staged state.
  5. use git push --force to update the remote branch without your removed commit.

Now you'll have removed the commit from your remote, but will still have the changes locally.

Remove First and Last Character C++

std::string trimmed(std::string str ) {
if(str.length() == 0 ) { return "" ; }
else if ( str == std::string(" ") ) { return "" ; } 
else {
    while( == ' ') { str.erase(0, 1);}
    while( == ' ') { str.pop_back() ; }
    return str ;

Command to escape a string in bash

In Bash:

printf "%q" "hello\world" | someprog

for example:

printf "%q" "hello\world"

This could be used through variables too:

printf -v var "%q\n" "hello\world"
echo "$var"

JavaScript: How to join / combine two arrays to concatenate into one array?

var a = ['a','b','c'];
var b = ['d','e','f'];
var c = a.concat(b); //c is now an an array with: ['a','b','c','d','e','f']
console.log( c[3] ); //c[3] will be 'd'

Initialization of all elements of an array to one default value in C++?

The page you linked states

If an explicit array size is specified, but an shorter initiliazation list is specified, the unspecified elements are set to zero.

Speed issue: Any differences would be negligible for arrays this small. If you work with large arrays and speed is much more important than size, you can have a const array of the default values (initialized at compile time) and then memcpy them to the modifiable array.

How to print pthread_t

On Centos 5.4 x86_64, pthread_t is a typedef to a unsigned long.

Therefore, we could do this...

#include <iostream>
#include <pthread.h>

int main() {
    pthread_t x;
    printf("%li\n", (unsigned long int) x);
    std::cout << (unsigned long int) x << "\n";

How do I format a date in Jinja2?

There is a jinja2 extension you can use just need pip install (

How to reload current page in ReactJS?

You can use window.location.reload(); in your componentDidMount() lifecycle method. If you are using react-router, it has a refresh method to do that.

Edit: If you want to do that after a data update, you might be looking to a re-render not a reload and you can do that by using this.setState(). Here is a basic example of it to fire a re-render after data is fetched.

import React from 'react'

const ROOT_URL = '';
const url = `${ROOT_URL}/users`;

class MyComponent extends React.Component {
    state = {
        users: null
    componentDidMount() {
            .then(response => response.json())
            .then(users => this.setState({users: users}));
    render() {
        const {users} = this.state;
        if (users) {
            return (
                    { => <li>{}</li>)}
        } else {
            return (<h1>Loading ...</h1>)

export default MyComponent;

How to find the Number of CPU Cores via .NET/C#?

WMI queries are slow, so try to Select only the desired members instead of using Select *.

The following query takes 3.4s:

foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_Processor").Get())

While this one takes 0.122s:

foreach (var item in new System.Management.ManagementObjectSearcher("Select NumberOfCores from Win32_Processor").Get())

Using CSS td width absolute, position

This may not be what you want to hear, but display: table-cell does not respect width and will be collapsed based on the width of the entire table. You can get around this easily just by having a display: block element inside of the table cell itself whose width you specify, e.g

<td><div style="width: 300px;">wide</div></td>

This shouldn't make much of a difference if the <table> itself is position: fixed or absolute because the position of the cells are all static relative to the table.

EDIT: I can't take credit, but as the comments say you can just use min-width instead of width on the table cell instead.

Remove trailing zeros

In case you want to keep decimal number, try following example:

number = Math.Floor(number * 100000000) / 100000000;

How can I rollback a git repository to a specific commit?

In github, the easy way is to delete the remote branch in the github UI, under branches tab. You have to make sure remove following settings to make the branch deletable:

  1. Not a default branch
  2. No opening poll requests.
  3. The branch is not protected.

Now recreate it in your local repository to point to the previous commit point. and add it back to remote repo.

git checkout -b master 734c2b9b   # replace with your commit point

Then push the local branch to remote

git push -u origin master

Add back the default branch and branch protection, etc.

Make a link in the Android browser start up my app?

I also faced this issue and see many absurd pages. I've learned that to make your app browsable, change the order of the XML elements, this this:


        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />

        <data android:scheme="http" />     
        <!-- or you can use deep linking like  -->               

        <data android:scheme="http" android:host=""/>
        <action android:name="android.intent.action.VIEW"/>
        <category android:name="android.intent.category.BROWSABLE"/>
        <category android:name="android.intent.category.DEFAULT"/>


This worked for me and might help you.

Vue equivalent of setTimeout?

ES6 can bind 'this'

setTimeout(() => {


How to zoom in/out an UIImage object when user pinches screen?

Keep in mind that you don't want to zoom in/out UIImage. Instead try to zoom in/out the View which contains the UIImage View Controller.

I have made a solution for this problem. Take a look at my code:

@IBAction func scaleImage(sender: UIPinchGestureRecognizer) {
        self.view.transform = CGAffineTransformScale(self.view.transform, sender.scale, sender.scale)
        sender.scale = 1
    override func viewDidLoad() {
        // Do any additional setup after loading the view, typically from a nib.
        view.backgroundColor = UIColor.blackColor()

N.B.: Don't forget to hook up the PinchGestureRecognizer.

MySQL LIMIT on DELETE statement

Use row_count - your_desired_offset

So if we had 10 rows and want to offset 3

 10 - 3 = 7

Now the query delete from table where this = that order asc limit 7 keeps the last 3, and order desc to keep the first 3:

$row_count - $offset = $limit

Delete from table where entry = criteria order by ts asc limit $limit

Full Screen DialogFragment in Android

This below answer works for me in fragment dialog.  

  Dialog dialog = getDialog();
        if (dialog != null)
            int width = ViewGroup.LayoutParams.MATCH_PARENT;
            int height = ViewGroup.LayoutParams.MATCH_PARENT;
            dialog.getWindow().setLayout(width, height);

How to echo xml file in php

You can use the asXML method

echo $xml->asXML();

You can also give it a filename


Dynamically replace img src attribute with jQuery

In my case, I replaced the src taq using:

   $('#gmap_canvas').attr('src', newSrc);

If a DOM Element is removed, are its listeners also removed from memory?

Yes, the garbage collector will remove them as well. Might not always be the case with legacy browsers though.

swift 3.0 Data to String?

I found the way to do it. You need to convert Data to NSData:

let characterSet = CharacterSet(charactersIn: "<>")
let nsdataStr = NSData.init(data: deviceToken)
let deviceStr = nsdataStr.description.trimmingCharacters(in: characterSet).replacingOccurrences(of: " ", with: "")

find_spec_for_exe': can't find gem bundler (>= 0.a) (Gem::GemNotFoundException)

The reason is your current ruby environment, you got a different version of bundler with the version in Gemfile.lock.

  • Safe way, install bundler with the same version in Gemfile.lock, this won't break anything if there is some incampatibly thing happened.
  • Hard way, just remove Gemfile.lock, and run bundle install.

How to insert data to MySQL having auto incremented primary key?

Check out this post

According to it

No value was specified for the AUTO_INCREMENT column, so MySQL assigned sequence numbers automatically. You can also explicitly assign NULL or 0 to the column to generate sequence numbers.

write a shell script to ssh to a remote machine and execute commands

If you are able to write Perl code, then you should consider using Net::OpenSSH::Parallel.

You would be able to describe the actions that have to be run in every host in a declarative manner and the module will take care of all the scary details. Running commands through sudo is also supported.

How can one create an overlay in css?

Quick answer without seeing examples of your current HTML and CSS is to use z-index


#div1 {
position: relative;
z-index: 1;

#div2 {
position: relative;
z-index: 2;

Where div2 is the overlay

PHP, MySQL error: Column count doesn't match value count at row 1

The number of column parameters in your insert query is 9, but you've only provided 8 values.

INSERT INTO dbname (id, Name, Description, shortDescription, Ingredients, Method, Length, dateAdded, Username) VALUES ('', '%s', '%s', '%s', '%s', '%s', '%s', '%s')

The query should omit the "id" parameter, because it is auto-generated (or should be anyway):

INSERT INTO dbname (Name, Description, shortDescription, Ingredients, Method, Length, dateAdded, Username) VALUES ('', '%s', '%s', '%s', '%s', '%s', '%s', '%s')

Linux : Search for a Particular word in a List of files under a directory

You could club find with exec as follows to get the list of the files as well as the occurrence of the word/string that you are looking for

find . -exec grep "my word" '{}' \; -print

Display milliseconds in Excel

First represent the epoch of the millisecond time as a date (usually 1/1/1970), then add your millisecond time divided by the number of milliseconds in a day (86400000):


If your cell is properly formatted, you should see a human-readable date/time.

Set environment variables from file of key/value pairs

My .env file looks like:


Using the @henke's ways, the exported value ends up containing the quotation marks "


But I want the exported value to contain only:


To fix it, I edit the command to delete the quotation marks:

export $(grep -v '^#' dev.env | tr --delete '"' | xargs -d '\n')

How do I initialize a TypeScript Object with a JSON-Object?

Another option using factories

export class A {

    id: number;

    date: Date;

    bId: number;
    readonly b: B;

export class B {

    id: number;

export class AFactory {

        private readonly createB: BFactory
    ) { }

    create(data: any): A {

        const createB = this.createB.create;

        return Object.assign(new A(),
                get b(): B {

                    return createB({ id: data.bId });
                date: new Date(

export class BFactory {

    create(data: any): B {

        return Object.assign(new B(), data);

use like this

import { A, B, AFactory, BFactory } from "./deserialize";

// create a factory, simplified by DI
const aFactory = new AFactory(new BFactory());

// get an anon js object like you'd get from the http call
const data = { bId: 1, date: '2017-1-1' };

// create a real model from the anon js object
const a = aFactory.create(data);

// confirm instances e.g. dates are Dates 
console.log(' is instanceof Date', instanceof Date);
console.log('a.b is instanceof B', a.b instanceof B);
  1. keeps your classes simple
  2. injection available to the factories for flexibility

Text in a flex container doesn't wrap in IE11

As Tyler has suggested in one of the comments here, using

max-width: 100%;

on the child may work (worked for me). Using align-self: stretch only works if you aren't using align-items: center (which I did). width: 100% only works if you haven't multiple childs inside your flexbox which you want to show side by side.

Setting Remote Webdriver to run tests in a remote computer using Java

By Default the InternetExplorerDriver listens on port "5555". Change your huburl to match that. you can look on the cmd box window to confirm.

Deep copy vs Shallow Copy

Shallow copy:

Some members of the copy may reference the same objects as the original:

class X
    int i;
    int *pi;
        : pi(new int)
    { }
    X(const X& copy)   // <-- copy ctor
        : i(copy.i), pi(copy.pi)
    { }

Here, the pi member of the original and copied X object will both point to the same int.

Deep copy:

All members of the original are cloned (recursively, if necessary). There are no shared objects:

class X
    int i;
    int *pi;
        : pi(new int)
    { }
    X(const X& copy)   // <-- copy ctor
        : i(copy.i), pi(new int(*copy.pi))  // <-- note this line in particular!
    { }

Here, the pi member of the original and copied X object will point to different int objects, but both of these have the same value.

The default copy constructor (which is automatically provided if you don't provide one yourself) creates only shallow copies.

Correction: Several comments below have correctly pointed out that it is wrong to say that the default copy constructor always performs a shallow copy (or a deep copy, for that matter). Whether a type's copy constructor creates a shallow copy, or deep copy, or something in-between the two, depends on the combination of each member's copy behaviour; a member's type's copy constructor can be made to do whatever it wants, after all.

Here's what section 12.8, paragraph 8 of the 1998 C++ standard says about the above code examples:

The implicitly defined copy constructor for class X performs a memberwise copy of its subobjects. [...] Each subobject is copied in the manner appropriate to its type: [...] [I]f the subobject is of scalar type, the builtin assignment operator is used.

Simplest way to serve static data from outside the application server in a Java web application

if anyone not able to resolve his problem with accepted answer, then note these below considerations:

  1. no need to mention localhost:<port> with <img> src attribute.
  2. make sure you are running this project outside eclipse, because eclipse creates context docBase entry on its own inside its local server.xml file.

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

\xe2 is the '-' character, it appears in some copy and paste it uses a different equal looking '-' that causes encoding errors. Replace the '-'(from copy paste) with the correct '-' (from you keyboard button).

Stupid error: Failed to load resource: net::ERR_CACHE_MISS

If you are using bootstrap that will be the problem. If you want to use same bootstrap file in two locations use it below the header section .(example - inside body)

Note : "specially when you use html editors. "

Thank you.

What algorithms compute directions from point A to point B on a map?

Graph algorithms like Dijkstra's algorithm will not work because the graph is enormous.

This argument doesn't necessarily hold because Dijkstra will not usually look at the complete graph but rather just a very small subset (the better interconnected the graph, the smaller this subset).

Dijkstra may actually perform rather well for well-behaved graphs. On the other hand, with careful parametrization A* will always perform just as good, or better. Have you already tried how it would perform on your data?

That said, I'd also be very interested to hear about other peoples' experiences. Of course, prominent examples like Google Map's search are particularly interesting. I could imagine something like a directed nearest neighbour heuristic.

How can I simulate a click to an anchor tag?

There is a simpler way to achieve it,


<a href="" id="fooLinkID" target="_blank">Bootstrap is life !</a>


// Simulating click after 3 seconds
}, 3 * 1000);

Using plain javascript to simulate a click along with addressing the target property.

You can check working example here on jsFiddle.

Draw Circle using css alone

border radius is good option, if struggling with old IE versions then try HTML codes


and use css to change color. Output:

MySQL table is marked as crashed and last (automatic?) repair failed

This was my experience resolving this issue. I'm using XAMPP. I was getting the error below

 Fatal error: Can't open and lock privilege tables: Table '.\mysql\db' is marked as crashed and last (automatic?) repair failed  

This is what I did to resolve it, step by step:

  1. went to location C:\xampp\mysql, For you, location may be different, make sure you are in right file location.
  2. created backup of the data folder as data-old.
  3. copied folder "mysql" from C:\xampp\mysql\backup
  4. pasted it inside C:\xampp\mysql\data\ replacing the old mysql folder.

And it worked. Keep in mind, I have already tried around 10 solutions and they didnt work for me. This solutions may or may not work for you but regardless, make backup of your data folder before you do anything.

Note: I would always opt to resolve this with repair command but in my case, i wasnt able to get mysql started at all and i wasnt able to get myisamchk command to work.

Regardless of what you do, create a periodic backup of your database.

Using the Web.Config to set up my SQL database connection string?

Your best bet, starting fresh like you are, is to go grab the enterprise library. They have a configuration tool you can use to wire everything up for you nicely.

They also have a data access application block which is very useful and documentation filled with good samples.

Set a default font for whole iOS app?

We have achieved the same in Swift -Xcode 7.2 using Parent View Controller and Child view controller (Inheritance).

File - New - Cocoa Touch class - ParentViewController.

    import UIKit
    import Foundation

    class ParentViewController: UIViewController {

        var appUIColor:UIColor = UIColor.redColor()
        var appFont:UIFont = UIFont(name: "Copperplate", size: 20)!

        override func viewDidLoad() {
        func addStatusBar()
            let view = UIView(frame:
                CGRect(x: 0.0, y: 0.0, width: UIScreen.mainScreen().bounds.size.width, height: 20.0)
            view.backgroundColor = appUIColor

Make child view controllers and associate with a StoryBoard VC, add a textLabel.

    import UIKit

    class FontTestController: ParentViewController {
        @IBOutlet var testLabel: UILabel!

        override func viewDidLoad() {
            testLabel.font =  appFont
            testLabel.textColor = appUIColor

OR Make a custom UILabel Class(Sub classing method) and associate required labels to it.

import Foundation
import UIKit

class CustomFontLabel: UILabel {
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
        backgroundColor = ParentViewController().appUIColor
        font = ParentViewController().appFont
        textColor = UIColor.blackColor()

Note: The Font and colour declared in Parent VC are implemented in CustomFontLabel . The advantage is we can alter the properties of uilabel/any view all together in some simple changes in Parent VC.

2)'for' looping UIView for sub views. It works only on a particular VC.

    override func viewWillLayoutSubviews() {
            for view in self.view.subviews  {
                if view.isKindOfClass(UITextField) {
                UITextField.appearance().font =  UIFont(name: "Copperplate", size: 20)
                if view.isKindOfClass(UILabel) {
                    UILabel.appearance().font =  UIFont(name: "Copperplate", size: 20)    

jQuery see if any or no checkboxes are selected

This is what I used for checking if any checkboxes in a list of checkboxes had changed:


        var itemName = $('select option:selected').text();  

         //Do something.


Converting an array to a function arguments list

@bryc - yes, you could do it like this:


But that seems like a lot of work and obfuscation compared to:


How do I deserialize a complex JSON object in C# .NET?

If you use C# 2010 or newer, you can use dynamic type:

dynamic json = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonstring);

Then you can access attributes and arrays in dynamic object using dot notation:

string nemo = json.response[0].images[0].report.nemo;

For..In loops in JavaScript - key value pairs

let test = {a: 1, b: 2, c: 3};
Object.entries(test).forEach(([key, value]) => console.log(key, value))

// a 1
// b 2
// c 3

Set order of columns in pandas dataframe

Just select the order yourself by typing in the column names. Note the double brackets:

frame = frame[['column I want first', 'column I want second'...etc.]]

Reset select value to default

This code will help you out.

    <script type="text/JavaScript" src="jquery-2.0.2.min.js"></script>
    <script type="text/JavaScript">
            var defaultValue = $("#my_select").val();
            $("#reset").click(function () {
    <select id="my_select">
        <option value="a">a</option>
        <option value="b" selected="selected">b</option>
        <option value="c">c</option>
    <div id="reset">
        <input type="button" value="reset"/>

Uncaught TypeError: $(...).datepicker is not a function(anonymous function)

Including more than one reference to Jquery library is the reason for the error Only Include one reference to the Jquery library and that will resolve the issue

Convert a string to an enum in C#

// str.ToEnum<EnumType>()
T static ToEnum<T>(this string str) 
    return (T) Enum.Parse(typeof(T), str);

Where are include files stored - Ubuntu Linux, GCC

Karl answered your search-path question, but as far as the "source of the files" goes, one thing to be aware of is that if you install the libfoo package and want to do some development with it (i.e., use its headers), you will also need to install libfoo-dev. The standard library header files are already in /usr/include, as you saw.

Note that some libraries with a lot of headers will install them to a subdirectory, e.g., /usr/include/openssl. To include one of those, just provide the path without the /usr/include part, for example:

#include <openssl/aes.h>

Import-Module : The specified module 'activedirectory' was not loaded because no valid module file was found in any module directory

Even better use implicit remoting to use a module from another Machine!

$s = New-PSSession Server-Name
Invoke-Command -Session $s -ScriptBlock {Import-Module ActiveDirectory}
Import-PSSession -Session $s -Module ActiveDirectory -Prefix REM

This will allow you to use the module off a remote PC for as long as the PSSession is connected.

More Information:

Changing Background Image with CSS3 Animations

You can use the jquery-backstretch image which allows for animated slideshows as your background-images! Scroll down to setup and all of the documentation is there.

ReactJS - Does render get called any time "setState" is called?

Not All Components.

the state in component looks like the source of the waterfall of state of the whole APP.

So the change happens from where the setState called. The tree of renders then get called from there. If you've used pure component, the render will be skipped.

ORA-28001: The password has expired

Just go to the machine where your database resides, search windows -> search SqlPlus Type the user name, then type password, it will prompt you to give new password. On providing new password, it will say successfully changed the password.

Cannot read property 'map' of undefined

I think you forgot to change




in the render function of CommentBox. I did the same mistake when I was following the tutorial. Thus the whole render function should look like

render: function() {
  return (
    <div className="commentBox">
      <CommentList data={} />
      <CommentForm />

instead of

render: function() {
  return (
    <div className="commentBox">
      <CommentList data={} />
      <CommentForm />

Split text with '\r\n'

Following code gives intended results.

string text="some interesting text\nsome text that should be in the same line\r\nsome 
text should be in another line"
var results = text.Split(new[] {"\n","\r\n"}, StringSplitOptions.None);

How to unset (remove) a collection element after fetching it?

You would want to use ->forget()


Link to the forget method documentation

What __init__ and self do in Python?

Try out this code. Hope it helps many C programmers like me to Learn Py.

#! /usr/bin/python2

class Person:

    '''Doc - Inside Class '''

    def __init__(self, name):
        '''Doc - __init__ Constructor'''
        self.n_name = name        

    def show(self, n1, n2):
        '''Doc - Inside Show'''
        print self.n_name
        print 'Sum = ', (n1 + n2)

    def __del__(self):
        print 'Destructor Deleting object - ', self.n_name

p=Person('Jay'), 3)
print p.__doc__
print p.__init__.__doc__



Sum = 5

Doc - Inside Class

Doc - __init__ Constructor

Doc - Inside Show

Destructor Deleting object - Jay

List of foreign keys and the tables they reference in Oracle DB

Its a bit late to anwser, but I hope my answer been useful for someone, who needs to select Composite foreign keys.


Add a pipe separator after items in an unordered list unless that item is the last on a line

You can use the following CSS to solve.

ul li { float: left; }
ul li:before { content: "|"; padding: 0 .5em; }
ul li:first-child:before { content: ""; padding: 0; }

Should work on IE8+ as well.

How to make a HTML list appear horizontally instead of vertically using CSS only?

Using display: inline-flex

#menu ul {_x000D_
  list-style: none;_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  display: inline-flex_x000D_
<div id="menu">_x000D_
    <li>1 menu item</li>_x000D_
    <li>2 menu item</li>_x000D_
    <li>3 menu item</li>_x000D_

Using display: inline-block

#menu ul {_x000D_
  list-style: none;_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
#menu li {_x000D_
  display: inline-block;_x000D_
<div id="menu">_x000D_
    <li>1 menu item</li>_x000D_
    <li>2 menu item</li>_x000D_
    <li>3 menu item</li>_x000D_

Open file by its full path in C++

A different take on this question, which might help someone:

I came here because I was debugging in Visual Studio on Windows, and I got confused about all this / vs \\ discussion (it really should not matter in most cases).

For me, the problem was: the "current directory" was not set to what I wanted in Visual Studio. It defaults to the directory of the executable (depending on how you set up your project).

Change it via: Right-click the solution -> Properties -> Working Directory

I only mention it because the question seems Windows-centric, which generally also means VisualStudio-centric, which tells me this hint might be relevant (:

Android emulator-5554 offline

From the AVD Manager try the "Cold Boot Now" option in the drop-down. It worked for me!

How to prevent http file caching in Apache httpd (MAMP)

I had the same issue, but I found a good solution here: Stop caching for PHP 5.5.3 in MAMP

Basically find the php.ini file and comment out the OPCache lines. I hope this alternative answer helps others else out as well.

how to add value to combobox item

I am assuming that you are wanting to add items to a ComboBox on an Windows form. Although Klaus is on the right track I believe that the ListItem class is a member of the System.Web.UI.WebControls namespace. So you shouldn't be using it in a Windows forms solution. You can, however, create your own class that you can use in its place. Create a simple class called MyListItem (or whatever name you choose) like this:

Public Class MyListItem
    Private mText As String
    Private mValue As String

    Public Sub New(ByVal pText As String, ByVal pValue As String)
        mText = pText
        mValue = pValue
    End Sub

    Public ReadOnly Property Text() As String
            Return mText
        End Get
    End Property

    Public ReadOnly Property Value() As String
            Return mValue
        End Get
    End Property

    Public Overrides Function ToString() As String
        Return mText
    End Function
End Class

Now when you want to add the items to your ComboBox you can do it like this:

myComboBox.Items.Add(New MyListItem("Text to be displayed", "value of the item"))

Now when you want to retrieve the value of the selected item from your ComboBox you can do it like this:

Dim oItem As MyListItem = CType(myComboBox.SelectedItem, MyListItem)
MessageBox.Show("The Value of the Item selected is: " & oItem.Value)

One of the keys here is overriding the ToString method in the class. This is where the ComboBox gets the text that is displayed.

Matt made an excellent point, in his comment below, about using Generics to make this even more flexible. So I wondered what that would look like.

Here's the new and improved GenericListItem class:

Public Class GenericListItem(Of T)
    Private mText As String
    Private mValue As T

    Public Sub New(ByVal pText As String, ByVal pValue As T)
        mText = pText
        mValue = pValue
    End Sub

    Public ReadOnly Property Text() As String
            Return mText
        End Get
    End Property

    Public ReadOnly Property Value() As T
            Return mValue
        End Get
    End Property

    Public Overrides Function ToString() As String
        Return mText
    End Function
End Class

And here is how you would now add Generic items to your ComboBox. In this case an Integer:

Me.myComboBox.Items.Add(New GenericListItem(Of Integer)("Text to be displayed", 1))

And now the retrieval of the item:

Dim oItem As GenericListItem(Of Integer) = CType(Me.myComboBox.SelectedItem, GenericListItem(Of Integer))
MessageBox.Show("The value of the Item selected is: " & oItem.Value.ToString())

Keep in mind that the type Integer can be any type of object or value type. If you want it to be an object from one of your own custom classes that's fine. Basically anything goes with this approach.

Java - Getting Data from MySQL database

Here is what I just did right now:

import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.sun.javafx.runtime.VersionInfo;  

public class ConnectToMySql {
public static ConnectBean dataBean = new ConnectBean();

public static void main(String args[]) {

public static void getData () {

    try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mynewpage", 
 "root", "root");
 // here mynewpage is database name, root is username and password
Statement stmt = con.createStatement();
        System.out.println("stmt  " + stmt);
        ResultSet rs = stmt.executeQuery("select * from carsData");
        System.out.println("rs  " + rs);
        int count = 1;
        while ( {
            String vehicleType = rs.getString("VHCL_TYPE");
            System.out.println(count  +": " + vehicleType);


    } catch (Exception e) {
        Logger lgr = Logger.getLogger(VersionInfo.class.getName());
        lgr.log(Level.SEVERE, e.getMessage(), e);



The Above code will get you the first column of the table you have.

This is the table which you might need to create in your MySQL database


Best practices for API versioning?

The URL should NOT contain the versions. The version has nothing to do with "idea" of the resource you are requesting. You should try to think of the URL as being a path to the concept you would like - not how you want the item returned. The version dictates the representation of the object, not the concept of the object. As other posters have said, you should be specifying the format (including version) in the request header.

If you look at the full HTTP request for the URLs which have versions, it looks like this:

GET v3.0/customer/123 HTTP/1.1
Accept: application/xml

HTTP/1.1 200 OK
Content-Type: application/xml
<customer version="3.0">
  <name>Neil Armstrong</name>

The header contains the line which contains the representation you are asking for ("Accept: application/xml"). That is where the version should go. Everyone seems to gloss over the fact that you may want the same thing in different formats and that the client should be able ask for what it wants. In the above example, the client is asking for ANY XML representation of the resource - not really the true representation of what it wants. The server could, in theory, return something completely unrelated to the request as long as it was XML and it would have to be parsed to realize it is wrong.

A better way is:

GET /customer/123 HTTP/1.1
Accept: application/

HTTP/1.1 200 OK
Content-Type: application/
  <name>Neil Armstrong</name>

Further, lets say the clients think the XML is too verbose and now they want JSON instead. In the other examples you would have to have a new URL for the same customer, so you would end up with:


(or something similar). When in fact, every HTTP requests contains the format you are looking for:

GET /customer/123 HTTP/1.1
Accept: application/

HTTP/1.1 200 OK
Content-Type: application/

  {"name":"Neil Armstrong"}

Using this method, you have much more freedom in design and are actually adhering to the original idea of REST. You can change versions without disrupting clients, or incrementally change clients as the APIs are changed. If you choose to stop supporting a representation, you can respond to the requests with HTTP status code or custom codes. The client can also verify the response is in the correct format, and validate the XML.

There are many other advantages and I discuss some of them here on my blog:

One last example to show how putting the version in the URL is bad. Lets say you want some piece of information inside the object, and you have versioned your various objects (customers are v3.0, orders are v2.0, and shipto object is v4.2). Here is the nasty URL you must supply in the client:

(Another reason why version in the URL sucks)

SonarQube Exclude a directory

You can do the same with build.gradle

sonarqube {
properties {
    property "sonar.exclusions", "**/src/java/test/**/*.java"

And if you want to exclude more files/directories then:

sonarqube {
properties {
    property "sonar.exclusions", "**/src/java/test/**/*.java, **/src/java/main/**/*.java"

Reload .profile in bash shell script (in unix)?

Try this to reload your current shell:

source ~/.profile

Assign a class name to <img> tag instead of write it in css file?

It's just more versatile if you give it a class name as the style you specify will only apply to that class name. But if you exactly know every .column img and want to style that in the same way, there's no reason why you can't use that selector.

The performance difference, if any, is negligible these days.

Eclipse Java Missing required source folder: 'src'

Right-Click Project --> Build Path --> Configure Build Path-->source-->(Select missing folder or path)-->Add Folder-->Apply-->Ok

JavaScript loop through json array?

Since i already started looking into it:

var data = [{
    "id": "1",
    "msg": "hi",
    "tid": "2013-05-05 23:35",
    "fromWho": "[email protected]"
}, {
    "id": "2",
    "msg": "there",
    "tid": "2013-05-05 23:45",
    "fromWho": "[email protected]"

And this function

var iterateData =function(data){   for (var key in data) {
       if (data.hasOwnProperty(key)) {

You can call it like this

iterateData(data); // write 1 and 2 to the console

Update after Erics comment

As eric pointed out a for in loop for an array can have unexpected results. The referenced question has a lengthy discussion about pros and cons.

Test with for(var i ...

But it seems that the follwing is quite save:

for(var i = 0; i < array.length; i += 1)

Although a test in chrome had the following result

var ar = [];
ar[0] = "a"; 
ar[1] = "b";
ar[4] = "c";

function forInArray(ar){ 
     for(var i = 0; i < ar.length; i += 1) 

// calling the function
// returns a,b, undefined, undefined, c, undefined

Test with .forEach()

At least in chrome 30 this works as expected

var logAr = function(element, index, array) {
    console.log("a[" + index + "] = " + element);
ar.forEach(logAr); // returns a[0] = a, a[1] = b, a[4] = c


What function is to replace a substring from a string in C?

There isn't one.

You'd need to roll your own using something like strstr and strcat or strcpy.

How do I force "git pull" to overwrite local files?

I was trying to use the Material2 branch on the Angular2-Webpack-Starter and had a heck of a time. This was the only way I could download and use that branch.

git clone --depth 1

cd angular2-webpack-starter/

git checkout -b material2

Open the project folder and delete all non-hidden files and folders. Leave all the hidden ones.

git add .

git commit -m "pokemon go"

git reset --hard

git pull origin material2

(When the editor pops up, hit ':wq', and then press Enter)

Now you are ready.

Eclipse Workspaces: What for and why?

I'll provide you with my vision of somebody who feels very uncomfortable in the Java world, which I assume is also your case.

What it is

A workspace is a concept of grouping together:

  1. a set of (somehow) related projects
  2. some configuration pertaining to all these projects
  3. some settings for Eclipse itself

This happens by creating a directory and putting inside it (you don't have to do it, it's done for you) files that manage to tell Eclipse these information. All you have to do explicitly is to select the folder where these files will be placed. And this folder doesn't need to be the same where you put your source code - preferentially it won't be.

Exploring each item above:

  1. a set of (somehow) related projects

Eclipse seems to always be opened in association with a particular workspace, i.e., if you are in a workspace A and decide to switch to workspace B (File > Switch Workspaces), Eclipse will close itself and reopen. All projects that were associated with workspace A (and were appearing in the Project Explorer) won't appear anymore and projects associated with workspace B will now appear. So it seems that a project, to be open in Eclipse, MUST be associated to a workspace.

Notice that this doesn't mean that the project source code must be inside the workspace. The workspace will, somehow, have a relation to the physical path of your projects in your disk (anybody knows how? I've looked inside the workspace searching for some file pointing to the projects paths, without success).

This way, a project can be inside more than 1 workspace at a time. So it seems good to keep your workspace and your source code separated.

  1. some configuration pertaining to all these projects

I heard that something, like the Java compiler version (like 1.7, e.g - I don't know if 'version' is the word here), is a workspace-level configuration. If you have several projects inside your workspace, and compile them inside of Eclipse, all of them will be compiled with the same Java compiler.

  1. some settings for Eclipse itself

Some things like your key bindings are stored at a workspace-level, also. So, if you define that ctrl+tab will switch tabs in a smart way (not stacking them), this will only be bound to your current workspace. If you want to use the same key binding in another workspace (and I think you want!), it seems that you have to export/import them between workspaces (if that's true, this IDE was built over some really strange premises). Here is a link on this.

It also seems that workspaces are not necessarily compatible between different Eclipse versions. This article suggests that you name your workspaces containing the name of the Eclipse version.

And, more important, once you pick a folder to be your workspace, don't touch any file inside there or you are in for some trouble.

How I think is a good way to use it

(actually, as I'm writing this, I don't know how to use this in a good way, that's why I was looking for an answer – that I'm trying to assemble here)

  1. Create a folder for your projects:

  2. Create a folder for each project and group the projects' sub-projects inside of it:

  3. Create a separate folder for your workspaces:

  4. Create workspaces for your projects:

Ship an application with a database

I wrote a library to simplify this process.

dataBase = new DataBase.Builder(context, "myDb").
//        setAssetsPath(). // default "databases"
//        setDatabaseErrorHandler().
//        setCursorFactory().
//        setUpgradeCallback()
//        setVersion(). // default 1

It will create a dataBase from assets/databases/myDb.db file. In addition you will get all those functionality:

  • Load database from file
  • Synchronized access to the database
  • Using sqlite-android by requery, Android specific distribution of the latest versions of SQLite.

Clone it from github.

React fetch data in server before render

As a supplement of the answer of Michael Parker, you can make getData accept a callback function to active the setState update the data:

componentWillMount : function () {
    var data = this.getData(()=>this.setState({data : data}));

How to set margin of ImageView using code, not xml

In Kotlin you can write it in more pleasant way

myView.layoutParams = LinearLayout.LayoutParams(
                RadioGroup.LayoutParams.MATCH_PARENT, RadioGroup.LayoutParams.WRAP_CONTENT
            ).apply {
                setMargins(12, 12, 12, 12)

How to get visitor's location (i.e. country) using geolocation?

See a service I built that is fast and has reliable performance thanks to having 10 global endpoints each able to handle >10,000 requests per second!

This answer uses a 'test' API Key that is very limited and only meant for testing a few calls. Signup for your own Free API Key and get up to 1500 requests daily for development.

This snippet will return the details of your current ip. To lookup other ip addresses, simply append the ip to the url eg.

The API also provides an is_eu field indicating whether the user is in an EU country.

$.get("", function (response) {_x000D_
    $("#response").html(JSON.stringify(response, null, 4));_x000D_
}, "jsonp");
<script src=""></script>_x000D_
<pre id="response"></pre>

Here's the fiddle;

I also wrote this detailed analysis of 8 of the best IP Geolocation APIs.

Controlling number of decimal digits in print output in R

The reason it is only a suggestion is that you could quite easily write a print function that ignored the options value. The built-in printing and formatting functions do use the options value as a default.

As to the second question, since R uses finite precision arithmetic, your answers aren't accurate beyond 15 or 16 decimal places, so in general, more aren't required. The gmp and rcdd packages deal with multiple precision arithmetic (via an interace to the gmp library), but this is mostly related to big integers rather than more decimal places for your doubles.

Mathematica or Maple will allow you to give as many decimal places as your heart desires.

It might be useful to think about the difference between decimal places and significant figures. If you are doing statistical tests that rely on differences beyond the 15th significant figure, then your analysis is almost certainly junk.

On the other hand, if you are just dealing with very small numbers, that is less of a problem, since R can handle number as small as .Machine$double.xmin (usually 2e-308).

Compare these two analyses.

x1 <- rnorm(50, 1, 1e-15)
y1 <- rnorm(50, 1 + 1e-15, 1e-15)
t.test(x1, y1)  #Should throw an error

x2 <- rnorm(50, 0, 1e-15)
y2 <- rnorm(50, 1e-15, 1e-15)
t.test(x2, y2)  #ok

In the first case, differences between numbers only occur after many significant figures, so the data are "nearly constant". In the second case, Although the size of the differences between numbers are the same, compared to the magnitude of the numbers themselves they are large.

As mentioned by e3bo, you can use multiple-precision floating point numbers using the Rmpfr package.


These are slower and more memory intensive to use than regular (double precision) numeric vectors, but can be useful if you have a poorly conditioned problem or unstable algorithm.

json_encode function: special characters

Your input has to be encoded as UTF-8 or ISO-8859-1.

Because if you try to convert an array of non-utf8 characters you'll be getting 0 as return value.

Since 5.5.0 The return value on failure was changed from null string to FALSE.

Extract first and last row of a dataframe in pandas

I think the most simple way is .iloc[[0, -1]].

df = pd.DataFrame({'a':range(1,5), 'b':['a','b','c','d']})
df2 = df.iloc[[0, -1]]

print df2

   a  b
0  1  a
3  4  d

How to access parent Iframe from JavaScript

Once id of iframe is set, you can access iframe from inner document as shown below.

var iframe = parent.document.getElementById(;

Works well in IE, Chrome and FF.

WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()'

This is a warning spit out by build tools for two reasons.
1. One of the plugin is relying on Task instead of TaskProvider, there is nothing much we can do.
2. You have configured usage of task, where as it supports TaskProvider.

WARNING: API 'variant.getGenerateBuildConfig()' is obsolete and has been replaced with 'variant.getGenerateBuildConfigProvider()'.
It will be removed at the end of 2019.
For more information, see

WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()'.
It will be removed at the end of 2019.
For more information, see

WARNING: API 'variant.getMergeResources()' is obsolete and has been replaced with 'variant.getMergeResourcesProvider()'.
It will be removed at the end of 2019.
For more information, see

Look out for snippets as below & update.

android {
    <library|application>Variants.all { variant ->
        /* Disable Generating Build config */
        // variant.generateBuildConfig.enabled = true // <- Deprecated
        variant.generateBuildConfigProvider.configure {
            it.enabled = true // Replacement

Similarly, find usages of 'variant.getJavaCompile()' or 'variant.javaCompile', 'variant.getMergeResources()' or 'variant.mergeResources'. Replace as above.

More information at Task Configuration Avoidance

Set start value for column with autoincrement

From Resetting SQL Server Identity Columns:

Retrieving the identity for the table Employees:

DBCC checkident ('Employees')

Repairing the identity seed (if for some reason the database is inserting duplicate identities):

DBCC checkident ('Employees', reseed)

Changing the identity seed for the table Employees to 1000:

DBCC checkident ('Employees', reseed, 1000)

The next row inserted will begin at 1001.

Create text file and fill it using bash

Creating a text file in unix can be done through a text editor (vim, emacs, gedit, etc). But what you want might be something like this

echo "insert text here" > myfile.txt

That will put the text 'insert text here' into a file myfile.txt. To verify that this worked use the command 'cat'.

cat myfile.txt

If you want to append to a file use this

echo "append this text" >> myfile.txt

Prevent double submission of forms in jQuery

In my case the form's onsubmit had some validation code, so I increment Nathan Long answer including an onsubmit checkpoint

$.fn.preventDoubleSubmission = function() {
        var $form = $(this);
        //if the form has something in onsubmit
        var submitCode = $form.attr('onsubmit');
        if(submitCode != undefined && submitCode != ''){
            var submitFunction = new Function (submitCode);
                return false;

        if ($'submitted') === true) {
            /*Previously submitted - don't submit again */
        } else {
          /*Mark it so that the next submit can be ignored*/
          $'submitted', true);

      /*Keep chainability*/
      return this;

Git, How to reset origin/master to a commit?

origin/xxx branches are always pointer to a remote. You cannot check them out as they're not pointer to your local repository (you only checkout the commit. That's why you won't see the name written in the command line interface branch marker, only the commit hash).

What you need to do to update the remote is to force push your local changes to master:

git checkout master
git reset --hard e3f1e37
git push --force origin master
# Then to prove it (it won't print any diff)
git diff master..origin/master

Can you use if/else conditions in CSS?

You can add container div for all your condition scope.

Add the condition value as a class to the container div. (you can set it by server side programming - php/asp...)

<!--container div-->
<div class="true-value">
   <!-- your content -->
   <p>my content</p>
   <p>my content</p>
   <p>my content</p>

Now you can use the container class as a global variable for all elements in the div using a nested selector, without adding the class to each element.

.true-value p{
.false-value p{

How can I build a recursive function in python?

I'm wondering whether you meant "recursive". Here is a simple example of a recursive function to compute the factorial function:

def factorial(n):
    if n == 0:
        return 1
        return n * factorial(n - 1)

The two key elements of a recursive algorithm are:

  • The termination condition: n == 0
  • The reduction step where the function calls itself with a smaller number each time: factorial(n - 1)

Converting int to string in C

Better use sprintf(),

char stringNum[20];
int num=100;

How to return a complex JSON response with Node.js?

[Edit] After reviewing the Mongoose documentation, it looks like you can send each query result as a separate chunk; the web server uses chunked transfer encoding by default so all you have to do is wrap an array around the items to make it a valid JSON object.

Roughly (untested):

app.get('/users/:email/messages/unread', function(req, res, next) {
  var firstItem=true, query=MessageInfo.find(/*...*/);
  res.writeHead(200, {'Content-Type': 'application/json'});
  query.each(function(docs) {
    // Start the JSON array or separate the next element.
    res.write(firstItem ? (firstItem=false,'[') : ',');
    res.write(JSON.stringify({ msgId: msg.fileName }));
  res.end(']'); // End the JSON array and response.

Alternatively, as you mention, you can simply send the array contents as-is. In this case the response body will be buffered and sent immediately, which may consume a large amount of additional memory (above what is required to store the results themselves) for large result sets. For example:

// ...
var query = MessageInfo.find(/*...*/);
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify({ return x.fileName })));

How to convert string into float in JavaScript?

If they're meant to be separate values, try this:

var values = "554,20".split(",")
var v1 = parseFloat(values[0])
var v2 = parseFloat(values[1])

If they're meant to be a single value (like in French, where one-half is written 0,5)

var value = parseFloat("554,20".replace(",", "."));

How to stop event propagation with inline onclick attribute?

I had the same issue - js error box in IE - this works fine in all browsers as far as I can see (event.cancelBubble=true does the job in IE)


Can I have an onclick effect in CSS?

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

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

Here's how it looks like:

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

Simplest way to do grouped barplot

I wrote a function wrapper called bar() for barplot() to do what you are trying to do here, since I need to do similar things frequently. The Github link to the function is here. After copying and pasting it into R, you do

bar(dv = Species, 
    factors = c(Category, Reason), 
    dataframe = Reasonstats, 
    errbar = FALSE, 
    ylim=c(0, 140))  #I increased the upper y-limit to accommodate the legend. 

The one convenience is that it will put a legend on the plot using the names of the levels in your categorical variable (e.g., "Decline" and "Improved"). If each of your levels has multiple observations, it can also plot the error bars (which does not apply here, hence errbar=FALSE

enter image description here

#define macro for debug printing in C?

If you use a C99 or later compiler

#define debug_print(fmt, ...) \
            do { if (DEBUG) fprintf(stderr, fmt, __VA_ARGS__); } while (0)

It assumes you are using C99 (the variable argument list notation is not supported in earlier versions). The do { ... } while (0) idiom ensures that the code acts like a statement (function call). The unconditional use of the code ensures that the compiler always checks that your debug code is valid — but the optimizer will remove the code when DEBUG is 0.

If you want to work with #ifdef DEBUG, then change the test condition:

#ifdef DEBUG
#define DEBUG_TEST 1
#define DEBUG_TEST 0

And then use DEBUG_TEST where I used DEBUG.

If you insist on a string literal for the format string (probably a good idea anyway), you can also introduce things like __FILE__, __LINE__ and __func__ into the output, which can improve the diagnostics:

#define debug_print(fmt, ...) \
        do { if (DEBUG) fprintf(stderr, "%s:%d:%s(): " fmt, __FILE__, \
                                __LINE__, __func__, __VA_ARGS__); } while (0)

This relies on string concatenation to create a bigger format string than the programmer writes.

If you use a C89 compiler

If you are stuck with C89 and no useful compiler extension, then there isn't a particularly clean way to handle it. The technique I used to use was:

#define TRACE(x) do { if (DEBUG) dbg_printf x; } while (0)

And then, in the code, write:

TRACE(("message %d\n", var));

The double-parentheses are crucial — and are why you have the funny notation in the macro expansion. As before, the compiler always checks the code for syntactic validity (which is good) but the optimizer only invokes the printing function if the DEBUG macro evaluates to non-zero.

This does require a support function — dbg_printf() in the example — to handle things like 'stderr'. It requires you to know how to write varargs functions, but that isn't hard:

#include <stdarg.h>
#include <stdio.h>

void dbg_printf(const char *fmt, ...)
    va_list args;
    va_start(args, fmt);
    vfprintf(stderr, fmt, args);

You can also use this technique in C99, of course, but the __VA_ARGS__ technique is neater because it uses regular function notation, not the double-parentheses hack.

Why is it crucial that the compiler always see the debug code?

[Rehashing comments made to another answer.]

One central idea behind both the C99 and C89 implementations above is that the compiler proper always sees the debugging printf-like statements. This is important for long-term code — code that will last a decade or two.

Suppose a piece of code has been mostly dormant (stable) for a number of years, but now needs to be changed. You re-enable debugging trace - but it is frustrating to have to debug the debugging (tracing) code because it refers to variables that have been renamed or retyped, during the years of stable maintenance. If the compiler (post pre-processor) always sees the print statement, it ensures that any surrounding changes have not invalidated the diagnostics. If the compiler does not see the print statement, it cannot protect you against your own carelessness (or the carelessness of your colleagues or collaborators). See 'The Practice of Programming' by Kernighan and Pike, especially Chapter 8 (see also Wikipedia on TPOP).

This is 'been there, done that' experience — I used essentially the technique described in other answers where the non-debug build does not see the printf-like statements for a number of years (more than a decade). But I came across the advice in TPOP (see my previous comment), and then did enable some debugging code after a number of years, and ran into problems of changed context breaking the debugging. Several times, having the printing always validated has saved me from later problems.

I use NDEBUG to control assertions only, and a separate macro (usually DEBUG) to control whether debug tracing is built into the program. Even when the debug tracing is built in, I frequently do not want debug output to appear unconditionally, so I have mechanism to control whether the output appears (debug levels, and instead of calling fprintf() directly, I call a debug print function that only conditionally prints so the same build of the code can print or not print based on program options). I also have a 'multiple-subsystem' version of the code for bigger programs, so that I can have different sections of the program producing different amounts of trace - under runtime control.

I am advocating that for all builds, the compiler should see the diagnostic statements; however, the compiler won't generate any code for the debugging trace statements unless debug is enabled. Basically, it means that all of your code is checked by the compiler every time you compile - whether for release or debugging. This is a good thing!

debug.h - version 1.2 (1990-05-01)

@(#)File:            $RCSfile: debug.h,v $
@(#)Version:         $Revision: 1.2 $
@(#)Last changed:    $Date: 1990/05/01 12:55:39 $
@(#)Purpose:         Definitions for the debugging system
@(#)Author:          J Leffler

#ifndef DEBUG_H
#define DEBUG_H

/* -- Macro Definitions */

#ifdef DEBUG
#define TRACE(x)    db_print x
#define TRACE(x)
#endif /* DEBUG */

/* -- Declarations */

#ifdef DEBUG
extern  int     debug;

#endif  /* DEBUG_H */

debug.h - version 3.6 (2008-02-11)

@(#)File:           $RCSfile: debug.h,v $
@(#)Version:        $Revision: 3.6 $
@(#)Last changed:   $Date: 2008/02/11 06:46:37 $
@(#)Purpose:        Definitions for the debugging system
@(#)Author:         J Leffler
@(#)Copyright:      (C) JLSS 1990-93,1997-99,2003,2005,2008
@(#)Product:        :PRODUCT:

#ifndef DEBUG_H
#define DEBUG_H

#include "config.h"
#endif /* HAVE_CONFIG_H */

** Usage:  TRACE((level, fmt, ...))
** "level" is the debugging level which must be operational for the output
** to appear. "fmt" is a printf format string. "..." is whatever extra
** arguments fmt requires (possibly nothing).
** The non-debug macro means that the code is validated but never called.
** -- See chapter 8 of 'The Practice of Programming', by Kernighan and Pike.
#ifdef DEBUG
#define TRACE(x)    db_print x
#define TRACE(x)    do { if (0) db_print x; } while (0)
#endif /* DEBUG */

#ifndef lint
#ifdef DEBUG
/* This string can't be made extern - multiple definition in general */
static const char jlss_id_debug_enabled[] = "@(#)*** DEBUG ***";
#endif /* DEBUG */
const char jlss_id_debug_h[] = "@(#)$Id: debug.h,v 3.6 2008/02/11 06:46:37 jleffler Exp $";
#endif /* MAIN_PROGRAM */
#endif /* lint */

#include <stdio.h>

extern int      db_getdebug(void);
extern int      db_newindent(void);
extern int      db_oldindent(void);
extern int      db_setdebug(int level);
extern int      db_setindent(int i);
extern void     db_print(int level, const char *fmt,...);
extern void     db_setfilename(const char *fn);
extern void     db_setfileptr(FILE *fp);
extern FILE    *db_getfileptr(void);

/* Semi-private function */
extern const char *db_indent(void);


** Usage:  MDTRACE((subsys, level, fmt, ...))
** "subsys" is the debugging system to which this statement belongs.
** The significance of the subsystems is determined by the programmer,
** except that the functions such as db_print refer to subsystem 0.
** "level" is the debugging level which must be operational for the
** output to appear. "fmt" is a printf format string. "..." is
** whatever extra arguments fmt requires (possibly nothing).
** The non-debug macro means that the code is validated but never called.
#ifdef DEBUG
#define MDTRACE(x)  db_mdprint x
#define MDTRACE(x)  do { if (0) db_mdprint x; } while (0)
#endif /* DEBUG */

extern int      db_mdgetdebug(int subsys);
extern int      db_mdparsearg(char *arg);
extern int      db_mdsetdebug(int subsys, int level);
extern void     db_mdprint(int subsys, int level, const char *fmt,...);
extern void     db_mdsubsysnames(char const * const *names);

#endif /* DEBUG_H */

Single argument variant for C99 or later

Kyle Brandt asked:

Anyway to do this so debug_print still works even if there are no arguments? For example:


There's one simple, old-fashioned hack:

debug_print("%s\n", "Foo");

The GCC-only solution shown below also provides support for that.

However, you can do it with the straight C99 system by using:

#define debug_print(...) \
            do { if (DEBUG) fprintf(stderr, __VA_ARGS__); } while (0)

Compared to the first version, you lose the limited checking that requires the 'fmt' argument, which means that someone could try to call 'debug_print()' with no arguments (but the trailing comma in the argument list to fprintf() would fail to compile). Whether the loss of checking is a problem at all is debatable.

GCC-specific technique for a single argument

Some compilers may offer extensions for other ways of handling variable-length argument lists in macros. Specifically, as first noted in the comments by Hugo Ideler, GCC allows you to omit the comma that would normally appear after the last 'fixed' argument to the macro. It also allows you to use ##__VA_ARGS__ in the macro replacement text, which deletes the comma preceding the notation if, but only if, the previous token is a comma:

#define debug_print(fmt, ...) \
            do { if (DEBUG) fprintf(stderr, fmt, ##__VA_ARGS__); } while (0)

This solution retains the benefit of requiring the format argument while accepting optional arguments after the format.

This technique is also supported by Clang for GCC compatibility.

Why the do-while loop?

What's the purpose of the do while here?

You want to be able to use the macro so it looks like a function call, which means it will be followed by a semi-colon. Therefore, you have to package the macro body to suit. If you use an if statement without the surrounding do { ... } while (0), you will have:

/* BAD - BAD - BAD */
#define debug_print(...) \
            if (DEBUG) fprintf(stderr, __VA_ARGS__)

Now, suppose you write:

if (x > y)
    debug_print("x (%d) > y (%d)\n", x, y);
    do_something_useful(x, y);

Unfortunately, that indentation doesn't reflect the actual control of flow, because the preprocessor produces code equivalent to this (indented and braces added to emphasize the actual meaning):

if (x > y)
    if (DEBUG)
        fprintf(stderr, "x (%d) > y (%d)\n", x, y);
        do_something_useful(x, y);

The next attempt at the macro might be:

/* BAD - BAD - BAD */
#define debug_print(...) \
            if (DEBUG) { fprintf(stderr, __VA_ARGS__); }

And the same code fragment now produces:

if (x > y)
    if (DEBUG)
        fprintf(stderr, "x (%d) > y (%d)\n", x, y);
; // Null statement from semi-colon after macro
    do_something_useful(x, y);

And the else is now a syntax error. The do { ... } while(0) loop avoids both these problems.

There's one other way of writing the macro which might work:

/* BAD - BAD - BAD */
#define debug_print(...) \
            ((void)((DEBUG) ? fprintf(stderr, __VA_ARGS__) : 0))

This leaves the program fragment shown as valid. The (void) cast prevents it being used in contexts where a value is required — but it could be used as the left operand of a comma operator where the do { ... } while (0) version cannot. If you think you should be able to embed debug code into such expressions, you might prefer this. If you prefer to require the debug print to act as a full statement, then the do { ... } while (0) version is better. Note that if the body of the macro involved any semi-colons (roughly speaking), then you can only use the do { ... } while(0) notation. It always works; the expression statement mechanism can be more difficult to apply. You might also get warnings from the compiler with the expression form that you'd prefer to avoid; it will depend on the compiler and the flags you use.

TPOP was previously at and but both are now (2015-08-10) broken.

Code in GitHub

If you're curious, you can look at this code in GitHub in my SOQ (Stack Overflow Questions) repository as files debug.c, debug.h and mddebug.c in the src/libsoq sub-directory.

Java; String replace (using regular expressions)?

str.replaceAll("\\^([0-9]+)", "<sup>$1</sup>");

How to extract week number in sql

Try to replace 'w' for 'iw'. For example:

SELECT to_char(to_date(TRANSDATE, 'dd-mm-yyyy'), 'iw') as weeknumber from YOUR_TABLE;

How to add Drop-Down list (<select>) programmatically?

it's very simple yet tricky but here is what you wanted, hope it's helpful : this function generates a select list from 1990 to 2018 i think this example can help ya, if you want to add any other value just change value of x and y ;)

function dropDown(){
    var start = 1990;
    var today = 2019;
    for (var i = start ; i <= today; i++)
    document.write("<option>" + i + "</option>");


iOS 7 status bar back to iOS 6 default style in iPhone app?

If you don't want your view controllers to be overlapped by the status bar (and navigation bars), uncheck the "Extend Edges Under Top Bars" box in Interface Builder in Xcode 5.

Uncheck the Extend Edges Under Top Bars

How to stick <footer> element at the bottom of the page (HTML5 and CSS3)?

For footer change from position: relative; to position:fixed;

 footer {
            background-color: #333;
            width: 100%;
            bottom: 0;
            position: fixed;


from jquery $.ajax to angular $http

you can use $.param to assign data :

  url: "",
  method: "POST",
  data: $.param({"foo":"bar"})
  }).success(function(data, status, headers, config) {
   $ = data;
  }).error(function(data, status, headers, config) {
   $scope.status = status;

look at this : AngularJS + ASP.NET Web API Cross-Domain Issue

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

I am using this in my layout to capture all modals and focus on the first input

  $('.modal').on('shown', function() {

Java: Add elements to arraylist with FOR loop where element name has increasing number

That can't be done with a for-loop, unless you use the Reflection API. However, you can use Arrays.asList instead to accomplish the same:

List<Answer> answers = Arrays.asList(answer1, answer2, answer3);

jQuery autohide element after 5 seconds

You use setTimeout on you runEffect function :

function runEffect() {
        var selectedEffect = 'blind';
        var options = {};
        $("#successMessage").hide(selectedEffect, options, 500)
     }, 5000);

How can I turn a DataTable to a CSV?

To write to a file, I think the following method is the most efficient and straightforward: (You can add quotes if you want)

public static void WriteCsv(DataTable dt, string path)
    using (var writer = new StreamWriter(path)) {
        writer.WriteLine(string.Join(",", dt.Columns.Cast<DataColumn>().Select(dc => dc.ColumnName)));
        foreach (DataRow row in dt.Rows) {
            writer.WriteLine(string.Join(",", row.ItemArray));

How to while loop until the end of a file in Python without checking for empty line?

Find end position of file:

f = open("file.txt","r"),2) #Jumps to the end
f.tell()    #Give you the end location (characters from start)   #Jump to the beginning of the file again

Then you can to:

if line == '' and f.tell() == endLocation:

List method to delete last element in list as well as all elements

To delete the last element from the list just do this.

a = [1,2,3,4,5]
a = a[:-1]
#Output [1,2,3,4] 

Concept of void pointer in C programming

Because C is statically-typed, strongly-typed language, you must decide type of variable before compile. When you try to emulate generics in C, you'll end up attempt to rewrite C++ again, so it would be better to use C++ instead.

CORS Access-Control-Allow-Headers wildcard being ignored?

Support for wildcards in the Access-Control-Allow-Headers header was added to the living standard only in May 2016, so it may not be supported by all browsers. On browser which don't implement this yet, it must be an exact match:

If you expect a large number of headers, you can read in the value of the Access-Control-Request-Headers header and echo that value back in the Access-Control-Allow-Headers header.

ReportViewer Client Print Control "Unable to load client print control"?

I have had the same problem (on several different servers). Applying SP3 and Report Viewer SP1 has helped on some of the servers, allowing the client machines to connect and download the control with no problem. However, I have had one server that, even after applying the updates, when accessing the report viewer using a client machine, it was still giving me the error. On looking into the exact URL GET request that is being sent, I discovered that it is possible to force the client machine to connect directly to the Report Server to download the control.

The user would need to enter the following url:


This should then pop up the required download/install prompt.

Merge DLL into EXE?

The command should be the following script:

ilmerge myExe.exe Dll1.dll /target:winexe /targetplatform:"v4,c:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\" /out:merged.exe /out:merged.exe

Save attachments to a folder and rename them

Added simple code to save with readable date-time stamp.

Use sync2pst to sync all your data in outlook with all your devices, work like this:

  1. you only need to buy 1 license: save your pst file on one computer (let's call this pc 'server') on your network.
  2. create scheduled tasks that will synchronize the pst file on your 'server' with all the pst files on all your devices, no matter which device downloaded the emails first (you need some dos programming knowledge to bypass pst files that are open at sync time).
  3. save all your attachments on the same skydrive folder that is located on the same place on all your devices (e.g. e:\skydrive\attachments)
  4. Use the code below on all your devices to save attachments (change the path as mentioned above)
  5. Use ONLY ONE PST-file for all your accounts, make folders, subfolders and so ...

  6. in VBA: refer to 'microsoft scripting runtime'extra/references...'

  7. here's the code

Private Sub Application_NewMail()
End Sub

Public Sub SaveAttachments()
Dim objOL As Outlook.Application
Dim objMsg As Outlook.MailItem 'Object
Dim objAttachments As Outlook.Attachments
Dim objSelection As Outlook.Selection
Dim i As Long
Dim lngCount As Long
Dim strFile As String
Dim strFolderpath As String
Dim strDeletedFiles As String
Dim fs As FileSystemObject

' Get the path to your My Documents folder
strFolderpath = CreateObject("WScript.Shell").SpecialFolders(16)
On Error Resume Next

' Instantiate an Outlook Application object.
Set objOL = CreateObject("Outlook.Application")

' Get the collection of selected objects.
Set objSelection = objOL.ActiveExplorer.Selection

' Set the Attachment folder.
strFolderpath = "F:\SkyDrive\Attachments\"

' Check each selected item for attachments. If attachments exist,
' save them to the strFolderPath folder and strip them from the item.
For Each objMsg In objSelection

    ' This code only strips attachments from mail items.
    ' If objMsg.class=olMail Then
    ' Get the Attachments collection of the item.
    Set objAttachments = objMsg.Attachments
    lngCount = objAttachments.Count
    strDeletedFiles = ""

    If lngCount > 0 Then

        ' We need to use a count down loop for removing items
        ' from a collection. Otherwise, the loop counter gets
        ' confused and only every other item is removed.
        Set fs = New FileSystemObject

        For i = lngCount To 1 Step -1

            ' Save attachment before deleting from item.
            ' Get the file name.
            strFile = Left(objAttachments.Item(i).FileName, Len(objAttachments.Item(i).FileName) - 4) + "_" + Right("00" + Trim(Str$(Day(Now))), 2) + "_" + Right("00" + Trim(Str$(Month(Now))), 2) + "_" + Right("0000" + Trim(Str$(Year(Now))), 4) + "_" + Right("00" + Trim(Str$(Hour(Now))), 2) + "_" + Right("00" + Trim(Str$(Minute(Now))), 2) + "_" + Right("00" + Trim(Str$(Second(Now))), 2) + Right((objAttachments.Item(i).FileName), 4)

            ' Combine with the path to the Temp folder.
            strFile = strFolderpath & strFile

            ' Save the attachment as a file.
            objAttachments.Item(i).SaveAsFile strFile

            ' Delete the attachment.

            'write the save as path to a string to add to the message
            'check for html and use html tags in link
            If objMsg.BodyFormat <> olFormatHTML Then
                strDeletedFiles = strDeletedFiles & vbCrLf & "<file://" & strFile & ">"
                strDeletedFiles = strDeletedFiles & "<br>" & "<a href='file://" & _
                strFile & "'>" & strFile & "</a>"
            End If

            'Use the MsgBox command to troubleshoot. Remove it from the final code.
            'MsgBox strDeletedFiles

        Next i

        ' Adds the filename string to the message body and save it
        ' Check for HTML body
        If objMsg.BodyFormat <> olFormatHTML Then
            objMsg.Body = vbCrLf & "The file(s) were saved to " & strDeletedFiles & vbCrLf & objMsg.Body
            objMsg.HTMLBody = "<p>" & "The file(s) were saved to " & strDeletedFiles & "</p>" & objMsg.HTMLBody
        End If

    End If


Set objAttachments = Nothing
Set objMsg = Nothing
Set objSelection = Nothing
Set objOL = Nothing
End Sub

How to replace a set of tokens in a Java String?

In the past, I've solved this kind of problem with StringTemplate and Groovy Templates.

Ultimately, the decision of using a templating engine or not should be based on the following factors:

  • Will you have many of these templates in the application?
  • Do you need the ability to modify the templates without restarting the application?
  • Who will be maintaining these templates? A Java programmer or a business analyst involved on the project?
  • Will you need to the ability to put logic in your templates, like conditional text based on values in the variables?
  • Will you need the ability to include other templates in a template?

If any of the above applies to your project, I would consider using a templating engine, most of which provide this functionality, and more.

How do you print in Sublime Text 2

TL;DR Use Cmd/Ctrl+Shift+P then Package Control: Install Package, then Print to HTML and install it. Use Alt+Shift+P to print.

My favorite tool for printing from Sublime Text is Print to HTML package. You can "print" a selection or a whole file - via the web browser.


  1. Make a selection (or none for the whole file)
  2. Press Alt+Shift+P OR Shift+Command+P and type in "Print to HTML".

This opens your browser print dialog (Chrome for me) with the selected text neatly in the print dialog window and syntax highlighting intact. There you can choose a printer or export to PDF, and print.


Install the "Print to HTML" package using the package manager.

  1. Ctrl + Shift + P => Gives a list of commands.
  2. Find the package manager by typing "install"
  3. You see a few choices. Select "Package Control: Install Package"
  4. This opens a list of packages. Type "print to"
  5. One of the choices should be "Print to HTML". Select that, and it is being installed.
  6. You can use the "print to html" now by a keyboard shortcut Alt+Shift+P

How to continue the code on the next line in VBA

(i, j, n + 1) = k * b_xyt(xi, yi, tn) / (4 * hx * hy) * U_matrix(i + 1, j + 1, n) + _
(k * (a_xyt(xi, yi, tn) / hx ^ 2 + d_xyt(xi, yi, tn) / (2 * hx)))

From ms support

To continue a statement from one line to the next, type a space followed by the line-continuation character [the underscore character on your keyboard (_)].

You can break a line at an operator, list separator, or period.

Enabling HTTPS on express.js

First, you need to create selfsigned.key and selfsigned.crt files. Go to Create a Self-Signed SSL Certificate Or do following steps.

Go to the terminal and run the following command.

sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout ./selfsigned.key -out selfsigned.crt

  • After that put the following information
  • Country Name (2 letter code) [AU]: US
  • State or Province Name (full name) [Some-State]: NY
  • Locality Name (eg, city) []:NY
  • Organization Name (eg, company) [Internet Widgits Pty Ltd]: xyz (Your - Organization)
  • Organizational Unit Name (eg, section) []: xyz (Your Unit Name)
  • Common Name (e.g. server FQDN or YOUR name) []: (Your URL)
  • Email Address []: Your email

After creation adds key & cert file in your code, and pass the options to the server.

const express = require('express');
const https = require('https');
const fs = require('fs');
const port = 3000;

var key = fs.readFileSync(__dirname + '/../certs/selfsigned.key');
var cert = fs.readFileSync(__dirname + '/../certs/selfsigned.crt');
var options = {
  key: key,
  cert: cert

app = express()
app.get('/', (req, res) => {
   res.send('Now using https..');

var server = https.createServer(options, app);

server.listen(port, () => {
  console.log("server starting on port : " + port)
  • Finally run your application using https.

More information

What exactly does += do in python?

+= is just a shortcut for writing

number = 4
number = number + 1

So instead you would write

numbers = 4
numbers += 1

Both ways are correct but example two helps you write a little less code

Dynamically select data frame columns using $ and a character value

You can't do that kind of subsetting with $. In the source code (R/src/main/subset.c) it states:

/*The $ subset operator.
We need to be sure to only evaluate the first argument.
The second will be a symbol that needs to be matched, not evaluated.

Second argument? What?! You have to realise that $, like everything else in R, (including for instance ( , + , ^ etc) is a function, that takes arguments and is evaluated. df$V1 could be rewritten as

`$`(df , V1)

or indeed

`$`(df , "V1")


`$`(df , paste0("V1") )

...for instance will never work, nor will anything else that must first be evaluated in the second argument. You may only pass a string which is never evaluated.

Instead use [ (or [[ if you want to extract only a single column as a vector).

For example,

var <- "mpg"
#Doesn't work
#These both work, but note that what they return is different
# the first is a vector, the second is a data.frame

You can perform the ordering without loops, using to construct the call to order. Here is a reproducible example below:

#  set seed for reproducibility
df <- data.frame( col1 = sample(5,10,repl=T) , col2 = sample(5,10,repl=T) , col3 = sample(5,10,repl=T) )

#  We want to sort by 'col3' then by 'col1'
sort_list <- c("col3","col1")

#  Use '' to call order. Seccond argument in is a list of arguments
#  to pass to the first argument, in this case 'order'.
#  Since  a data.frame is really a list, we just subset the data.frame
#  according to the columns we want to sort in, in that order
df[ order , df[ , match( sort_list , names(df) ) ]  ) , ]

   col1 col2 col3
10    3    5    1
9     3    2    2
7     3    2    3
8     5    1    3
6     1    5    4
3     3    4    4
2     4    3    4
5     5    1    4
1     2    5    5
4     5    3    5

How to check that an element is in a std::set?

If you were going to add a contains function, it might look like this:

#include <algorithm>
#include <iterator>

template<class TInputIterator, class T> inline
bool contains(TInputIterator first, TInputIterator last, const T& value)
    return std::find(first, last, value) != last;

template<class TContainer, class T> inline
bool contains(const TContainer& container, const T& value)
    // This works with more containers but requires std::begin and std::end
    // from C++0x, which you can get either:
    //  1. By using a C++0x compiler or
    //  2. Including the utility functions below.
    return contains(std::begin(container), std::end(container), value);

    // This works pre-C++0x (and without the utility functions below, but doesn't
    // work for fixed-length arrays.
    //return contains(container.begin(), container.end(), value);

template<class T> inline
bool contains(const std::set<T>& container, const T& value)
    return container.find(value) != container.end();

This works with std::set, other STL containers, and even fixed-length arrays:

void test()
    std::set<int> set;
    assert(!contains(set, 3));

    int set2[] = { 1, 2, 3 };
    assert(contains(set2, 3));


As pointed out in the comments, I unintentionally used a function new to C++0x (std::begin and std::end). Here is the near-trivial implementation from VS2010:

namespace std {

template<class _Container> inline
    typename _Container::iterator begin(_Container& _Cont)
    { // get beginning of sequence
    return (_Cont.begin());

template<class _Container> inline
    typename _Container::const_iterator begin(const _Container& _Cont)
    { // get beginning of sequence
    return (_Cont.begin());

template<class _Container> inline
    typename _Container::iterator end(_Container& _Cont)
    { // get end of sequence
    return (_Cont.end());

template<class _Container> inline
    typename _Container::const_iterator end(const _Container& _Cont)
    { // get end of sequence
    return (_Cont.end());

template<class _Ty,
    size_t _Size> inline
    _Ty *begin(_Ty (&_Array)[_Size])
    { // get beginning of array
    return (&_Array[0]);

template<class _Ty,
    size_t _Size> inline
    _Ty *end(_Ty (&_Array)[_Size])
    { // get end of array
    return (&_Array[0] + _Size);


Basic Apache commands for a local Windows machine

Going back to absolute basics here. The answers on this page and a little googling have brought me to the following resolution to my issue. Steps to restart the apache service with Xampp installed:-

  1. Click the start button and type CMD (if on Windows Vista or later and Apache is installed as a service make sure this is an elevated command prompt)
  2. In the command window that appears type cd C:\xampp\apache\bin (the default installation path for Xampp)
  3. Then type httpd -k restart

I hope that this is of use to others just starting out with running a local Apache server.

less than 10 add 0 to number

if(myNumber.toString().length < 2)
   myNumber= "0"+myNumber;


return (myNumber.toString().length < 2) ? "0"+myNumber : myNumber;

Convert boolean to int in Java

public int boolToInt(boolean b) {
    return b ? 1 : 0;


"psql: could not connect to server: Connection refused" Error when connecting to remote database

In my case I had removed a locale and generated another locale. Database failed to open because of fatal errors in the postgresql.conf file, on 'lc_messages', 'lc_monetary', 'lc_numberic', and 'lc_time'.

Restoring the locale sorted it out for me.

SSH Key: “Permissions 0644 for '' are too open.” on mac

Just run below to your pem's

sudo chmod 600 /path/to/my/key.pem 

WCF error: The caller was not authenticated by the service

Have you tried using basicHttpBinding instead of wsHttpBinding? If do not need any authentication and the Ws-* implementations are not required, you'd probably be better off with plain old basicHttpBinding. WsHttpBinding implements WS-Security for message security and authentication.

How to implement a binary search tree in Python?

class Node: 
    rChild,lChild,data = None,None,None

This is wrong - it makes your variables class variables - that is, every instance of Node uses the same values (changing rChild of any node changes it for all nodes!). This is clearly not what you want; try

class Node: 
    def __init__(self, key):
        self.rChild = None
        self.lChild = None = key

now each node has its own set of variables. The same applies to your definition of Tree,

class Tree:
    root,size = None,0    # <- lose this line!
    def __init__(self):
        self.root = None
        self.size = 0

Further, each class should be a "new-style" class derived from the "object" class and should chain back to object.__init__():

class Node(object): 
    def __init__(self, data, rChild=None, lChild=None):
        super(Node,self).__init__()   = data
        self.rChild = rChild
        self.lChild = lChild

class Tree(object):
    def __init__(self):
        self.root = None
        self.size = 0

Also, main() is indented too far - as shown, it is a method of Tree which is uncallable because it does not accept a self argument.

Also, you are modifying the object's data directly (t.root = Node(4)) which kind of destroys encapsulation (the whole point of having classes in the first place); you should be doing something more like

def main():
    t = Tree()
    t.add(4)    # <- let the tree create a data Node and insert it

PackagesNotFoundError: The following packages are not available from current channels:

Thanks, Max S. conda-forge worked for me as well.

scikit-learn on Anaconda-Jupyter Notebook.

Upgrading my scikit-learn from 0.19.1 to 0.19.2 in anaconda installed on Ubuntu on Google VM instance:

Run the following commands in the terminal:

First, check available the packages with versions

conda list    

It will show packages and their installed versions in the output:

scikit-learn              0.19.1           py36hedc7406_0  

Upgrade to 0.19.2 July 2018 release.

conda config --append channels conda-forge
conda install scikit-learn=0.19.2

Now check the version installed correctly or not?

conda list 

Output is:

scikit-learn              0.19.2          py36_blas_openblasha84fab4_201  [blas_openblas]  conda-forge

Note: Don't use pip command if you are using Anaconda or Miniconda

I tried following commands:

!conda update conda 
!pip install -U scikit-learn

It will install the required packages also will show in the conda list but when try to import that package it will not work.

On the website it is mentioned as: Warning To upgrade or uninstall scikit-learn installed with Anaconda or conda you should not use the pip.

Including .cpp files

Because of the One Definition Rule (probably1).

In C++, each non-inline object and function must have exactly one definition within the program. By #includeing the file in which foo(int) is defined (the CPP file), it is defined both in every file where foop.cpp is #included, and in foop.cpp itself (assuming foop.cpp is compiled).

You can make a function inline to override this behavior, but I'm not recommending that here. I have never seen a situation where it is necessary or even desirable to #include a CPP file.

There are situations where it is desireable to include a definition of something. This is specially true when you try to seperate the definition of a template from the declaration of it. In those cases, I name the file HPP rather than CPP to denote the difference.

1: "(probably)" I say probably here because the actual code you've posted should compile without errors, but given the compiler error it seems likely that the code you posted isn't exactly the same as the code you're compiling.

Significance of ios_base::sync_with_stdio(false); cin.tie(NULL);

The two calls have different meanings that have nothing to do with performance; the fact that it speeds up the execution time is (or might be) just a side effect. You should understand what each of them does and not blindly include them in every program because they look like an optimization.


This disables the synchronization between the C and C++ standard streams. By default, all standard streams are synchronized, which in practice allows you to mix C- and C++-style I/O and get sensible and expected results. If you disable the synchronization, then C++ streams are allowed to have their own independent buffers, which makes mixing C- and C++-style I/O an adventure.

Also keep in mind that synchronized C++ streams are thread-safe (output from different threads may interleave, but you get no data races).


This unties cin from cout. Tied streams ensure that one stream is flushed automatically before each I/O operation on the other stream.

By default cin is tied to cout to ensure a sensible user interaction. For example:

std::cout << "Enter name:";
std::cin >> name;

If cin and cout are tied, you can expect the output to be flushed (i.e., visible on the console) before the program prompts input from the user. If you untie the streams, the program might block waiting for the user to enter their name but the "Enter name" message is not yet visible (because cout is buffered by default, output is flushed/displayed on the console only on demand or when the buffer is full).

So if you untie cin from cout, you must make sure to flush cout manually every time you want to display something before expecting input on cin.

In conclusion, know what each of them does, understand the consequences, and then decide if you really want or need the possible side effect of speed improvement.

getContext is not a function

I recently got this error because the typo, I write 'canavas' instead of 'canvas', hope this could help someone who is searching for this.

MySQL: Invalid use of group function

First, the error you're getting is due to where you're using the COUNT function -- you can't use an aggregate (or group) function in the WHERE clause.

Second, instead of using a subquery, simply join the table to itself:

FROM Catalog as a LEFT JOIN Catalog as b USING( pid )
WHERE a.sid != b.sid

Which I believe should return only rows where at least two rows exist with the same pid but there is are at least 2 sids. To make sure you get back only one row per pid I've applied a grouping clause.

How to solve npm install throwing fsevents warning on non-MAC OS?

I got the same error. In my case, I was using a mapped drive to edit code off of a second computer, that computer was running linux. Not sure exactly why gulp-watch relies on operating system compatibility prior to install (I would assume it has to do with security purposes). Essentially the error is checking against your operating system and the operating system calling the node module, in my case the two operating systems were not the same so it threw it error. Which from the looks of your error is the same as mine.

The Error

Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

How I fixed it?

I logged into the linux computer directly and ran

npm install --save-dev <module-name>

Then went back into my coding environment and everything was fine after that.

Hope that helps!

How do I write good/correct package files

Your should have a docstring.

Although all the functionality is implemented in modules and subpackages, your package docstring is the place to document where to start. For example, consider the python email package. The package documentation is an introduction describing the purpose, background, and how the various components within the package work together. If you automatically generate documentation from docstrings using sphinx or another package, the package docstring is exactly the right place to describe such an introduction.

For any other content, see the excellent answers by firecrow and Alex Martelli.

how to add <script>alert('test');</script> inside a text box?

is you want fix XSS on input element? you can encode string before output to input field


$str = htmlentities($str);


str = WebUtility.HtmlEncode(str);

after that output value direct to input field:

<input type="text" value="<?php echo $str" />

How to calculate the median of an array?

Use Arrays.sort and then take the middle element (in case the number n of elements in the array is odd) or take the average of the two middle elements (in case n is even).

  public static long median(long[] l)
    int middle = l.length / 2;
    if (l.length % 2 == 0)
      long left = l[middle - 1];
      long right = l[middle];
      return (left + right) / 2;
      return l[middle];

Here are some examples:

  public void evenTest()
    long[] l = {
        5, 6, 1, 3, 2
    Assert.assertEquals((3 + 4) / 2, median(l));

  public oddTest()
    long[] l = {
        5, 1, 3, 2, 4
    Assert.assertEquals(3, median(l));

And in case your input is a Collection, you might use Google Guava to do something like this:

public static long median(Collection<Long> numbers)
  return median(Longs.toArray(numbers)); // requires import;

WebDriver - wait for element using Java

We're having a lot of race conditions with elementToBeClickable. See Something along these lines worked reasonably well even if a little brute force

                    Matchers.containsString("is not clickable at point")
            () -> {
                return true;

How to Implement Custom Table View Section Headers and Footers with Storyboard

I got it working in iOS7 using a prototype cell in the storyboard. I have a button in my custom section header view that triggers a segue that is set up in the storyboard.

Start with Tieme's solution

As pedro.m points out, the problem with this is that tapping the section header causes the first cell in the section to be selected.

As Paul Von points out, this is fixed by returning the cell's contentView instead of the whole cell.

However, as Hons points out, a long press on said section header will crash the app.

The solution is to remove any gestureRecognizers from contentView.

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
     static NSString *CellIdentifier = @"SectionHeader";
     UITableViewCell *sectionHeaderView = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

     while (sectionHeaderView.contentView.gestureRecognizers.count) {
         [sectionHeaderView.contentView removeGestureRecognizer:[sectionHeaderView.contentView.gestureRecognizers objectAtIndex:0]];

     return sectionHeaderView.contentView; }

If you aren't using gestures in your section header views, this little hack seems to get it done.

There is already an object named in the database

Note: I did it because I don't have anything in my database. In my case: 1. I removed a migration by command remove-migration in Package Manager Console 2. Removed database by 'SQL Server Object Explorer' panel > on current database > right-click > Remove 3. Migrated in Package Manager Console write Add-Migration and click Enter 4. The last update by command update-database

ld cannot find an existing library

As just formulated by grepsedawk, the answer lies in the -l option of g++, calling ld. If you look at the man page of this command, you can either do:

  • g++ [...]
  • or: g++ -lmagic [...] , if you have a symlink named in your libs path

How to Convert unsigned char* to std::string in C++?

Here is the complete code

#include <bits/stdc++.h>

using namespace std;

typedef unsigned char BYTE;

int main() {
  //method 1;
  std::vector<BYTE> data = {'H','E','L','L','O','1','2','3'};
  //string constructor accepts only const char
  std::string s((const char*)&(data[0]), data.size());
  std::cout << s << std::endl;

  //method 2
  std::string s2(data.begin(),data.end());
  std::cout << s2 << std::endl;

  //method 3
  std::string s3(reinterpret_cast<char const*>(&data[0]), data.size()) ;
  std::cout << s3 << std::endl;
  return 0;

Delete multiple objects in django

You can delete any QuerySet you'd like. For example, to delete all blog posts with some Post model


and to delete any Post with a future publication date


You do, however, need to come up with a way to narrow down your QuerySet. If you just want a view to delete a particular object, look into the delete generic view.


Sorry for the misunderstanding. I think the answer is somewhere between. To implement your own, combine ModelForms and generic views. Otherwise, look into 3rd party apps that provide similar functionality. In a related question, the recommendation was django-filter.

Unable to copy file - access to the path is denied

I had the same issue, To resolved this i had checked/done several things

What Didn't work

1) Read/write permissions were given to directory 
2) Restarted visual studio
3) Tried deleting visual studio temp files

What worked at last

Just paste the command given by Fred Morrison into the "Package Manager Console":

Get-Process | Where-Object -Property Name -EQ 'VBCSCompiler' | Stop-Process -Force -Verbose

Note: Just an observation Restarting Visual studio might not work in this case but restarting system can because stoppin process "VBCSCompiler" was the solution so we can do it either way.

Android How to adjust layout in Full Screen Mode when softkeyboard is visible

In my case, this issue started happening once I added Crosswalk to my Cordova application. My app is not used in fullscreen and android:windowSoftInputMode="adjustPan".

I already had the ionic keyboard plugin in the application, so detecting if the keyboard was up or down was easy thanks to it:

// Listen for events to when the keyboard is opened and closed
window.addEventListener("native.keyboardshow", keyboardUp, false);
window.addEventListener('native.keyboardhide', keyboardDown, false);

function keyboardUp()

function keyboardDown()

I tried all of the fixes above but the simple line that ended up doing it for me was this bit of css:

&.keyboardUp {
        overflow-y: scroll;

Hope this saves you the few days I spent on this. :)

What does [object Object] mean?

Consider the following example:

const foo = {};
foo[Symbol.toStringTag] = "bar";
console.log("" + foo);

Which outputs

[object bar]

Basically, any object in javascript can define a property with the tag Symbol.toStringTag and override the output.

Behind the scenes construction of a new object in javascript prototypes from some object with a "toString" method. The default object provides this method as a property, and that method internally invokes the tag to determine how to coerce the object to a string. If the tag is present, then it's used, if missing you get "Object".

Should you set Symbol.toStringTag? Maybe. But relying on the string always being [object Object] for "true" objects is not the best idea.

GCC dump preprocessor defines

While working in a big project which has complex build system and where it is hard to get (or modify) the gcc/g++ command directly there is another way to see the result of macro expansion. Simply redefine the macro, and you will get output similiar to following:

file.h: note: this is the location of the previous definition
#define MACRO current_value

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve

In my case I used google play services...I increase library service it solved

implementation ''

Google play service must be same in library and app modules


Difference between FetchType LAZY and EAGER in Java Persistence API?

Sometimes you have two entities and there's a relationship between them. For example, you might have an entity called University and another entity called Student and a University might have many Students:

The University entity might have some basic properties such as id, name, address, etc. as well as a collection property called students that returns the list of students for a given university:

A university has many students

public class University {
   private String id;
   private String name;
   private String address;
   private List<Student> students;

   // setters and getters

Now when you load a University from the database, JPA loads its id, name, and address fields for you. But you have two options for how students should be loaded:

  1. To load it together with the rest of the fields (i.e. eagerly), or
  2. To load it on-demand (i.e. lazily) when you call the university's getStudents() method.

When a university has many students it is not efficient to load all of its students together with it, especially when they are not needed and in suchlike cases you can declare that you want students to be loaded when they are actually needed. This is called lazy loading.

Here's an example, where students is explicitly marked to be loaded eagerly:

public class University {

    private String id;

    private String name;

    private String address;

    @OneToMany(fetch = FetchType.EAGER)
    private List<Student> students;

    // etc.    

And here's an example where students is explicitly marked to be loaded lazily:

public class University {

    private String id;

    private String name;

    private String address;

    @OneToMany(fetch = FetchType.LAZY)
    private List<Student> students;

    // etc.

MongoDB: How to query for records where field is null or not set?


db.emails.count({sent_at: null})

Which counts all emails whose sent_at property is null or is not set. The above query is same as below.

db.emails.count($or: [
  {sent_at: {$exists: false}},
  {sent_at: null}

Why am I getting this redefinition of class error?

You're defining the class in the header file, include the header file into a *.cpp file and define the class a second time because the first definition is dragged into the translation unit by the header file. But only one gameObject class definition is allowed per translation unit.

You actually don't need to define the class a second time just to implement the functions. Implement the functions like this:

#include "gameObject.h"

gameObject::gameObject(int inx, int iny)
    x = inx;
    y = iny;

int gameObject::add()
    return x+y;


Facebook Like-Button - hide count?

If you're using Facebook's javascript like button (so you can capture like events), here's what we had to do:

Due to a change Facebook recently made in the way comment dialogs display, we had to change how we were hiding it. The way they show the comment dialog has been 'moving' the content inside of the my overflow:hidden element so that the button looks really odd to the user after they click the like button.

In addition to adding a wrapping element with an 'overflow:none' style, you will need to hide the comment element that Facebook is putting onto your page:


span.no_overflow {
  overflow: none;
  width: 50px;

.no_overflow span.fb_edge_comment_widget.fb_iframe_widget {
  display: none;


<span class="no_overflow">

We're still using the fb:like markup though. I have not tested this with the new div-based markup that Facebook is providing on their site now.

How can I capitalize the first letter of each word in a string using JavaScript?

Below is another way to capitalize the first alphabet of each word in a string.

Create a custom method for a String object by using prototype.

String.prototype.capitalize = function() {
    var c = '';
    var s = this.split(' ');
    for (var i = 0; i < s.length; i++) {
        c+= s[i].charAt(0).toUpperCase() + s[i].slice(1) + ' ';
    return c;
var name = "john doe";

char initial value in Java

you can initialize it to ' ' instead. Also, the reason that you received an error -1 being too many characters is because it is treating '-' and 1 as separate.

"VT-x is not available" when I start my Virtual machine

You might try reducing your base memory under settings to around 3175MB and reduce your cores to 1. That should work given that your BIOS is set for virtualization. Use the f12 key, security, virtualization to make sure that it is enabled. If it doesn't say VT-x that is ok, it should say VT-d or the like.

How to make an array of arrays in Java


String[][] arrays = new String[5][];

How to check if a windows form is already open, and close it if it is?

if( ((Form1)Application.OpenForms["Form1"]).Visible == true)
    //form is visible
    //form is invisible

where Form1 is the name of your form.

Send email using the GMail SMTP server from a PHP page

Your code does not appear to be using TLS (SSL), which is necessary to deliver mail to Google (and using ports 465 or 587).

You can do this by setting

$host = "ssl://";

Your code looks suspiciously like this example which refers to ssl:// in the hostname scheme.

Using git to get just the latest revision

Use git clone with the --depth option set to 1 to create a shallow clone with a history truncated to the latest commit.

For example:

git clone --depth 1

To also initialize and update any nested submodules, also pass --recurse-submodules and to clone them shallowly, also pass --shallow-submodules.

For example:

git clone --depth 1 --recurse-submodules --shallow-submodules

How do I get a list of locked users in an Oracle database?

select username,
  from dba_users 
 where lock_date is not null;

This will actually give you the list of locked users.

How to prevent user from typing in text field without disabling the field?

One option is to bind a handler to the input event.

The advantage of this approach is that we don't prevent keyboard behaviors that the user expects (e.g. tab, page up/down, etc.).

Another advantage is that it also handles the case when the input value is changed by pasting text through the context menu.

This approach works best if you only care about keeping the input empty. If you want to maintain a specific value, you'll have to track that somewhere else (in a data attribute?) since it will not be available when the input event is received.

const inputEl = document.querySelector('input');_x000D_
inputEl.addEventListener('input', (event) => {_x000D_ = '';_x000D_
<input type="text" />

Tested in Safari 10, Firefox 49, Chrome 54, IE 11.

Determine the type of an object?

In general you can extract a string from object with the class name,

str_class = object.__class__.__name__

and using it for comparison,

if str_class == 'dict':
    # blablabla..
elif str_class == 'customclass':
    # blebleble..

How to compare two tables column by column in oracle

It won't be fast, and there will be a lot for you to type (unless you generate the SQL from user_tab_columns), but here is what I use when I need to compare two tables row-by-row and column-by-column.

The query will return all rows that

  • Exists in table1 but not in table2
  • Exists in table2 but not in table1
  • Exists in both tables, but have at least one column with a different value

(common identical rows will be excluded).

"PK" is the column(s) that make up your primary key. "a" will contain A if the present row exists in table1. "b" will contain B if the present row exists in table2.

select pk
      ,decode(a.rowid, null, null, 'A') as a
      ,decode(b.rowid, null, null, 'B') as b
      ,a.col1, b.col1
      ,a.col2, b.col2
      ,a.col3, b.col3
  from table1 a 
  full outer 
  join table2 b using(pk)
 where decode(a.col1, b.col1, 1, 0) = 0
    or decode(a.col2, b.col2, 1, 0) = 0
    or decode(a.col3, b.col3, 1, 0) = 0
    or ...;

Edit Added example code to show the difference described in comment. Whenever one of the values contains NULL, the result will be different.

with a as(
   select 0    as col1 from dual union all
   select 1    as col1 from dual union all
   select null as col1 from dual
,b as(
   select 1    as col1 from dual union all
   select 2    as col1 from dual union all
   select null as col1 from dual
select a.col1
      ,decode(a.col1, b.col1, 'Same', 'Different') as approach_1
      ,case when a.col1 <> b.col1 then 'Different' else 'Same' end as approach_2       
  from a,b
    by a.col1

col1   col1_1   approach_1  approach_2
====   ======   ==========  ==========
  0        1    Different   Different  
  0        2    Different   Different  
  0      null   Different   Same         <--- 
  1        1    Same        Same       
  1        2    Different   Different  
  1      null   Different   Same         <---
null       1    Different   Same         <---
null       2    Different   Same         <---
null     null   Same        Same       

git-upload-pack: command not found, when cloning remote Git repo

I have been having issues connecting to a Gitolite repo using SSH from Windows and it turned out that my problem was PLINK! It kept asking me for a password, but the ssh gitolite@[host] would return the repo list fine.

Check your environment variable: GIT_SSH. If it is set to Plink, then try it without any value ("set GIT_SSH=") and see if that works.

How to make a Qt Widget grow with the window size?

The accepted answer (its image) is wrong, at least now in QT5. Instead you should assign a layout to the root object/widget (pointing to the aforementioned image, it should be the MainWindow instead of centralWidget). Also note that you must have at least one QObject created beneath it for this to work. Do this and your ui will become responsive to window resizing.