Programs & Examples On #Linguistics

Linguistics is the scientific study of language and its structure, including the study of morphology, syntax, phonetics, and semantics.

Is there an online application that automatically draws tree structures for phrases/sentences?

In short, yes. I assume you're looking to parse English: for that you can use the Link Parser from Carnegie Mellon.

It is important to remember that there are many theories of syntax, that can give completely different-looking phrase structure trees; further, the trees are different for each language, and tools may not exist for those languages.

As a note for the future: if you need a sentence parsed out and tag it as linguistics (and syntax or whatnot, if that's available), someone can probably parse it out for you and guide you through it.

How To Convert A Number To an ASCII Character?

you can simply cast it.

char c = (char)100;

Adding a HTTP header to the Angular HttpClient doesn't send the header, why?

The instances of the new HttpHeader class are immutable objects. Invoking class methods will return a new instance as result. So basically, you need to do the following:

let headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json; charset=utf-8');

or

const headers = new HttpHeaders({'Content-Type':'application/json; charset=utf-8'});

Update: adding multiple headers

let headers = new HttpHeaders();
headers = headers.set('h1', 'v1').set('h2','v2');

or

const headers = new HttpHeaders({'h1':'v1','h2':'v2'});

Update: accept object map for HttpClient headers & params

Since 5.0.0-beta.6 is now possible to skip the creation of a HttpHeaders object an directly pass an object map as argument. So now its possible to do the following:

http.get('someurl',{
   headers: {'header1':'value1','header2':'value2'}
});

How to add a custom right-click menu to a webpage?

Try This

$(function() {
var doubleClicked = false;
$(document).on("contextmenu", function (e) {
if(doubleClicked == false) {
e.preventDefault(); // To prevent the default context menu.
var windowHeight = $(window).height()/2;
var windowWidth = $(window).width()/2;
if(e.clientY > windowHeight && e.clientX <= windowWidth) {
  $("#contextMenuContainer").css("left", e.clientX);
  $("#contextMenuContainer").css("bottom", $(window).height()-e.clientY);
  $("#contextMenuContainer").css("right", "auto");
  $("#contextMenuContainer").css("top", "auto");
} else if(e.clientY > windowHeight && e.clientX > windowWidth) {
  $("#contextMenuContainer").css("right", $(window).width()-e.clientX);
  $("#contextMenuContainer").css("bottom", $(window).height()-e.clientY);
  $("#contextMenuContainer").css("left", "auto");
  $("#contextMenuContainer").css("top", "auto");
} else if(e.clientY <= windowHeight && e.clientX <= windowWidth) {
  $("#contextMenuContainer").css("left", e.clientX);
  $("#contextMenuContainer").css("top", e.clientY);
  $("#contextMenuContainer").css("right", "auto");
  $("#contextMenuContainer").css("bottom", "auto");
} else {
  $("#contextMenuContainer").css("right", $(window).width()-e.clientX);
  $("#contextMenuContainer").css("top", e.clientY);
  $("#contextMenuContainer").css("left", "auto");
  $("#contextMenuContainer").css("bottom", "auto");
}
 $("#contextMenuContainer").fadeIn(500, FocusContextOut());
  doubleClicked = true;
} else {
  e.preventDefault();
  doubleClicked = false;
  $("#contextMenuContainer").fadeOut(500);
}
});
function FocusContextOut() {
 $(document).on("click", function () {
   doubleClicked = false; 
   $("#contextMenuContainer").fadeOut(500);
   $(document).off("click");           
 });
}
});

http://jsfiddle.net/AkshayBandivadekar/zakn7Lwb/14/

Can I install Python 3.x and 2.x on the same Windows computer?

Here you go...

winpylaunch.py

#
# Looks for a directive in the form: #! C:\Python30\python.exe
# The directive must start with #! and contain ".exe".
# This will be assumed to be the correct python interpreter to
# use to run the script ON WINDOWS. If no interpreter is
# found then the script will be run with 'python.exe'.
# ie: whatever one is found on the path.
# For example, in a script which is saved as utf-8 and which
# runs on Linux and Windows and uses the Python 2.6 interpreter...
#
#    #!/usr/bin/python
#    #!C:\Python26\python.exe
#    # -*- coding: utf-8 -*-
#
# When run on Linux, Linux uses the /usr/bin/python. When run
# on Windows using winpylaunch.py it uses C:\Python26\python.exe.
#
# To set up the association add this to the registry...
#
#    HKEY_CLASSES_ROOT\Python.File\shell\open\command
#    (Default) REG_SZ = "C:\Python30\python.exe" S:\usr\bin\winpylaunch.py "%1" %*
#
# NOTE: winpylaunch.py itself works with either 2.6 and 3.0. Once
# this entry has been added python files can be run on the
# commandline and the use of winpylaunch.py will be transparent.
#

import subprocess
import sys

USAGE = """
USAGE: winpylaunch.py <script.py> [arg1] [arg2...]
"""

if __name__ == "__main__":
  if len(sys.argv) > 1:
    script = sys.argv[1]
    args   = sys.argv[2:]
    if script.endswith(".py"):
      interpreter = "python.exe" # Default to wherever it is found on the path.
      lines = open(script).readlines()
      for line in lines:
        if line.startswith("#!") and line.find(".exe") != -1:
          interpreter = line[2:].strip()
          break
      process = subprocess.Popen([interpreter] + [script] + args)
      process.wait()
      sys.exit()
  print(USAGE)

I've just knocked this up on reading this thread (because it's what I was needing too). I have Pythons 2.6.1 and 3.0.1 on both Ubuntu and Windows. If it doesn't work for you post fixes here.

Check if a user has scrolled to the bottom

I used @ddanone answear and added Ajax call.

$('#mydiv').on('scroll', function(){
  function infiniScroll(this);
});

function infiniScroll(mydiv){
console.log($(mydiv).scrollTop()+' + '+ $(mydiv).height()+' = '+ ($(mydiv).scrollTop() + $(mydiv).height())   +' _ '+ $(mydiv)[0].scrollHeight  );

if($(mydiv).scrollTop() + $(mydiv).height() == $(mydiv)[0].scrollHeight){
    console.log('bottom found');
    if(!$.active){ //if there is no ajax call active ( last ajax call waiting for results ) do again my ajax call
        myAjaxCall();
    }
}

}

Plot mean and standard deviation

You may find an answer with this example : errorbar_demo_features.py

"""
Demo of errorbar function with different ways of specifying error bars.

Errors can be specified as a constant value (as shown in `errorbar_demo.py`),
or as demonstrated in this example, they can be specified by an N x 1 or 2 x N,
where N is the number of data points.

N x 1:
    Error varies for each point, but the error values are symmetric (i.e. the
    lower and upper values are equal).

2 x N:
    Error varies for each point, and the lower and upper limits (in that order)
    are different (asymmetric case)

In addition, this example demonstrates how to use log scale with errorbar.
"""
import numpy as np
import matplotlib.pyplot as plt

# example data
x = np.arange(0.1, 4, 0.5)
y = np.exp(-x)
# example error bar values that vary with x-position
error = 0.1 + 0.2 * x
# error bar values w/ different -/+ errors
lower_error = 0.4 * error
upper_error = error
asymmetric_error = [lower_error, upper_error]

fig, (ax0, ax1) = plt.subplots(nrows=2, sharex=True)
ax0.errorbar(x, y, yerr=error, fmt='-o')
ax0.set_title('variable, symmetric error')

ax1.errorbar(x, y, xerr=asymmetric_error, fmt='o')
ax1.set_title('variable, asymmetric error')
ax1.set_yscale('log')
plt.show()

Which plots this:

enter image description here

Response Buffer Limit Exceeded

In my case i just have writing this line before rs.Open .....

Response.flush

rs.Open query, conn

Calling a java method from c++ in Android

Solution posted by Denys S. in the question post:

I quite messed it up with c to c++ conversion (basically env variable stuff), but I got it working with the following code for C++:

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

jstring Java_the_package_MainActivity_getJniString( JNIEnv* env, jobject obj){

    jstring jstr = (*env)->NewStringUTF(env, "This comes from jni.");
    jclass clazz = (*env)->FindClass(env, "com/inceptix/android/t3d/MainActivity");
    jmethodID messageMe = (*env)->GetMethodID(env, clazz, "messageMe", "(Ljava/lang/String;)Ljava/lang/String;");
    jobject result = (*env)->CallObjectMethod(env, obj, messageMe, jstr);

    const char* str = (*env)->GetStringUTFChars(env,(jstring) result, NULL); // should be released but what a heck, it's a tutorial :)
    printf("%s\n", str);

    return (*env)->NewStringUTF(env, str);
}

And next code for java methods:

    public class MainActivity extends Activity {
    private static String LIB_NAME = "thelib";

    static {
        System.loadLibrary(LIB_NAME);
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView tv = (TextView) findViewById(R.id.textview);
        tv.setText(this.getJniString());
    }

    // please, let me live even though I used this dark programming technique
    public String messageMe(String text) {
        System.out.println(text);
        return text;
    }

    public native String getJniString();
}

Is Laravel really this slow?

I found that biggest speed gain with Laravel 4 you can achieve choosing right session drivers;

Sessions "driver" file;

Requests per second:    188.07 [#/sec] (mean)
Time per request:       26.586 [ms] (mean)
Time per request:       5.317 [ms] (mean, across all concurrent requests)


Session "driver" database;

Requests per second:    41.12 [#/sec] (mean)
Time per request:       121.604 [ms] (mean)
Time per request:       24.321 [ms] (mean, across all concurrent requests)

Hope that helps

Add carriage return to a string

Environment.NewLine should be used as Dan Rigby said but there is one problem with the String.Empty. It will remain always empty no matter if it is read before or after it reads. I had a problem in my project yesterday with that. I removed it and it worked the way it was supposed to. It's better to declare the variable and then call it when it's needed. String.Empty will always keep it empty unless the variable needs to be initialized which only then should you use String.Empty. Thought I would throw this tid-bit out for everyone as I've experienced it.

how to call url of any other website in php

If you meant .. to REDIRECT from that page to another, the function is really simple

header("Location:www.google.com");

What is .htaccess file?

What

  • A settings file for the server
  • Cannot be accessed by end-user
  • There is no need to reboot the server, changes work immediately
  • It might serve as a bridge between your code and server

We can do

  • URL rewriting
  • Custom error pages
  • Caching
  • Redirections
  • Blocking ip's

"The POM for ... is missing, no dependency information available" even though it exists in Maven Repository

In my case the reason was since the remote repo artifact (non-central) had dependencies from the Maven Central in the .pom file, and the older version of mvn (older than 3.6.0) was used. So, it tried to check the Maven Central artifacts mentioned in the remote repo's .pom for the specific artifact I've added to my dependencies and faced the Maven Central http access issue behind the scenes (I believe the same as described there: Maven dependencies are failing with a 501 error - that is about using https access to Maven Central by default and prohibiting the http access).

Using more recent Maven (from 3.1 to 3.6.0) made it use https to check Maven Central repo dependencies mentioned in the .pom files of the remote repositories and I no longer face the issue.

How to import classes defined in __init__.py

Add something like this to lib/__init__.py

from .helperclass import Helper

now you can import it directly:

from lib import Helper

Pretty Printing a pandas dataframe

Following up on Mark's answer, if you're not using Jupyter for some reason, e.g. you want to do some quick testing on the console, you can use the DataFrame.to_string method, which works from -- at least -- Pandas 0.12 (2014) onwards.

import pandas as pd

matrix = [(1, 23, 45), (789, 1, 23), (45, 678, 90)]
df = pd.DataFrame(matrix, columns=list('abc'))
print(df.to_string())

#  outputs:
#       a    b   c
#  0    1   23  45
#  1  789    1  23
#  2   45  678  90

What is the difference between Select and Project Operations

Select Operation : This operation is used to select rows from a table (relation) that specifies a given logic, which is called as a predicate. The predicate is a user defined condition to select rows of user's choice.

Project Operation : If the user is interested in selecting the values of a few attributes, rather than selection all attributes of the Table (Relation), then one should go for PROJECT Operation.

See more : Relational Algebra and its operations

How do I get into a non-password protected Java keystore or change the password?

Mac Mountain Lion has the same password now it uses Oracle.

Filter multiple values on a string column in dplyr

 by_type_year_tag_filtered <- by_type_year_tag %>%
      dplyr:: filter(tag_name %in% c("dplyr", "ggplot2"))

Using Jquery Datatable with AngularJs

Adding a new answer just as a reference for future researchers and as nobody mentioned that yet I think it's valid.

Another good option is ng-grid http://angular-ui.github.io/ng-grid/.

And there's a beta version (http://ui-grid.info/) available already with some improvements:

  • Native AngularJS implementation, no jQuery
  • Performs well with large data sets; even 10,000+ rows
  • Plugin architecture allows you to use only the features you need

UPDATE:

It seems UI GRID is not beta anymore.

With the 3.0 release, the repository has been renamed from "ng-grid" to "ui-grid".

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

HTML4 specification states that:

Inline elements may contain only data and other inline elements

Span is an inline element, therefore having span inside span is valid. There's a related question: Can <span> tags have any type of tags inside them? which makes it completely clear.

HTML5 specification (including the most current draft of HTML 5.3 dated November 16, 2017) changes terminology, but it's still perfectly valid to place span inside another span.

Laravel Eloquent update just if changes have been made

You can use getChanges() on Eloquent model even after persisting.

Given an array of numbers, return array of products of all other numbers (no division)

I came up with 2 solutions in Javascript, one with division and one without

_x000D_
_x000D_
// without division
function methodOne(arr) {
  return arr.map(item => {
    return arr.reduce((result, num) => {
      if (num !== item) {
        result = result * num;
      }
      return result;
    },1)
  });
}

// with division
function methodTwo(arr) {
  var mul = arr.reduce((result, num) => {
    result = result * num;
    return result;
  },1)
 return arr.map(item => mul/item);
}

console.log(methodOne([1, 2, 3, 4, 5]));
console.log(methodTwo([1, 2, 3, 4, 5]));
_x000D_
_x000D_
_x000D_

mysqli_fetch_array while loop columns

I think this would be a more simpler way of outputting your results.

Sorry for using my own data should be easy to replace .

$query = "SELECT * FROM category ";

$result = mysqli_query($connection, $query);


    while($row = mysqli_fetch_assoc($result))
    {
        $cat_id = $row['cat_id'];
        $cat_title = $row['cat_title'];

        echo $cat_id . " " . $cat_title  ."<br>";
    }

This would output :

  • -ID Title
  • -1 Gary
  • -2 John
  • -3 Michaels

Loading an image to a <img> from <input file>

As iEamin said in his answer, HTML 5 does now support this. The link he gave, http://www.html5rocks.com/en/tutorials/file/dndfiles/ , is excellent. Here is a minimal sample based on the samples at that site, but see that site for more thorough examples.

Add an onchange event listener to your HTML:

<input type="file" onchange="onFileSelected(event)">

Make an image tag with an id (I'm specifying height=200 to make sure the image isn't too huge onscreen):

<img id="myimage" height="200">

Here is the JavaScript of the onchange event listener. It takes the File object that was passed as event.target.files[0], constructs a FileReader to read its contents, and sets up a new event listener to assign the resulting data: URL to the img tag:

function onFileSelected(event) {
  var selectedFile = event.target.files[0];
  var reader = new FileReader();

  var imgtag = document.getElementById("myimage");
  imgtag.title = selectedFile.name;

  reader.onload = function(event) {
    imgtag.src = event.target.result;
  };

  reader.readAsDataURL(selectedFile);
}

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

From the Python glossary:

It’s important to keep in mind that all packages are modules, but not all modules are packages. Or put another way, packages are just a special kind of module. Specifically, any module that contains a __path__ attribute is considered a package.

Python files with a dash in the name, like my-file.py, cannot be imported with a simple import statement. Code-wise, import my-file is the same as import my - file which will raise an exception. Such files are better characterized as scripts whereas importable files are modules.

delete image from folder PHP

There are a few routes. One, the most simple, would involve making that into a form; when it submits you react to POST data and delete the image using unlink

DISCLAIMER: This is not secure. An attacker could use this code to delete any file on your server. You must expand on this demonstration code to add some measure of security, otherwise you can expect bad things.

Each image's display markup would contain a form something like this:

echo '<form method="post">';
  echo '<input type="hidden" value="'.$file.'" name="delete_file" />';
  echo '<input type="submit" value="Delete image" />';
echo '</form>';

...and at at the top of that same PHP file:

if (array_key_exists('delete_file', $_POST)) {
  $filename = $_POST['delete_file'];
  if (file_exists($filename)) {
    unlink($filename);
    echo 'File '.$filename.' has been deleted';
  } else {
    echo 'Could not delete '.$filename.', file does not exist';
  }
}
// existing code continues below...

You can elaborate on this by using javascript: instead of submitting the form, you could send an AJAX request. The server-side code would look rather similar to this.

Documentation and Related Reading

LINQ Aggregate algorithm explained

Definition

Aggregate method is an extension method for generic collections. Aggregate method applies a function to each item of a collection. Not just only applies a function, but takes its result as initial value for the next iteration. So, as a result, we will get a computed value (min, max, avg, or other statistical value) from a collection.

Therefore, Aggregate method is a form of safe implementation of a recursive function.

Safe, because the recursion will iterate over each item of a collection and we can’t get any infinite loop suspension by wrong exit condition. Recursive, because the current function’s result is used as a parameter for the next function call.

Syntax:

collection.Aggregate(seed, func, resultSelector);
  • seed - initial value by default;
  • func - our recursive function. It can be a lambda-expression, a Func delegate or a function type T F(T result, T nextValue);
  • resultSelector - it can be a function like func or an expression to compute, transform, change, convert the final result.

How it works:

var nums = new[]{1, 2};
var result = nums.Aggregate(1, (result, n) => result + n); //result = (1 + 1) + 2 = 4
var result2 = nums.Aggregate(0, (result, n) => result + n, response => (decimal)response/2.0); //result2 = ((0 + 1) + 2)*1.0/2.0 = 3*1.0/2.0 = 3.0/2.0 = 1.5

Practical usage:

  1. Find Factorial from a number n:

int n = 7;
var numbers = Enumerable.Range(1, n);
var factorial = numbers.Aggregate((result, x) => result * x);

which is doing the same thing as this function:

public static int Factorial(int n)
{
   if (n < 1) return 1;

   return n * Factorial(n - 1);
}
  1. Aggregate() is one of the most powerful LINQ extension method, like Select() and Where(). We can use it to replace the Sum(), Min(). Max(), Avg() functionality, or to change it by implementing addition context:
    var numbers = new[]{3, 2, 6, 4, 9, 5, 7};
    var avg = numbers.Aggregate(0.0, (result, x) => result + x, response => (double)response/(double)numbers.Count());
    var min = numbers.Aggregate((result, x) => (result < x)? result: x);
  1. More complex usage of extension methods:
    var path = @“c:\path-to-folder”;

    string[] txtFiles = Directory.GetFiles(path).Where(f => f.EndsWith(“.txt”)).ToArray<string>();
    var output = txtFiles.Select(f => File.ReadAllText(f, Encoding.Default)).Aggregate<string>((result, content) => result + content);

    File.WriteAllText(path + “summary.txt”, output, Encoding.Default);

    Console.WriteLine(“Text files merged into: {0}”, output); //or other log info

How to make all controls resize accordingly proportionally when window is maximized?

Just thought i'd share this with anyone who needs more clarity on how to achieve this:

myCanvas is a Canvas control and Parent to all other controllers. This code works to neatly resize to any resolution from 1366 x 768 upward. Tested up to 4k resolution 4096 x 2160

Take note of all the MainWindow property settings (WindowStartupLocation, SizeToContent and WindowState) - important for this to work correctly - WindowState for my user case requirement was Maximized

xaml

<Window x:Name="mainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:MyApp" 
    xmlns:ed="http://schemas.microsoft.com/expression/2010/drawing"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"
    x:Class="MyApp.MainWindow" 
     Title="MainWindow"  SizeChanged="MainWindow_SizeChanged"
    Width="1366" Height="768" WindowState="Maximized" WindowStartupLocation="CenterOwner" SizeToContent="WidthAndHeight">
  
    <Canvas x:Name="myCanvas" HorizontalAlignment="Left" Height="768" VerticalAlignment="Top" Width="1356">
        <Image x:Name="maxresdefault_1_1__jpg" Source="maxresdefault-1[1].jpg" Stretch="Fill" Opacity="0.6" Height="767" Canvas.Left="-6" Width="1366"/>

        <Separator Margin="0" Background="#FF302D2D" Foreground="#FF111010" Height="0" Canvas.Left="-811" Canvas.Top="148" Width="766"/>
        <Separator Margin="0" Background="#FF302D2D" Foreground="#FF111010" HorizontalAlignment="Right" Width="210" Height="0" Canvas.Left="1653" Canvas.Top="102"/>
        <Image x:Name="imgscroll" Source="BcaKKb47i[1].png" Stretch="Fill" RenderTransformOrigin="0.5,0.5" Height="523" Canvas.Left="-3" Canvas.Top="122" Width="580">
            <Image.RenderTransform>
                <TransformGroup>
                    <ScaleTransform/>
                    <SkewTransform/>
                    <RotateTransform Angle="89.093"/>
                    <TranslateTransform/>
                </TransformGroup>
            </Image.RenderTransform>
        </Image>

.cs

 private void MainWindow_SizeChanged(object sender, SizeChangedEventArgs e)
    {
        myCanvas.Width = e.NewSize.Width;
        myCanvas.Height = e.NewSize.Height;

        double xChange = 1, yChange = 1;

        if (e.PreviousSize.Width != 0)
            xChange = (e.NewSize.Width / e.PreviousSize.Width);

        if (e.PreviousSize.Height != 0)
            yChange = (e.NewSize.Height / e.PreviousSize.Height);

        ScaleTransform scale = new ScaleTransform(myCanvas.LayoutTransform.Value.M11 * xChange, myCanvas.LayoutTransform.Value.M22 * yChange);
        myCanvas.LayoutTransform = scale;
        myCanvas.UpdateLayout();
    }

How to group by week in MySQL?

If you need the "week ending" date this will work as well. This will count the number of records for each week. Example: If three work orders were created between (inclusive) 1/2/2010 and 1/8/2010 and 5 were created between (inclusive) 1/9/2010 and 1/16/2010 this would return:

3 1/8/2010
5 1/16/2010

I had to use the extra DATE() function to truncate my datetime field.

SELECT COUNT(*), DATE_ADD( DATE(wo.date_created), INTERVAL (7 - DAYOFWEEK( wo.date_created )) DAY) week_ending
FROM work_order wo
GROUP BY week_ending;

What does it mean to "call" a function in Python?

When you "call" a function you are basically just telling the program to execute that function. So if you had a function that added two numbers such as:

def add(a,b):
    return a + b

you would call the function like this:

add(3,5)

which would return 8. You can put any two numbers in the parentheses in this case. You can also call a function like this:

answer = add(4,7)

Which would set the variable answer equal to 11 in this case.

How to update a value in a json file and save it through node.js

Doing this asynchronously is quite easy. It's particularly useful if you're concerned for blocking the thread (likely).

const fs = require('fs');
const fileName = './file.json';
const file = require(fileName);
    
file.key = "new value";
    
fs.writeFile(fileName, JSON.stringify(file), function writeJSON(err) {
  if (err) return console.log(err);
  console.log(JSON.stringify(file));
  console.log('writing to ' + fileName);
});

The caveat is that json is written to the file on one line and not prettified. ex:

{
  "key": "value"
}

will be...

{"key": "value"}

To avoid this, simply add these two extra arguments to JSON.stringify

JSON.stringify(file, null, 2)

null - represents the replacer function. (in this case we don't want to alter the process)

2 - represents the spaces to indent.

Eclipse does not highlight matching variables

I wish I could have read the response by @Ján Lazár.

In addition to all the configurations mentioned in the accepted answer, below setting solved my misery:

For large files the scalability mode must be turned off. Enabling scalability mode will disable reference highlighting.

enter image description here

PS: @Rob Hruska It would be great if this point is added in the accepted answer. Most of the readers do not bother to read the last response.

npm ERR! network getaddrinfo ENOTFOUND

Make sure to use the latest npm version while installing packages using npm.

While installing JavaScript, mention the latest version of NodeJS. For example, while installing JavaScript using devtools, use the below code:

devtools i --javascript nodejs:10.15.1

This will download and install the mentioned NodeJS version. Try installing the packages with npm after updating the version. This worked for me.

how to evenly distribute elements in a div next to each other?

_x000D_
_x000D_
.container {_x000D_
  padding: 10px;_x000D_
}_x000D_
.parent {_x000D_
  width: 100%;_x000D_
  background: #7b7b7b;_x000D_
  display: flex;_x000D_
  justify-content: space-between;_x000D_
  height: 4px;_x000D_
}_x000D_
.child {_x000D_
  color: #fff;_x000D_
  background: green;_x000D_
  padding: 10px 10px;_x000D_
  border-radius: 50%;_x000D_
  position: relative;_x000D_
  top: -8px;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="parent">_x000D_
    <span class="child"></span>_x000D_
    <span class="child"></span>_x000D_
    <span class="child"></span>_x000D_
    <span class="child"></span>_x000D_
    <span class="child"></span>_x000D_
    <span class="child"></span>_x000D_
    <span class="child"></span>_x000D_
    <span class="child"></span>_x000D_
    <span class="child"></span>_x000D_
    <span class="child"></span>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Checking whether a string starts with XXXX

I did a little experiment to see which of these methods

  • string.startswith('hello')
  • string.rfind('hello') == 0
  • string.rpartition('hello')[0] == ''
  • string.rindex('hello') == 0

are most efficient to return whether a certain string begins with another string.

Here is the result of one of the many test runs I've made, where each list is ordered to show the least time it took (in seconds) to parse 5 million of each of the above expressions during each iteration of the while loop I used:

['startswith: 1.37', 'rpartition: 1.38', 'rfind: 1.62', 'rindex: 1.62']
['startswith: 1.28', 'rpartition: 1.44', 'rindex: 1.67', 'rfind: 1.68']
['startswith: 1.29', 'rpartition: 1.42', 'rindex: 1.63', 'rfind: 1.64']
['startswith: 1.28', 'rpartition: 1.43', 'rindex: 1.61', 'rfind: 1.62']
['rpartition: 1.48', 'startswith: 1.48', 'rfind: 1.62', 'rindex: 1.67']
['startswith: 1.34', 'rpartition: 1.43', 'rfind: 1.64', 'rindex: 1.64']
['startswith: 1.36', 'rpartition: 1.44', 'rindex: 1.61', 'rfind: 1.63']
['startswith: 1.29', 'rpartition: 1.37', 'rindex: 1.64', 'rfind: 1.67']
['startswith: 1.34', 'rpartition: 1.44', 'rfind: 1.66', 'rindex: 1.68']
['startswith: 1.44', 'rpartition: 1.41', 'rindex: 1.61', 'rfind: 2.24']
['startswith: 1.34', 'rpartition: 1.45', 'rindex: 1.62', 'rfind: 1.67']
['startswith: 1.34', 'rpartition: 1.38', 'rindex: 1.67', 'rfind: 1.74']
['rpartition: 1.37', 'startswith: 1.38', 'rfind: 1.61', 'rindex: 1.64']
['startswith: 1.32', 'rpartition: 1.39', 'rfind: 1.64', 'rindex: 1.61']
['rpartition: 1.35', 'startswith: 1.36', 'rfind: 1.63', 'rindex: 1.67']
['startswith: 1.29', 'rpartition: 1.36', 'rfind: 1.65', 'rindex: 1.84']
['startswith: 1.41', 'rpartition: 1.44', 'rfind: 1.63', 'rindex: 1.71']
['startswith: 1.34', 'rpartition: 1.46', 'rindex: 1.66', 'rfind: 1.74']
['startswith: 1.32', 'rpartition: 1.46', 'rfind: 1.64', 'rindex: 1.74']
['startswith: 1.38', 'rpartition: 1.48', 'rfind: 1.68', 'rindex: 1.68']
['startswith: 1.35', 'rpartition: 1.42', 'rfind: 1.63', 'rindex: 1.68']
['startswith: 1.32', 'rpartition: 1.46', 'rfind: 1.65', 'rindex: 1.75']
['startswith: 1.37', 'rpartition: 1.46', 'rfind: 1.74', 'rindex: 1.75']
['startswith: 1.31', 'rpartition: 1.48', 'rfind: 1.67', 'rindex: 1.74']
['startswith: 1.44', 'rpartition: 1.46', 'rindex: 1.69', 'rfind: 1.74']
['startswith: 1.44', 'rpartition: 1.42', 'rfind: 1.65', 'rindex: 1.65']
['startswith: 1.36', 'rpartition: 1.44', 'rfind: 1.64', 'rindex: 1.74']
['startswith: 1.34', 'rpartition: 1.46', 'rfind: 1.61', 'rindex: 1.74']
['startswith: 1.35', 'rpartition: 1.56', 'rfind: 1.68', 'rindex: 1.69']
['startswith: 1.32', 'rpartition: 1.48', 'rindex: 1.64', 'rfind: 1.65']
['startswith: 1.28', 'rpartition: 1.43', 'rfind: 1.59', 'rindex: 1.66']

I believe that it is pretty obvious from the start that the startswith method would come out the most efficient, as returning whether a string begins with the specified string is its main purpose.

What surprises me is that the seemingly impractical string.rpartition('hello')[0] == '' method always finds a way to be listed first, before the string.startswith('hello') method, every now and then. The results show that using str.partition to determine if a string starts with another string is more efficient then using both rfind and rindex.

Another thing I've noticed is that string.rindex('hello') == 0 and string.rindex('hello') == 0 have a good battle going on, each rising from fourth to third place, and dropping from third to fourth place, which makes sense, as their main purposes are the same.

Here is the code:

from time import perf_counter

string = 'hello world'
places = dict()

while True:
    start = perf_counter()
    for _ in range(5000000):
        string.startswith('hello')
    end = perf_counter()
    places['startswith'] = round(end - start, 2)

    start = perf_counter()
    for _ in range(5000000):
        string.rfind('hello') == 0
    end = perf_counter()
    places['rfind'] = round(end - start, 2)

    start = perf_counter()
    for _ in range(5000000):
        string.rpartition('hello')[0] == ''
    end = perf_counter()
    places['rpartition'] = round(end - start, 2)

    start = perf_counter()
    for _ in range(5000000):
        string.rindex('hello') == 0
    end = perf_counter()
    places['rindex'] = round(end - start, 2)
    
    print([f'{b}: {str(a).ljust(4, "4")}' for a, b in sorted(i[::-1] for i in places.items())])

How to fix: "No suitable driver found for jdbc:mysql://localhost/dbname" error when using pools?

I also had the same problem some time before, but I solved that issue.

There may be different reasons for this exception. And one of them may be that the jar you are adding to your lib folder may be old.

Try to find out the latest mysql-connector-jar version and add that to your classpath. It may solve your issue. Mine was solved like that.

Create boolean column in MySQL with false as default value?

You have to specify 0 (meaning false) or 1 (meaning true) as the default. Here is an example:

create table mytable (
     mybool boolean not null default 0
);

FYI: boolean is an alias for tinyint(1).

Here is the proof:

mysql> create table mytable (
    ->          mybool boolean not null default 0
    ->     );
Query OK, 0 rows affected (0.35 sec)

mysql> insert into mytable () values ();
Query OK, 1 row affected (0.00 sec)

mysql> select * from mytable;
+--------+
| mybool |
+--------+
|      0 |
+--------+
1 row in set (0.00 sec)

FYI: My test was done on the following version of MySQL:

mysql> select version();
+----------------+
| version()      |
+----------------+
| 5.0.18-max-log |
+----------------+
1 row in set (0.00 sec)

Subscript out of range error in this Excel VBA script

Set sh1 = Worksheets(filenum(lngPosition)).Activate

You are getting Subscript out of range error error becuase it cannot find that Worksheet.

Also please... please... please do not use .Select/.Activate/Selection/ActiveCell You might want to see How to Avoid using Select in Excel VBA Macros.

How do I remove repeated elements from ArrayList?

If you're willing to use a third-party library, you can use the method distinct() in Eclipse Collections (formerly GS Collections).

ListIterable<Integer> integers = FastList.newListWith(1, 3, 1, 2, 2, 1);
Assert.assertEquals(
    FastList.newListWith(1, 3, 2),
    integers.distinct());

The advantage of using distinct() instead of converting to a Set and then back to a List is that distinct() preserves the order of the original List, retaining the first occurrence of each element. It's implemented by using both a Set and a List.

MutableSet<T> seenSoFar = UnifiedSet.newSet();
int size = list.size();
for (int i = 0; i < size; i++)
{
    T item = list.get(i);
    if (seenSoFar.add(item))
    {
        targetCollection.add(item);
    }
}
return targetCollection;

If you cannot convert your original List into an Eclipse Collections type, you can use ListAdapter to get the same API.

MutableList<Integer> distinct = ListAdapter.adapt(integers).distinct();

Note: I am a committer for Eclipse Collections.

Why does overflow:hidden not work in a <td>?

I'm not familiar with the specific issue, but you could stick a div, etc inside the td and set overflow on that.

How do you use "git --bare init" repository?

Answering your questions one by one:

Bare repository is the one that has no working tree. It means its whole contents is what you have in .git directory.

You can only commit to bare repository by pushing to it from your local clone. It has no working tree, so it has no files modified, no changes.

To have central repository the only way it is to have a bare repository.

Image inside div has extra space below the image

You can use several methods for this issue like

  1. Using line-height

    #wrapper {  line-height: 0px;  }
    
  2. Using display: flex

    #wrapper {  display: flex;         }
    #wrapper {  display: inline-flex;  }
    
  3. Using display: block, table, flex and inherit

    #wrapper img {  display: block;    }
    #wrapper img {  display: table;    }
    #wrapper img {  display: flex;     }
    #wrapper img {  display: inherit;  }
    

Flask at first run: Do not use the development server in a production environment

If for some people (like me earlier) the above answers don't work, I think the following answer would work (for Mac users I think) Enter the following commands to do flask run

$ export FLASK_APP = hello.py
$ export FLASK_ENV = development
$ flask run

Alternatively you can do the following (I haven't tried this but one resource online talks about it)

$ export FLASK_APP = hello.py
$ python -m flask run

source: For more

Reading JSON POST using PHP

You have empty $_POST. If your web-server wants see data in json-format you need to read the raw input and then parse it with JSON decode.

You need something like that:

$json = file_get_contents('php://input');
$obj = json_decode($json);

Also you have wrong code for testing JSON-communication...

CURLOPT_POSTFIELDS tells curl to encode your parameters as application/x-www-form-urlencoded. You need JSON-string here.

UPDATE

Your php code for test page should be like that:

$data_string = json_encode($data);

$ch = curl_init('http://webservice.local/');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Content-Length: ' . strlen($data_string))
);

$result = curl_exec($ch);
$result = json_decode($result);
var_dump($result);

Also on your web-service page you should remove one of the lines header('Content-type: application/json');. It must be called only once.

How to disable PHP Error reporting in CodeIgniter?

Here is the typical structure of new Codeigniter project:

- application/
- system/
- user_guide/
- index.php <- this is the file you need to change

I usually use this code in my CI index.php. Just change local_server_name to the name of your local webserver.

With this code you can deploy your site to your production server without changing index.php each time.

// Domain-based environment
if ($_SERVER['SERVER_NAME'] == 'local_server_name') {
    define('ENVIRONMENT', 'development');
} else {
    define('ENVIRONMENT', 'production');
}

/*
 *---------------------------------------------------------------
 * ERROR REPORTING
 *---------------------------------------------------------------
 *
 * Different environments will require different levels of error reporting.
 * By default development will show errors but testing and live will hide them.
 */

if (defined('ENVIRONMENT')) {
    switch (ENVIRONMENT) {
        case 'development':
            error_reporting(E_ALL);
            break;
        case 'testing':
        case 'production':
            error_reporting(0);
            ini_set('display_errors', 0);  
            break;
        default:
            exit('The application environment is not set correctly.');
    }
}

How to iterate std::set?

How do you iterate std::set?

int main(int argc,char *argv[]) 
{
    std::set<int> mset;
    mset.insert(1); 
    mset.insert(2);
    mset.insert(3);

    for ( auto it = mset.begin(); it != mset.end(); it++ )
        std::cout << *it;
}

Timer for Python game

Using time.time()/datetime.datetime.now() will break if the system time is changed (the user changes the time, it is corrected by a timesyncing services such as NTP or switching from/to dayligt saving time!).

time.monotonic() or time.perf_counter() seems to be the correct way to go, however they are only available from python 3.3. Another possibility is using threading.Timer. Whether or not this is more reliable than time.time() and friends depends on the internal implementation. Also note that creating a new thread is not completely free in terms of system resources, so this might be a bad choice in cases where a lot of timers has to be run in parallel.

Adding n hours to a date in Java?

Check Calendar class. It has add method (and some others) to allow time manipulation.

Something like this should work:

Calendar cal = Calendar.getInstance(); // creates calendar
cal.setTime(new Date());               // sets calendar time/date
cal.add(Calendar.HOUR_OF_DAY, 1);      // adds one hour
cal.getTime();                         // returns new date object plus one hour

Check API for more.

Why does the 'int' object is not callable error occur when using the sum() function?

This means that somewhere else in your code, you have something like:

sum = 0

Which shadows the builtin sum (which is callable) with an int (which isn't).

Datatype for storing ip address in SQL Server

We do a lot of work where we need to figure out which IP's are within certain subnets. I've found that the simplest and most reliable way to do this is:

  1. Add a field to each table called IPInteger (bigint) (when invalid, set IP= '0.0.0.0')
  2. For smaller tables, I use a trigger that updates IPInteger on change
  3. For larger tables, I use a SPROC to refresh the IPIntegers
    ALTER FUNCTION [dbo].[IP_To_INT ]
    ( 
        @IP CHAR(15) 
    ) 
    RETURNS BIGINT 
    AS 
    BEGIN 
        DECLARE @IntAns BIGINT, 
            @block1 BIGINT, 
            @block2 BIGINT, 
            @block3 BIGINT, 
            @block4 BIGINT, 
            @base BIGINT 
     
        SELECT 
            @block1 = CONVERT(BIGINT, PARSENAME(@IP, 4)), 
            @block2 = CONVERT(BIGINT, PARSENAME(@IP, 3)), 
            @block3 = CONVERT(BIGINT, PARSENAME(@IP, 2)), 
            @block4 = CONVERT(BIGINT, PARSENAME(@IP, 1)) 
     
        IF (@block1 BETWEEN 0 AND 255) 
            AND (@block2 BETWEEN 0 AND 255) 
            AND (@block3 BETWEEN 0 AND 255) 
            AND (@block4 BETWEEN 0 AND 255) 
        BEGIN      
            SET @base = CONVERT(BIGINT, @block1 * 16777216)
            SET @IntAns = @base +  
                (@block2 * 65536) +  
                (@block3 * 256) + 
                (@block4) 
        END 
        ELSE 
            SET @IntAns = -1 
        RETURN @IntAns 
    END

span with onclick event inside a tag

Fnd the answer.

I have use some styles inorder to achive this.

<span 
   class="pseudolink" 
   onclick="location='https://jsfiddle.net/'">
Go TO URL
</span>

.pseudolink { 
   color:blue; 
   text-decoration:underline; 
   cursor:pointer; 
   }

https://jsfiddle.net/mafais/bys46d5w/

Reset local repository branch to be just like remote repository HEAD

I did:

git branch -D master
git checkout master

to totally reset branch


note, you should checkout to another branch to be able to delete required branch

How can I set a custom baud rate on Linux?

I noticed the same thing about BOTHER not being defined. Like Jamey Sharp said, you can find it in <asm/termios.h>. Just a forewarning, I think I ran into problems including both it and the regular <termios.h> file at the same time.

Aside from that, I found with the glibc I have, it still didn't work because glibc's tcsetattr was doing the ioctl for the old-style version of struct termios which doesn't pay attention to the speed setting. I was able to set a custom speed by manually doing an ioctl with the new style termios2 struct, which should also be available by including <asm/termios.h>:

struct termios2 tio;

ioctl(fd, TCGETS2, &tio);
tio.c_cflag &= ~CBAUD;
tio.c_cflag |= BOTHER;
tio.c_ispeed = 12345;
tio.c_ospeed = 12345;
ioctl(fd, TCSETS2, &tio);

How to control border height?

A border will always be at the full length of the containing box (the height of the element plus its padding), it can't be controlled except for adjusting the height of the element to which it applies. If all you need is a vertical divider, you could use:

<div id="left">
  content
</div>
<span class="divider"></span>
<div id="right">
  content
</div>

With css:

span {
 display: inline-block;
 width: 0;
 height: 1em;
 border-left: 1px solid #ccc;
 border-right: 1px solid #ccc;
}

Demo at JS Fiddle, adjust the height of the span.container to adjust the border 'height'.

Or, to use pseudo-elements (::before or ::after), given the following HTML:

<div id="left">content</div>
<div id="right">content</div>

The following CSS adds a pseudo-element before any div element that's the adjacent sibling of another div element:

div {
    display: inline-block;
    position: relative;
}

div + div {
    padding-left: 0.3em;
}

div + div::before {
    content: '';
    border-left: 2px solid #000;
    position: absolute;
    height: 50%;
    left: 0;
    top: 25%;
}

JS Fiddle demo.

Convert pandas data frame to series

You can also use stack()

df= DataFrame([list(range(5))], columns = [“a{}”.format(I) for I in range(5)])

After u run df, then run:

df.stack()

You obtain your dataframe in series

Can't find out where does a node.js app running and can't kill it

List node process:

$ ps -e|grep node

Kill the process using

$kill -9 XXXX

Here XXXX is the process number

Redirect from an HTML page

Just use the onload event of the body tag:

<body onload="window.location = 'http://example.com/'">

How to retrieve element value of XML using Java?

If you are just looking to get a single value from the XML you may want to use Java's XPath library. For an example see my answer to a previous question:

It would look something like:

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class Demo {

    public static void main(String[] args) {
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder builder = domFactory.newDocumentBuilder();
            Document dDoc = builder.parse("E:/test.xml");

            XPath xPath = XPathFactory.newInstance().newXPath();
            Node node = (Node) xPath.evaluate("/Request/@name", dDoc, XPathConstants.NODE);
            System.out.println(node.getNodeValue());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

Why doesn't git recognize that my file has been changed, therefore git add not working

Did you move the directory out from under your shell? This can happen if you restored your project from a backup. To fix this, just cd out and back in:

cd ../
cd -

How to remove gaps between subplots in matplotlib?

The problem is the use of aspect='equal', which prevents the subplots from stretching to an arbitrary aspect ratio and filling up all the empty space.

Normally, this would work:

import matplotlib.pyplot as plt

ax = [plt.subplot(2,2,i+1) for i in range(4)]

for a in ax:
    a.set_xticklabels([])
    a.set_yticklabels([])

plt.subplots_adjust(wspace=0, hspace=0)

The result is this:

However, with aspect='equal', as in the following code:

import matplotlib.pyplot as plt

ax = [plt.subplot(2,2,i+1) for i in range(4)]

for a in ax:
    a.set_xticklabels([])
    a.set_yticklabels([])
    a.set_aspect('equal')

plt.subplots_adjust(wspace=0, hspace=0)

This is what we get:

The difference in this second case is that you've forced the x- and y-axes to have the same number of units/pixel. Since the axes go from 0 to 1 by default (i.e., before you plot anything), using aspect='equal' forces each axis to be a square. Since the figure is not a square, pyplot adds in extra spacing between the axes horizontally.

To get around this problem, you can set your figure to have the correct aspect ratio. We're going to use the object-oriented pyplot interface here, which I consider to be superior in general:

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(8,8)) # Notice the equal aspect ratio
ax = [fig.add_subplot(2,2,i+1) for i in range(4)]

for a in ax:
    a.set_xticklabels([])
    a.set_yticklabels([])
    a.set_aspect('equal')

fig.subplots_adjust(wspace=0, hspace=0)

Here's the result:

The client and server cannot communicate, because they do not possess a common algorithm - ASP.NET C# IIS TLS 1.0 / 1.1 / 1.2 - Win32Exception

My app is running in .net 4.7.2. Simplest solution was to add this to the config:

  <system.web>
    <httpRuntime targetFramework="4.7.2"/>
  </system.web>

How to drop column with constraint?

I got the same:

ALTER TABLE DROP COLUMN failed because one or more objects access this column message.

My column had an index which needed to be deleted first. Using sys.indexes did the trick:

DECLARE @sql VARCHAR(max)

SELECT @sql = 'DROP INDEX ' + idx.NAME + ' ON tblName'
FROM sys.indexes idx
INNER JOIN sys.tables tbl ON idx.object_id = tbl.object_id
INNER JOIN sys.index_columns idxCol ON idx.index_id = idxCol.index_id
INNER JOIN sys.columns col ON idxCol.column_id = col.column_id
WHERE idx.type <> 0
    AND tbl.NAME = 'tblName'
    AND col.NAME = 'colName'

EXEC sp_executeSql @sql
GO

ALTER TABLE tblName
DROP COLUMN colName

Submit HTML form, perform javascript function (alert then redirect)

You need to prevent the default behaviour. You can either use e.preventDefault() or return false; In this case, the best thing is, you can use return false; here:

<form onsubmit="completeAndRedirect(); return false;">

Rounding a number to the nearest 5 or 10 or X

I cannot add comment so I will use this

in a vbs run that and have fun figuring out why the 2 give a result of 2

you can't trust round

 msgbox round(1.5) 'result to 2
 msgbox round(2.5) 'yes, result to 2 too

Add text to textarea - Jquery

Just append() the text nodes:

$('#replyBox').append(quote); 

http://jsfiddle.net/nQErc/

How to export data to an excel file using PHPExcel

Work 100%. maybe not relation to creator answer but i share it for users have a problem with export mysql query to excel with phpexcel. Good Luck.

require('../phpexcel/PHPExcel.php');

require('../phpexcel/PHPExcel/Writer/Excel5.php');

$filename = 'userReport'; //your file name

    $objPHPExcel = new PHPExcel();
    /*********************Add column headings START**********************/
    $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A1', 'username')
                ->setCellValue('B1', 'city_name');

    /*********************Add data entries START**********************/
//get_result_array_from_class**You can replace your sql code with this line.
$result = $get_report_clas->get_user_report();
//set variable for count table fields.
$num_row = 1;
foreach ($result as $value) {
  $user_name = $value['username'];
  $c_code = $value['city_name'];
  $num_row++;
        $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A'.$num_row, $user_name )
                ->setCellValue('B'.$num_row, $c_code );
}

    /*********************Autoresize column width depending upon contents START**********************/
    foreach(range('A','B') as $columnID) {
        $objPHPExcel->getActiveSheet()->getColumnDimension($columnID)->setAutoSize(true);
    }
    $objPHPExcel->getActiveSheet()->getStyle('A1:B1')->getFont()->setBold(true);



//Make heading font bold

        /*********************Add color to heading START**********************/
        $objPHPExcel->getActiveSheet()
                    ->getStyle('A1:B1')
                    ->getFill()
                    ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
                    ->getStartColor()
                    ->setARGB('99ff99');

        $objPHPExcel->getActiveSheet()->setTitle('userReport'); //give title to sheet
        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;Filename=$filename.xls");
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');

JavaScript open in a new window, not tab

Answered here. But posting it again for reference.

window.open() will not open in new tab if it is not happening on actual click event. In the example given the url is being opened on actual click event. This will work provided user has appropriate settings in the browser.

<a class="link">Link</a>
<script  type="text/javascript">
     $("a.link").on("click",function(){
         window.open('www.yourdomain.com','_blank');
     });
</script>

Similarly, if you are trying to do an ajax call within the click function and want to open a window on success, ensure you are doing the ajax call with async : false option set.

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

I've been having this issue also for about 8-9 days. Here's some background: I'm developing a simple Java application that runs in bash.

Details:

  • Spring 2.5.6
  • Hibernate3.2.3.ga
  • With maven. (The base of the project is from mkyong.com , the spring tutorial without anotations )
  • MySQL version:
[jvazquez@archbox ~]$ mysql --version
mysql  Ver 14.14 Distrib 5.5.9, for Linux (i686) using readline 5.1
Linux archbox 2.6.37-ARCH #1 SMP PREEMPT Fri Feb 18 16:58:42 UTC 2011 i686 Intel(R) Core(TM)2 Quad CPU Q8200 @ 2.33GHz GenuineIntel GNU/Linux

The application works fine in Arch Linux, Mac OS X 10.6, and FreeBSD 7.2. When I moved the jar file to another arch linux in a different host, using the same mysql, a similar my.cnf, and the similar kernel version, the connection died and obtained the same error as the original poster:

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

I tried every possible combination for this that I found on so and the forums (http://forums.mysql.com/read.php?39,180347,180347#msg-180347 for example, which is closed now and I can't post .. ), specifically:

  • Triple check that I wasn't using skip networking. (verified with ps aux and the my.cnf)
  • Tried enable log_warnings=1 in the my.cnf but obviously, I wasn't hitting the server so I didn't saw anything while using the app
  • SHOW ENGINE innodb STATUS didn't show anything at all; during the tests I could connect via shell, and php also connected to the mysql server
  • /etc/hosts has localhost 127.0.0.1
  • Tried the jdbc properties using localhost and 127.0.0.1 with no results
  • Tried adding c3p0 and changed the max_wait
  • Max connections in the my.cnf was changed to 900 , 2000 and still nothing my.cnf
  • Added wait_timeout = 60 my.cnf
  • Added net_wait_timeout = 360 my.cnf
  • Added the destroy-method="close" spring.xml

As it was pointed out (if you look up for the same exception , you will find several so threads about the issue Reproduce com.mysql.jdbc.exceptions.jdbc4.CommunicationsException with a setup of Spring, hibernate and C3P0 for example ).

  1. If you are using tomcat, please check the security exception (again, it is on SO, you will find it )
  2. Check that you can resolve that url that you are using
  3. Try adding c3p0.
  4. Verify that there isn't a firewall rejecting your connections
  5. Finally , if you are using GNU/Linux ( ARch linux for example and you indeed obtain this exception ) Try MySQL Forums :: JDBC and Java :: EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost

If the link get's removed, just add mysqld:ALL to /etc/hosts.allow

I know that is a bit extense, but it may help anybody using GNU/Linux and having this exception and this thread seemed the best place to post my research.

Hope it helps

How to enable DataGridView sorting when user clicks on the column header?

KISS : Keep it simple, stupid

Way A: Implement an own SortableBindingList class when like to use DataBinding and sorting.

Way B: Use a List<string> sorting works also but does not work with DataBinding.

C++ Convert string (or char*) to wstring (or wchar_t*)

method s2ws works well. Hope helps.

std::wstring s2ws(const std::string& s) {
    std::string curLocale = setlocale(LC_ALL, ""); 
    const char* _Source = s.c_str();
    size_t _Dsize = mbstowcs(NULL, _Source, 0) + 1;
    wchar_t *_Dest = new wchar_t[_Dsize];
    wmemset(_Dest, 0, _Dsize);
    mbstowcs(_Dest,_Source,_Dsize);
    std::wstring result = _Dest;
    delete []_Dest;
    setlocale(LC_ALL, curLocale.c_str());
    return result;
}

DBNull if statement

Yes, just a syntax problem. Try this instead:

if (reader["usr.ursrdaystime"] != DBNull.Value)

.Equals() is checking to see if two Object instances are the same.

Get JSON object from URL

You could use PHP's json_decode function:

$url = "http://urlToYourJsonFile.com";
$json = file_get_contents($url);
$json_data = json_decode($json, true);
echo "My token: ". $json_data["access_token"];

How do you return the column names of a table?

One method is to query syscolumns:

select
   syscolumns.name as [Column],
   syscolumns.xusertype as [Type],
   sysobjects.xtype as [Objtype]
from 
   sysobjects 
inner join 
   syscolumns on sysobjects.id = syscolumns.id
where sysobjects.xtype = 'u'
and   sysobjects.name = 'MyTableName'
order by syscolumns.name

Best way to test for a variable's existence in PHP; isset() is clearly broken

I have to say in all my years of PHP programming, I have never encountered a problem with isset() returning false on a null variable. OTOH, I have encountered problems with isset() failing on a null array entry - but array_key_exists() works correctly in that case.

For some comparison, Icon explicitly defines an unused variable as returning &null so you use the is-null test in Icon to also check for an unset variable. This does make things easier. On the other hand, Visual BASIC has multiple states for a variable that doesn't have a value (Null, Empty, Nothing, ...), and you often have to check for more than one of them. This is known to be a source of bugs.

How to list only top level directories in Python?

scanDir = "abc"
directories = [d for d in os.listdir(scanDir) if os.path.isdir(os.path.join(os.path.abspath(scanDir), d))]

In jQuery how can I set "top,left" properties of an element with position values relative to the parent and not the document?

Refreshing my memory on setting position, I'm coming to this so late I don't know if anyone else will see it, but --

I don't like setting position using css(), though often it's fine. I think the best bet is to use jQuery UI's position() setter as noted by xdazz. However if jQuery UI is, for some reason, not an option (yet jQuery is), I prefer this:

const leftOffset = 200;
const topOffset = 200;
let $div = $("#mydiv");
let baseOffset = $div.offsetParent().offset();
$div.offset({
  left: baseOffset.left + leftOffset,
  top: baseOffset.top + topOffset
});

This has the advantage of not arbitrarily setting $div's parent to relative positioning (what if $div's parent was, itself, absolute positioned inside something else?). I think the only major edge case is if $div doesn't have any offsetParent, not sure if it would return document, null, or something else entirely.

offsetParent has been available since jQuery 1.2.6, sometime in 2008, so this technique works now and when the original question was asked.

Is there any way to set environment variables in Visual Studio Code?

Assuming you mean for a debugging session(?) then you can include a env property in your launch configuration.

If you open the .vscode/launch.json file in your workspace or select Debug > Open Configurations then you should see a set of launch configurations for debugging your code. You can then add to it an env property with a dictionary of string:string.

Here is an example for an ASP.NET Core app from their standard web template setting the ASPNETCORE_ENVIRONMENT to Development :

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": ".NET Core Launch (web)",
      "type": "coreclr",
      "request": "launch",
      "preLaunchTask": "build",
      // If you have changed target frameworks, make sure to update the program path.
      "program": "${workspaceFolder}/bin/Debug/netcoreapp2.0/vscode-env.dll",
      "args": [],
      "cwd": "${workspaceFolder}",
      "stopAtEntry": false,
      "internalConsoleOptions": "openOnSessionStart",
      "launchBrowser": {
        "enabled": true,
        "args": "${auto-detect-url}",
        "windows": {
          "command": "cmd.exe",
          "args": "/C start ${auto-detect-url}"
        },
        "osx": {
          "command": "open"
        },
        "linux": {
          "command": "xdg-open"
        }
      },
      "env": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "sourceFileMap": {
        "/Views": "${workspaceFolder}/Views"
      }
    },
    {
      "name": ".NET Core Attach",
      "type": "coreclr",
      "request": "attach",
      "processId": "${command:pickProcess}"
    }
  ]
}

Excel VBA Password via Hex Editor

New version, now you also have the GC= try to replace both DPB and GC with those

DPB="DBD9775A4B774B77B4894C77DFE8FE6D2CCEB951E8045C2AB7CA507D8F3AC7E3A7F59012A2" GC="BAB816BBF4BCF4BCF4"

password will be "test"

Bootstrap how to get text to vertical align in a div container

Could you not have simply added:

align-items:center;

to a new class in your row div. Essentially:

<div class="row align_center">

.align_center { align-items:center; }

Passing javascript variable to html textbox

You could also use to localStorage feature of HTML5 to store your test value and then access it at any other point in your website by using the localStorage.getItem() method. To see how this works you should look at the w3schools explanation or the explanation from the Opera Developer website. Hope this helps.

Variable might not have been initialized error

Since no other answer has cited the Java language standard, I have decided to write an answer of my own:

In Java, local variables are not, by default, initialized with a certain value (unlike, for example, the field of classes). From the language specification one (§4.12.5) can read the following:

A local variable (§14.4, §14.14) must be explicitly given a value before it is used, by either initialization (§14.4) or assignment (§15.26), in a way that can be verified using the rules for definite assignment (§16 (Definite Assignment)).

Therefore, since the variables a and b are not initialized :

 for (int l= 0; l<x.length; l++) 
    {
        if (x[l] == 0) 
        a++ ;
        else if (x[l] == 1) 
        b++ ;
    }

the operations a++; and b++; could not produce any meaningful results, anyway. So it is logical for the compiler to notify you about it:

Rand.java:72: variable a might not have been initialized
                a++ ;
                ^
Rand.java:74: variable b might not have been initialized
                b++ ;
                ^

However, one needs to understand that the fact that a++; and b++; could not produce any meaningful results has nothing to do with the reason why the compiler displays an error. But rather because it is explicitly set on the Java language specification that

A local variable (§14.4, §14.14) must be explicitly given a value (...)

To showcase the aforementioned point, let us change a bit your code to:

public static Rand searchCount (int[] x) 
{
    if(x == null || x.length  == 0)
      return null;
    int a ; 
    int b ; 

    ...   

    for (int l= 0; l<x.length; l++) 
    {
        if(l == 0)
           a = l;
        if(l == 1)
           b = l;
    }

    ...   
}

So even though the code above can be formally proven to be valid (i.e., the variables a and b will be always assigned with the value 0 and 1, respectively) it is not the compiler job to try to analyze your application's logic, and neither does the rules of local variable initialization rely on that. The compiler checks if the variables a and b are initialized according to the local variable initialization rules, and reacts accordingly (e.g., displaying a compilation error).

xcode library not found

If you are using Pods to include the GoogleAnalytics iOS SDK into your project, it's worth noting that since the 3.0 release your Other Linker Flags needs to include -lGoogleAnalyticsServices not the old -lGoogleAnalytics

How to select a single field for all documents in a MongoDB collection?

db.student.find({}, {"roll":1, "_id":0})

This is equivalent to -

Select roll from student



db.student.find({}, {"roll":1, "name":1, "_id":0})

This is equivalent to -

Select roll, name from student

How do I close an Android alertdialog

put this line in OnCreate()

Context mcontext = this;    

and them use this variable in following code

final AlertDialog.Builder alert = new AlertDialog.Builder(mcontext);
alert.setTitle(title);
alert.setMessage(description);
alert.setPositiveButton("Ok",
    new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });
alert.show();

Try this code.. It is running successfully..

What is the minimum I have to do to create an RPM file?

As an application distributor, fpm sounds perfect for your needs. There is an example here which shows how to package an app from source. FPM can produce both deb files and RPM files.

PHP: Get the key from an array in a foreach loop

you need nested foreach loops

foreach($samplearr as $key => $item){
   echo $key;
    foreach($item as $detail){
       echo $detail['value1'] . " " . $detail['value2']
     }
 }

how to deal with google map inside of a hidden div (Updated picture)

How to refresh the map when you resize your div

It's not enough just to call google.maps.event.trigger(map, 'resize'); You should reset the center of the map as well.

var map;

var initialize= function (){
    ...
}

var resize = function () {
    if (typeof(map) == "undefined") {) {
        // initialize the map. You only need this if you may not have initialized your map when resize() is called.
        initialize();
    } else {
        // okay, we've got a map and we need to resize it
        var center = map.getCenter();
        google.maps.event.trigger(map, 'resize');
        map.setCenter(center);
    }
}

How to listen for the resize event

Angular (ng-show or ui-bootstrap collapse)

Bind directly to the element's visibility rather than to the value bound to ng-show, because the $watch can fire before the ng-show is updated (so the div will still be invisible).

scope.$watch(function () { return element.is(':visible'); },
    function () {
        resize();
    }
);

jQuery .show()

Use the built in callback

$("#myMapDiv").show(speed, function() { resize(); });

Bootstrap 3 Modal

$('#myModal').on('shown.bs.modal', function() {
    resize();
})

What is the difference between an abstract function and a virtual function?

Abstract methods are always virtual. They cannot have an implementation.

That's the main difference.

Basically, you would use a virtual method if you have the 'default' implementation of it and want to allow descendants to change its behaviour.

With an abstract method, you force descendants to provide an implementation.

Getting only 1 decimal place

>>> "{:.1f}".format(45.34531)
'45.3'

Or use the builtin round:

>>> round(45.34531, 1)
45.299999999999997

How can I stop float left?

Sometimes clear will not work. Use float: none as an override

How to reload page the page with pagination in Angular 2?

This should technically be achievable using window.location.reload():

HTML:

<button (click)="refresh()">Refresh</button>

TS:

refresh(): void {
    window.location.reload();
}

Update:

Here is a basic StackBlitz example showing the refresh in action. Notice the URL on "/hello" path is retained when window.location.reload() is executed.

PowerMockito mock single static method and return object

What you want to do is a combination of part of 1 and all of 2.

You need to use the PowerMockito.mockStatic to enable static mocking for all static methods of a class. This means make it possible to stub them using the when-thenReturn syntax.

But the 2-argument overload of mockStatic you are using supplies a default strategy for what Mockito/PowerMock should do when you call a method you haven't explicitly stubbed on the mock instance.

From the javadoc:

Creates class mock with a specified strategy for its answers to interactions. It's quite advanced feature and typically you don't need it to write decent tests. However it can be helpful when working with legacy systems. It is the default answer so it will be used only when you don't stub the method call.

The default default stubbing strategy is to just return null, 0 or false for object, number and boolean valued methods. By using the 2-arg overload, you're saying "No, no, no, by default use this Answer subclass' answer method to get a default value. It returns a Long, so if you have static methods which return something incompatible with Long, there is a problem.

Instead, use the 1-arg version of mockStatic to enable stubbing of static methods, then use when-thenReturn to specify what to do for a particular method. For example:

import static org.mockito.Mockito.*;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

class ClassWithStatics {
  public static String getString() {
    return "String";
  }

  public static int getInt() {
    return 1;
  }
}

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassWithStatics.class)
public class StubJustOneStatic {
  @Test
  public void test() {
    PowerMockito.mockStatic(ClassWithStatics.class);

    when(ClassWithStatics.getString()).thenReturn("Hello!");

    System.out.println("String: " + ClassWithStatics.getString());
    System.out.println("Int: " + ClassWithStatics.getInt());
  }
}

The String-valued static method is stubbed to return "Hello!", while the int-valued static method uses the default stubbing, returning 0.

Passing data into "router-outlet" child components

<router-outlet [node]="..."></router-outlet> 

is just invalid. The component added by the router is added as sibling to <router-outlet> and does not replace it.

See also https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service

@Injectable() 
export class NodeService {
  private node:Subject<Node> = new BehaviorSubject<Node>([]);

  get node$(){
    return this.node.asObservable().filter(node => !!node);
  }

  addNode(data:Node) {
    this.node.next(data);
  }
}
@Component({
    selector : 'node-display',
    providers: [NodeService],
    template : `
        <router-outlet></router-outlet>
    `
})
export class NodeDisplayComponent implements OnInit {
    constructor(private nodeService:NodeService) {}
    node: Node;
    ngOnInit(): void {
        this.nodeService.getNode(path)
            .subscribe(
                node => {
                    this.nodeService.addNode(node);
                },
                err => {
                    console.log(err);
                }
            );
    }
}
export class ChildDisplay implements OnInit{
    constructor(nodeService:NodeService) {
      nodeService.node$.subscribe(n => this.node = n);
    }
}

Using an attribute of the current class instance as a default value for method's parameter

It's written as:

def my_function(self, param_one=None): # Or custom sentinel if None is vaild
    if param_one is None:
        param_one = self.one_of_the_vars

And I think it's safe to say that will never happen in Python due to the nature that self doesn't really exist until the function starts... (you can't reference it, in its own definition - like everything else)

For example: you can't do d = {'x': 3, 'y': d['x'] * 5}

Is there a difference between PhoneGap and Cordova commands?

Here are differences that I have discovered:

I am comparing the phonegap 3.3.0-0.18.0 CLI to the functionality described in the cordova 3.3.0 documentation for that CLI.

  1. "ls" is an option for "cordova plugin" but not for "phonegap plugin". You must use "list" instead. e.g.: "phonegap plugin list"

  2. "serve" is not documented in "phonegap -help" but it does exist and it does work. It will not find and load phonegap.js so the pages never fully load but it still does provide some value. I'm not sure if this is different than the behavior cordova.

  3. "phonegap platform add " does not work in phonegap. You must do a "phonegap build " to add support for a platform.

Note that you may also experience some confusing error messages in phonegap where the suggested solution refers to using the cordova command.

ActiveXObject is not defined and can't find variable: ActiveXObject

ActiveXObject is non-standard and only supported by Internet Explorer on Windows.

There is no native cross browser way to write to the file system without using plugins, even the draft File API gives read only access.

If you want to work cross platform, then you need to look at such things as signed Java applets (keeping in mind that that will only work on platforms for which the Java runtime is available).

How do I redirect users after submit button click?

Why don't you use plain html?

<form action="login.php" method="post" name="form1" id="form1">
...
</form>

In your login.php you can then use the header() function.

header("Location: welcome.php");

Trying to create a file in Android: open failed: EROFS (Read-only file system)

As others have mentioned, app on Android can't write a file to any folder the internal storage but their own private storage (which is under /data/data/PACKAGE_NAME ).

You should use the API to get the correct path that is allowed for your app.

read this .

Is it possible to view RabbitMQ message contents directly from the command line?

you can use RabbitMQ API to get count or messages :

/api/queues/vhost/name/get

Get messages from a queue. (This is not an HTTP GET as it will alter the state of the queue.) You should post a body looking like:

{"count":5,"requeue":true,"encoding":"auto","truncate":50000}

count controls the maximum number of messages to get. You may get fewer messages than this if the queue cannot immediately provide them.

requeue determines whether the messages will be removed from the queue. If requeue is true they will be requeued - but their redelivered flag will be set. encoding must be either "auto" (in which case the payload will be returned as a string if it is valid UTF-8, and base64 encoded otherwise), or "base64" (in which case the payload will always be base64 encoded). If truncate is present it will truncate the message payload if it is larger than the size given (in bytes). truncate is optional; all other keys are mandatory.

Please note that the publish / get paths in the HTTP API are intended for injecting test messages, diagnostics etc - they do not implement reliable delivery and so should be treated as a sysadmin's tool rather than a general API for messaging.

http://hg.rabbitmq.com/rabbitmq-management/raw-file/rabbitmq_v3_1_3/priv/www/api/index.html

int value under 10 convert to string two digit number

i.ToString("00")

or

i.ToString("000")

depending on what you want

Look at the MSDN article on custom numeric format strings for more options: http://msdn.microsoft.com/en-us/library/0c899ak8(VS.71).aspx

What does <? php echo ("<pre>"); ..... echo("</pre>"); ?> mean?

try this:

$names = array('Jesse', 'joey', 'jelnny', 'justine');
$names = new ArrayObject($names);

echo '<pre>';
print_r($names);

vs this:

$names = array('Jesse', 'joey', 'jelnny', 'justine');
$names = new ArrayObject($names);

//echo '<pre>';
print_r($names);

and it shows what the PRE does very neatly

HTTP Headers for File Downloads

You can try this force-download script. Even if you don't use it, it'll probably point you in the right direction:

<?php

$filename = $_GET['file'];

// required for IE, otherwise Content-disposition is ignored
if(ini_get('zlib.output_compression'))
  ini_set('zlib.output_compression', 'Off');

// addition by Jorg Weske
$file_extension = strtolower(substr(strrchr($filename,"."),1));

if( $filename == "" ) 
{
  echo "<html><title>eLouai's Download Script</title><body>ERROR: download file NOT SPECIFIED. USE force-download.php?file=filepath</body></html>";
  exit;
} elseif ( ! file_exists( $filename ) ) 
{
  echo "<html><title>eLouai's Download Script</title><body>ERROR: File not found. USE force-download.php?file=filepath</body></html>";
  exit;
};
switch( $file_extension )
{
  case "pdf": $ctype="application/pdf"; break;
  case "exe": $ctype="application/octet-stream"; break;
  case "zip": $ctype="application/zip"; break;
  case "doc": $ctype="application/msword"; break;
  case "xls": $ctype="application/vnd.ms-excel"; break;
  case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
  case "gif": $ctype="image/gif"; break;
  case "png": $ctype="image/png"; break;
  case "jpeg":
  case "jpg": $ctype="image/jpg"; break;
  default: $ctype="application/octet-stream";
}
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers 
header("Content-Type: $ctype");
// change, added quotes to allow spaces in filenames, by Rajkumar Singh
header("Content-Disposition: attachment; filename=\"".basename($filename)."\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filename));
readfile("$filename");
exit();

Differences between Ant and Maven

Maven acts as both a dependency management tool - it can be used to retrieve jars from a central repository or from a repository you set up - and as a declarative build tool. The difference between a "declarative" build tool and a more traditional one like ant or make is you configure what needs to get done, not how it gets done. For example, you can say in a maven script that a project should be packaged as a WAR file, and maven knows how to handle that.

Maven relies on conventions about how project directories are laid out in order to achieve its "declarativeness." For example, it has a convention for where to put your main code, where to put your web.xml, your unit tests, and so on, but also gives the ability to change them if you need to.

You should also keep in mind that there is a plugin for running ant commands from within maven:

http://maven.apache.org/plugins/maven-ant-plugin/

Also, maven's archetypes make getting started with a project really fast. For example, there is a Wicket archetype, which provides a maven command you run to get a whole, ready-to-run hello world-type project.

https://wicket.apache.org/start/quickstart.html

In Python, how do I determine if an object is iterable?

I found a nice solution here:

isiterable = lambda obj: isinstance(obj, basestring) \
    or getattr(obj, '__iter__', False)

Checking that a List is not empty in Hamcrest

If you're after readable fail messages, you can do without hamcrest by using the usual assertEquals with an empty list:

assertEquals(new ArrayList<>(0), yourList);

E.g. if you run

assertEquals(new ArrayList<>(0), Arrays.asList("foo", "bar");

you get

java.lang.AssertionError
Expected :[]
Actual   :[foo, bar]

How to make a function wait until a callback has been called using node.js

If you don't want to use call back then you can Use "Q" module.

For example:

function getdb() {
    var deferred = Q.defer();
    MongoClient.connect(databaseUrl, function(err, db) {
        if (err) {
            console.log("Problem connecting database");
            deferred.reject(new Error(err));
        } else {
            var collection = db.collection("url");
            deferred.resolve(collection);
        }
    });
    return deferred.promise;
}


getdb().then(function(collection) {
   // This function will be called afte getdb() will be executed. 

}).fail(function(err){
    // If Error accrued. 

});

For more information refer this: https://github.com/kriskowal/q

What does 'git blame' do?

From git-blame:

Annotates each line in the given file with information from the revision which last modified the line. Optionally, start annotating from the given revision.

When specified one or more times, -L restricts annotation to the requested lines.

Example:

[email protected]:~# git blame .htaccess
...
^e1fb2d7 (John Doe 2015-07-03 06:30:25 -0300  4) allow from all
^72fgsdl (Arthur King 2015-07-03 06:34:12 -0300  5)
^e1fb2d7 (John Doe 2015-07-03 06:30:25 -0300  6) <IfModule mod_rewrite.c>
^72fgsdl (Arthur King 2015-07-03 06:34:12 -0300  7)     RewriteEngine On
...

Please note that git blame does not show the per-line modifications history in the chronological sense. It only shows who was the last person to have changed a line in a document up to the last commit in HEAD.

That is to say that in order to see the full history/log of a document line, you would need to run a git blame path/to/file for each commit in your git log.

Static methods in Python?

Perhaps the simplest option is just to put those functions outside of the class:

class Dog(object):
    def __init__(self, name):
        self.name = name

    def bark(self):
        if self.name == "Doggy":
            return barking_sound()
        else:
            return "yip yip"

def barking_sound():
    return "woof woof"

Using this method, functions which modify or use internal object state (have side effects) can be kept in the class, and the reusable utility functions can be moved outside.

Let's say this file is called dogs.py. To use these, you'd call dogs.barking_sound() instead of dogs.Dog.barking_sound.

If you really need a static method to be part of the class, you can use the staticmethod decorator.

iOS 7 - Failing to instantiate default view controller

First click on the View Controller in the right hand side Utilities bar. Next select the Attributes Inspector and make sure that under the View Controller section the 'Is Initial View Controller' checkbox is checked!

Call an angular function inside html

Yep, just add parenthesis (calling the function). Make sure the function is in scope and actually returns something.

<ul class="ui-listview ui-radiobutton" ng-repeat="meter in meters">
  <li class = "ui-divider">
    {{ meter.DESCRIPTION }}
    {{ htmlgeneration() }}
  </li>
</ul>

Allow anything through CORS Policy

Try configuration at /config/application.rb:

config.middleware.insert_before 0, "Rack::Cors" do
  allow do
    origins '*'
    resource '*', :headers => :any, :methods => [:get, :post, :options, :delete, :put, :patch], credentials: true
  end
end

Failed to authenticate on SMTP server error using gmail

If you still get this error when sending email: "Failed to authenticate on SMTP server with username "[email protected]" using 3 possible authenticators"

You may try one of these methods:

Go to https://accounts.google.com/UnlockCaptcha, click continue and unlock your account for access through other media/sites.

Use double quote for your password: like - "Abc@%$67eSDu"

UICollectionView cell selection and cell reuse

you can just set the selectedBackgroundView of the cell to be backgroundColor=x.

Now any time you tap on cell his selected mode will change automatically and will couse to the background color to change to x.

Bower: ENOGIT Git is not installed or not in the PATH

I solved the problem by install Git Bash from Download Git Bash.

Setting this option 3 when installing the software as shown bellow.

Setting Path variable

Finally select the project folder by right click using Bash as shown below.

enter image description here

and type

npm install

. It works for me.

How do I find the stack trace in Visual Studio?

Do you mean finding a stack trace of the thrown exception location? That's either Debug/Exceptions, or better - Ctrl-Alt-E. Set filters for the exceptions you want to break on.

There's even a way to reconstruct the thrower stack after the exception was caught, but it's really unpleasant. Much, much easier to set a break on the throw.

What's the difference between INNER JOIN, LEFT JOIN, RIGHT JOIN and FULL JOIN?

INNER JOIN gets all records that are common between both tables based on the supplied ON clause.

LEFT JOIN gets all records from the LEFT linked and the related record from the right table ,but if you have selected some columns from the RIGHT table, if there is no related records, these columns will contain NULL.

RIGHT JOIN is like the above but gets all records in the RIGHT table.

FULL JOIN gets all records from both tables and puts NULL in the columns where related records do not exist in the opposite table.

How to call VS Code Editor from terminal / command line

When installing on Windows, you will be prompted to add VS Code to your PATH.

I was trying to figure out how to open files with VS Code from the command line and I already had the capability - I just forgot I had already added it. You might already have it installed - check by navigating to a folder you want to open and running the command code . to open that folder.

How do you make div elements display inline?

As mentioned, display:inline is probably what you want. Some browsers also support inline-blocks.

http://www.quirksmode.org/css/display.html#inlineblock

Change selected value of kendo ui dropdownlist

It's possible to "natively" select by value:

dropdownlist.select(1);

How to create many labels and textboxes dynamically depending on the value of an integer variable?

I would create a user control which holds a Label and a Text Box in it and simply create instances of that user control 'n' times. If you want to know a better way to do it and use properties to get access to the values of Label and Text Box from the user control, please let me know.

Simple way to do it would be:

int n = 4; // Or whatever value - n has to be global so that the event handler can access it

private void btnDisplay_Click(object sender, EventArgs e)
{
    TextBox[] textBoxes = new TextBox[n];
    Label[] labels = new Label[n];

    for (int i = 0; i < n; i++)
    {
        textBoxes[i] = new TextBox();
        // Here you can modify the value of the textbox which is at textBoxes[i]

        labels[i] = new Label();
        // Here you can modify the value of the label which is at labels[i]
    }

    // This adds the controls to the form (you will need to specify thier co-ordinates etc. first)
    for (int i = 0; i < n; i++)
    {
        this.Controls.Add(textBoxes[i]);
        this.Controls.Add(labels[i]);
    }
}

The code above assumes that you have a button btnDisplay and it has a onClick event assigned to btnDisplay_Click event handler. You also need to know the value of n and need a way of figuring out where to place all controls. Controls should have a width and height specified as well.

To do it using a User Control simply do this.

Okay, first of all go and create a new user control and put a text box and label in it.

Lets say they are called txtSomeTextBox and lblSomeLabel. In the code behind add this code:

public string GetTextBoxValue() 
{ 
    return this.txtSomeTextBox.Text; 
} 

public string GetLabelValue() 
{ 
    return this.lblSomeLabel.Text; 
} 

public void SetTextBoxValue(string newText) 
{ 
    this.txtSomeTextBox.Text = newText; 
} 

public void SetLabelValue(string newText) 
{ 
    this.lblSomeLabel.Text = newText; 
}

Now the code to generate the user control will look like this (MyUserControl is the name you have give to your user control):

private void btnDisplay_Click(object sender, EventArgs e)
{
    MyUserControl[] controls = new MyUserControl[n];

    for (int i = 0; i < n; i++)
    {
        controls[i] = new MyUserControl();

        controls[i].setTextBoxValue("some value to display in text");
        controls[i].setLabelValue("some value to display in label");
        // Now if you write controls[i].getTextBoxValue() it will return "some value to display in text" and controls[i].getLabelValue() will return "some value to display in label". These value will also be displayed in the user control.
    }

    // This adds the controls to the form (you will need to specify thier co-ordinates etc. first)
    for (int i = 0; i < n; i++)
    {
        this.Controls.Add(controls[i]);
    }
}

Of course you can create more methods in the usercontrol to access properties and set them. Or simply if you have to access a lot, just put in these two variables and you can access the textbox and label directly:

public TextBox myTextBox;
public Label myLabel;

In the constructor of the user control do this:

myTextBox = this.txtSomeTextBox;
myLabel = this.lblSomeLabel;

Then in your program if you want to modify the text value of either just do this.

control[i].myTextBox.Text = "some random text"; // Same applies to myLabel

Hope it helped :)

How to disable Excel's automatic cell reference change after copy/paste?

This macro does the whole job.

Sub Absolute_Reference_Copy_Paste()
'By changing "=" in formulas to "#" the content is no longer seen as a formula.
' C+S+e (my keyboard shortcut)

Dim Dummy As Range
Dim FirstSelection As Range
Dim SecondSelection As Range
Dim SheetFirst As Worksheet
Dim SheetSecond As Worksheet

On Error GoTo Whoa

Application.EnableEvents = False

' Set starting selection variable.
Set FirstSelection = Selection
Set SheetFirst = FirstSelection.Worksheet

' Reset the Find function so the scope of the search area is the current worksheet.
Set Dummy = Worksheets(1).Range("A1:A1").Find("Dummy", LookIn:=xlValues)

' Change "=" to "#" in selection.
Selection.Replace What:="=", Replacement:="#", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False

' Select the area you want to paste the formulas; must be same size as original
  selection and outside of the original selection.
Set SecondSelection = Application.InputBox("Select a range", "Obtain Range Object", Type:=8)
Set SheetSecond = SecondSelection.Worksheet

' Copy the original selection and paste it into the newly selected area. The active
  selection remains FirstSelection.
FirstSelection.Copy SecondSelection

' Restore "=" in FirstSelection.
Selection.Replace What:="#", Replacement:="=", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False

' Select SecondSelection.
SheetSecond.Activate
SecondSelection.Select

' Restore "=" in SecondSelection.
Selection.Replace What:="#", Replacement:="=", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False

' Return active selection to the original area: FirstSelection.
SheetFirst.Activate
FirstSelection.Select

Application.EnableEvents = True

Exit Sub

Whoa:
' If something goes wrong after "=" has been changed in FirstSelection, restore "=".
FirstSelection.Select
Selection.Replace What:="#", Replacement:="=", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False

End Sub

Note that you must match the size and shape of the original selection when you make your new selection.

Scroll Element into View with Selenium

If nothing works, try this before clicking:

public void mouseHoverJScript(WebElement HoverElement) {

    String mouseOverScript = "if(document.createEvent){var evObj = document.createEvent('MouseEvents');evObj.initEvent('mouseover', true, false); arguments[0].dispatchEvent(evObj);} else if(document.createEventObject) { arguments[0].fireEvent('onmouseover');}";
    ((JavascriptExecutor) driver).executeScript(mouseOverScript, HoverElement);
}

How to check if a file exists in a shell script

If you're using a NFS, "test" is a better solution, because you can add a timeout to it, in case your NFS is down:

time timeout 3 test -f 
/nfs/my_nfs_is_currently_down
real    0m3.004s <<== timeout is taken into account
user    0m0.001s
sys     0m0.004s
echo $?
124   <= 124 means the timeout has been reached

A "[ -e my_file ]" construct will freeze until the NFS is functional again:

if [ -e /nfs/my_nfs_is_currently_down ]; then echo "ok" else echo "ko" ; fi

<no answer from the system, my session is "frozen">

Reflection generic get field value

I use the reflections in the toString() implementation of my preference class to see the class members and values (simple and quick debugging).

The simplified code I'm using:

@Override
public String toString() {
    StringBuilder sb = new StringBuilder();

    Class<?> thisClass = null;
    try {
        thisClass = Class.forName(this.getClass().getName());

        Field[] aClassFields = thisClass.getDeclaredFields();
        sb.append(this.getClass().getSimpleName() + " [ ");
        for(Field f : aClassFields){
            String fName = f.getName();
            sb.append("(" + f.getType() + ") " + fName + " = " + f.get(this) + ", ");
        }
        sb.append("]");
    } catch (Exception e) {
        e.printStackTrace();
    }

    return sb.toString();
}

I hope that it will help someone, because I also have searched.

How can I parse String to Int in an Angular expression?

You can use javascript Number method to parse it to an number,

var num=Number (num_str);

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

This is what worked for me on LinuxMint 19.

curl -s https://yum.dockerproject.org/gpg | sudo apt-key add
apt-key fingerprint 58118E89F3A912897C070ADBF76221572C52609D
sudo add-apt-repository "deb https://apt.dockerproject.org/repo ubuntu-$(lsb_release -cs) main"
sudo apt-get update
sudo apt-get install docker-ce docker-ce-cli containerd.io

Using column alias in WHERE clause of MySQL query produces an error

Standard SQL (or MySQL) does not permit the use of column aliases in a WHERE clause because

when the WHERE clause is evaluated, the column value may not yet have been determined.

(from MySQL documentation). What you can do is calculate the column value in the WHERE clause, save the value in a variable, and use it in the field list. For example you could do this:

SELECT `users`.`first_name`, `users`.`last_name`, `users`.`email`,
@postcode AS `guaranteed_postcode`
FROM `users` LEFT OUTER JOIN `locations`
ON `users`.`id` = `locations`.`user_id`
WHERE (@postcode := SUBSTRING(`locations`.`raw`,-6,4)) NOT IN
(
 SELECT `postcode` FROM `postcodes` WHERE `region` IN
 (
  'australia'
 )
)

This avoids repeating the expression when it grows complicated, making the code easier to maintain.

What is SYSNAME data type in SQL Server?

Just as an FYI....

select * from sys.types where system_type_id = 231 gives you two rows.

(i'm not sure what this means yet but i'm 100% sure it's messing up my code right now)

edit: i guess what it means is that you should join by the user_type_id in this situation (my situation) or possibly both the user_type_id and the system_type_id

name        system_type_id   user_type_id   schema_id   principal_id    max_length  precision   scale   collation_name                  is_nullable     is_user_defined     is_assembly_type    default_object_id   rule_object_id
nvarchar    231              231            4           NULL            8000        0           0       SQL_Latin1_General_CP1_CI_AS    1               0                   0                   0                   0
sysname     231              256            4           NULL            256         0           0       SQL_Latin1_General_CP1_CI_AS    0               0                   0                   0                   0

create procedure dbo.yyy_test (
    @col_one    nvarchar(max),
    @col_two    nvarchar(max)  = 'default',
    @col_three  nvarchar(1),
    @col_four   nvarchar(1)    = 'default',
    @col_five   nvarchar(128),
    @col_six    nvarchar(128)  = 'default',
    @col_seven  sysname  
)
as begin 

    select 1
end 

This query:

select  parm.name AS Parameter,    
        parm.max_length, 
        parm.parameter_id 
         
from    sys.procedures sp

        join sys.parameters parm ON sp.object_id = parm.object_id 
        
where   sp.name = 'yyy_test'

order   by parm.parameter_id

Yields:

parameter           max_length  parameter_id
@col_one            -1          1
@col_two            -1          2
@col_three           2          3
@col_four            2          4
@col_five            256        5
@col_six             256        6
@col_seven           256        7

And This:

select  parm.name as parameter,    
        parm.max_length, 
        parm.parameter_id,
        typ.name as data_type, 
        typ.system_type_id, 
        typ.user_type_id,
        typ.collation_name,
        typ.is_nullable 
from    sys.procedures sp

        join sys.parameters parm ON sp.object_id = parm.object_id
        
        join sys.types typ ON parm.system_type_id = typ.system_type_id
        
where   sp.name = 'yyy_test'

order   by parm.parameter_id

Gives You This:

parameter   max_length  parameter_id    data_type   system_type_id  user_type_id    collation_name                  is_nullable
@col_one    -1          1               nvarchar    231             231             SQL_Latin1_General_CP1_CI_AS    1
@col_one    -1          1               sysname     231             256             SQL_Latin1_General_CP1_CI_AS    0
@col_two    -1          2               nvarchar    231             231             SQL_Latin1_General_CP1_CI_AS    1
@col_two    -1          2               sysname     231             256             SQL_Latin1_General_CP1_CI_AS    0
@col_three   2          3               nvarchar    231             231             SQL_Latin1_General_CP1_CI_AS    1
@col_three   2          3               sysname     231             256             SQL_Latin1_General_CP1_CI_AS    0
@col_four    2          4               nvarchar    231             231             SQL_Latin1_General_CP1_CI_AS    1
@col_four    2          4               sysname     231             256             SQL_Latin1_General_CP1_CI_AS    0
@col_five    256        5               nvarchar    231             231             SQL_Latin1_General_CP1_CI_AS    1
@col_five    256        5               sysname     231             256             SQL_Latin1_General_CP1_CI_AS    0
@col_six     256        6               nvarchar    231             231             SQL_Latin1_General_CP1_CI_AS    1
@col_six     256        6               sysname     231             256             SQL_Latin1_General_CP1_CI_AS    0
@col_seven   256        7               nvarchar    231             231             SQL_Latin1_General_CP1_CI_AS    1
@col_seven   256        7               sysname     231             256             SQL_Latin1_General_CP1_CI_AS    0

Error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat) when running Python script

Python 3.3 and later now uses the 2010 compiler. To best way to solve the issue is to just install Visual C++ Express 2010 for free.

Now comes the harder part for 64 bit users and to be honest I just moved to 32 bit but 2010 express doesn't come with a 64 bit compiler (you get a new error, ValueError: ['path'] ) so you have to install Microsoft SDK 7.1 and follow the directions here to get the 64 bit compiler working with python: Python PIP has issues with path for MS Visual Studio 2010 Express for 64-bit install on Windows 7

It may just be easier for you to use the 32 bit version for now. In addition to getting the compiler working, you can bypass the need to compile many modules by getting the binary wheel file from this locaiton http://www.lfd.uci.edu/~gohlke/pythonlibs/

Just download the .whl file you need, shift + right click the download folder and select "open command window here" and run

pip install module-name.whl 

I used that method on 64 bit 3.4.3 before I broke down and decided to just get a working compiler for pip compiles modules from source by default, which is why the binary wheel files work and having pip build from source doesn't.

People getting this (vcvarsall.bat) error on Python 2.7 can instead install "Microsoft Visual C++ Compiler for Python 2.7"

Using scanner.nextLine()

I think your problem is that

int selection = scanner.nextInt();

reads just the number, not the end of line or anything after the number. When you declare

String sentence = scanner.nextLine();

This reads the remainder of the line with the number on it (with nothing after the number I suspect)

Try placing a scanner.nextLine(); after each nextInt() if you intend to ignore the rest of the line.

checking memory_limit in PHP

Checking on command line:

php -i | grep "memory_limit"

How can I see all the "special" characters permissible in a varchar or char field in SQL Server?

The specific characters that can be stored in a varchar or char column depend upon the column collation. See my answer here for a script that will show you these for the various different collations.

If you want to find all characters outside a particular ASCII range see my answer here.

iOS 7.0 No code signing identities found

After Pulling hair for a long time,I finally found an issue.I've selected wrong certificate while creating Provisioning Profile,By selecting right one,It helped for me.In your case,If it is multiple then You have to try and select one by one to get this issue solved.

Display QImage with QtGui

As far as I know, QPixmap is used for displaying images and QImage for reading them. There are QPixmap::convertFromImage() and QPixmap::fromImage() functions to convert from QImage.

Open a workbook using FileDialog and manipulate it in Excel VBA

Thankyou Frank.i got the idea. Here is the working code.

Option Explicit
Private Sub CommandButton1_Click()

  Dim directory As String, fileName As String, sheet As Worksheet, total As Integer
  Dim fd As Office.FileDialog

  Set fd = Application.FileDialog(msoFileDialogFilePicker)

  With fd
    .AllowMultiSelect = False
    .Title = "Please select the file."
    .Filters.Clear
    .Filters.Add "Excel 2003", "*.xls?"

    If .Show = True Then
      fileName = Dir(.SelectedItems(1))

    End If
  End With

  Application.ScreenUpdating = False
  Application.DisplayAlerts = False

  Workbooks.Open (fileName)

  For Each sheet In Workbooks(fileName).Worksheets
    total = Workbooks("import-sheets.xlsm").Worksheets.Count
    Workbooks(fileName).Worksheets(sheet.Name).Copy _
        after:=Workbooks("import-sheets.xlsm").Worksheets(total)
  Next sheet

  Workbooks(fileName).Close

  Application.ScreenUpdating = True
  Application.DisplayAlerts = True

End Sub

Getting Error - ORA-01858: a non-numeric character was found where a numeric was expected

This error can come not only because of the Date conversions

This error can come when we try to pass date whereas varchar is expected
or
when we try to pass varchar whereas date is expected.

Use to_char(sysdate,'YYYY-MM-DD') when varchar is expected

SignalR Console app example

To build on @dyslexicanaboko's answer for dotnet core, here is a client console application:

Create a helper class:

using System;
using Microsoft.AspNetCore.SignalR.Client;

namespace com.stackoverflow.SignalRClientConsoleApp
{
    public class SignalRConnection
    {
        public async void Start()
        {
            var url = "http://signalr-server-url/hubname";

            var connection = new HubConnectionBuilder()
                .WithUrl(url)
                .WithAutomaticReconnect()
                .Build();

            // receive a message from the hub
            connection.On<string, string>("ReceiveMessage", (user, message) => OnReceiveMessage(user, message));

            var t = connection.StartAsync();

            t.Wait();

            // send a message to the hub
            await connection.InvokeAsync("SendMessage", "ConsoleApp", "Message from the console app");
        }

        private void OnReceiveMessage(string user, string message)
        {
            Console.WriteLine($"{user}: {message}");
        }

    }
}

Then implement in your console app's entry point:

using System;

namespace com.stackoverflow.SignalRClientConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var signalRConnection = new SignalRConnection();
            signalRConnection.Start();

            Console.Read();
        }
    }
}

curl POST format for CURLOPT_POSTFIELDS

EDIT: From php5 upwards, usage of http_build_query is recommended:

string http_build_query ( mixed $query_data [, string $numeric_prefix [, 
                          string $arg_separator [, int $enc_type = PHP_QUERY_RFC1738 ]]] )

Simple example from the manual:

<?php
$data = array('foo'=>'bar',
              'baz'=>'boom',
              'cow'=>'milk',
              'php'=>'hypertext processor');

echo http_build_query($data) . "\n";

/* output:
foo=bar&baz=boom&cow=milk&php=hypertext+processor
*/

?>

before php5:

From the manual:

CURLOPT_POSTFIELDS

The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with @ and use the full path. The filetype can be explicitly specified by following the filename with the type in the format ';type=mimetype'. This parameter can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data. As of PHP 5.2.0, files thats passed to this option with the @ prefix must be in array form to work.

So something like this should work perfectly (with parameters passed in a associative array):

function preparePostFields($array) {
  $params = array();

  foreach ($array as $key => $value) {
    $params[] = $key . '=' . urlencode($value);
  }

  return implode('&', $params);
}

Why doesn't document.addEventListener('load', function) work in a greasemonkey script?

Apparently, document.addEventListener() is unreliable, and hence, my error. Use window.addEventListener() with the same parameters, instead.

java.util.Date format conversion yyyy-mm-dd to mm-dd-yyyy

tl;dr

LocalDate.parse( 
    "01-23-2017" , 
    DateTimeFormatter.ofPattern( "MM-dd-uuuu" )
)

Details

I have a java.util.Date in the format yyyy-mm-dd

As other mentioned, the Date class has no format. It has a count of milliseconds since the start of 1970 in UTC. No strings attached.

java.time

The other Answers use troublesome old legacy date-time classes, now supplanted by the java.time classes.

If you have a java.util.Date, convert to a Instant object. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = myUtilDate.toInstant();

Time zone

The other Answers ignore the crucial issue of time zone. Determining a date requires a time zone. For any given moment, the date varies around the globe by zone. A few minutes after midnight in Paris France is a new day, while still “yesterday” in Montréal Québec.

Define the time zone by which you want context for your Instant.

ZoneId z = ZoneId.of( "America/Montreal" );

Apply the ZoneId to get a ZonedDateTime.

ZonedDateTime zdt = instant.atZone( z );

LocalDate

If you only care about the date without a time-of-day, extract a LocalDate.

LocalDate localDate = zdt.toLocalDate();

To generate a string in standard ISO 8601 format, YYYY-MM-DD, simply call toString. The java.time classes use the standard formats by default when generating/parsing strings.

String output = localDate.toString();

2017-01-23

If you want a MM-DD-YYYY format, define a formatting pattern.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM-dd-uuuu" );
String output = localDate.format( f );

Note that the formatting pattern codes are case-sensitive. The code in the Question incorrectly used mm (minute of hour) rather than MM (month of year).

Use the same DateTimeFormatter object for parsing. The java.time classes are thread-safe, so you can keep this object around and reuse it repeatedly even across threads.

LocalDate localDate = LocalDate.parse( "01-23-2017" , f );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Merge r brings error "'by' must specify uniquely valid columns"

This is what I tried for a right outer join [as per my requirement]:

m1 <- merge(x=companies, y=rounds2, by.x=companies$permalink, 
            by.y=rounds2$company_permalink, all.y=TRUE)
# Error in fix.by(by.x, x) : 'by' must specify uniquely valid columns
m1 <- merge(x=companies, y=rounds2, by.x=c("permalink"), 
            by.y=c("company_permalink"), all.y=TRUE)

This worked.

Wrapping text inside input type="text" element HTML/CSS

Word Break will mimic some of the intent

_x000D_
_x000D_
    input[type=text] {
        word-wrap: break-word;
        word-break: break-all;
        height: 80px;
    }
_x000D_
<input type="text" value="The quick brown fox jumped over the lazy dog" />
_x000D_
_x000D_
_x000D_

As a workaround, this solution lost its effectiveness on some browsers. Please check the demo: http://cssdesk.com/dbCSQ

How to add parameters to a HTTP GET request in Android?

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("param1","value1");

String query = URLEncodedUtils.format(params, "utf-8");

URI url = URIUtils.createURI(scheme, userInfo, authority, port, path, query, fragment); //can be null
HttpGet httpGet = new HttpGet(url);

URI javadoc

Note: url = new URI(...) is buggy

I need to get all the cookies from the browser

You cannot. By design, for security purpose, you can access only the cookies set by your site. StackOverflow can't see the cookies set by UserVoice nor those set by Amazon.

System not declared in scope?

Chances are that you've not included the header file that declares system().

In order to be able to compile C++ code that uses functions which you don't (manually) declare yourself, you have to pull in the declarations. These declarations are normally stored in so-called header files that you pull into the current translation unit using the #include preprocessor directive. As the code does not #include the header file in which system() is declared, the compilation fails.

To fix this issue, find out which header file provides you with the declaration of system() and include that. As mentioned in several other answers, you most likely want to add #include <cstdlib>

AngularJS: ng-repeat list is not updated when a model element is spliced from the model array

Whenever you do some form of operation outside of AngularJS, such as doing an Ajax call with jQuery, or binding an event to an element like you have here you need to let AngularJS know to update itself. Here is the code change you need to do:

app.directive("remove", function () {
    return function (scope, element, attrs) {
        element.bind ("mousedown", function () {
            scope.remove(element);
            scope.$apply();
        })
    };

});

app.directive("resize", function () {
    return function (scope, element, attrs) {
        element.bind ("mousedown", function () {
            scope.resize(element);
            scope.$apply();
        })
    };
});

Here is the documentation on it: https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$apply

How to change the application launcher icon on Flutter?

I use few methods for chaging flutter app lancher icon but only the manuall method is a bit easy and good. Because you will know how it work.

So to change flutter ios icon. First get copy of your icon 1024×1024 pixel and generate set of icons for android and ios using appicon.co generator. When you get zip file it work contact two folder ios and android open ios folder and copy folder and replace the one in your ios/runner directory.

For android copy all folder present in android folder and replace the ones present in the android/app/src/main/res/drawable here.

After replacing folder on both ios and android stop the app and re run and your icons will be changed.

Find duplicate lines in a file and count how many time each line was duplicated?

Via :

awk '{dups[$1]++} END{for (num in dups) {print num,dups[num]}}' data

In awk 'dups[$1]++' command, the variable $1 holds the entire contents of column1 and square brackets are array access. So, for each 1st column of line in data file, the node of the array named dups is incremented.

And at the end, we are looping over dups array with num as variable and print the saved numbers first then their number of duplicated value by dups[num].

Note that your input file has spaces on end of some lines, if you clear up those, you can use $0 in place of $1 in command above :)

SQL Query - how do filter by null or not null

Wherever you are trying to check NULL value of a column, you should use

IS NULL and IS NOT NULL

You should not use =NULL or ==NULL


Example(NULL)

select * from user_registration where registered_time IS NULL 

will return the rows with registered_time value is NULL


Example(NOT NULL)

select * from user_registration where registered_time IS NOT NULL 

will return the rows with registered_time value is NOT NULL

Note: The keyword null, not null and is are not case sensitive.

Which Java library provides base64 encoding/decoding?

If you're an Android developer you can use android.util.Base64 class for this purpose.

How do I change the number of open files limit in Linux?

You could always try doing a ulimit -n 2048. This will only reset the limit for your current shell and the number you specify must not exceed the hard limit

Each operating system has a different hard limit setup in a configuration file. For instance, the hard open file limit on Solaris can be set on boot from /etc/system.

set rlim_fd_max = 166384
set rlim_fd_cur = 8192

On OS X, this same data must be set in /etc/sysctl.conf.

kern.maxfilesperproc=166384
kern.maxfiles=8192

Under Linux, these settings are often in /etc/security/limits.conf.

There are two kinds of limits:

  • soft limits are simply the currently enforced limits
  • hard limits mark the maximum value which cannot be exceeded by setting a soft limit

Soft limits could be set by any user while hard limits are changeable only by root. Limits are a property of a process. They are inherited when a child process is created so system-wide limits should be set during the system initialization in init scripts and user limits should be set during user login for example by using pam_limits.

There are often defaults set when the machine boots. So, even though you may reset your ulimit in an individual shell, you may find that it resets back to the previous value on reboot. You may want to grep your boot scripts for the existence ulimit commands if you want to change the default.

How to set the color of "placeholder" text?

Try this

_x000D_
_x000D_
input::-webkit-input-placeholder { /* WebKit browsers */_x000D_
    color:    #f51;_x000D_
}_x000D_
input:-moz-placeholder { /* Mozilla Firefox 4 to 18 */_x000D_
    color:    #f51;_x000D_
}_x000D_
input::-moz-placeholder { /* Mozilla Firefox 19+ */_x000D_
    color:    #f51;_x000D_
}_x000D_
input:-ms-input-placeholder { /* Internet Explorer 10+ */_x000D_
    color:    #f51;_x000D_
}
_x000D_
<input type="text" placeholder="Value" />
_x000D_
_x000D_
_x000D_

Valid values for android:fontFamily and what they map to?

Where do these values come from? The documentation for android:fontFamily does not list this information in any place

These are indeed not listed in the documentation. But they are mentioned here under the section 'Font families'. The document lists every new public API for Android Jelly Bean 4.1.

In the styles.xml file in the application I'm working on somebody listed this as the font family, and I'm pretty sure it's wrong:

Yes, that's wrong. You don't reference the font file, you have to use the font name mentioned in the linked document above. In this case it should have been this:

<item name="android:fontFamily">sans-serif</item>

Like the linked answer already stated, 12 variants are possible:

Added in Android Jelly Bean (4.1) - API 16 :

Regular (default):

<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">normal</item> 

Italic:

<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">italic</item>

Bold:

<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">bold</item>

Bold-italic:

<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">bold|italic</item>

Light:

<item name="android:fontFamily">sans-serif-light</item>
<item name="android:textStyle">normal</item>

Light-italic:

<item name="android:fontFamily">sans-serif-light</item>
<item name="android:textStyle">italic</item>

Thin :

<item name="android:fontFamily">sans-serif-thin</item>
<item name="android:textStyle">normal</item>

Thin-italic :

<item name="android:fontFamily">sans-serif-thin</item>
<item name="android:textStyle">italic</item>

Condensed regular:

<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">normal</item>

Condensed italic:

<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">italic</item>

Condensed bold:

<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">bold</item>

Condensed bold-italic:

<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">bold|italic</item>

Added in Android Lollipop (v5.0) - API 21 :

Medium:

<item name="android:fontFamily">sans-serif-medium</item>
<item name="android:textStyle">normal</item>

Medium-italic:

<item name="android:fontFamily">sans-serif-medium</item>
<item name="android:textStyle">italic</item>

Black:

<item name="android:fontFamily">sans-serif-black</item>
<item name="android:textStyle">italic</item>

For quick reference, this is how they all look like:

RESTful web service - how to authenticate requests from other services?

There are several different approaches you can take.

  1. The RESTful purists will want you to use BASIC authentication, and send credentials on every request. Their rationale is that no one is storing any state.

  2. The client service could store a cookie, which maintains a session ID. I don't personally find this as offensive as some of the purists I hear from - it can be expensive to authenticate over and over again. It sounds like you're not too fond of this idea, though.

  3. From your description, it really sounds like you might be interested in OAuth2 My experience so far, from what I've seen, is that it's kind of confusing, and kind of bleeding edge. There are implementations out there, but they're few and far between. In Java, I understand that it has been integrated into Spring3's security modules. (Their tutorial is nicely written.) I've been waiting to see if there will be an extension in Restlet, but so far, although it's been proposed, and may be in the incubator, it's still not been fully incorporated.

How to convert float to int with Java

Use Math.round(value) then after type cast it to integer.

float a = 8.61f;
int b = (int)Math.round(a);

What's the UIScrollView contentInset property for?

While jball's answer is an excellent description of content insets, it doesn't answer the question of when to use it. I'll borrow from his diagrams:

  _|?_cW_?_|_?_
   |       | 
---------------
   |content| ?
 ? |content| contentInset.top
cH |content|
 ? |content| contentInset.bottom
   |content| ?
---------------
   |content|    
-------------?-

That's what you get when you do it, but the usefulness of it only shows when you scroll:

  _|?_cW_?_|_?_
   |content| ? content is still visible
---------------
   |content| ?
 ? |content| contentInset.top
cH |content|
 ? |content| contentInset.bottom
   |content| ?
---------------
  _|_______|___ 
             ?

That top row of content will still be visible because it's still inside the frame of the scroll view. One way to think of the top offset is "how much to shift the content down the scroll view when we're scrolled all the way to the top"

To see a place where this is actually used, look at the build-in Photos app on the iphone. The Navigation bar and status bar are transparent, and the contents of the scroll view are visible underneath. That's because the scroll view's frame extends out that far. But if it wasn't for the content inset, you would never be able to have the top of the content clear that transparent navigation bar when you go all the way to the top.

jQuery Popup Bubble/Tooltip

I have programmed an useful jQuery Plugin to create easily smart bubble popups with only a line of code in jQuery!

What You can do: - attach popups to any DOM element! - mouseover/mouseout events automatically managed! - set custom popups events! - create smart shadowed popups! (in IE too!) - choose popup’s style templates at runtime! - insert HTML messages inside popups! - set many options as: distances, velocity, delays, colors…

Popup’s shadows and colorized templates are fully supported by Internet Explorer 6+, Firefox, Opera 9+, Safari

You can download sources from http://plugins.jquery.com/project/jqBubblePopup

PHP Date Time Current Time Add Minutes

It looks like you are after the DateTime function add - use it like this:

$date = new DateTime();
date_add($date, new DateInterval("PT30M"));

(Note: untested, but according to the docs, it should work)

How to permanently set $PATH on Linux/Unix?

You need to add it to your ~/.profile or ~/.bashrc file. 

export PATH="$PATH:/path/to/dir"

Depending on what you're doing, you also may want to symlink to binaries:

cd /usr/bin
sudo ln -s /path/to/binary binary-name

Note that this will not automatically update your path for the remainder of the session. To do this, you should run:

source ~/.profile 
or
source ~/.bashrc

How to avoid Sql Query Timeout

This is happen because another instance of sql server is running. So you need to kill first then you can able to login to SQL Server.

For that go to Task Manager and Kill or End Task the SQL Server service then go to Services.msc and start the SQL Server service.

How do I grep recursively?

I guess this is what you're trying to write

grep myText $(find .)

and this may be something else helpful if you want to find the files grep hit

grep myText $(find .) | cut -d : -f 1 | sort | uniq

Python set to list

Your code works with Python 3.2.1 on Win7 x64

a = set(["Blah", "Hello"])
a = list(a)
type(a)
<class 'list'>

Errors: Data path ".builders['app-shell']" should have required property 'class'

What actually worked for me was to update the application and its dependencies with:

ng update @angular/cli @angular/core

Angular documentation

How can I fill a div with an image while keeping it proportional?

Here is an answer with support to IE using object-fit so you won't lose ratio

Using a simple JS snippet to detect if the object-fit is supported and then replace the img for a svg

_x000D_
_x000D_
//ES6 version
if ('objectFit' in document.documentElement.style === false) {
  document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('img[data-object-fit]').forEach(image => {
      (image.runtimeStyle || image.style).background = `url("${image.src}") no-repeat 50%/${image.currentStyle ? image.currentStyle['object-fit'] : image.getAttribute('data-object-fit')}`
      image.src = `data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='${image.width}' height='${image.height}'%3E%3C/svg%3E`
    })
  })
}

//ES5 version
if ('objectFit' in document.documentElement.style === false) {
  document.addEventListener('DOMContentLoaded', function() {
    Array.prototype.forEach.call(document.querySelectorAll('img[data-object-fit]').forEach(function(image) {
      (image.runtimeStyle || image.style).background = "url(\"".concat(image.src, "\") no-repeat 50%/").concat(image.currentStyle ? image.currentStyle['object-fit'] : image.getAttribute('data-object-fit'));
      image.src = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='".concat(image.width, "' height='").concat(image.height, "'%3E%3C/svg%3E");
    }));
  });
}
_x000D_
img {
  display: inline-flex;
  width: 175px;
  height: 175px;
  margin-right: 10px;
  border: 1px solid red
}


/*for browsers which support object fit */

[data-object-fit='cover'] {
  object-fit: cover
}

[data-object-fit='contain'] {
  object-fit: contain
}
_x000D_
<img data-object-fit='cover' src='//picsum.photos/1200/600' />
<img data-object-fit='contain' src='//picsum.photos/1200/600' />
<img src='//picsum.photos/1200/600' />
_x000D_
_x000D_
_x000D_


Note: There are also a few object-fit polyfills out there that will make object-fit work.

Here are a few examples:

How to configure socket connect timeout

I dont program in C# but in C, we solve the same problem by making the socket non-blocking and then putting the fd in a select/poll loop with a timeout value equal to the amount of time we are willing to wait for the connect to succeed.

I found this for Visual C++ and the explanation there also bends towards the select/poll mechanism I explained before.

In my experience, you cannot change connect timeout values per socket. You change it for all (by tuning OS parameters).

Find duplicate records in a table using SQL Server

Select EventID,count() as cnt from dbo.EventInstances group by EventID having count() > 1

Delegation: EventEmitter or Observable in Angular

Update 2016-06-27: instead of using Observables, use either

  • a BehaviorSubject, as recommended by @Abdulrahman in a comment, or
  • a ReplaySubject, as recommended by @Jason Goemaat in a comment

A Subject is both an Observable (so we can subscribe() to it) and an Observer (so we can call next() on it to emit a new value). We exploit this feature. A Subject allows values to be multicast to many Observers. We don't exploit this feature (we only have one Observer).

BehaviorSubject is a variant of Subject. It has the notion of "the current value". We exploit this: whenever we create an ObservingComponent, it gets the current navigation item value from the BehaviorSubject automatically.

The code below and the plunker use BehaviorSubject.

ReplaySubject is another variant of Subject. If you want to wait until a value is actually produced, use ReplaySubject(1). Whereas a BehaviorSubject requires an initial value (which will be provided immediately), ReplaySubject does not. ReplaySubject will always provide the most recent value, but since it does not have a required initial value, the service can do some async operation before returning it's first value. It will still fire immediately on subsequent calls with the most recent value. If you just want one value, use first() on the subscription. You do not have to unsubscribe if you use first().

import {Injectable}      from '@angular/core'
import {BehaviorSubject} from 'rxjs/BehaviorSubject';

@Injectable()
export class NavService {
  // Observable navItem source
  private _navItemSource = new BehaviorSubject<number>(0);
  // Observable navItem stream
  navItem$ = this._navItemSource.asObservable();
  // service command
  changeNav(number) {
    this._navItemSource.next(number);
  }
}
import {Component}    from '@angular/core';
import {NavService}   from './nav.service';
import {Subscription} from 'rxjs/Subscription';

@Component({
  selector: 'obs-comp',
  template: `obs component, item: {{item}}`
})
export class ObservingComponent {
  item: number;
  subscription:Subscription;
  constructor(private _navService:NavService) {}
  ngOnInit() {
    this.subscription = this._navService.navItem$
       .subscribe(item => this.item = item)
  }
  ngOnDestroy() {
    // prevent memory leak when component is destroyed
    this.subscription.unsubscribe();
  }
}
@Component({
  selector: 'my-nav',
  template:`
    <div class="nav-item" (click)="selectedNavItem(1)">nav 1 (click me)</div>
    <div class="nav-item" (click)="selectedNavItem(2)">nav 2 (click me)</div>`
})
export class Navigation {
  item = 1;
  constructor(private _navService:NavService) {}
  selectedNavItem(item: number) {
    console.log('selected nav item ' + item);
    this._navService.changeNav(item);
  }
}

Plunker


Original answer that uses an Observable: (it requires more code and logic than using a BehaviorSubject, so I don't recommend it, but it may be instructive)

So, here's an implementation that uses an Observable instead of an EventEmitter. Unlike my EventEmitter implementation, this implementation also stores the currently selected navItem in the service, so that when an observing component is created, it can retrieve the current value via API call navItem(), and then be notified of changes via the navChange$ Observable.

import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/share';
import {Observer} from 'rxjs/Observer';

export class NavService {
  private _navItem = 0;
  navChange$: Observable<number>;
  private _observer: Observer;
  constructor() {
    this.navChange$ = new Observable(observer =>
      this._observer = observer).share();
    // share() allows multiple subscribers
  }
  changeNav(number) {
    this._navItem = number;
    this._observer.next(number);
  }
  navItem() {
    return this._navItem;
  }
}

@Component({
  selector: 'obs-comp',
  template: `obs component, item: {{item}}`
})
export class ObservingComponent {
  item: number;
  subscription: any;
  constructor(private _navService:NavService) {}
  ngOnInit() {
    this.item = this._navService.navItem();
    this.subscription = this._navService.navChange$.subscribe(
      item => this.selectedNavItem(item));
  }
  selectedNavItem(item: number) {
    this.item = item;
  }
  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

@Component({
  selector: 'my-nav',
  template:`
    <div class="nav-item" (click)="selectedNavItem(1)">nav 1 (click me)</div>
    <div class="nav-item" (click)="selectedNavItem(2)">nav 2 (click me)</div>
  `,
})
export class Navigation {
  item:number;
  constructor(private _navService:NavService) {}
  selectedNavItem(item: number) {
    console.log('selected nav item ' + item);
    this._navService.changeNav(item);
  }
}

Plunker


See also the Component Interaction Cookbook example, which uses a Subject in addition to observables. Although the example is "parent and children communication," the same technique is applicable for unrelated components.

Loop Through Each HTML Table Column and Get the Data using jQuery

When you create your table, put your td with class = "suma"

$(function(){   

   //funcion suma todo

   var sum = 0;
   $('.suma').each(function(x,y){
       sum += parseInt($(this).text());                                   
   })           
   $('#lblTotal').text(sum);   

   // funcion suma por check                                           

    $( "input:checkbox").change(function(){
    if($(this).is(':checked')){     
        $(this).parent().parent().find('td:last').addClass('suma2');
   }else{       
        $(this).parent().parent().find('td:last').removeClass('suma2');
   }    
   suma2Total();                                                           
   })                                                      

   function suma2Total(){
      var sum2 = 0;
      $('.suma2').each(function(x,y){
        sum2 += parseInt($(this).text());       
      })
      $('#lblTotal2').text(sum2);                                              
   }                                                                      
});

Ejemplo completo

Bootstrap 4 - Responsive cards in card-columns

Update 2019 - Bootstrap 4

You can simply use the SASS mixin to change the number of cards across in each breakpoint / grid tier.

.card-columns {
  @include media-breakpoint-only(xl) {
    column-count: 5;
  }
  @include media-breakpoint-only(lg) {
    column-count: 4;
  }
  @include media-breakpoint-only(md) {
    column-count: 3;
  }
  @include media-breakpoint-only(sm) {
    column-count: 2;
  }
}

SASS Demo: http://www.codeply.com/go/FPBCQ7sOjX

Or, CSS only like this...

@media (min-width: 576px) {
    .card-columns {
        column-count: 2;
    }
}

@media (min-width: 768px) {
    .card-columns {
        column-count: 3;
    }
}

@media (min-width: 992px) {
    .card-columns {
        column-count: 4;
    }
}

@media (min-width: 1200px) {
    .card-columns {
        column-count: 5;
    }
}

CSS-only Demo: https://www.codeply.com/go/FIqYTyyWWZ

Windows batch - concatenate multiple text files into one

Windows type command works similarly to UNIX cat.

Example 1: Merge with file names (This will merge file1.csv & file2.csv to create concat.csv)

type file1.csv file2.csv > concat.csv

Example 2: Merge files with pattern (This will merge all files with csv extension and create concat.csv)

When using asterisk(*) to concatenate all files. Please DON'T use same extension for target file(Eg. .csv). There should be some difference in pattern else target file will also be considered in concatenation

type  *.csv > concat_csv.txt

Creating a script for a Telnet session?

Another method is to use netcat (or nc, dependent upon which posix) in the same format as vatine shows or you can create a text file that contains each command on it's own line.

I have found that some posix' telnets do not handle redirect correctly (which is why I suggest netcat)

Executing Shell Scripts from the OS X Dock?

In the Script Editor:

do shell script "/full/path/to/your/script -with 'all desired args'"

Save as an application bundle.

As long as all you want to do is get the effect of the script, this will work fine. You won't see STDOUT or STDERR.

Python method for reading keypress?

from msvcrt import getch

pos = [0, 0]

def fright():
    global pos
    pos[0] += 1

def fleft():
    global pos 
    pos[0] -= 1

def fup():
    global pos
    pos[1] += 1

def fdown():
    global pos
    pos[1] -= 1

while True:
    print'Distance from zero: ', pos
    key = ord(getch())
    if key == 27: #ESC
        break
    elif key == 13: #Enter
        print('selected')
    elif key == 32: #Space
        print('jump')
    elif key == 224: #Special keys (arrows, f keys, ins, del, etc.)
        key = ord(getch())
        if key == 80: #Down arrow
            print('down')
            fdown
        elif key == 72: #Up arrow
            print('up')
            fup()
        elif key == 75: #Left arrow
            print('left')
            fleft()
        elif key == 77: #Right arrow
            print('right')
            fright()

Refreshing all the pivot tables in my excel workbook with a macro

If you are using MS Excel 2003 then go to view->Tool bar->Pivot Table From this tool bar we can do refresh by clicking ! this symbol.

How to change the DataTable Column Name?

Rename the Column by doing the following:

dataTable.Columns["ColumnName"].ColumnName = "newColumnName";

How to get the sign, mantissa and exponent of a floating point number

I think it is better to use unions to do the casts, it is clearer.

#include <stdio.h>

typedef union {
  float f;
  struct {
    unsigned int mantisa : 23;
    unsigned int exponent : 8;
    unsigned int sign : 1;
  } parts;
} float_cast;

int main(void) {
  float_cast d1 = { .f = 0.15625 };
  printf("sign = %x\n", d1.parts.sign);
  printf("exponent = %x\n", d1.parts.exponent);
  printf("mantisa = %x\n", d1.parts.mantisa);
}

Example based on http://en.wikipedia.org/wiki/Single_precision

How can I set a dynamic model name in AngularJS?

To make the answer provided by @abourget more complete, the value of scopeValue[field] in the following line of code could be undefined. This would result in an error when setting subfield:

<textarea ng-model="scopeValue[field][subfield]"></textarea>

One way of solving this problem is by adding an attribute ng-focus="nullSafe(field)", so your code would look like the below:

<textarea ng-focus="nullSafe(field)" ng-model="scopeValue[field][subfield]"></textarea>

Then you define nullSafe( field ) in a controller like the below:

$scope.nullSafe = function ( field ) {
  if ( !$scope.scopeValue[field] ) {
    $scope.scopeValue[field] = {};
  }
};

This would guarantee that scopeValue[field] is not undefined before setting any value to scopeValue[field][subfield].

Note: You can't use ng-change="nullSafe(field)" to achieve the same result because ng-change happens after the ng-model has been changed, which would throw an error if scopeValue[field] is undefined.

Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]

I am using Eclipse mars, Hibernate 5.2.1, Jdk7 and Oracle 11g.

I get the same error when I run Hibernate code generation tool. I guess it is a versions issue due to I have solved it through choosing Hibernate version (5.1 to 5.0) in the type frame in my Hibernate console configuration.

BadImageFormatException. This will occur when running in 64 bit mode with the 32 bit Oracle client components installed

Please download the correct version of Oracle Client like Oracle Client 11.2 32-Bit; which resolved the problem for me.

Convert a JSON Object to Buffer and Buffer to JSON Object back

You need to stringify the json, not calling toString

var buf = Buffer.from(JSON.stringify(obj));

And for converting string to json obj :

var temp = JSON.parse(buf.toString());

How to install a specific JDK on Mac OS X?

I think this other Stack Overflow question could help:

How to get JDK 1.5 on Mac OS X

It basically says that if you need to compile or execute a Java application with an older version of the JDK (for example 1.4 or 1.5), you can do it using the 1.6 because it is backwards compatible. To do it so you will need to add the parameter -source 1.5 and/or -target 1.5 in the javac options or in your IDE.

Angular 2: How to style host element of the component?

I have found a solution how to style just the component element. I have not found any documentation how it works, but you can put attributes values into the component directive, under the 'host' property like this:

@Component({
    ...
    styles: [`
      :host {
        'style': 'display: table; height: 100%',
        'class': 'myClass'
      }`
})
export class MyComponent
{
    constructor() {}

    // Also you can use @HostBinding decorator
    @HostBinding('style.background-color') public color: string = 'lime';
    @HostBinding('class.highlighted') public highlighted: boolean = true;
}

UPDATE: As Günter Zöchbauer mentioned, there was a bug, and now you can style the host element even in css file, like this:

:host{ ... }

Retrieve data from a ReadableStream object?

In order to access the data from a ReadableStream you need to call one of the conversion methods (docs available here).

As an example:

fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(function(response) {
    // The response is a Response instance.
    // You parse the data into a useable format using `.json()`
    return response.json();
  }).then(function(data) {
    // `data` is the parsed version of the JSON returned from the above endpoint.
    console.log(data);  // { "userId": 1, "id": 1, "title": "...", "body": "..." }
  });

EDIT: If your data return type is not JSON or you don't want JSON then use text()

As an example:

fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(function(response) {
    return response.text();
  }).then(function(data) {
    console.log(data); // this will be a string
  });

Hope this helps clear things up.

How to format a number 0..9 to display with 2 digits (it's NOT a date)

The String class comes with the format abilities:

System.out.println(String.format("%02d", 5));

for full documentation, here is the doc

Is there a library function for Root mean square error (RMSE) in python?

from sklearn import metrics
import bumpy as np
print(no.sqrt(metrics.mean_squared_error(actual,predicted)))

I don't have "Dynamic Web Project" option in Eclipse new Project wizard

I think you need the Web Tools Platform package for this. Not very sure though. You can add it to your current eclipse through Help > install new software.

Then add the software repository site location for WTP for your version of eclipse. This is how you can install plugins in eclipse.

How to navigate to a section of a page

Use HTML's anchors:

Main Page:

<a href="sample.html#sushi">Sushi</a>
<a href="sample.html#bbq">BBQ</a>

Sample Page:

<div id='sushi'><a name='sushi'></a></div>
<div id='bbq'><a name='bbq'></a></div>

How to make popup look at the centre of the screen?

If the effect you want is to center in the center of the screen no matter where you've scrolled to, it's even simpler than that:

In your CSS use (for example)

div.centered{
  width: 100px;
  height: 50px;
  position:fixed; 
  top: calc(50% - 25px); // half of width
  left: calc(50% - 50px); // half of height
}

No JS required.

Can't connect to MySQL server error 111

If you're running cPanel/WHM, make sure that IP is whitelisted in the firewall. You will als need to add that IP to the remote SQL IP list in the cPanel account you're trying to connect to.

Moment js date time comparison

You should be able to compare them directly.

var date = moment("2013-03-24")
var now = moment();

if (now > date) {
   // date is past
} else {
   // date is future
}

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  _x000D_
  $('.compare').click(function(e) {_x000D_
  _x000D_
    var date = $('#date').val();_x000D_
  _x000D_
    var now = moment();_x000D_
    var then = moment(date);_x000D_
  _x000D_
    if (now > then) {_x000D_
      $('.result').text('Date is past');_x000D_
    } else {_x000D_
      $('.result').text('Date is future');_x000D_
    }_x000D_
_x000D_
  });_x000D_
_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<input type="text" name="date" id="date" value="2014-12-18"  placeholder="yyyy-mm-dd">_x000D_
<button class="compare">Compare date to current date</button>_x000D_
<br>_x000D_
<div class="result"></div>
_x000D_
_x000D_
_x000D_

How to programmatically get iOS status bar height

Swift 3 or Swift 4:

UIApplication.shared.statusBarFrame.height

Can we make unsigned byte in Java

The fact that primitives are signed in Java is irrelevant to how they're represented in memory / transit - a byte is merely 8 bits and whether you interpret that as a signed range or not is up to you. There is no magic flag to say "this is signed" or "this is unsigned".

As primitives are signed the Java compiler will prevent you from assigning a value higher than +127 to a byte (or lower than -128). However, there's nothing to stop you downcasting an int (or short) in order to achieve this:

int i = 200; // 0000 0000 0000 0000 0000 0000 1100 1000 (200)
byte b = (byte) 200; // 1100 1000 (-56 by Java specification, 200 by convention)

/*
 * Will print a negative int -56 because upcasting byte to int does
 * so called "sign extension" which yields those bits:
 * 1111 1111 1111 1111 1111 1111 1100 1000 (-56)
 *
 * But you could still choose to interpret this as +200.
 */
System.out.println(b); // "-56"

/*
 * Will print a positive int 200 because bitwise AND with 0xFF will
 * zero all the 24 most significant bits that:
 * a) were added during upcasting to int which took place silently
 *    just before evaluating the bitwise AND operator.
 *    So the `b & 0xFF` is equivalent with `((int) b) & 0xFF`.
 * b) were set to 1s because of "sign extension" during the upcasting
 *
 * 1111 1111 1111 1111 1111 1111 1100 1000 (the int)
 * &
 * 0000 0000 0000 0000 0000 0000 1111 1111 (the 0xFF)
 * =======================================
 * 0000 0000 0000 0000 0000 0000 1100 1000 (200)
 */
System.out.println(b & 0xFF); // "200"

/*
 * You would typically do this *within* the method that expected an 
 * unsigned byte and the advantage is you apply `0xFF` only once
 * and than you use the `unsignedByte` variable in all your bitwise
 * operations.
 *
 * You could use any integer type longer than `byte` for the `unsignedByte` variable,
 * i.e. `short`, `int`, `long` and even `char`, but during bitwise operations
 * it would get casted to `int` anyway.
 */
void printUnsignedByte(byte b) {
    int unsignedByte = b & 0xFF;
    System.out.println(unsignedByte); // "200"
}

How to get the first element of the List or Set?

You can use the get(index) method to access an element from a List.

Sets, by definition, simply contain elements and have no particular order. Therefore, there is no "first" element you can get, but it is possible to iterate through it using iterator (using the for each loop) or convert it to an array using the toArray() method.

Java keytool easy way to add server cert from url/port

Was looking at how to trust a certificate while using jenkins cli, and found https://issues.jenkins-ci.org/browse/JENKINS-12629 which has some recipe for that.

This will give you the certificate:

openssl s_client -connect ${HOST}:${PORT} </dev/null

if you are interested only in the certificate part, cut it out by piping it to:

| sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p'

and redirect to a file:

> ${HOST}.cert

Then import it using keytool:

keytool -import -noprompt -trustcacerts -alias ${HOST} -file ${HOST}.cert \
    -keystore ${KEYSTOREFILE} -storepass ${KEYSTOREPASS}

In one go:

HOST=myhost.example.com
PORT=443
KEYSTOREFILE=dest_keystore
KEYSTOREPASS=changeme

# get the SSL certificate
openssl s_client -connect ${HOST}:${PORT} </dev/null \
    | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > ${HOST}.cert

# create a keystore and import certificate
keytool -import -noprompt -trustcacerts \
    -alias ${HOST} -file ${HOST}.cert \
    -keystore ${KEYSTOREFILE} -storepass ${KEYSTOREPASS}

# verify we've got it.
keytool -list -v -keystore ${KEYSTOREFILE} -storepass ${KEYSTOREPASS} -alias ${HOST}

Why is `input` in Python 3 throwing NameError: name... is not defined

I got the same error. In the terminal when I typed "python filename.py", with this command, python2 was tring to run python3 code, because the is written python3. It runs correctly when I type "python3 filename.py" in the terminal. I hope this works for you too.