Programs & Examples On #Directcast

"The underlying connection was closed: An unexpected error occurred on a send." With SSL Certificate

You just change your application version like 4.0 to 4.6 and publish those code.

Also add below code lines:

httpRequest.ProtocolVersion = HttpVersion.Version10; 
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

How to get status code from webclient?

Just in case someone else needs an F# version of the above described hack.

open System
open System.IO
open System.Net

type WebClientEx() =
     inherit WebClient ()
     [<DefaultValue>] val mutable m_Resp : WebResponse

     override x.GetWebResponse (req: WebRequest ) =
        x.m_Resp <- base.GetWebResponse(req)
        (req :?> HttpWebRequest).AllowAutoRedirect <- false;

     override x.GetWebResponse (req: WebRequest , ar: IAsyncResult  ) =
        x.m_Resp <- base.GetWebResponse(req, ar)
        (req :?> HttpWebRequest).AllowAutoRedirect <- false;

     member x.StatusCode with get() : HttpStatusCode = 
            if not (obj.ReferenceEquals (x.m_Resp, null)) && x.m_Resp.GetType() = typeof<HttpWebResponse> then
                (x.m_Resp :?> HttpWebResponse).StatusCode

let wc = new WebClientEx()
let st = wc.OpenRead("")
let sr = new StreamReader(st)
let res = sr.ReadToEnd()

How to reload / refresh model data from the server programmatically?

Before I show you how to reload / refresh model data from the server programmatically? I have to explain for you the concept of Data Binding. This is an extremely powerful concept that will truly revolutionize the way you develop. So may be you have to read about this concept from this link or this seconde link in order to unterstand how AngularjS work.

now I'll show you a sample example that exaplain how can you update your model from server.

HTML Code:

<div ng-controller="PersonListCtrl">
        <li ng-repeat="person in persons">
            Name: {{}}, Age {{person.age}}
   <button ng-click="updateData()">Refresh Data</button>

So our controller named: PersonListCtrl and our Model named: persons. go to your Controller js in order to develop the function named: updateData() that will be invoked when we are need to update and refresh our Model persons.

Javascript Code:

app.controller('adsController', function($log,$scope,...){


$scope.updateData = function(){
$http.get('/persons').success(function(data) {
       $scope.persons = data;// Update Model-- Line X


Now I explain for you how it work: when user click on button Refresh Data, the server will call to function updateData() and inside this function we will invoke our web service by the function $http.get() and when we have the result from our ws we will affect it to our model (Line X).Dice that affects the results for our model, our View of this list will be changed with new Data.

Smooth scroll to div id jQuery

If you want to override standard href-id navigation on the page without changing the HTML markup for smooth scrolling, use this (example):

// handle links with @href started with '#' only
$(document).on('click', 'a[href^="#"]', function(e) {
    // target element id
    var id = $(this).attr('href');

    // target element
    var $id = $(id);
    if ($id.length === 0) {

    // prevent standard hash navigation (avoid blinking in IE)

    // top position relative to the document
    var pos = $id.offset().top;

    // animated top scrolling
    $('body, html').animate({scrollTop: pos});

React img tag issue with url and class

var Hello = React.createClass({
    render: function() {
      return (
        <div className="divClass">
           <img src={this.props.url} alt={`${this.props.title}'s picture`}  className="img-responsive" />
           <span>Hello {}</span>

Ignore .classpath and .project from Git

If the .project and .classpath are already committed, then they need to be removed from the index (but not the disk)

git rm --cached .project
git rm --cached .classpath

Then the .gitignore would work (and that file can be added and shared through clones).
For instance, this file will then work, which does include:

# Eclipse Core      

# JDT-specific (Eclipse Java Development Tools)     

Note that you could use a "Template Directory" when cloning (make sure your users have an environment variable $GIT_TEMPLATE_DIR set to a shared folder accessible by all).
That template folder can contain an info/exclude file, with ignore rules that you want enforced for all repos, including the new ones (git init) that any user would use.

As commented by Abdollah

When you change the index, you need to commit the change and push it.
Then the file is removed from the repository. So the newbies cannot checkout the files .classpath and .project from the repo.

How to have an auto incrementing version number (Visual Studio)?

This is my implementation of the T4 suggestion... This will increment the build number every time you build the project regardless of the selected configuration (i.e. Debug|Release), and it will increment the revision number every time you do a Release build. You can continue to update the major and minor version numbers through Application ➤ Assembly Information...

To explain in more detail, this will read the existing AssemblyInfo.cs file, and use regex to find the AssemblyVersion information and then increment the revision and build numbers based on input from TextTransform.exe.

  1. Delete your existing AssemblyInfo.cs file.
  2. Create a file in its place. Visual Studio should create AssemblyInfo.cs and group it with the T4 file after you save the T4 file.

    <#@ template debug="true" hostspecific="true" language="C#" #>
    <#@ output extension=".cs" #>
    <#@ import namespace="System.IO" #>
    <#@ import namespace="System.Text.RegularExpressions" #>
        string output = File.ReadAllText(this.Host.ResolvePath("AssemblyInfo.cs"));
        Regex pattern = new Regex("AssemblyVersion\\(\"(?<major>\\d+)\\.(?<minor>\\d+)\\.(?<revision>\\d+)\\.(?<build>\\d+)\"\\)");
        MatchCollection matches = pattern.Matches(output);
        if( matches.Count == 1 )
            major = Convert.ToInt32(matches[0].Groups["major"].Value);
            minor = Convert.ToInt32(matches[0].Groups["minor"].Value);
            build = Convert.ToInt32(matches[0].Groups["build"].Value) + 1;
            revision = Convert.ToInt32(matches[0].Groups["revision"].Value);
            if( this.Host.ResolveParameterValue("-","-","BuildConfiguration") == "Release" )
    using System.Reflection;
    using System.Runtime.CompilerServices;
    using System.Runtime.InteropServices;
    using System.Resources;
    // General Information
    [assembly: AssemblyTitle("Insert title here")]
    [assembly: AssemblyDescription("Insert description here")]
    [assembly: AssemblyConfiguration("")]
    [assembly: AssemblyCompany("Insert company here")]
    [assembly: AssemblyProduct("Insert product here")]
    [assembly: AssemblyCopyright("Insert copyright here")]
    [assembly: AssemblyTrademark("Insert trademark here")]
    [assembly: AssemblyCulture("")]
    // Version informationr(
    [assembly: AssemblyVersion("<#= this.major #>.<#= this.minor #>.<#= this.revision #>.<#= #>")]
    [assembly: AssemblyFileVersion("<#= this.major #>.<#= this.minor #>.<#= this.revision #>.<#= #>")]
    [assembly: NeutralResourcesLanguageAttribute( "en-US" )]
        int major = 1;
        int minor = 0;
        int revision = 0;
        int build = 0;
  3. Add this to your pre-build event:

    "%CommonProgramFiles(x86)%\microsoft shared\TextTemplating\$(VisualStudioVersion)\TextTransform.exe" -a !!BuildConfiguration!$(Configuration) "$(ProjectDir)Properties\"

Remove all padding and margin table HTML and CSS

Try this:

table { 
border-spacing: 0;
border-collapse: collapse;

How can I get a web site's favicon?

You'll want to tackle this a few ways:

  1. Look for the favicon.ico at the root of the domain

  2. Look for a <link> tag with the rel="shortcut icon" attribute

    <link rel="shortcut icon" href="/favicon.ico" />

  3. Look for a <link> tag with the rel="icon" attribute

    <link rel="icon" href="/favicon.png" />

The latter two will usually yield a higher quality image.

Just to cover all of the bases, there are device specific icon files that might yield higher quality images since these devices usually have larger icons on the device than a browser would need:

<link rel="apple-touch-icon" href="images/touch.png" />

<link rel="apple-touch-icon-precomposed" href="images/touch.png" />

And to download the icon without caring what the icon is you can use a utility like which will do all of the heavy lifting:

var client = new System.Net.WebClient();


Is it more efficient to copy a vector by reserving and copying, or by creating and swapping?

They aren't the same though, are they? One is a copy, the other is a swap. Hence the function names.

My favourite is:

a = b;

Where a and b are vectors.

Eclipse HotKey: how to switch between tabs?

3 line AutoHotKey script (on Windows, anyway):

#IfWinActive ahk_class SWT_Window0

Put this in your startup folder (save it as *.ahk, must have AutoHotKey installed) and Eclipse tabs will now work like Chrome or Firefox.

Escape @ character in razor view engine

I couldn't get any of these to work inside my placeholder attribute, so I used xml special character.

<input type="text" placeholder="fex: firstname&#64;"/>

See more examples here.

finding the type of an element using jQuery

The following will return true if the element is an input:


or you can use the following to get the name of the tag:


Remove duplicates from dataframe, based on two columns A,B, keeping row with max value in another column C

You can do it using group by:

c_maxes = df.groupby(['A', 'B']).C.transform(max)
df = df.loc[df.C == c_maxes]

c_maxes is a Series of the maximum values of C in each group but which is of the same length and with the same index as df. If you haven't used .transform then printing c_maxes might be a good idea to see how it works.

Another approach using drop_duplicates would be

df.sort('C').drop_duplicates(subset=['A', 'B'], take_last=True)

Not sure which is more efficient but I guess the first approach as it doesn't involve sorting.

EDIT: From pandas 0.18 up the second solution would be

df.sort_values('C').drop_duplicates(subset=['A', 'B'], keep='last')

or, alternatively,

df.sort_values('C', ascending=False).drop_duplicates(subset=['A', 'B'])

In any case, the groupby solution seems to be significantly more performing:

%timeit -n 10 df.loc[df.groupby(['A', 'B']).C.max == df.C]
10 loops, best of 3: 25.7 ms per loop

%timeit -n 10 df.sort_values('C').drop_duplicates(subset=['A', 'B'], keep='last')
10 loops, best of 3: 101 ms per loop

How to grep and replace

Usually not with grep, but rather with sed -i 's/string_to_find/another_string/g' or perl -i.bak -pe 's/string_to_find/another_string/g'.

First letter capitalization for EditText

For Capitalisation in EditText you can choose the below two input types:

  1. android:inputType="textCapSentences"
  2. android:inputType="textCapWords"

This will let the first letter of the first word as Capital in every sentence.

textCapWords This will let the first letter of every word as Capital.

If you want both the attributes just use | sign with both the attributes


linux: kill background task

There's a special variable for this in bash:

kill $!

$! expands to the PID of the last process executed in the background.

Angular: Can't find Promise, Map, Set and Iterator

I found the reference in boot.ts wasn't the correct path. Updating that path to /// <reference path=">../../../node_modules/angular2/typings/browser.d.ts" /> resolved the Promise errors.

How do I create an abstract base class in JavaScript?

Javascript can have inheritance, check out the URL below:


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

Other option, for similar example but with anidated selects, think that you have two select, the name of the first is "ea_pub_dest" and the name of the second is "ea_pub_dest_2", ok, now take the event click of the first and display the second.


function test()
    value = document.getElementById("ea_pub_dest").value;
    if ( valor == "value_1" )
        document.getElementById("ea_pub_dest_nivel").style.display = "block";

Understanding the Gemfile.lock file

It seems no clear document talking on the Gemfile.lock format. Maybe it's because Gemfile.lock is just used by bundle internally.

However, since Gemfile.lock is a snapshot of Gemfile, which means all its information should come from Gemfile (or from default value if not specified in Gemfile).

For GEM, it lists all the dependencies you introduce directly or indirectly in the Gemfile. remote under GEM tells where to get the gems, which is specified by source in Gemfile.

If a gem is not fetch from remote, PATH tells the location to find it. PATH's info comes from path in Gemfile when you declare a dependency.

And PLATFORM is from here.

For DEPENDENCIES, it's the snapshot of dependencies resolved by bundle.

Maven fails to find local artifact

When this happened to me, it was because I'd blindly copied my settings.xml from a template and it still had the blank <localRepository/> element. This means that there's no local repository used when resolving dependencies (though your installed artifacts do still get put in the default location). When I'd replaced that with <localRepository>${user.home}\.m2\repository</localRepository> it started working.

For *nix, that would be <localRepository>${user.home}/.m2/repository</localRepository>, I suppose.

SSIS Text was truncated with status value 4

If this is coming from SQL Server Import Wizard, try editing the definition of the column on the Data Source, it is 50 characters by default, but it can be longer.

Data Soruce -> Advanced -> Look at the column that goes in error -> change OutputColumnWidth to 200 and try again.

How do I make an html link look like a button?

Use below snippet.

  color: $brn-acc-clr;
  background-color: transparent;
  border-color: #888888;

    outline: none;
    color: #888888;
    border-color: #888888;
    background-color: #888888;
    color: #fff;
    box-shadow: 0 3px 10px rgba(#888888, 0.5);
      color: #fff;
      transform: translateY(-2px);
      background-color: darken(#888888, 4);

Postgresql - select something where date = "01/01/11"

With PostgreSQL there are a number of date/time functions available, see here.

In your example, you could use:

SELECT * FROM myTable WHERE date_trunc('day', dt) = 'YYYY-MM-DD';

If you are running this query regularly, it is possible to create an index using the date_trunc function as well:

CREATE INDEX date_trunc_dt_idx ON myTable ( date_trunc('day', dt) );

One advantage of this is there is some more flexibility with timezones if required, for example:

CREATE INDEX date_trunc_dt_idx ON myTable ( date_trunc('day', dt at time zone 'Australia/Sydney') );
SELECT * FROM myTable WHERE date_trunc('day', dt at time zone 'Australia/Sydney') = 'YYYY-MM-DD';

Git - Ignore node_modules folder everywhere


This works for me

recursive approach to ignore all node_modules present in sub folders

Where to place and how to read configuration resource files in servlet based application?

Ex: In web.xml file the tag

        <!--  Name of the chat properties file. It contains the name and description                   of rooms.-->     

And you can declare your properties like this

For Ex :

Jsp = Discussion about JSP can be made here.
Java = Talk about java and related technologies like J2EE.
ASP = Discuss about Active Server Pages related technologies like VBScript and JScript etc.
Web_Designing = Any discussion related to HTML, JavaScript, DHTML etc.
StartUp = Startup chat room. Chatter is added to this after he logs in.

Swift GET request with parameters

I use:

let dictionary = ["method":"login_user",
                  "password":password.text!] as  Dictionary<String,String>

for (key, value) in dictionary {

request.HTTPBody = data.dataUsingEncoding(NSUTF8StringEncoding);

Select the first row by group

now, for dplyr, adding a distinct counter.

df %>%
    group_by(aa, bb) %>%
    summarise(first=head(value,1), count=n_distinct(value))

You create groups, them summarise within groups.

If data is numeric, you can use:
first(value) [there is also last(value)] in place of head(value, 1)



> df
Source: local data frame [16 x 3]

   aa bb value
1   1  1   GUT
2   1  1   PER
3   1  2   SUT
4   1  2   GUT
5   1  3   SUT
6   1  3   GUT
7   1  3   PER
8   2  1   221
9   2  1   224
10  2  1   239
11  2  2   217
12  2  2   221
13  2  2   224
14  3  1   GUT
15  3  1   HUL
16  3  1   GUT

> library(dplyr)
> df %>%
>   group_by(aa, bb) %>%
>   summarise(first=head(value,1), count=n_distinct(value))

Source: local data frame [6 x 4]
Groups: aa

  aa bb first count
1  1  1   GUT     2
2  1  2   SUT     2
3  1  3   SUT     3
4  2  1   221     3
5  2  2   217     3
6  3  1   GUT     2

The pipe ' ' could not be found angular2 custom pipe

Custom Pipes: When a custom pipe is created, It must be registered in Module and Component that is being used.

export class SummaryPipe implements PipeTransform{
//Implementing transform

  transform(value: string, limit?: number): any { 
    if (!value) {
        return null;
    else {
        let actualLimit=limit>0?limit:50
       return value.substr(0,actualLimit)+'...'

Add Pipe Decorator


and refer

import { SummaryPipe } from '../summary.pipe';` //**In Component and Module**
    **{{text | summary}}**  //Name should same as it is mentioned in the decorator.

//summary is the name declared in Pipe decorator

Check if one date is between two dates

Try this

var gdate='01-05-2014';
        date =Date.parse(gdate.split('-')[1]+'-'+gdate.split('-')[0]+'-'+gdate.split('-')[2]);
        if(parseInt(date) < parseInt(


How can I check if a string represents an int, without using try/except?

I suggest the following:

import ast

def is_int(s):
    return isinstance(ast.literal_eval(s), int)

From the docs:

Safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.

I should note that this will raise a ValueError exception when called against anything that does not constitute a Python literal. Since the question asked for a solution without try/except, I have a Kobayashi-Maru type solution for that:

from ast import literal_eval
from contextlib import suppress

def is_int(s):
    with suppress(ValueError):
        return isinstance(literal_eval(s), int)
    return False


Changing SqlConnection timeout

If you want to provide a timeout for a particular query, then CommandTimeout is the way forward.

Its usage is:

command.CommandTimeout = 60; //The time in seconds to wait for the command to execute. The default is 30 seconds.

How to use mouseover and mouseout in Angular 6

Adding to what was already said.

if you want to *ngFor an element , and hide \ show elements in it, on hover, like you added in the comments, you should re-think the whole concept.

a more appropriate way to do it, does not involve angular at all. I would go with pure CSS instead, using its native :hover property.

something like:


div span.only-show-on-hover {
    visibility: hidden;
div:hover span.only-show-on-hover  {
    visibility: visible;


  <div *ngFor="let i of [1,2,3,4]" > hover me please.
    <span class="only-show-on-hover">you only see me when hovering</span>

added a demo:

Is there any use for unique_ptr with array?

I faced a case where I had to use std::unique_ptr<bool[]>, which was in the HDF5 library (A library for efficient binary data storage, used a lot in science). Some compilers (Visual Studio 2015 in my case) provide compression of std::vector<bool> (by using 8 bools in every byte), which is a catastrophe for something like HDF5, which doesn't care about that compression. With std::vector<bool>, HDF5 was eventually reading garbage because of that compression.

Guess who was there for the rescue, in a case where std::vector didn't work, and I needed to allocate a dynamic array cleanly? :-)

How to implement OnFragmentInteractionListener

I'd like to add the destruction of the listener when the fragment is detached from the activity or destroyed.

public void onDetach() {
    mListener = null;

and when using the new onStart() method with Context

public void onDestroy() {
    mListener = null;

Going from MM/DD/YYYY to DD-MMM-YYYY in java


You should use java.time classes with Java 8 and later. To use java.time, add:

import java.time.* ;

Below is an example, how you can format date.

DateTimeFormatter format = DateTimeFormatter.ofPattern("dd-MMM-yyyy");
String date = "15-Oct-2018";
LocalDate localDate = LocalDate.parse(date, formatter);


Extract parameter value from url using regular expressions

I use seperate custom functions which gets all URL Parameters and URL parts . For URL parameters, (which is the final part of an URI String, http://domain.tld/urlpart/?x=a&y=b

    function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
        vars[key] = value;
    return vars;

The above function will return an array consisting of url variables.

For URL Parts or functions, (which is http://domain.tld/urlpart/?x=a&y=b I use a simple uri split,

function getUrlParams() { 
    var vars = {};
    var parts = window.location.href.split('/' );
    return parts;

You can even combine them both to be able to use with a single call in a page or in javascript.

How to Avoid Response.End() "Thread was being aborted" Exception during the Excel file download

I found that the following worked better...

   private void EndResponse()
        catch (System.Threading.ThreadAbortException err)
        catch (Exception err)

Get record counts for all tables in MySQL database

 WHERE TABLE_SCHEMA = 'your_db' 

That's all you need.

Convert Python ElementTree to string

Element objects have no .getroot() method. Drop that call, and the .tostring() call works:

xmlstr = ElementTree.tostring(et, encoding='utf8', method='xml')

You only need to use .getroot() if you have an ElementTree instance.

Other notes:

  • This produces a bytestring, which in Python 3 is the bytes type.
    If you must have a str object, you have two options:

    1. Decode the resulting bytes value, from UTF-8: xmlstr.decode("utf8")

    2. Use encoding='unicode'; this avoids an encode / decode cycle:

      xmlstr = ElementTree.tostring(et, encoding='unicode', method='xml')
  • If you wanted the UTF-8 encoded bytestring value or are using Python 2, take into account that ElementTree doesn't properly detect utf8 as the standard XML encoding, so it'll add a <?xml version='1.0' encoding='utf8'?> declaration. Use utf-8 or UTF-8 (with a dash) if you want to prevent this. When using encoding="unicode" no declaration header is added.

What is the best IDE for C Development / Why use Emacs over an IDE?

How come nobody mentions Bloodshed Devc++? Havent used it in a while, but i learnt c/c++ on it. very similar to MS Visual c++.

Modulo operation with negative numbers

Can a modulus be negative?

% can be negative as it is the remainder operator, the remainder after division, not after Euclidean_division. Since C99 the result may be 0, negative or positive.

 // a % b
 7 %  3 -->  1  
 7 % -3 -->  1  
-7 %  3 --> -1  
-7 % -3 --> -1  

The modulo OP wanted is a classic Euclidean modulo, not %.

I was expecting a positive result every time.

To perform a Euclidean modulo that is well defined whenever a/b is defined, a,b are of any sign and the result is never negative:

int modulo_Euclidean(int a, int b) {
  int m = a % b;
  if (m < 0) {
    // m += (b < 0) ? -b : b; // avoid this form: it is UB when b == INT_MIN
    m = (b < 0) ? m - b : m + b;
  return m;

modulo_Euclidean( 7,  3) -->  1  
modulo_Euclidean( 7, -3) -->  1  
modulo_Euclidean(-7,  3) -->  2  
modulo_Euclidean(-7, -3) -->  2   

Increase JVM max heap size for Eclipse

It is possible to increase heap size allocated by the Java Virtual Machine (JVM) by using command line options.

-Xms<size>        set initial Java heap size
-Xmx<size>        set maximum Java heap size
-Xss<size>        set java thread stack size

If you are using the tomcat server, you can change the heap size by going to Eclipse/Run/Run Configuration and select Apache Tomcat/your_server_name/Arguments and under VM arguments section use the following:

-Xms256m -Xmx512M

If you are not using any server, you can type the following on the command line before you run your code:

java -Xms64m -Xmx256m HelloWorld

More information on increasing the heap size can be found here

Target a css class inside another css class

I use div instead of tables and am able to target classes within the main class, as below:


.main {
    .width: 800px;
    .margin: 0 auto;
    .text-align: center;
.main .table {
    width: 80%;
.main .row {
   / ***something ***/
.main .column {
    font-size: 14px;
    display: inline-block;
.main .left {
    width: 140px;
    margin-right: 5px;
    font-size: 12px;
.main .right {
    width: auto;
    margin-right: 20px;
    color: #fff;
    font-size: 13px;
    font-weight: normal;


<div class="main">
    <div class="table">
        <div class="row">
            <div class="column left">Swing Over Bed</div>
            <div class="column right">650mm</div>
            <div class="column left">Swing In Gap</div>
            <div class="column right">800mm</div>

If you want to style a particular "cell" exclusively you can use another sub-class or the id of the div e.g:

.main #red { color: red; }

<div class="main">
    <div class="table">
        <div class="row">
            <div id="red" class="column left">Swing Over Bed</div>
            <div class="column right">650mm</div>
            <div class="column left">Swing In Gap</div>
            <div class="column right">800mm</div>

How to copy to clipboard in Vim?

for OSX, like the 10342 answers above made clear, you need to make sure that vim supports the clipboard feature, said the the one that comes pre-shipped with OSX does NOT support clipboard, and that if you run brew install vim it would work.

Except that running vi will still make you run the preshipped OSX version, not the one you installed from brew.

to get over this, I simply aliased my vim command to the brew version, not the OSX default one:

alias vim="/usr/local/Cellar/vim/8.0.1100_1/bin/vim"

and now i'm golden

How can I specify a [DllImport] path at runtime?

Contrary to the suggestions by some of the other answers, using the DllImport attribute is still the correct approach.

I honestly don't understand why you can't do just like everyone else in the world and specify a relative path to your DLL. Yes, the path in which your application will be installed differs on different people's computers, but that's basically a universal rule when it comes to deployment. The DllImport mechanism is designed with this in mind.

In fact, it isn't even DllImport that handles it. It's the native Win32 DLL loading rules that govern things, regardless of whether you're using the handy managed wrappers (the P/Invoke marshaller just calls LoadLibrary). Those rules are enumerated in great detail here, but the important ones are excerpted here:

Before the system searches for a DLL, it checks the following:

  • If a DLL with the same module name is already loaded in memory, the system uses the loaded DLL, no matter which directory it is in. The system does not search for the DLL.
  • If the DLL is on the list of known DLLs for the version of Windows on which the application is running, the system uses its copy of the known DLL (and the known DLL's dependent DLLs, if any). The system does not search for the DLL.

If SafeDllSearchMode is enabled (the default), the search order is as follows:

  1. The directory from which the application loaded.
  2. The system directory. Use the GetSystemDirectory function to get the path of this directory.
  3. The 16-bit system directory. There is no function that obtains the path of this directory, but it is searched.
  4. The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.
  5. The current directory.
  6. The directories that are listed in the PATH environment variable. Note that this does not include the per-application path specified by the App Paths registry key. The App Paths key is not used when computing the DLL search path.

So, unless you're naming your DLL the same thing as a system DLL (which you should obviously not be doing, ever, under any circumstances), the default search order will start looking in the directory from which your application was loaded. If you place the DLL there during the install, it will be found. All of the complicated problems go away if you just use relative paths.

Just write:

[DllImport("MyAppDll.dll")] // relative path; just give the DLL's name
static extern bool MyGreatFunction(int myFirstParam, int mySecondParam);

But if that doesn't work for whatever reason, and you need to force the application to look in a different directory for the DLL, you can modify the default search path using the SetDllDirectory function.
Note that, as per the documentation:

After calling SetDllDirectory, the standard DLL search path is:

  1. The directory from which the application loaded.
  2. The directory specified by the lpPathName parameter.
  3. The system directory. Use the GetSystemDirectory function to get the path of this directory.
  4. The 16-bit system directory. There is no function that obtains the path of this directory, but it is searched.
  5. The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.
  6. The directories that are listed in the PATH environment variable.

So as long as you call this function before you call the function imported from the DLL for the first time, you can modify the default search path used to locate DLLs. The benefit, of course, is that you can pass a dynamic value to this function that is computed at run-time. That isn't possible with the DllImport attribute, so you will still use a relative path (the name of the DLL only) there, and rely on the new search order to find it for you.

You'll have to P/Invoke this function. The declaration looks like this:

[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool SetDllDirectory(string lpPathName);

Python sys.argv lists and indexes

As explained in the different asnwers already, sys.argv contains the command line arguments that called your Python script.

However, Python comes with libraries that help you parse command line arguments very easily. Namely, the new standard argparse. Using argparse would spare you the need to write a lot of boilerplate code.

Removing duplicate objects with Underscore for Javascript

You can do it in a shorthand as:

_.uniq(foo, 'a')

Java: how do I check if a Date is within a certain range?


ZoneId z = ZoneId.of( "America/Montreal" );  // A date only has meaning within a specific time zone. At any given moment, the date varies around the globe by zone.
LocalDate ld = 
    givenJavaUtilDate.toInstant()  // Convert from legacy class `Date` to modern class `Instant` using new methods added to old classes.
                     .atZone( z )  // Adjust into the time zone in order to determine date.
                     .toLocalDate();  // Extract date-only value.

LocalDate today = z );  // Get today’s date for specific time zone.
LocalDate kwanzaaStart = today.withMonth( Month.DECEMBER ).withDayOfMonth( 26 );  // Kwanzaa starts on Boxing Day, day after Christmas.
LocalDate kwanzaaStop = kwanzaaStart.plusWeeks( 1 );  // Kwanzaa lasts one week.
Boolean isDateInKwanzaaThisYear = (
    ( ! today.isBefore( kwanzaaStart ) ) // Short way to say "is equal to or is after".
    today.isBefore( kwanzaaStop )  // Half-Open span of time, beginning inclusive, ending is *exclusive*.


Date-time work commonly employs the "Half-Open" approach to defining a span of time. The beginning is inclusive while the ending is exclusive. So a week starting on a Monday runs up to, but does not include, the following Monday.


Java 8 and later comes with the java.time framework built-in. Supplants the old troublesome classes including java.util.Date/.Calendar and SimpleDateFormat. Inspired by the successful Joda-Time library. Defined by JSR 310. Extended by the ThreeTen-Extra project.

An Instant is a moment on the timeline in UTC with nanosecond resolution.


Convert your java.util.Date objects to Instant objects.

Instant start = myJUDateStart.toInstant();
Instant stop = …

If getting java.sql.Timestamp objects through JDBC from a database, convert to java.time.Instant in a similar way. A java.sql.Timestamp is already in UTC so no need to worry about time zones.

Instant start = mySqlTimestamp.toInstant() ;
Instant stop = …

Get the current moment for comparison.

Instant now =;

Compare using the methods isBefore, isAfter, and equals.

Boolean containsNow = ( ! now.isBefore( start ) ) && ( now.isBefore( stop ) ) ;


Perhaps you want to work with only the date, not the time-of-day.

The LocalDate class represents a date-only value, without time-of-day and without time zone.

LocalDate start = LocalDate.of( 2016 , 1 , 1 ) ;
LocalDate stop = LocalDate.of( 2016 , 1 , 23 ) ;

To get the current date, specify a time zone. At any given moment, today’s date varies by time zone. For example, a new day dawns earlier in Paris than in Montréal.

LocalDate today = ZoneId.of( "America/Montreal" ) );

We can use the isEqual, isBefore, and isAfter methods to compare. In date-time work we commonly use the Half-Open approach where the beginning of a span of time is inclusive while the ending is exclusive.

Boolean containsToday = ( ! today.isBefore( start ) ) && ( today.isBefore( stop ) ) ;


If you chose to add the ThreeTen-Extra library to your project, you could use the Interval class to define a span of time. That class offers methods to test if the interval contains, abuts, encloses, or overlaps other date-times/intervals.

The Interval class works on Instant objects. 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).

We can adjust the LocalDate into a specific moment, the first moment of the day, by specifying a time zone to get a ZonedDateTime. From there we can get back to UTC by extracting a Instant.

ZoneId z = ZoneId.of( "America/Montreal" );
Interval interval = 
        start.atStartOfDay( z ).toInstant() , 
        stop.atStartOfDay( z ).toInstant() );
Instant now =;
Boolean containsNow = interval.contains( now );

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?

  • Java SE 8 and SE 9 and later
  • Built-in.
  • Part of the standard Java API with a bundled implementation.
  • Java 9 adds some minor features and fixes.
  • Java SE 6 and SE 7
  • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
  • The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
  • See How to use….

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.

How to get a random number in Ruby

Don't forget to seed the RNG with srand() first.

How to detect when WIFI Connection has been established in Android?

You can start a wifi connection if you give the user a choice to override the normal behavior of asking each time.

I choose to use three methods...

public boolean isOnline() 
 ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
 NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
 return (networkInfo != null && networkInfo.isConnected());

This is quick check if there is an internet connect either Wifi or CellData. From here you can choose what action you want to take. Is it in Airplane mode needs to be checked also.

On a separate thread. I set a variable IpAddress to = " " And poll until I have a valid an ip address.

  WifiManager wifi;
  wifi = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
  WifiInfo wifiInfo = wifi.getConnectionInfo();
  int ipAddress = wifiInfo.getIpAddress();
  String ip = null;
  ip = String.format("%d.%d.%d.%d",
  (ipAddress & 0xff),
  (ipAddress >> 8 & 0xff),
  (ipAddress >> 16 & 0xff),
  (ipAddress >> 24 & 0xff));
  Log.e(" >>IP number Begin ",ip);

Another code snippet... If its not on turn it on (with users prior permission)


Changing ImageView source


is used for setting image in the current image view, but if want to delete this image then you can use this code like:

((ImageView) v.findViewById(;

now this will delete the image from your image view, because it has set the resources value to zero.

Visual Studio 2012 Web Publish doesn't copy files

I had this same problem however none of the answers in this thread worked for me. My issue was that there is a directory that contains dynamically generated (by my app) static HTML files. The entire directory was not being published.

The solution that worked for me was found here:

One issue I got a while back and thought I should document was that certain file types were not being uploaded when I published my project.

The file types in question were .pdf files and .rtf.

The reason this happened was because these file extensions were not recognized as requiring publishing by Visual Studio. Luckily this can be changed in Visual Studio.

Select the file(s) that aren’t being copied. In Properties ensure that Build Action is set to Content.

If this doesn’t work the following can be tried.

Under the Project menu select Package/Publish Web and notice this drop down:

enter image description here

Try changing this to All files in this project folder.

How to get address of a pointer in c/c++?

To get the address of p do:

int **pp = &p;

and you can go on:

int ***ppp = &pp;
int ****pppp = &ppp;

or, only in C++11, you can do:

auto pp = std::addressof(p);

To print the address in C, most compilers support %p, so you can simply do:

printf("addr: %p", pp);

otherwise you need to cast it (assuming a 32 bit platform)

printf("addr: 0x%u", (unsigned)pp);

In C++ you can do:

cout << "addr: " << pp;

How to use log4net in core 2.0

Click here to learn how to implement log4net in .NET Core 2.2

The following steps are taken from the above link, and break down how to add log4net to a .NET Core 2.2 project.

First, run the following command in the Package-Manager console:

Install-Package Log4Net_Logging -Version 1.0.0

Then add a log4net.config with the following information (please edit it to match your set up):

<?xml version="1.0" encoding="utf-8" ?>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
    <appender name="FileAppender" type="log4net.Appender.FileAppender">
      <file value="logfile.log" />
      <appendToFile value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%d [%t] %-5p - %m%n" />
      <!--LogLevel: OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL -->
      <level value="ALL" />
      <appender-ref ref="FileAppender" />

Then, add the following code into a controller (this is an example, please edit it before adding it to your controller):

public ValuesController()
    LogFourNet.SetUp(Assembly.GetEntryAssembly(), "log4net.config");
// GET api/values
public ActionResult<IEnumerable<string>> Get()
    LogFourNet.Info(this, "This is Info logging");
    LogFourNet.Debug(this, "This is Debug logging");
    LogFourNet.Error(this, "This is Error logging");    
    return new string[] { "value1", "value2" };

Then call the relevant controller action (using the above example, call /Values/Get with an HTTP GET), and you will receive the output matching the following:

2019-06-05 19:58:45,103 [9] INFO-[Log4NetLogging_Project.Controllers.ValuesController.Get:23] - This is Info logging

phpmyadmin logs out after 1440 secs

You just Increase the phpMyAdmin Session Timeout, open in the root phpMyAdmin directory and add this line.

from the wamp folder path wamp\apps\phpmyadmin4.0.4\

$cfg['LoginCookieValidity'] = <your_timeout>;


$cfg['LoginCookieValidity'] = '1440';

Note: short cookie lifetime is all well and good for the development server not for your production server.

How to use addTarget method in swift 3

Try this

button.addTarget(self, action:#selector(handleRegister()), for: .touchUpInside). 

Just add parenthesis with name of method.

Also you can refer link : Value of type 'CustomButton' has no member 'touchDown'

Facebook API "This app is in development mode"

I had also faced the same issue in which my FB app was automatically stopped and users were not able to login and were getting the message "app is in development mode.....".

Reason why FB automatically stopped my app was that I had not provided a valid PRIVACY policy & terms URL. So, make sure you enter these URLs on your app basic settings page and then make your app PUBLIC from app review page as described in above posts.

Error # 1045 - Cannot Log in to MySQL server -> phpmyadmin

You need to do two additional things after following the link that you have mentioned in your post:

One have to map the changed login cridentials in phpmyadmin's

and second, you need to restart your web and mysql servers..

php version is not the issue need to go to phpmyadmin installation directory and find file and in that file put your current mysql password at line

$cfg['Servers'][$i]['user'] = 'root'; //mysql username here
$cfg['Servers'][$i]['password'] = 'password'; //mysql password here

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

the solustion when we use routes like this:

Route::get('/', function () {
    return view('welcome');

laravel call them Closure so you cant optimize routes uses as Closures you must route to controller to use php artisan optimize

How to change the map center in Leaflet.js

Use map.panTo(); does not do anything if the point is in the current view. Use map.setView() instead.

I had a polyline and I had to center map to a new point in polyline at every second. Check the code : GOOD:

mymap.setView(point, 11, { animation: true });        



How to locate the php.ini file (xampp)

in my case it is present as "php.ini-development" and "php.ini-production" in php folder

How to pass a value to razor variable from javascript variable?

Okay, so this question is old... but I wanted to do something similar and I found a solution that works for me. Maybe it might help someone else.

I have a List<QuestionType> that I fill a drop down with. I want to put that selection into the QuestionType property on the Question object that I'm creating in the form. I'm using Knockout.js for the select binding. This sets the self.QuestionType knockout observable property to a QuestionType object when the user selects one.

<select class="form-control form-control-sm"
    data-bind="options: QuestionTypes, optionsText: 'QuestionTypeText', value: QuestionType, optionsCaption: 'Choose...'">

I have a hidden field that will hold this object:

@Html.Hidden("NewQuestion.QuestionTypeJson", Model.NewQuestion.QuestionTypeJson)

In the subscription for the observable, I set the hidden field to a JSON.stringify-ed version of the object.

self.QuestionType.subscribe(function(newValue) {
    if (newValue !== null && newValue !== undefined) {                       
        document.getElementById('NewQuestion_QuestionTypeJson').value = JSON.stringify(newValue);

In the Question object, I have a field called QuestionTypeJson that is filled when the user selects a question type. I use this field to get the QuestionType in the Question object like this:

public string QuestionTypeJson { get; set; }

private QuestionType _questionType = new QuestionType();
public QuestionType QuestionType
    get => string.IsNullOrEmpty(QuestionTypeJson) ? _questionType : JsonConvert.DeserializeObject<QuestionType>(QuestionTypeJson);
    set => _questionType = value;

So if the QuestionTypeJson field contains something, it will deserialize that and use it for QuestionType, otherwise it'll just use what is in the backing field.

I have essentially 'passed' a JavaScript object to my model without using Razor or an Ajax call. You can probably do something similar to this without using Knockout.js, but that's what I'm using so...

How to set time zone of a java.util.Date?


…parsed … from a String … time zone is not specified … I want to set a specific time zone

LocalDateTime.parse( "2018-01-23T01:23:45.123456789" )  // Parse string, lacking an offset-from-UTC and lacking a time zone, as a `LocalDateTime`.
    .atZone( ZoneId.of( "Africa/Tunis" ) )              // Assign the time zone for which you are certain this date-time was intended. Instantiates a `ZonedDateTime` object.

No Time Zone in j.u.Date

As the other correct answers stated, a java.util.Date has no time zone. It represents UTC/GMT (no time zone offset). Very confusing because its toString method applies the JVM's default time zone when generating a String representation.

Avoid j.u.Date

For this and many other reasons, you should avoid using the built-in java.util.Date & .Calendar & java.text.SimpleDateFormat. They are notoriously troublesome.

Instead use the java.time package bundled with Java 8.


The java.time classes can represent a moment on the timeline in three ways:

  • UTC (Instant)
  • With an offset (OffsetDateTime with ZoneOffset)
  • With a time zone (ZonedDateTime with ZoneId)


In java.time, the basic building block is Instant, a moment on the time line in UTC. Use Instant objects for much of your business logic.

Instant instant =;


Apply an offset-from-UTC to adjust into some locality’s wall-clock time.

Apply a ZoneOffset to get an OffsetDateTime.

ZoneOffset zoneOffset = ZoneOffset.of( "-04:00" );
OffsetDateTime odt = OffsetDateTime.ofInstant( instant , zoneOffset );


Better is to apply a time zone, an offset plus the rules for handling anomalies such as Daylight Saving Time (DST).

Apply a ZoneId to an Instant to get a ZonedDateTime. Always specify a proper time zone name. Never use 3-4 abbreviations such as EST or IST that are neither unique nor standardized.

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );


If the input string lacked any indicator of offset or zone, parse as a LocalDateTime.

If you are certain of the intended time zone, assign a ZoneId to produce a ZonedDateTime. See code example above in tl;dr section at top.

Formatted Strings

Call the toString method on any of these three classes to generate a String representing the date-time value in standard ISO 8601 format. The ZonedDateTime class extends standard format by appending the name of the time zone in brackets.

String outputInstant = instant.toString(); // Ex: 2011-12-03T10:15:30Z
String outputOdt = odt.toString(); // Ex: 2007-12-03T10:15:30+01:00
String outputZdt = zdt.toString(); // Ex: 2007-12-03T10:15:30+01:00[Europe/Paris]

For other formats use the DateTimeFormatter class. Generally best to let that class generate localized formats using the user’s expected human language and cultural norms. Or you can specify a particular format.

Table of all date-time types in Java, both modern and legacy

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.

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

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

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?


While Joda-Time is still actively maintained, its makers have told us to migrate to java.time as soon as is convenient. I leave this section intact as a reference, but I suggest using the java.time section above instead.

In Joda-Time, a date-time object (DateTime) truly does know its assigned time zone. That means an offset from UTC and the rules and history of that time zone’s Daylight Saving Time (DST) and other such anomalies.

String input = "2014-01-02T03:04:05";
DateTimeZone timeZone = DateTimeZone.forID( "Asia/Kolkata" );
DateTime dateTimeIndia = new DateTime( input, timeZone );
DateTime dateTimeUtcGmt = dateTimeIndia.withZone( DateTimeZone.UTC );

Call the toString method to generate a String in ISO 8601 format.

String output = dateTimeIndia.toString();

Joda-Time also offers rich capabilities for generating all kinds of other String formats.

If required, you can convert from Joda-Time DateTime to a java.util.Date.

Java.util.Date date = dateTimeIndia.toDate();

Search StackOverflow for "joda date" to find many more examples, some quite detailed.

Actually there is a time zone embedded in a java.util.Date, used for some internal functions (see comments on this Answer). But this internal time zone is not exposed as a property, and cannot be set. This internal time zone is not the one used by the toString method in generating a string representation of the date-time value; instead the JVM’s current default time zone is applied on-the-fly. So, as shorthand, we often say “j.u.Date has no time zone”. Confusing? Yes. Yet another reason to avoid these tired old classes.

Automatic creation date for Django model form objects?

You can use the auto_now and auto_now_add options for updated_at and created_at respectively.

class MyModel(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

How can I generate a 6 digit unique number?

I would use an algorithm, brute force could be as follows:

First time through loop: Generate a random number between 100,000 through 999,999 and call that x1

Second time through the loop Generate a random number between 100,000 and x1 call this xt2, then generate a random number between x1 and 999,999 call this xt3, then randomly choose x2 or x3, call this x2

Nth time through the loop Generate random number between 100,000 and x1, x1 and x2, and x2 through 999,999 and so forth...

watch out for endpoints, also watch out for x1

How to dismiss notification after action has been clicked

I found that when you use the action buttons in expanded notifications, you have to write extra code and you are more constrained.

You have to manually cancel your notification when the user clicks an action button. The notification is only cancelled automatically for the default action.

Also if you start a broadcast receiver from the button, the notification drawer doesn't close.

I ended up creating a new NotificationActivity to address these issues. This intermediary activity without any UI cancels the notification and then starts the activity I really wanted to start from the notification.

I've posted sample code in a related post Clicking Android Notification Actions does not close Notification drawer.

Changing Java Date one hour back

This can be achieved using java.util.Date. The following code will subtract 1 hour from your date.

Date date = new Date(yourdate in date format);
Date newDate = DateUtils.addHours(date, -1)

Similarly for subtracting 20 seconds from your date

newDate = DateUtils.addSeconds(date, -20)    

Check if a string contains a string in C++

You can try this

string s1 = "Hello";
string s2 = "el";
   cout << " S1 Contains S2";

W3WP.EXE using 100% CPU - where to start?

It's not much of an answer, but you might need to go old school and capture an image snapshot of the IIS process and debug it. You might also want to check out Tess Ferrandez's blog - she is a kick a** microsoft escalation engineer and her blog focuses on debugging windows ASP.NET, but the blog is relevant to windows debugging in general. If you select the ASP.NET tag (which is what I've linked to) then you'll see several items that are similar.

What certificates are trusted in truststore?

Is there any equivalent for the truststore? How can I view the trusted certificates?

Yes there is.The exact same command since keystore and truststore differ only in what they store i.e. private key or signed public key (certificate)

No other difference

At least one JAR was scanned for TLDs yet contained no TLDs


If you want to enable debug logging in tomcat for TLD scanned jars then you have to change /conf/ file in tomcat directory.

uncomment the line :
org.apache.jasper.servlet.TldScanner.level = FINE

FINE level is for debug log.

This should work for normal tomcat.

If the tomcat is running under eclipse. Then you have to set the path of tomcat in eclipse.

  1. Open servers view in eclipse.Stop the server.Double click your tomcat server.
    This will open Overview window for the server.
  2. Click on Open launch configuration.This will open another window.
  3. Go to the Arguments tab(second tab).Go to VM arguments section.
  4. paste this two line there :-
    Here CATALINA_HOME is your PC's corresponding tomcat server directory.
  5. Save the Changes.Restart the server.

Now the jar files that scanned for TLDs should show in the log.

Spring Boot and multiple external configuration files

I had the same problem. I wanted to have the ability to overwrite an internal configuration file at startup with an external file, similar to the Spring Boot detection. In my case it's a file where my applications users are stored.

My requirements:

Load the file from the following locations (in this order)

  1. The classpath
  2. A /config subdir of the current directory.
  3. The current directory
  4. From directory or a file location given by a command line parameter at startup

I came up with the following solution:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;

import java.util.Properties;

import static;

public class PropertiesConfig {

    private static final Logger LOG = LoggerFactory.getLogger(PropertiesConfig.class);

    private final static String PROPERTIES_FILENAME = "";

    private String propertiesLocation;

    Properties userProperties() throws IOException {
        final Resource[] possiblePropertiesResources = {
                new ClassPathResource(PROPERTIES_FILENAME),
                new PathResource("config/" + PROPERTIES_FILENAME),
                new PathResource(PROPERTIES_FILENAME),
                new PathResource(getCustomPath())
        // Find the last existing properties location to emulate spring boot discovery
        final Resource propertiesResource = stream(possiblePropertiesResources)
                .reduce((previous, current) -> current)
        final Properties userProperties = new Properties();

        userProperties.load(propertiesResource.getInputStream());"Using {} as user resource", propertiesResource);

        return userProperties;

    private String getCustomPath() {
        return propertiesLocation.endsWith(".properties") ? propertiesLocation : propertiesLocation + PROPERTIES_FILENAME;


Now the application uses the classpath resource, but checks for a resource at the other given locations too. The last resource which exists will be picked and used. I'm able to start my app with java -jar myapp.jar --properties.location=/directory/ to use an properties location which floats my boat.

An important detail here: Use an empty String as default value for the properties.location in the @Value annotation to avoid errors when the property is not set.

The convention for a properties.location is: Use a directory or a path to a properties file as properties.location.

If you want to override only specific properties, a PropertiesFactoryBean with setIgnoreResourceNotFound(true) can be used with the resource array set as locations.

I'm sure that this solution can be extended to handle multiple files...


Here my solution for multiple files :) Like before, this can be combined with a PropertiesFactoryBean.

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;
import java.util.Properties;

import static;
import static;

class PropertiesConfig {

    private final static Logger LOG = LoggerFactory.getLogger(PropertiesConfig.class);
    private final static String[] PROPERTIES_FILENAMES = {"", "", ""};

    private String propertiesLocation;

    Map<String, Properties> myProperties() {
        return stream(PROPERTIES_FILENAMES)
                .collect(toMap(filename -> filename, this::loadProperties));

    private Properties loadProperties(final String filename) {
        final Resource[] possiblePropertiesResources = {
                new ClassPathResource(filename),
                new PathResource("config/" + filename),
                new PathResource(filename),
                new PathResource(getCustomPath(filename))
        final Resource resource = stream(possiblePropertiesResources)
                .reduce((previous, current) -> current)
        final Properties properties = new Properties();

        try {
        } catch(final IOException exception) {
            throw new RuntimeException(exception);
        }"Using {} as user resource", resource);

        return properties;

    private String getCustomPath(final String filename) {
        return propertiesLocation.endsWith(".properties") ? propertiesLocation : propertiesLocation + filename;


How can I turn a DataTable to a CSV?

Try changing sb.Append(Environment.NewLine); to sb.AppendLine();.

StringBuilder sb = new StringBuilder();          
foreach (DataColumn col in dt.Columns)         
    sb.Append(col.ColumnName + ',');         

sb.Remove(sb.Length - 1, 1);         

foreach (DataRow row in dt.Rows)         
    for (int i = 0; i < dt.Columns.Count; i++)             
        sb.Append(row[i].ToString() + ",");             


File.WriteAllText("test.csv", sb.ToString());

Xcode 8 shows error that provisioning profile doesn't include signing certificate

I unchecked and then checked the "Automatically manage signing" option. That fixed it for me.

Comparing two hashmaps for equal values and same key sets?

if you have two maps lets say map1 and map2 then using java8 Streams,we can compare maps using code below.But it is recommended to use equals rather then != or ==

boolean b = map1.entrySet().stream().filter(value -> 
            map2.entrySet().stream().anyMatch(value1 -> 
            (value1.getKey().equals(value.getKey()) && 

System.out.println("comparison  "+b);

Hive ParseException - cannot recognize input near 'end' 'string'

The issue isn't actually a syntax error, the Hive ParseException is just caused by a reserved keyword in Hive (in this case, end).

The solution: use backticks around the offending column name:

CREATE EXTERNAL TABLE moveProjects (cid string, `end` string, category string)
STORED BY 'org.apache.hadoop.hive.dynamodb.DynamoDBStorageHandler'
TBLPROPERTIES ("" = "Projects",
    "dynamodb.column.mapping" = "cid:cid,end:end,category:category");

With the added backticks around end, the query works as expected.

Reserved words in Amazon Hive (as of February 2013):


Source: This Hive ticket from the Facebook Phabricator tracker

Get list from pandas dataframe column or row?

As this question attained a lot of attention and there are several ways to fulfill your task, let me present several options.

Those are all one-liners by the way ;)

Starting with:

  cluster load_date budget actual fixed_price
0       A  1/1/2014   1000   4000           Y
1       A  2/1/2014  12000  10000           Y
2       A  3/1/2014  36000   2000           Y
3       B  4/1/2014  15000  10000           N
4       B  4/1/2014  12000  11500           N
5       B  4/1/2014  90000  11000           N
6       C  7/1/2014  22000  18000           N
7       C  8/1/2014  30000  28960           N
8       C  9/1/2014  53000  51200           N

Overview of potential operations:

ser_aggCol (collapse each column to a list)
cluster          [A, A, A, B, B, B, C, C, C]
load_date      [1/1/2014, 2/1/2014, 3/1/2...
budget         [1000, 12000, 36000, 15000...
actual         [4000, 10000, 2000, 10000,...
fixed_price      [Y, Y, Y, N, N, N, N, N, N]
dtype: object

ser_aggRows (collapse each row to a list)
0     [A, 1/1/2014, 1000, 4000, Y]
1    [A, 2/1/2014, 12000, 10000...
2    [A, 3/1/2014, 36000, 2000, Y]
3    [B, 4/1/2014, 15000, 10000...
4    [B, 4/1/2014, 12000, 11500...
5    [B, 4/1/2014, 90000, 11000...
6    [C, 7/1/2014, 22000, 18000...
7    [C, 8/1/2014, 30000, 28960...
8    [C, 9/1/2014, 53000, 51200...
dtype: object

df_gr (here you get lists for each cluster)
                             load_date                 budget                 actual fixed_price
A        [1/1/2014, 2/1/2014, 3/1/2...   [1000, 12000, 36000]    [4000, 10000, 2000]   [Y, Y, Y]
B        [4/1/2014, 4/1/2014, 4/1/2...  [15000, 12000, 90000]  [10000, 11500, 11000]   [N, N, N]
C        [7/1/2014, 8/1/2014, 9/1/2...  [22000, 30000, 53000]  [18000, 28960, 51200]   [N, N, N]

a list of separate dataframes for each cluster

df for cluster A
  cluster load_date budget actual fixed_price
0       A  1/1/2014   1000   4000           Y
1       A  2/1/2014  12000  10000           Y
2       A  3/1/2014  36000   2000           Y

df for cluster B
  cluster load_date budget actual fixed_price
3       B  4/1/2014  15000  10000           N
4       B  4/1/2014  12000  11500           N
5       B  4/1/2014  90000  11000           N

df for cluster C
  cluster load_date budget actual fixed_price
6       C  7/1/2014  22000  18000           N
7       C  8/1/2014  30000  28960           N
8       C  9/1/2014  53000  51200           N

just the values of column load_date
0    1/1/2014
1    2/1/2014
2    3/1/2014
3    4/1/2014
4    4/1/2014
5    4/1/2014
6    7/1/2014
7    8/1/2014
8    9/1/2014
Name: load_date, dtype: object

just the values of column number 2
0     1000
1    12000
2    36000
3    15000
4    12000
5    90000
6    22000
7    30000
8    53000
Name: budget, dtype: object

just the values of row number 7
cluster               C
load_date      8/1/2014
budget            30000
actual            28960
fixed_price           N
Name: 7, dtype: object

============================== JUST FOR COMPLETENESS ==============================

you can convert a series to a list
['C', '8/1/2014', '30000', '28960', 'N']
<class 'list'>

you can convert a dataframe to a nested list
[['A', '1/1/2014', '1000', '4000', 'Y'], ['A', '2/1/2014', '12000', '10000', 'Y'], ['A', '3/1/2014', '36000', '2000', 'Y'], ['B', '4/1/2014', '15000', '10000', 'N'], ['B', '4/1/2014', '12000', '11500', 'N'], ['B', '4/1/2014', '90000', '11000', 'N'], ['C', '7/1/2014', '22000', '18000', 'N'], ['C', '8/1/2014', '30000', '28960', 'N'], ['C', '9/1/2014', '53000', '51200', 'N']]
<class 'list'>

the content of a dataframe can be accessed as a numpy.ndarray
[['A' '1/1/2014' '1000' '4000' 'Y']
 ['A' '2/1/2014' '12000' '10000' 'Y']
 ['A' '3/1/2014' '36000' '2000' 'Y']
 ['B' '4/1/2014' '15000' '10000' 'N']
 ['B' '4/1/2014' '12000' '11500' 'N']
 ['B' '4/1/2014' '90000' '11000' 'N']
 ['C' '7/1/2014' '22000' '18000' 'N']
 ['C' '8/1/2014' '30000' '28960' 'N']
 ['C' '9/1/2014' '53000' '51200' 'N']]
<class 'numpy.ndarray'>


# prefix ser refers to pd.Series object
# prefix df refers to pd.DataFrame object
# prefix lst refers to list object

import pandas as pd
import numpy as np

        ['A',   '1/1/2014',    '1000',    '4000',    'Y'],
        ['A',   '2/1/2014',    '12000',   '10000',   'Y'],
        ['A',   '3/1/2014',    '36000',   '2000',    'Y'],
        ['B',   '4/1/2014',    '15000',   '10000',   'N'],
        ['B',   '4/1/2014',    '12000',   '11500',   'N'],
        ['B',   '4/1/2014',    '90000',   '11000',   'N'],
        ['C',   '7/1/2014',    '22000',   '18000',   'N'],
        ['C',   '8/1/2014',    '30000',   '28960',   'N'],
        ['C',   '9/1/2014',    '53000',   '51200',   'N']
        ], columns=['cluster', 'load_date',   'budget',  'actual',  'fixed_price'])
print('df',df, sep='\n', end='\n\n')

ser_aggCol=df.aggregate(lambda x: [x.tolist()], axis=0).map(lambda x:x[0])
print('ser_aggCol (collapse each column to a list)',ser_aggCol, sep='\n', end='\n\n\n')

print('ser_aggRows (collapse each row to a list)',ser_aggRows, sep='\n', end='\n\n\n')

df_gr=df.groupby('cluster').agg(lambda x: list(x))
print('df_gr (here you get lists for each cluster)',df_gr, sep='\n', end='\n\n\n')

lst_dfFiltGr=[ df.loc[df['cluster']==val,:] for val in df['cluster'].unique() ]
print('a list of separate dataframes for each cluster', sep='\n', end='\n\n')
for dfTmp in lst_dfFiltGr:
    print('df for cluster '+str(dfTmp.loc[dfTmp.index[0],'cluster']),dfTmp, sep='\n', end='\n\n')

print('just the values of column load_date',ser_singleColLD, sep='\n', end='\n\n\n')

print('just the values of column number 2',ser_singleCol2, sep='\n', end='\n\n\n')

print('just the values of row number 7',ser_singleRow7, sep='\n', end='\n\n\n')

print('='*30+' JUST FOR COMPLETENESS '+'='*30, end='\n\n\n')

print('you can convert a series to a list',lst_fromSer, type(lst_fromSer), sep='\n', end='\n\n\n')

print('you can convert a dataframe to a nested list',lst_fromDf, type(lst_fromDf), sep='\n', end='\n\n')

print('the content of a dataframe can be accessed as a numpy.ndarray',arr_fromDf, type(arr_fromDf), sep='\n', end='\n\n')

as pointed out by cs95 other methods should be preferred over pandas .values attribute from pandas version 0.24 on see here. I use it here, because most people will (by 2019) still have an older version, which does not support the new recommendations. You can check your version with print(pd.__version__)

How to use support FileProvider for sharing content to other apps?

Since as Phil says in his comment on the original question, this is unique and there is no other info on SO on in google, I thought I should also share my results:

In my app FileProvider worked out of the box to share files using the share intent. There was no special configuration or code necessary, beyond that to setup the FileProvider. In my manifest.xml I placed:

        android:grantUriPermissions="true" >
            android:resource="@xml/my_paths" />

In my_paths.xml I have:

<paths xmlns:android="">
    <files-path name="files" path="." />

In my code I have:

    Intent shareIntent = new Intent();

    Uri uri = FileProvider.getUriForFile(this, "", fileToShare);
    shareIntent.putExtra(Intent.EXTRA_STREAM, uri);

    startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.share_file)));

And I am able to share my files store in my apps private storage with apps such as Gmail and google drive without any trouble.

Change type of varchar field to integer: "cannot be cast automatically to type integer"

this worked for me.

change varchar column to int

change_column :table_name, :column_name, :integer


PG::DatatypeMismatch: ERROR:  column "column_name" cannot be cast automatically to type integer
HINT:  Specify a USING expression to perform the conversion.

chnged to

change_column :table_name, :column_name, 'integer USING CAST(column_name AS integer)'

How to detect the physical connected state of a network cable/connector?

You can use ethtool:

$ sudo ethtool eth0
Settings for eth0:
    Supported ports: [ TP ]
    Supported link modes:   10baseT/Half 10baseT/Full
                            100baseT/Half 100baseT/Full
    Supports auto-negotiation: Yes
    Advertised link modes:  10baseT/Half 10baseT/Full
                            100baseT/Half 100baseT/Full
    Advertised auto-negotiation: Yes
    Speed: 1000Mb/s
    Duplex: Full
    Port: Twisted Pair
    PHYAD: 0
    Transceiver: internal
    Auto-negotiation: on
    Supports Wake-on: umbg
    Wake-on: g
    Current message level: 0x00000007 (7)
    Link detected: yes

To only get the Link status you can use grep:

$ sudo ethtool eth0 | grep Link
    Link detected: yes

How to call function on child component on parent events

Calling child component in parent

<component :is="my_component" ref="my_comp"></component>
<v-btn @click="$refs.my_comp.alertme"></v-btn>

in Child component



SmartGit Installation and Usage on Ubuntu

You can add a PPA that provides a relatively current version of SmartGit(as well as SmartGitHg, the predecessor of SmartGit).

To add the PPA run:

sudo add-apt-repository ppa:eugenesan/ppa
sudo apt-get update

To install smartgit (after adding the PPA) run:

sudo apt-get install smartgit

To install smartgithg (after adding the PPA) run:

sudo apt-get install smartgithg

This should add a menu option for you

For more information, see Eugene San PPA.

This repository contains collection of customized, updated, ported and backported packages for two last LTS releases and latest pre-LTS release

How to find locked rows in Oracle

Look at the dba_blockers, dba_waiters and dba_locks for locking. The names should be self explanatory.

You could create a job that runs, say, once a minute and logged the values in the dba_blockers and the current active sql_id for that session. (via v$session and v$sqlstats).

You may also want to look in v$sql_monitor. This will be default log all SQL that takes longer than 5 seconds. It is also visible on the "SQL Monitoring" page in Enterprise Manager.

Tri-state Check box in HTML?

Building on the answers above using the indeterminate state, I've come up with a little bit that handles individual checkboxes and makes them tri-state.

MVC razor uses 2 inputs per checkbox anyway (the checkbox and a hidden with the same name to always force a value in the submit). MVC uses things like "true" as the checkbox value and "false" as the hidden of the same name; makes it amenable to boolean use in api calls. This snippet uses an third hidden to persist the last request values across submits.

Checkboxes initialized with the below will start indeterminate. Checking once turns on the checkbox. Checking twice turns off the checkbox (returning the hidden value of the same name). Checking a third time returns it to indeterminate (and clears out the hidden so a submit will produce a blank).

The page also populates another hidden (e.g. triBox2Orig) with whatever value was on the query string to start, so the 3 states can be initialized and persisted between submits.

$(document).ready(function () {
    var initCheckbox = function (chkBox)
        var hidden = $('[name="' + $(chkBox).prop("name") + '"][type="hidden"]');
        var hiddenOrig = $('[name="' + $(chkBox).prop("name") + 'Orig"][type="hidden"]').prop("value");
        hidden.prop("origValue", hidden.prop("value"));
        if (!chkBox.prop("checked") && !hiddenOrig) chkBox.prop("indeterminate", true);
        if (chkBox.prop("indeterminate")) hidden.prop("value", null);

    var checkBoxToggleFun = function ()
        var isChecked = $(this).prop('checked');
        var hidden = $('[name="' + $(this).prop("name") + '"][type="hidden"]');
        var thirdState = isChecked && hidden.prop("value") === hidden.prop("origValue");
        if (thirdState) {   // on 3rd click of a checkbox, set it back to indeterminate
            $(this).prop("indeterminate", true);
            $(this).prop('checked', false);
        hidden.prop("value", thirdState ? null : hidden.prop("origValue"));

    var chkBox = $('#triBox1');

    chkBox = $('#triBox2');

Pass a PHP string to a JavaScript variable (and escape newlines)

Micah's solution below worked for me as the site I had to customise was not in UTF-8, so I could not use json; I'd vote it up but my rep isn't high enough.

function escapeJavaScriptText($string) 
    return str_replace("\n", '\n', str_replace('"', '\"', addcslashes(str_replace("\r", '', (string)$string), "\0..\37'\\"))); 

SQL query: Delete all records from the table except latest N?

I know I'm resurrecting quite an old question, but I recently ran into this issue, but needed something that scales to large numbers well. There wasn't any existing performance data, and since this question has had quite a bit of attention, I thought I'd post what I found.

The solutions that actually worked were the Alex Barrett's double sub-query/NOT IN method (similar to Bill Karwin's), and Quassnoi's LEFT JOIN method.

Unfortunately both of the above methods create very large intermediate temporary tables and performance degrades quickly as the number of records not being deleted gets large.

What I settled on utilizes Alex Barrett's double sub-query (thanks!) but uses <= instead of NOT IN:

DELETE FROM `test_sandbox`
  WHERE id <= (
    SELECT id
    FROM (
      SELECT id
      FROM `test_sandbox`
      ORDER BY id DESC
      LIMIT 1 OFFSET 42 -- keep this many records
    ) foo

It uses OFFSET to get the id of the Nth record and deletes that record and all previous records.

Since ordering is already an assumption of this problem (ORDER BY id DESC), <= is a perfect fit.

It is much faster, since the temporary table generated by the subquery contains just one record instead of N records.

Test case

I tested the three working methods and the new method above in two test cases.

Both test cases use 10000 existing rows, while the first test keeps 9000 (deletes the oldest 1000) and the second test keeps 50 (deletes the oldest 9950).

|           | 10000 TOTAL, KEEP 9000 | 10000 TOTAL, KEEP 50 |
| NOT IN    |         3.2542 seconds |       0.1629 seconds |
| NOT IN v2 |         4.5863 seconds |       0.1650 seconds |
| <=,OFFSET |         0.0204 seconds |       0.1076 seconds |

What's interesting is that the <= method sees better performance across the board, but actually gets better the more you keep, instead of worse.

automating telnet session using bash scripts

This worked for me..

I was trying to automate multiple telnet logins which require a username and password. The telnet session needs to run in the background indefinitely since I am saving logs from different servers to my machine. automates telnet login using the 'expect' command. More info can be found here:

set timeout 20
set hostName [lindex $argv 0]
set userName [lindex $argv 1]
set password [lindex $argv 2]

spawn telnet $hostName

expect "User Access Verification"
expect "Username:"
send "$userName\r"
expect "Password:"
send "$password\r";
interact is used to create a background process for each of the telnet sessions by running More information can be found in the comments section of the code.

#start screen in detached mode with session-name 'default_session' 
screen -dmS default_session -t screen_name 
#save the generated logs in a log file 'abc.log' 
screen -S default_session -p screen_name -X stuff "script -f /tmp/abc.log $(printf \\r)"
#start the telnet session and generate logs
screen -S default_session -p screen_name -X stuff "expect hostname username password $(printf \\r)"
  1. Make sure there is no screen running in the backgroud by using the command 'screen -ls'.
  2. Read to read more about screen and its options.
  3. '-p' option in preselects and reattaches to a specific window to send a command via the ‘-X’ option otherwise you get a 'No screen session found' error.

How do I lowercase a string in Python?

How to convert string to lowercase in Python?

Is there any way to convert an entire user inputted string from uppercase, or even part uppercase to lowercase?

E.g. Kilometers --> kilometers

The canonical Pythonic way of doing this is

>>> 'Kilometers'.lower()

However, if the purpose is to do case insensitive matching, you should use case-folding:

>>> 'Kilometers'.casefold()

Here's why:

>>> "Maße".casefold()
>>> "Maße".lower()
>>> "MASSE" == "Maße"
>>> "MASSE".lower() == "Maße".lower()
>>> "MASSE".casefold() == "Maße".casefold()

This is a str method in Python 3, but in Python 2, you'll want to look at the PyICU or py2casefold - several answers address this here.

Unicode Python 3

Python 3 handles plain string literals as unicode:

>>> string = '????????'
>>> string
>>> string.lower()

Python 2, plain string literals are bytes

In Python 2, the below, pasted into a shell, encodes the literal as a string of bytes, using utf-8.

And lower doesn't map any changes that bytes would be aware of, so we get the same string.

>>> string = '????????'
>>> string
>>> string.lower()
>>> print string.lower()

In scripts, Python will object to non-ascii (as of Python 2.5, and warning in Python 2.4) bytes being in a string with no encoding given, since the intended coding would be ambiguous. For more on that, see the Unicode how-to in the docs and PEP 263

Use Unicode literals, not str literals

So we need a unicode string to handle this conversion, accomplished easily with a unicode string literal, which disambiguates with a u prefix (and note the u prefix also works in Python 3):

>>> unicode_literal = u'????????'
>>> print(unicode_literal.lower())

Note that the bytes are completely different from the str bytes - the escape character is '\u' followed by the 2-byte width, or 16 bit representation of these unicode letters:

>>> unicode_literal
>>> unicode_literal.lower()

Now if we only have it in the form of a str, we need to convert it to unicode. Python's Unicode type is a universal encoding format that has many advantages relative to most other encodings. We can either use the unicode constructor or str.decode method with the codec to convert the str to unicode:

>>> unicode_from_string = unicode(string, 'utf-8') # "encoding" unicode from string
>>> print(unicode_from_string.lower())
>>> string_to_unicode = string.decode('utf-8') 
>>> print(string_to_unicode.lower())
>>> unicode_from_string == string_to_unicode == unicode_literal

Both methods convert to the unicode type - and same as the unicode_literal.

Best Practice, use Unicode

It is recommended that you always work with text in Unicode.

Software should only work with Unicode strings internally, converting to a particular encoding on output.

Can encode back when necessary

However, to get the lowercase back in type str, encode the python string to utf-8 again:

>>> print string
>>> string
>>> string.decode('utf-8')
>>> string.decode('utf-8').lower()
>>> string.decode('utf-8').lower().encode('utf-8')
>>> print string.decode('utf-8').lower().encode('utf-8')

So in Python 2, Unicode can encode into Python strings, and Python strings can decode into the Unicode type.

How to use the "required" attribute with a "radio" input field

TL;DR: Set the required attribute for at least one input of the radio group.

Setting required for all inputs is more clear, but not necessary (unless dynamically generating radio-buttons).

To group radio buttons they must all have the same name value. This allows only one to be selected at a time and applies required to the whole group.

  Select Gender:<br>_x000D_
    <input type="radio" name="gender" value="male" required>_x000D_
    <input type="radio" name="gender" value="female">_x000D_
    <input type="radio" name="gender" value="other">_x000D_
  <input type="submit">_x000D_

Also take note of:

To avoid confusion as to whether a radio button group is required or not, authors are encouraged to specify the attribute on all the radio buttons in a group. Indeed, in general, authors are encouraged to avoid having radio button groups that do not have any initially checked controls in the first place, as this is a state that the user cannot return to, and is therefore generally considered a poor user interface.


Error handling in C code

Returning error code is the usual approach for error handling in C.

But recently we experimented with the outgoing error pointer approach as well.

It has some advantages over the return value approach:

  • You can use the return value for more meaningful purposes.

  • Having to write out that error parameter reminds you to handle the error or propagate it. (You never forget checking the return value of fclose, don't you?)

  • If you use an error pointer, you can pass it down as you call functions. If any of the functions set it, the value won't get lost.

  • By setting a data breakpoint on the error variable, you can catch where does the error occurred first. By setting a conditional breakpoint you can catch specific errors too.

  • It makes it easier to automatize the check whether you handle all errors. The code convention may force you to call your error pointer as err and it must be the last argument. So the script can match the string err); then check if it's followed by if (*err. Actually in practice we made a macro called CER (check err return) and CEG (check err goto). So you don't need to type it out always when we just want to return on error, and can reduce the visual clutter.

Not all functions in our code has this outgoing parameter though. This outgoing parameter thing are used for cases where you would normally throw an exception.

Sass nth-child nesting

I'd be careful about trying to get too clever here. I think it's confusing as it is and using more advanced nth-child parameters will only make it more complicated. As for the background color I'd just set that to a variable.

Here goes what I came up with before I realized trying to be too clever might be a bad thing.

#romtest {
 $bg: #e5e5e5;
 .detailed {
    th {
      &:nth-child(-2n+6) {
        background-color: $bg;
    td {
      &:nth-child(3n), &:nth-child(2), &:nth-child(7) {
        background-color: $bg;
      &.last {
          background-color: $bg;

and here is a quick demo:


Here's another approach to avoid retyping background-color:

#romtest {
  %highlight {
    background-color: #e5e5e5; 
  .detailed {
    th {
      &:nth-child(-2n+6) {
        @extend %highlight;

    td {
      &:nth-child(3n), &:nth-child(2), &:nth-child(7) {
        @extend %highlight;
      &.last {
          @extend %highlight;

How do I add multiple conditions to "ng-disabled"?

this way worked for me

ng-disabled="(user.Role.ID != 1) && (user.Role.ID != 2)"

Implicit function declarations in C

It should be considered an error. But C is an ancient language, so it's only a warning.
Compiling with -Werror (gcc) fixes this problem.

When C doesn't find a declaration, it assumes this implicit declaration: int f();, which means the function can receive whatever you give it, and returns an integer. If this happens to be close enough (and in case of printf, it is), then things can work. In some cases (e.g. the function actually returns a pointer, and pointers are larger than ints), it may cause real trouble.

Note that this was fixed in newer C standards (C99, C11). In these standards, this is an error. However, gcc doesn't implement these standards by default, so you still get the warning.

Save child objects automatically using JPA Hibernate

in your setChilds, you might want to try looping thru the list and doing something like

child.parent = this;

you also should set up the cascade on the parent to the appropriate values.

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

Go to Eclipse --> Help

and click--->Install new software

then you can see a window ...There a click add

Then put below url in url box:

i am having juno

if u have any other means put that name . then click ok.

Equivalent of LIMIT for DB2



To get ranges, you'd have to use ROW_NUMBER() (since v5r4) and use that within the WHERE clause: (stolen from here:

SELECT code, name, address
  SELECT row_number() OVER ( ORDER BY code ) AS rid, code, name, address
  FROM contacts
  WHERE name LIKE '%Bob%' 
  ) AS t
WHERE t.rid BETWEEN 20 AND 25;

How do I write the 'cd' command in a makefile?

To change dir

    $(MAKE) -C mydir

    $(MAKE) -C / -C my-custom-dir   ## Equivalent to /my-custom-dir

Bootstrap 3: how to make head of dropdown link clickable in navbar

This topic is super old, but I needed a solution that worked on desktop AND mobile and none of these seemed to work for me. Unfortunately, this is the solution I came up with that involves checking the window width and comparing it to the mobile menu breakpoint:

$( 'a.dropdown-toggle' ).on( 'click', function( e ) {
    var $a = $( this ),
        $parent = $a.parent( 'li' ),
        mobile_bp = 767, // Default breakpoint, may need to change this.
        window_width = $( window ).width(),
        is_mobile = window_width <= mobile_bp;

    if ( is_mobile && ! $parent.hasClass( 'open' ) ) {
        return false;

    location.href = $a.attr( 'href' );
    return true;

C++ terminate called without an active exception

How to reproduce that error:

#include <iostream>
#include <stdlib.h>
#include <string>
#include <thread>
using namespace std;
void task1(std::string msg){
  cout << "task1 says: " << msg;
int main() { 
  std::thread t1(task1, "hello"); 
  return 0;

Compile and run:

el@defiant ~/foo4/39_threading $ g++ -o s s.cpp -pthread -std=c++11
el@defiant ~/foo4/39_threading $ ./s
terminate called without an active exception
Aborted (core dumped)

You get that error because you didn't join or detach your thread.

One way to fix it, join the thread like this:

#include <iostream>
#include <stdlib.h>
#include <string>
#include <thread>
using namespace std;
void task1(std::string msg){
  cout << "task1 says: " << msg;
int main() { 
  std::thread t1(task1, "hello"); 
  return 0;

Then compile and run:

el@defiant ~/foo4/39_threading $ g++ -o s s.cpp -pthread -std=c++11
el@defiant ~/foo4/39_threading $ ./s
task1 says: hello

The other way to fix it, detach it like this:

#include <iostream>
#include <stdlib.h>
#include <string>
#include <unistd.h>
#include <thread>
using namespace std;
void task1(std::string msg){
  cout << "task1 says: " << msg;
int main() 

        std::thread t1(task1, "hello"); 

     } //thread handle is destroyed here, as goes out of scope!

     usleep(1000000); //wait so that hello can be printed.

Compile and run:

el@defiant ~/foo4/39_threading $ g++ -o s s.cpp -pthread -std=c++11
el@defiant ~/foo4/39_threading $ ./s
task1 says: hello

Read up on detaching C++ threads and joining C++ threads.

How to get selected option using Selenium WebDriver with Java

var option = driver.FindElement(By.Id("employmentType"));
        var selectElement = new SelectElement(option);

How to truncate milliseconds off of a .NET DateTime

I know the answer is quite late, but the best way to get rid of milliseconds is

var currentDateTime = DateTime.Now.ToString("s");

Try printing the value of the variable, it will show the date time, without milliseconds.


In regards to using extension to define data type. I noticed that MailChimp API is doing it, but I don't think this is a good idea.

GET /zzz/cars.json/1

GET /zzz/cars.xml/1

My sound like a good idea, but I think "older" approach is better - using HTTP headers

GET /xxx/cars/1
Accept: application/json

Also HTTP headers are much better for cross data type communication (if ever someone would need it)

POST /zzz/cars
Content-Type: application/xml     <--- indicates we sent XML to server
Accept: application/json          <--- indicates we want get data back in JSON format  

How can I check the current status of the GPS receiver?

The GPS icon seems to change its state according to received broadcast intents. You can change its state yourself with the following code samples:

Notify that the GPS has been enabled:

Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);

Notify that the GPS is receiving fixes:

Intent intent = new Intent("android.location.GPS_FIX_CHANGE");
intent.putExtra("enabled", true);

Notify that the GPS is no longer receiving fixes:

Intent intent = new Intent("android.location.GPS_FIX_CHANGE");
intent.putExtra("enabled", false);

Notify that the GPS has been disabled:

Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", false);

Example code to register receiver to the intents:

// MyReceiver must extend BroadcastReceiver
MyReceiver receiver = new MyReceiver();
IntentFilter filter = new IntentFilter("android.location.GPS_ENABLED_CHANGE");
registerReceiver(receiver, filter);

By receiving these broadcast intents you can notice the changes in GPS status. However, you will be notified only when the state changes. Thus it is not possible to determine the current state using these intents.

How can I remove 3 characters at the end of a string in php?

<?php echo substr("abcabcabc", 0, -3); ?>

There is already an object named in the database

In my case I had re-named the assembly that contained the code-first entity framework model. Although the actual schema hadn't changed at all the migrations table called


contains a list of already performed migrations based on the old assembly name. I updated the old name in the migrations table to match the new and the migration then worked again.

DateDiff to output hours and minutes

In case someone is still searching for a query to display the difference in hr min and sec format: (This will display the difference in this format: 2 hr 20 min 22 secs)

CAST(DATEDIFF(minute, StartDateTime, EndDateTime)/ 60 as nvarchar(20)) + ' hrs ' + CAST(DATEDIFF(second, StartDateTime, EndDateTime)/60 as nvarchar(20)) + ' mins' +          CAST(DATEDIFF(second, StartDateTime, EndDateTime)% 60 as nvarchar(20))  + ' secs'

OR can be in the format as in the question:

CAST(DATEDIFF(minute, StartDateTime, EndDateTime)/ 60 as nvarchar(20)) + ':' + CAST(DATEDIFF(second, StartDateTime, EndDateTime)/60 as nvarchar(20))

What does the @Valid annotation indicate in Spring?

IIRC @Valid isn't a Spring annotation but a JSR-303 annotation (which is the Bean Validation standard). What it does is it basically checks if the data that you send to the method is valid or not (it will validate the scriptFile for you).

SQL: How To Select Earliest Row

Simply use min()

SELECT company, workflow, MIN(date) 
FROM workflowTable 
GROUP BY company, workflow

Setting up enviromental variables in Windows 10 to use java and javac

Here are the typical steps to set JAVA_HOME on Windows 10.

  1. Search for Advanced System Settings in your windows Search box. Click on Advanced System Settings.
  2. Click on Environment variables button: Environment Variables popup will open.
  3. Goto system variables session, and click on New button to create new variable (HOME_PATH), then New System Variables popup will open.
  4. Give Variable Name: JAVA_HOME, and Variable value : Your Java SDK home path. Ex: C:\Program Files\java\jdk1.8.0_151 Note: It should not include \bin. Then click on OK button.
  5. Now you are able to see your JAVA_HOME in system variables list. (If you are not able to, try doing it again.)
  6. Select Path (from system variables list) and click on Edit button, A new pop will opens (Edit Environment Variables). It was introduced in windows 10.
  7. Click on New button and give %JAVA_HOME%\bin at highlighted field and click Ok button.

You can find complete tutorials on my blog :

How to set JAVA_HOME in 64 bit Windows 10 OS

Print text in Oracle SQL Developer SQL Worksheet window

The main answer left out a step for new installs where one has to open up the dbms output window.

enter image description here

Then the script I used:


Another script:

set serveroutput on format wrapped;

OpenCV with Network Cameras

#include <stdio.h>
#include "opencv.hpp"

int main(){

    CvCapture *camera=cvCaptureFromFile("http://username:pass@cam_address/axis-cgi/mjpg/video.cgi?resolution=640x480&req_fps=30&.mjpg");
    if (camera==NULL)
        printf("camera is null\n");
        printf("camera is not null");

    while (cvWaitKey(10)!=atoi("q")){
        double t1=(double)cvGetTickCount();
        IplImage *img=cvQueryFrame(camera);
        double t2=(double)cvGetTickCount();
        printf("time: %gms  fps: %.2g\n",(t2-t1)/(cvGetTickFrequency()*1000.), 1000./((t2-t1)/(cvGetTickFrequency()*1000.)));

onClick not working on mobile (touch)

better to use touchstart event with .on() jQuery method:

$(window).load(function() { // better to use $(document).ready(function(){
    $('.List li').on('click touchstart', function() {

And i don't understand why you are using $(window).load() method because it waits for everything on a page to be loaded, this tend to be slow, while you can use $(document).ready() method which does not wait for each element on the page to be loaded first.

How to change font size in a textbox in html

To actually do it in HTML with inline CSS (not with an external CSS style sheet)

<input type="text" style="font-size: 44pt">

A lot of people would consider putting the style right into the html like this to be poor form. However, I frequently make extreeemly simple web pages for my own use that don't even have a <html> or <body> tag, and such is appropriate there.

How can I get the named parameters from a URL using Flask?

Use request.args to get parsed contents of query string:

from flask import request

def login():
    username = request.args.get('username')
    password = request.args.get('password')

Setting action for back button in navigation controller

Found new way to do it :


- (void)didMoveToParentViewController:(UIViewController *)parent{
    if (parent == NULL) {
        NSLog(@"Back Pressed");


override func didMoveToParentViewController(parent: UIViewController?) {
    if parent == nil {
        println("Back Pressed")

How to see the proxy settings on windows?

You can figure out which proxy server you're using by accessing some websites with a browser and then running the DOS command:


and you'll see some connections in the Foreign Address column on port 80 or 8080 (common proxy server ports). Ideally you will be able to identify the proxy server by its naming convention.

[see also]

Forking / Multi-Threaded Processes | Bash

I don't like using wait because it gets blocked until the process exits, which is not ideal when there are multiple process to wait on as I can't get a status update until the current process is done. I prefer to use a combination of kill -0 and sleep to this.

Given an array of pids to wait on, I use the below waitPids() function to get a continuous feedback on what pids are still pending to finish.

declare -a pids
waitPids() {
    while [ ${#pids[@]} -ne 0 ]; do
        echo "Waiting for pids: ${pids[@]}"
        local range=$(eval echo {0..$((${#pids[@]}-1))})
        local i
        for i in $range; do
            if ! kill -0 ${pids[$i]} 2> /dev/null; then
                echo "Done -- ${pids[$i]}"
                unset pids[$i]
        pids=("${pids[@]}") # Expunge nulls created by unset.
        sleep 1
    echo "Done!"

When I start a process in the background, I add its pid immediately to the pids array by using this below utility function:

addPid() {
    local desc=$1
    local pid=$2
    echo "$desc -- $pid"
    pids=(${pids[@]} $pid)

Here is a sample that shows how to use:

for i in {2..5}; do
    sleep $i &
    addPid "Sleep for $i" $!

And here is how the feedback looks:

Sleep for 2 -- 36271
Sleep for 3 -- 36272
Sleep for 4 -- 36273
Sleep for 5 -- 36274
Waiting for pids: 36271 36272 36273 36274
Waiting for pids: 36271 36272 36273 36274
Waiting for pids: 36271 36272 36273 36274
Done -- 36271
Waiting for pids: 36272 36273 36274
Done -- 36272
Waiting for pids: 36273 36274
Done -- 36273
Waiting for pids: 36274
Done -- 36274

How to create a GUID / UUID

Fastest GUID like string generator method in the format XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX. This does not generate standard-compliant GUID.

Ten million executions of this implementation take just 32.5 seconds, which is the fastest I've ever seen in a browser (the only solution without loops/iterations).

The function is as simple as:

 * Generates a GUID string.
 * @returns {string} The generated GUID.
 * @example af8a8416-6e18-a307-bd9c-f2c947bbb3aa
 * @author Slavik Meltser.
 * @link
function guid() {
    function _p8(s) {
        var p = (Math.random().toString(16)+"000000000").substr(2,8);
        return s ? "-" + p.substr(0,4) + "-" + p.substr(4,4) : p ;
    return _p8() + _p8(true) + _p8(true) + _p8();

To test the performance, you can run this code:

for (var i = 0; i < 10000000; i++) { 

I'm sure most of you will understand what I did there, but maybe there is at least one person that will need an explanation:

The algorithm:

  • The Math.random() function returns a decimal number between 0 and 1 with 16 digits after the decimal fraction point (for example 0.4363923368509859).
  • Then we take this number and convert it to a string with base 16 (from the example above we'll get 0.6fb7687f).
  • Then we cut off the 0. prefix (0.6fb7687f => 6fb7687f) and get a string with eight hexadecimal characters long.
  • Sometimes the Math.random() function will return shorter number (for example 0.4363), due to zeros at the end (from the example above, actually the number is 0.4363000000000000). That's why I'm appending to this string "000000000" (a string with nine zeros) and then cutting it off with substr() function to make it nine characters exactly (filling zeros to the right).
  • The reason for adding exactly nine zeros is because of the worse case scenario, which is when the Math.random() function will return exactly 0 or 1 (probability of 1/10^16 for each one of them). That's why we needed to add nine zeros to it ("0"+"000000000" or "1"+"000000000"), and then cutting it off from the second index (3rd character) with a length of eight characters. For the rest of the cases, the addition of zeros will not harm the result because it is cutting it off anyway.

The assembly:

  • The GUID is in the following format XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX.
  • I divided the GUID into 4 pieces, each piece divided into 2 types (or formats): XXXXXXXX and -XXXX-XXXX.
  • Now I'm building the GUID using these 2 types to assemble the GUID with call 4 pieces, as follows: XXXXXXXX -XXXX-XXXX -XXXX-XXXX XXXXXXXX.
  • To differ between these two types, I added a flag parameter to a pair creator function _p8(s), the s parameter tells the function whether to add dashes or not.
  • Eventually we build the GUID with the following chaining: _p8() + _p8(true) + _p8(true) + _p8(), and return it.

Link to this post on my blog

Enjoy! :-)

Join two sql queries

perhaps not the most elegant way to solve this

select  Activity, 
        SUM(Amount) as "Total_Amount",
        2009 AS INCOME_YEAR
from    Activities, Incomes
where Activities.UnitName = ? AND
      Incomes.ActivityId = Activities.ActivityID
GROUP BY Activity
ORDER BY Activity;


select  Activity, 
        SUM(Amount) as "Total_Amount",
        2008 AS INCOME_YEAR
from Activities, Incomes2008
where Activities.UnitName = ? AND
      Incomes2008.ActivityId = Activities.ActivityID
GROUP BY Activity
ORDER BY Activity;

jquery select option click handler

$('#mySelect').on('change', function() {_x000D_
  var value = $(this).val();_x000D_
<script src=""></script>_x000D_
<select id="mySelect">_x000D_
  <option value='1'>1</option>_x000D_
  <option value='2'>2</option>_x000D_
  <option value='3'>3</option>_x000D_
  <option value='4'>4</option>_x000D_
  <option value='5'>5</option>_x000D_
  <option value='6'>6</option>_x000D_
  <option value='7'>7</option>_x000D_
  <option value='8'>8</option>_x000D_


How do you perform a left outer join using linq extension methods

For a (left outer) join of a table Bar with a table Foo on Foo.Foo_Id = Bar.Foo_Id in lambda notation:

var qry = Foo.GroupJoin(
          foo => foo.Foo_Id,
          bar => bar.Foo_Id,
          (x,y) => new { Foo = x, Bars = y })
           x => x.Bars.DefaultIfEmpty(),
           (x,y) => new { Foo=x.Foo, Bar=y});

Find duplicates and delete all in notepad++

You need the textFX plugin. Then, just follow these instructions:

Paste the text into Notepad++ (CTRL+V). ...
Mark all the text (CTRL+A). ...
Click TextFX ? Click TextFX Tools ? Click Sort lines case insensitive (at column)
Duplicates and blank lines have been removed and the data has been sorted alphabetically.

Personally, I would use sort -i -u source >dest instead of notepad++

Convert an ArrayList to an object array

TypeA[] array = (TypeA[]) a.toArray();

how can I connect to a remote mongo server from Mac OS terminal

Another way to do this is:

mongo mongodb://mongoDbIPorDomain:port

How to uninstall Anaconda completely from macOS

The following line doesn't work?

rm -rf ~/anaconda3 

You should know where your anaconda3(or anaconda1, anaconda2) is installed. So write

which anaconda


output: somewhere

Now use that somewhere and run:

rm -rf somewhere 

Checking if an input field is required using jQuery

The below code works fine but I am not sure about the radio button and dropdown list

$( '#form_id' ).submit( function( event ) {

    //validate fields
    var fail = false;
    var fail_log = '';
    var name;
    $( '#form_id' ).find( 'select, textarea, input' ).each(function(){
        if( ! $( this ).prop( 'required' )){

        } else {
            if ( ! $( this ).val() ) {
                fail = true;
                name = $( this ).attr( 'name' );
                fail_log += name + " is required \n";


    //submit if fail never got set to true
    if ( ! fail ) {
        //process form here.
    } else {
        alert( fail_log );


Malformed String ValueError ast.literal_eval() with String representation of Tuple

From the documentation for ast.literal_eval():

Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

Decimal isn't on the list of things allowed by ast.literal_eval().

How do I use StringUtils in Java?

StringUtils is an Apache Commons project. You need to download and add the library to your classpath.

To use:

import org.apache.commons.lang3.StringUtils;

check all socket opened in linux OS

Also you can use ss utility to dump sockets statistics.

To dump summary:

ss -s

Total: 91 (kernel 0)
TCP:   18 (estab 11, closed 0, orphaned 0, synrecv 0, timewait 0/0), ports 0

Transport Total     IP        IPv6
*         0         -         -        
RAW       0         0         0        
UDP       4         2         2        
TCP       18        16        2        
INET      22        18        4        
FRAG      0         0         0

To display all sockets:

ss -a

To display UDP sockets:

ss -u -a

To display TCP sockets:

ss -t -a

Here you can read ss man: ss

Hash function for a string

Java's String implements hashCode like this:

public int hashCode()

Returns a hash code for this string. The hash code for a String object is computed as

     s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]

using int arithmetic, where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation. (The hash value of the empty string is zero.) 

So something like this:

int HashTable::hash (string word) {
    int result = 0;
    for(size_t i = 0; i < word.length(); ++i) {
        result += word[i] * pow(31, i);
    return result;

How to deny access to a file in .htaccess

Within an htaccess file, the scope of the <Files> directive only applies to that directory (I guess to avoid confusion when rules/directives in the htaccess of subdirectories get applied superceding ones from the parent).

So you can have:

<Files "log.txt">  
  Order Allow,Deny
  Deny from all

For Apache 2.4+, you'd use:

<Files "log.txt">  
  Require all denied

In an htaccess file in your inscription directory. Or you can use mod_rewrite to sort of handle both cases deny access to htaccess file as well as log.txt:

RewriteRule /?\.htaccess$ - [F,L]

RewriteRule ^/?inscription/log\.txt$ - [F,L]

What's the difference between StaticResource and DynamicResource in WPF?

A StaticResource will be resolved and assigned to the property during the loading of the XAML which occurs before the application is actually run. It will only be assigned once and any changes to resource dictionary ignored.

A DynamicResource assigns an Expression object to the property during loading but does not actually lookup the resource until runtime when the Expression object is asked for the value. This defers looking up the resource until it is needed at runtime. A good example would be a forward reference to a resource defined later on in the XAML. Another example is a resource that will not even exist until runtime. It will update the target if the source resource dictionary is changed.

How to compare only date in moment.js

For checking one date is after another by using isAfter() method.

moment('2020-01-20').isAfter('2020-01-21'); // false
moment('2020-01-20').isAfter('2020-01-19'); // true

For checking one date is before another by using isBefore() method.

moment('2020-01-20').isBefore('2020-01-21'); // true
moment('2020-01-20').isBefore('2020-01-19'); // false

For checking one date is same as another by using isSame() method.

moment('2020-01-20').isSame('2020-01-21'); // false
moment('2020-01-20').isSame('2020-01-20'); // true

Inverse of matrix in R

solve(c) does give the correct inverse. The issue with your code is that you are using the wrong operator for matrix multiplication. You should use solve(c) %*% c to invoke matrix multiplication in R.

R performs element by element multiplication when you invoke solve(c) * c.

Increase max_execution_time in PHP?

Is very easy, this work for me:


set_time_limit(300); // Time in seconds, max_execution_time

Here is the PHP documentation

How to format date and time in Android?

Use build in Time class!

Time time = new Time();
time.set(0, 0, 17, 4, 5, 1999);
Log.i("DateTime", time.format("%d.%m.%Y %H:%M:%S"));

Arrays vs Vectors: Introductory Similarities and Differences


  • are a builtin language construct;
  • come almost unmodified from C89;
  • provide just a contiguous, indexable sequence of elements; no bells and whistles;
  • are of fixed size; you can't resize an array in C++ (unless it's an array of POD and it's allocated with malloc);
  • their size must be a compile-time constant unless they are allocated dynamically;
  • they take their storage space depending from the scope where you declare them;
  • if dynamically allocated, you must explicitly deallocate them;
  • if they are dynamically allocated, you just get a pointer, and you can't determine their size; otherwise, you can use sizeof (hence the common idiom sizeof(arr)/sizeof(*arr), that however fails silently when used inadvertently on a pointer);
  • automatically decay to a pointers in most situations; in particular, this happens when passing them to a function, which usually requires passing a separate parameter for their size;
  • can't be returned from a function;
  • can't be copied/assigned directly;
  • dynamical arrays of objects require a default constructor, since all their elements must be constructed first;


  • is a template class;
  • is a C++ only construct;
  • is implemented as a dynamic array;
  • grows and shrinks dynamically;
  • automatically manage their memory, which is freed on destruction;
  • can be passed to/returned from functions (by value);
  • can be copied/assigned (this performs a deep copy of all the stored elements);
  • doesn't decay to pointers, but you can explicitly get a pointer to their data (&vec[0] is guaranteed to work as expected);
  • always brings along with the internal dynamic array its size (how many elements are currently stored) and capacity (how many elements can be stored in the currently allocated block);
  • the internal dynamic array is not allocated inside the object itself (which just contains a few "bookkeeping" fields), but is allocated dynamically by the allocator specified in the relevant template parameter; the default one gets the memory from the freestore (the so-called heap), independently from how where the actual object is allocated;
  • for this reason, they may be less efficient than "regular" arrays for small, short-lived, local arrays;
  • when reallocating, the objects are copied (moved, in C++11);
  • does not require a default constructor for the objects being stored;
  • is better integrated with the rest of the so-called STL (it provides the begin()/end() methods, the usual STL typedefs, ...)

Also consider the "modern alternative" to arrays - std::array; I already described in another answer the difference between std::vector and std::array, you may want to have a look at it.

T-SQL: Looping through an array of known values

You can try as below :

declare @list varchar(MAX), @i int
select @i=0, @list ='4,7,12,22,19,'

while( @i < LEN(@list))
    declare @item varchar(MAX)
    SELECT  @item = SUBSTRING(@list,  @i,CHARINDEX(',',@list,@i)-@i)
    select @item

     --do your stuff here with @item 
     exec p_MyInnerProcedure @item 

    set @i = CHARINDEX(',',@list,@i)+1
    if(@i = 0) set @i = LEN(@list) 

How to write a UTF-8 file with Java?

Below sample code can read file line by line and write new file in UTF-8 format. Also, i am explicitly specifying Cp1252 encoding.

    public static void main(String args[]) throws IOException {

    BufferedReader br = new BufferedReader(new InputStreamReader(
            new FileInputStream("c:\\filenonUTF.txt"),
    String line;

    Writer out = new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream(
                    "c:\\fileUTF.txt"), "UTF-8"));

    try {

        while ((line = br.readLine()) != null) {



    } finally {



Android; Check if file exists without creating a new one

The methods in the Path class are syntactic, meaning that they operate on the Path instance. But eventually you must access the file system to verify that a particular Path exists

 File file = new File("FileName");
 System.out.println("file is already there");
 System.out.println("Not find file ");

Count the number occurrences of a character in a string

count is definitely the most concise and efficient way of counting the occurrence of a character in a string but I tried to come up with a solution using lambda, something like this :

sentence = 'Mary had a little lamb'
sum(map(lambda x : 1 if 'a' in x else 0, sentence))

This will result in :


Also, there is one more advantage to this is if the sentence is a list of sub-strings containing same characters as above, then also this gives the correct result because of the use of in. Have a look :

sentence = ['M', 'ar', 'y', 'had', 'a', 'little', 'l', 'am', 'b']
sum(map(lambda x : 1 if 'a' in x else 0, sentence))

This also results in :


But Of-course this will work only when checking occurrence of single character such as 'a' in this particular case.

Hidden Features of C#?

It's not actually a C# hidden feature, but I recently discovered the WeakReference class and was blown away by it (although this may be biased by the fact that it helped me found a solution to a particular problem of mine...)

How to enable scrolling on website that disabled scrolling?

With Chrome, one way to automatically re-enable scrolling on a website is to download the Tampermonkey extension, then add this script (click "Install this script").

In general, if you have a URL for a script where the URL ends in .user.js and have Tampermonkey installed, you can paste it into Chrome's Omnibox to install the script. More ways to install scripts with Tampermonkey can be found here.

Error handling with try and catch in Laravel

You are inside a namespace so you should use \Exception to specify the global namespace:

try {


} catch (\Exception $e) {

    return $e->getMessage();

In your code you've used catch (Exception $e) so Exception is being searched in/as:


Since there is no Exception class inside App\Services\PayUService so it's not being triggered. Alternatively, you can use a use statement at the top of your class like use Exception; and then you can use catch (Exception $e).

Declaring an HTMLElement Typescript

Okay: weird syntax!

var el: HTMLElement = document.getElementById('content');

fixes the problem. I wonder why the example didn't do this in the first place?

complete code:

class Greeter {
    element: HTMLElement;
    span: HTMLElement;
    timerToken: number;

    constructor (element: HTMLElement) { 
        this.element = element;
        this.element.innerText += "The time is: ";
        this.span = document.createElement('span');
        this.span.innerText = new Date().toUTCString();

    start() {
        this.timerToken = setInterval(() => this.span.innerText = new Date().toUTCString(), 500);

    stop() {


window.onload = () => {
    var el: HTMLElement = document.getElementById('content');
    var greeter = new Greeter(el);

What's a good way to extend Error in JavaScript?

Since JavaScript Exceptions are difficult to sub-class, I don't sub-class. I just create a new Exception class and use an Error inside of it. I change the property so that it looks like my custom exception on the console:

var InvalidInputError = function(message) {
    var error = new Error(message); = 'InvalidInputError';
    return error;

The above new exception can be thrown just like a regular Error and it will work as expected, for example:

throw new InvalidInputError("Input must be a string");
// Output: Uncaught InvalidInputError: Input must be a string 

Caveat: the stack trace is not perfect, as it will bring you to where the new Error is created and not where you throw. This is not a big deal on Chrome because it provides you with a full stack trace directly in the console. But it's more problematic on Firefox, for example.

Change the content of a div based on selection from dropdown menu

here is a jsfiddle with an example of showing/hiding div's via a select.


<div id="option1" class="group">asdf</div>
<div id="option2" class="group">kljh</div>
<div id="option3" class="group">zxcv</div>
<div id="option4" class="group">qwerty</div>
<select id="selectMe">
  <option value="option1">option1</option>
  <option value="option2">option2</option>
  <option value="option3">option3</option>
  <option value="option4">option4</option>


$(document).ready(function () {
  $('#selectMe').change(function () {

Branch from a previous commit using Git

Go to a particular commit of a git repository

Sometimes when working on a git repository you want to go back to a specific commit (revision) to have a snapshot of your project at a specific time. To do that all you need it the SHA-1 hash of the commit which you can easily find checking the log with the command:

git log --abbrev-commit --pretty=oneline

which will give you a compact list of all the commits and the short version of the SHA-1 hash.

Now that you know the hash of the commit you want to go to you can use one of the following 2 commands:

git checkout HASH


git reset --hard HASH


git checkout <commit> <paths>

Tells git to replace the current state of paths with their state in the given commit. Paths can be files or directories.

If no branch is given, git assumes the HEAD commit.

git checkout <path> // restores path from your last commit. It is a 'filesystem-undo'.

If no path is given, git moves HEAD to the given commit (thereby changing the commit you're sitting and working on).

git checkout branch //means switching branches.


git reset <commit> //re-sets the current pointer to the given commit.

If you are on a branch (you should usually be), HEAD and this branch are moved to commit.

If you are in detached HEAD state, git reset does only move HEAD. To reset a branch, first check it out.

If you wanted to know more about the difference between git reset and git checkout I would recommend to read the official git blog.

Get the closest number out of an array

For a small range, the simplest thing is to have a map array, where, eg, the 80th entry would have the value 82 in it, to use your example. For a much larger, sparse range, probably the way to go is a binary search.

With a query language you could query for values some distance either side of your input number and then sort through the resulting reduced list. But SQL doesn't have a good concept of "next" or "previous", to give you a "clean" solution.

SQL Bulk Insert with FIRSTROW parameter skips the following line

To let SQL handle quote escape and everything else do this

FROM  'C:\MyCSV.csv' 
 --FIRSTROW = 2,  --uncomment this if your CSV contains header, so start parsing at line 2

In regards to other answers, here is valuable info as well:

I keep seeing this in all answers: ROWTERMINATOR = '\n'
The \n means LF and it is Linux style EOL

In Windows the EOL is made of 2 chars CRLF so you need ROWTERMINATOR = '\r\n'

enter image description here

enter image description here

Curl : connection refused restricts access on every interface on port 8000 except development computer. change it to this will allow connection from curl.

How do you clear the SQL Server transaction log?

Most answers here so far are assuming you do not actually need the Transaction Log file, however if your database is using the FULL recovery model, and you want to keep your backups in case you need to restore the database, then do not truncate or delete the log file the way many of these answers suggest.

Eliminating the log file (through truncating it, discarding it, erasing it, etc) will break your backup chain, and will prevent you from restoring to any point in time since your last full, differential, or transaction log backup, until the next full or differential backup is made.

From the Microsoft article onBACKUP

We recommend that you never use NO_LOG or TRUNCATE_ONLY to manually truncate the transaction log, because this breaks the log chain. Until the next full or differential database backup, the database is not protected from media failure. Use manual log truncation in only very special circumstances, and create backups of the data immediately.

To avoid that, backup your log file to disk before shrinking it. The syntax would look something like this:

BACKUP LOG MyDatabaseName 
TO DISK='C:\DatabaseBackups\MyDatabaseName_backup_2013_01_31_095212_8797154.trn'

DBCC SHRINKFILE (N'MyDatabaseName_Log', 200)

How to close a GUI when I push a JButton?

Add your button:

JButton close = new JButton("Close");

Add an ActionListener:

close.addActionListner(new CloseListener());

Add a class for the Listener implementing the ActionListener interface and override its main function:

private class CloseListener implements ActionListener{
    public void actionPerformed(ActionEvent e) {
        //DO SOMETHING

This might be not the best way, but its a point to start. The class for example can be made public and not as a private class inside another one.

Print a list of all installed node.js modules

list of all globally installed third party modules, write in console:

 npm -g ls

Run an exe from C# code



Compiling the Code

Copy the code and paste it into the Main method of a console application. Replace "mspaint.exe" with the path to the application you want to run.

How to get current route

For your purposes you can use this.activatedRoute.pathFromRoot.

import {ActivatedRoute} from "@angular/router";
constructor(public activatedRoute: ActivatedRoute){


With the help of pathFromRoot you can get the list of parent urls and check if the needed part of the URL matches your condition.

For additional information please check this article or install ng2-router-helper from npm

npm install ng2-router-helper

why should I make a copy of a data frame in pandas

This expands on Paul's answer. In Pandas, indexing a DataFrame returns a reference to the initial DataFrame. Thus, changing the subset will change the initial DataFrame. Thus, you'd want to use the copy if you want to make sure the initial DataFrame shouldn't change. Consider the following code:

df = DataFrame({'x': [1,2]})
df_sub = df[0:1]
df_sub.x = -1

You'll get:

0 -1
1  2

In contrast, the following leaves df unchanged:

df_sub_copy = df[0:1].copy()
df_sub_copy.x = -1

Woocommerce, get current product id

2017 Update - since WooCommerce 3:

global $product;
$id = $product->get_id();

Woocommerce doesn't like you accessing those variables directly. This will get rid of any warnings from woocommerce if your wp_debug is true.

ERROR 1064 (42000): You have an error in your SQL syntax; Want to configure a password as root being the user

This worked perfectly for me.

mysql> use mysql; mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'my-password-here';

What in layman's terms is a Recursive Function using PHP

Recursion is an alternative to loops, it's quite seldom that they bring more clearness or elegance to your code. A good example was given by Progman's answer, if he wouldn't use recursion he would be forced to keep track in which directory he is currently (this is called state) recursions allows him to do the bookkeeping using the stack (the area where variables and return adress of a method are stored)

The standard examples factorial and Fibonacci are not useful for understanding the concept because they're easy to replace by a loop.

How do I get countifs to select all non-blank cells in Excel?

Use a criteria of "<>". It will count anything which isn't an empty cell, including #NAME? or #DIV/0!. As to why it works, damned if I know, but Excel seems to understand it.

Note: works nicely in Google Spreadsheet too

How to change the remote a branch is tracking?

I've found @critikaster's post helpful, except that I had to perform these commands with GIT 2.21:

$ git remote set-url origin https://some_url/some_repo
$ git push --set-upstream origin master

Are multi-line strings allowed in JSON?

Write property value as a array of strings. Like example given over here This will help.

We can always use array of strings for multiline strings like following.

    "singleLine": "Some singleline String",
    "multiline": ["Line one", "line Two", "Line Three"]

And we can easily iterate array to display content in multi line fashion.

Force drop mysql bypassing foreign key constraint

Simple solution to drop all the table at once from terminal.

This involved few steps inside your mysql shell (not a one step solution though), this worked me and saved my day.

Worked for Server version: 5.6.38 MySQL Community Server (GPL)

Steps I followed:

 1. generate drop query using concat and group_concat.
 2. use database
 3. turn off / disable foreign key constraint check (SET FOREIGN_KEY_CHECKS = 0;), 
 4. copy the query generated from step 1
 5. re enable foreign key constraint check (SET FOREIGN_KEY_CHECKS = 1;)
 6. run show table

MySQL shell

$ mysql -u root -p
Enter password: ****** (your mysql root password)
mysql> SELECT CONCAT('DROP TABLE IF EXISTS `', GROUP_CONCAT(table_name SEPARATOR '`, `'), '`;') AS dropquery FROM information_schema.tables WHERE table_schema = 'emall_duplicate';
| dropquery                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| DROP TABLE IF EXISTS `admin`, `app`, `app_meta_settings`, `commission`, `commission_history`, `coupon`, `email_templates`, `infopages`, `invoice`, `m_pc_xref`, `member`, `merchant`, `message_templates`, `mnotification`, `mshipping_address`, `notification`, `order`, `orderdetail`, `pattributes`, `pbrand`, `pcategory`, `permissions`, `pfeatures`, `pimage`, `preport`, `product`, `product_review`, `pspecification`, `ptechnical_specification`, `pwishlist`, `role_perms`, `roles`, `settings`, `test`, `testanother`, `user_perms`, `user_roles`, `users`, `wishlist`; |
1 row in set (0.00 sec)

mysql> USE emall_duplicate;
Database changed
mysql> SET FOREIGN_KEY_CHECKS = 0;                                                                                                                                                   Query OK, 0 rows affected (0.00 sec)

// copy and paste generated query from step 1
mysql> DROP TABLE IF EXISTS `admin`, `app`, `app_meta_settings`, `commission`, `commission_history`, `coupon`, `email_templates`, `infopages`, `invoice`, `m_pc_xref`, `member`, `merchant`, `message_templates`, `mnotification`, `mshipping_address`, `notification`, `order`, `orderdetail`, `pattributes`, `pbrand`, `pcategory`, `permissions`, `pfeatures`, `pimage`, `preport`, `product`, `product_review`, `pspecification`, `ptechnical_specification`, `pwishlist`, `role_perms`, `roles`, `settings`, `test`, `testanother`, `user_perms`, `user_roles`, `users`, `wishlist`;
Query OK, 0 rows affected (0.18 sec)

Query OK, 0 rows affected (0.00 sec)

mysql> SHOW tables;
Empty set (0.01 sec)


How to remove rows with any zero value

I would do the following.

Set the zero to NA.

 data[data==0] <- NA

Delete the rows associated with NA.


Iterate through every file in one directory

As others have said, Dir::foreach is a good option here. However, note that Dir::foreach and Dir::entries will always include . and .. (the current and parent directories). You will generally not want to work on them, so you can use Dir::each_child or Dir::children (as suggested by ma11hew28) or do something like this:

Dir.foreach('/path/to/dir') do |filename|
  next if filename == '.' or filename == '..'
  # Do work on the remaining files & directories

Dir::foreach and Dir::entries (as well as Dir::each_child and Dir::children) also include hidden files & directories. Often this is what you want, but if it isn't, you need to do something to skip over them.

Alternatively, you might want to look into Dir::glob which provides simple wildcard matching:

Dir.glob('/path/to/dir/*.rb') do |rb_filename|
  # Do work on files & directories ending in .rb

How can I set the max-width of a table cell using percentages?

I know this is literally a year later, but I figured I'd share. I was trying to do the same thing and came across this solution that worked for me. We set a max width for the entire table, then worked with the cell sizes for the desired effect.

Put the table in its own div, then set the width, min-width, and/or max-width of the div as desired for the entire table. Then, you can work and set width and min-widths for other cells, and max width for the div effectively working around and backwards to achieve the max width we wanted.

#tablediv {

.tdleft {
<div id="tablediv">
  <table width="100%" border="1">
      <td class="tdleft">Test</td>
      <td>A long string blah blah blah</td>

Admittedly, this does not give you a "max" width of a cell per se, but it does allow some control that might work in-lieu of such an option. Not sure if it will work for your needs. I know it worked for our situation where we want the navigation side in the page to scale up and down to a point but for all the wide screens these days.

Is it possible to append to innerHTML without destroying descendants' event listeners?

The easiest way is to use an array and push elements into it and then insert the array subsequent values into the array dynamically. Here is my code:

var namesArray = [];

function myclick(){
    var readhere = prompt ("Insert value");
    document.getElementById('demo').innerHTML= namesArray;


This could also be an issue of building the code using a 64 bit configuration. You can try to select x86 as the build platform which can solve this issue. To do this right-click the solution and select Configuration Manager From there you can change the Platform of the project using the 32-bit .dll to x86

C++ Cout & Cin & System "Ambiguous"

This kind of thing doesn't just magically happen on its own; you changed something! In industry we use version control to make regular savepoints, so when something goes wrong we can trace back the specific changes we made that resulted in that problem.

Since you haven't done that here, we can only really guess. In Visual Studio, Intellisense (the technology that gives you auto-complete dropdowns and those squiggly red lines) works separately from the actual C++ compiler under the bonnet, and sometimes gets things a bit wrong.

In this case I'd ask why you're including both cstdlib and stdlib.h; you should only use one of them, and I recommend the former. They are basically the same header, a C header, but cstdlib puts them in the namespace std in order to "C++-ise" them. In theory, including both wouldn't conflict but, well, this is Microsoft we're talking about. Their C++ toolchain sometimes leaves something to be desired. Any time the Intellisense disagrees with the compiler has to be considered a bug, whichever way you look at it!

Anyway, your use of using namespace std (which I would recommend against, in future) means that std::system from cstdlib now conflicts with system from stdlib.h. I can't explain what's going on with std::cout and std::cin.

Try removing #include <stdlib.h> and see what happens.

If your program is building successfully then you don't need to worry too much about this, but I can imagine the false positives being annoying when you're working in your IDE.

Proxy Basic Authentication in C#: HTTP 407 error

I was getting a very similar situation where the HttpWebRequest wasn't picking up the correct proxy details by default and setting the UseDefaultCredentials didn't work either. Forcing the settings in code however worked a treat:

IWebProxy proxy = myWebRequest.Proxy;
if (proxy != null) {
    string proxyuri = proxy.GetProxy(myWebRequest.RequestUri).ToString();
    myWebRequest.UseDefaultCredentials = true;
    myWebRequest.Proxy = new WebProxy(proxyuri, false);
    myWebRequest.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;

and because this uses the default credentials it should not ask the user for their details.

Max or Default?

Think about what you're asking!

The max of {1, 2, 3, -1, -2, -3} is obviously 3. The max of {2} is obviously 2. But what is the max of the empty set { }? Obviously that is a meaningless question. The max of the empty set is simply not defined. Attempting to get an answer is a mathematical error. The max of any set must itself be an element in that set. The empty set has no elements, so claiming that some particular number is the max of that set without being in that set is a mathematical contradiction.

Just as it is correct behavior for the computer to throw an exception when the programmer asks it to divide by zero, so it is correct behavior for the computer to throw an exception when the programmer asks it to take the max of the empty set. Division by zero, taking the max of the empty set, wiggering the spacklerorke, and riding the flying unicorn to Neverland are all meaningless, impossible, undefined.

Now, what is it that you actually want to do?

Checking if a list of objects contains a property with a specific value

Further to the other answers suggesting LINQ, another alternative in this case would be to use the FindAll instance method:

List<SampleClass> results = myList.FindAll(x => x.Name == nameToExtract);

phpmailer error "Could not instantiate mail function"

Seems in my case it was just SERVER REJECTION. Please check your mail server log / smtp connection accessibility.

Count the number of all words in a string

Also from stringi package, the straight forward function stri_count_words

#[1] 7

Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {"name":"value"}) to deserialize correctly

var objResponse1 = 


Using openssl to get the certificate from a server

You can get and store the server root certificate using next bash script:

CERTS=$(echo -n | openssl s_client -connect $HOST_NAME:$PORT -showcerts | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p')
echo "$CERTS" | awk -v RS="-----BEGIN CERTIFICATE-----" 'NR > 1 { printf RS $0 > "'$SERVER_ROOT_CERTIFICATE'"; close("'$SERVER_ROOT_CERTIFICATE'") }'

Just overwrite required variables.

Changing Locale within the app itself

I couldn't used android:anyDensity="true" because objects in my game would be positioned completely different... seems this also does the trick:

// creating locale
Locale locale2 = new Locale(loc); 
Configuration config2 = new Configuration();
config2.locale = locale2;

// updating locale
mContext.getResources().updateConfiguration(config2, null);

What's the net::ERR_HTTP2_PROTOCOL_ERROR about?

This happened to me when I registered a new domain name, e.g., "new" for ( The name could not be resolved temporarily in my location for a couple of hours, while it could be resolved abroad. So I used a proxy to test the website where I saw net::ERR_HTTP2_PROTOCOL_ERROR in chrome console for some AJAX posts. Hours later, when the name could be resloved locally, those error just dissappeared.

I think the reason for that error is those AJAX requests were not redirected by my proxy, it just visit a website which had not been resolved by my local DNS resolver.

How can I count the number of elements of a given value in a matrix?

assume w contains week numbers ([1:7])

n = histc(M,w)

if you do not know the range of numbers in M:

n = histc(M,unique(M))

It is such as a SQL Group by command!

Best way to define error codes/strings in Java?

Well there's certainly a better implementation of the enum solution (which is generally quite nice):

public enum Error {
  DATABASE(0, "A database error has occurred."),
  DUPLICATE_USER(1, "This user already exists.");

  private final int code;
  private final String description;

  private Error(int code, String description) {
    this.code = code;
    this.description = description;

  public String getDescription() {
     return description;

  public int getCode() {
     return code;

  public String toString() {
    return code + ": " + description;

You may want to override toString() to just return the description instead - not sure. Anyway, the main point is that you don't need to override separately for each error code. Also note that I've explicitly specified the code instead of using the ordinal value - this makes it easier to change the order and add/remove errors later.

Don't forget that this isn't internationalised at all - but unless your web service client sends you a locale description, you can't easily internationalise it yourself anyway. At least they'll have the error code to use for i18n at the client side...

Division in Python 2.7. and 3.3

In python 2.7, the / operator is integer division if inputs are integers.

If you want float division (which is something I always prefer), just use this special import:

from __future__ import division

See it here:

>>> 7 / 2
>>> from __future__ import division
>>> 7 / 2

Integer division is achieved by using //, and modulo by using %

>>> 7 % 2
>>> 7 // 2


As commented by user2357112, this import has to be done before any other normal import.

SSIS Excel Connection Manager failed to Connect to the Source

you can try this:

Uninstall office365

then install only Access Database Engine 2016 Redistributable 64 bit

Also set Project Configuration Properties for Debugging Run64BitRuntime = False

It should work.

What is "export default" in JavaScript?

There are two different types of export, named and default. You can have multiple named exports per module but only one default export. Each type corresponds to one of the above. Source: MDN

Named Export

export class NamedExport1 { }

export class NamedExport2 { }

// Import class
import { NamedExport1 } from 'path-to-file'
import { NamedExport2 } from 'path-to-file'

// OR you can import all at once
import * as namedExports from 'path-to-file'

Default Export

export default class DefaultExport1 { }

// Import class
import DefaultExport1 from 'path-to-file' // No curly braces - {}

// You can use a different name for the default import

import Foo from 'path-to-file' // This will assign any default export to Foo.

Delete many rows from a table using id in Mysql

Hope it helps:

DELETE FROM tablename 
WHERE = ANY (SELECT id FROM tablename WHERE id = id);

How do I find the width & height of a terminal window?

There are some cases where your rows/LINES and columns do not match the actual size of the "terminal" being used. Perhaps you may not have a "tput" or "stty" available.

Here is a bash function you can use to visually check the size. This will work up to 140 columns x 80 rows. You can adjust the maximums as needed.

function term_size
    local i=0 digits='' tens_fmt='' tens_args=()
    for i in {80..8}
        echo $i $(( i - 2 ))
    echo "If columns below wrap, LINES is first number in highest line above,"
    echo "If truncated, LINES is second number."
    for i in {1..14}
        tens_args=("${tens_args[@]}" $i)
    printf "$tens_fmt\n" "${tens_args[@]}"
    echo "$digits"

SEVERE: Unable to create initial connections of pool - tomcat 7 with context.xml file

When you encounter exceptions like this, the most useful information is generally at the bottom of the stacktrace:

Caused by: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
  at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(

The problem is that Tomcat can't find com.mysql.jdbc.Driver. This is usually caused by the JAR containing the MySQL driver not being where Tomcat expects to find it (namely in the webapps/<yourwebapp>/WEB-INF/lib directory).

How do I make a Git commit in the past?

You can always change a date on your computer, make a commit, then change the date back and push.

Connection timeout for SQL server

Yes, you could append ;Connection Timeout=30 to your connection string and specify the value you wish.

The timeout value set in the Connection Timeout property is a time expressed in seconds. If this property isn't set, the timeout value for the connection is the default value (15 seconds).

Moreover, setting the timeout value to 0, you are specifying that your attempt to connect waits an infinite time. As described in the documentation, this is something that you shouldn't set in your connection string:

A value of 0 indicates no limit, and should be avoided in a ConnectionString because an attempt to connect waits indefinitely.

How to check if an element is visible with WebDriver

Here is how I would do it (please ignore worry Logger class calls):

public boolean isElementExist(By by) {
    int count = driver.findElements(by).size();
    if (count>=1) {
        Logger.LogMessage("isElementExist: " + by + " | Count: " + count, Priority.Medium);
        return true;
    else {
        Logger.LogMessage("isElementExist: " + by + " | Could not find element", Priority.High);
        return false;

public boolean isElementNotExist(By by) {
    int count = driver.findElements(by).size();
    if (count==0) {
        Logger.LogMessage("ElementDoesNotExist: " + by, Priority.Medium);
        return true;
    else {
        Logger.LogMessage("ElementDoesExist: " + by, Priority.High);
        return false;

public boolean isElementVisible(By by) {
    try {
        if (driver.findElement(by).isDisplayed()) {
            Logger.LogMessage("Element is Displayed: " + by, Priority.Medium);
            return true;
    catch(Exception e) {       
        Logger.LogMessage("Element is Not Displayed: " + by, Priority.High);
        return false;

    return false;

"Field has incomplete type" error

The problem is that your ui property uses a forward declaration of class Ui::MainWindowClass, hence the "incomplete type" error.

Including the header file in which this class is declared will fix the problem.


Based on your comment, the following code:

namespace Ui
    class MainWindowClass;

does NOT declare a class. It's a forward declaration, meaning that the class will exist at some point, at link time.
Basically, it just tells the compiler that the type will exist, and that it shouldn't warn about it.

But the class has to be defined somewhere.

Note this can only work if you have a pointer to such a type.
You can't have a statically allocated instance of an incomplete type.

So either you actually want an incomplete type, and then you should declare your ui member as a pointer:

namespace Ui
    // Forward declaration - Class will have to exist at link time
    class MainWindowClass;

class MainWindow : public QMainWindow

        // Member needs to be a pointer, as it's an incomplete type
        Ui::MainWindowClass * ui;

Or you want a statically allocated instance of Ui::MainWindowClass, and then it needs to be declared. You can do it in another header file (usually, there's one header file per class).
But simply changing the code to:

namespace Ui
    // Real class declaration - May/Should be in a specific header file
    class MainWindowClass

class MainWindow : public QMainWindow

        // Member can be statically allocated, as the type is complete
        Ui::MainWindowClass ui;

will also work.

Note the difference between the two declarations. First uses a forward declaration, while the second one actually declares the class (here with no properties nor methods).

Can we create an instance of an interface in Java?

You can never instantiate an interface in java. You can, however, refer to an object that implements an interface by the type of the interface. For example,

public interface A
public class B implements A

public static void main(String[] args)
    A test = new B();
    //A test = new A(); // wont compile

What you did above was create an Anonymous class that implements the interface. You are creating an Anonymous object, not an object of type interface Test.

How to use shell commands in Makefile


FILES = $(shell ls)

indented underneath all like that, it's a build command. So this expands $(shell ls), then tries to run the command FILES ....

If FILES is supposed to be a make variable, these variables need to be assigned outside the recipe portion, e.g.:

FILES = $(shell ls)
        echo $(FILES)

Of course, that means that FILES will be set to "output from ls" before running any of the commands that create the .tgz files. (Though as Kaz notes the variable is re-expanded each time, so eventually it will include the .tgz files; some make variants have FILES := ... to avoid this, for efficiency and/or correctness.1)

If FILES is supposed to be a shell variable, you can set it but you need to do it in shell-ese, with no spaces, and quoted:

        FILES="$(shell ls)"

However, each line is run by a separate shell, so this variable will not survive to the next line, so you must then use it immediately:

        FILES="$(shell ls)"; echo $$FILES

This is all a bit silly since the shell will expand * (and other shell glob expressions) for you in the first place, so you can just:

        echo *

as your shell command.

Finally, as a general rule (not really applicable to this example): as esperanto notes in comments, using the output from ls is not completely reliable (some details depend on file names and sometimes even the version of ls; some versions of ls attempt to sanitize output in some cases). Thus, as l0b0 and idelic note, if you're using GNU make you can use $(wildcard) and $(subst ...) to accomplish everything inside make itself (avoiding any "weird characters in file name" issues). (In sh scripts, including the recipe portion of makefiles, another method is to use find ... -print0 | xargs -0 to avoid tripping over blanks, newlines, control characters, and so on.)

1The GNU Make documentation notes further that POSIX make added ::= assignment in 2012. I have not found a quick reference link to a POSIX document for this, nor do I know off-hand which make variants support ::= assignment, although GNU make does today, with the same meaning as :=, i.e., do the assignment right now with expansion.

Note that VAR := $(shell command args...) can also be spelled VAR != command args... in several make variants, including all modern GNU and BSD variants as far as I know. These other variants do not have $(shell) so using VAR != command args... is superior in both being shorter and working in more variants.

How to add custom html attributes in JSX

You can use the "is" attribute to disable the React attribute whitelist for an element.

See my anwser here: Stackoverflow

Good Free Alternative To MS Access

One thing to keep in mind here is the MS Access product is much more than just the raw database engine. It provides a full application development platform, including form and menu designer, client application language and environment (VBA), and report designer. When you take all those things together, MS Access really has no peer.

But for the scope of this question, we're concerned with the raw database engine. With that in mind:

VistaDB (not free),
SQL Server Compact Edition (not Express)
and now SQL Server LocalDB
all come to mind.

Another thought: while the original question does ask about desktop databases, its likely some people will land here looking for a database to use with a web site. It's important to remember that these are all in-process databases, and as such are rarely if ever appropriate for use on the web. If you want to build a web site, where it's common to need to support significant concurrent access, you generally want a database server engine, like MS SQL, Postgresql, MySQL, Oracle, or their brethren. At the same time, those server engines are rarely if ever appropriate for a single-user desktop application.

Clang vs GCC - which produces faster binaries?

There is very little overall difference between GCC 4.8 and clang 3.3 in terms of speed of the resulting binary. In most cases code generated by both compilers performs similarly. Neither of these two compilers dominates the other one.

Benchmarks telling that there is a significant performance gap between GCC and clang are coincidental.

Program performance is affected by the choice of the compiler. If a developer or a group of developers is exclusively using GCC then the program can be expected to run slightly faster with GCC than with clang, and vice versa.

From developer viewpoint, a notable difference between GCC 4.8+ and clang 3.3 is that GCC has the -Og command line option. This option enables optimizations that do not interfere with debugging, so for example it is always possible to get accurate stack traces. The absence of this option in clang makes clang harder to use as an optimizing compiler for some developers.