Programs & Examples On #Target

In a makefile, targets are associated with a series of commands to execute when an action is requested.

The project was not built since its build path is incomplete

Here is what made the error disappear for me:

Close eclipse, open up a terminal window and run:

$ mvn clean eclipse:clean eclipse:eclipse

Are you using Maven? If so,

  1. Right-click on the project, Build Path and go to Configure Build Path
  2. Click the libraries tab. If Maven dependencies are not in the list, you need to add it.
  3. Close the dialog.

To add it: Right-click on the project, Maven → Disable Maven Nature Right-click on the project, Configure → Convert to Maven Project.

And then clean

Edit 1:

If that doesn't resolve the issue try right-clicking on your project and select properties. Select Java Build Path → Library tab. Look for a JVM. If it's not there, click to add Library and add the default JVM. If VM is there, click edit and select the default JVM. Hopefully, that works.

Edit 2:

You can also try going into the folder where you have all your projects and delete the .metadata for eclipse (be aware that you'll have to re-import all the projects afterwards! Also all the environment settings you've set would also have to be redone). After it was deleted just import the project again, and hopefully, it works.

What does this symbol mean in IntelliJ? (red circle on bottom-left corner of file name, with 'J' in it)

It means your Java source files aren't part of the project.

If the suggestions mentioned here don't resolve the issue, you may have hit a rare bug like I did. Researching the exceptions found in the log helped me. In my case, disabling the "Plugin DevKit", deleting the .idea directory, and reimporting the project worked.

Can I create links with 'target="_blank"' in Markdown?

You can add any attributes using {[attr]="[prop]"}

For example [Google] (http://www.google.com){target="_blank"}

Target elements with multiple classes, within one rule

.border-blue.background { ... } is for one item with multiple classes.
.border-blue, .background { ... } is for multiple items each with their own class.
.border-blue .background { ... } is for one item where '.background' is the child of '.border-blue'.

See Chris' answer for a more thorough explanation.

How to set child process' environment variable in Makefile

I only needed the environment variables locally to invoke my test command, here's an example setting multiple environment vars in a bash shell, and escaping the dollar sign in make.

SHELL := /bin/bash

.PHONY: test tests
test tests:
    PATH=./node_modules/.bin/:$$PATH \
    JSCOVERAGE=1 \
    nodeunit tests/

jQuery: go to URL with target="_blank"

Use,

var url = $(this).attr('href');
window.open(url, '_blank');

Update:the href is better off being retrieved with prop since it will return the full url and it's slightly faster.

var url = $(this).prop('href');

How to change target build on Android project?

I had this problem too. What worked for me was to first un-check the previously selected SDK version before checking the new desired version. Then click okay.

If conditions in a Makefile, inside a target

There are several problems here, so I'll start with my usual high-level advice: Start small and simple, add complexity a little at a time, test at every step, and never add to code that doesn't work. (I really ought to have that hotkeyed.)

You're mixing Make syntax and shell syntax in a way that is just dizzying. You should never have let it get this big without testing. Let's start from the outside and work inward.

UNAME := $(shell uname -m)

all:
    $(info Checking if custom header is needed)
    ifeq ($(UNAME), x86_64)
    ... do some things to build unistd_32.h
    endif

    @make -C $(KDIR) M=$(PWD) modules

So you want unistd_32.h built (maybe) before you invoke the second make, you can make it a prerequisite. And since you want that only in a certain case, you can put it in a conditional:

ifeq ($(UNAME), x86_64)
all: unistd_32.h
endif

all:
    @make -C $(KDIR) M=$(PWD) modules

unistd_32.h:
    ... do some things to build unistd_32.h

Now for building unistd_32.h:

F1_EXISTS=$(shell [ -e /usr/include/asm/unistd_32.h ] && echo 1 || echo 0 )
ifeq ($(F1_EXISTS), 1)
    $(info Copying custom header)
    $(shell sed -e 's/__NR_/__NR32_/g' /usr/include/asm/unistd_32.h > unistd_32.h)
else    
    F2_EXISTS=$(shell [[ -e /usr/include/asm-i386/unistd.h ]] && echo 1 || echo 0 )
    ifeq ($(F2_EXISTS), 1)
        $(info Copying custom header)
        $(shell sed -e 's/__NR_/__NR32_/g' /usr/include/asm-i386/unistd.h > unistd_32.h)
    else
        $(error asm/unistd_32.h and asm-386/unistd.h does not exist)
    endif
endif

You are trying to build unistd.h from unistd_32.h; the only trick is that unistd_32.h could be in either of two places. The simplest way to clean this up is to use a vpath directive:

vpath unistd.h /usr/include/asm /usr/include/asm-i386

unistd_32.h: unistd.h
    sed -e 's/__NR_/__NR32_/g' $< > $@

failed to find target with hash string 'android-22'

Open the Android SDK Manager and Update with latest :

  1. Android SDK Tools
  2. Android SDK Build Tools

Then Sync ,Re-Build and Restart Your Project Demo Code for build.gradle

   compileSdkVersion 21 // Now 23
   buildToolsVersion '21.1.2' //Now 23.0.1

   defaultConfig
    {
    minSdkVersion 15
    targetSdkVersion 19  
     }

Hope this helps .

Input button target="_blank" isn't causing the link to load in a new window/tab

use formtarget="_blank" its working for me

<input type="button" onClick="parent.location='http://www.facebook.com/'" value="facebook" formtarget="_blank">

Browser compatibility: from caniuse.com
IE: 10+ | Edge: 12+ | Firefox: 4+ | Chrome: 15+ | Safari/iOS: 5.1+ | Android: 4+

How can I convert a string to boolean in JavaScript?

WARNING: Never use this method for untrusted input, such as URL parameters.

You can use the eval() function. Directly pass your string to eval() function.

_x000D_
_x000D_
console.log(eval('true'), typeof eval('true'))
console.log(eval('false'), typeof eval('false'))
_x000D_
_x000D_
_x000D_

How to $http Synchronous call with AngularJS

I have worked with a factory integrated with google maps autocomplete and promises made??, I hope you serve.

http://jsfiddle.net/the_pianist2/vL9nkfe3/1/

you only need to replace the autocompleteService by this request with $ http incuida being before the factory.

app.factory('Autocomplete', function($q, $http) {

and $ http request with

 var deferred = $q.defer();
 $http.get('urlExample').
success(function(data, status, headers, config) {
     deferred.resolve(data);
}).
error(function(data, status, headers, config) {
     deferred.reject(status);
});
 return deferred.promise;

<div ng-app="myApp">
  <div ng-controller="myController">
  <input type="text" ng-model="search"></input>
  <div class="bs-example">
     <table class="table" >
        <thead>
           <tr>
              <th>#</th>
              <th>Description</th>
           </tr>
        </thead>
        <tbody>
           <tr ng-repeat="direction in directions">
              <td>{{$index}}</td>
              <td>{{direction.description}}</td>
           </tr>
        </tbody>
     </table>
  </div>

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

  app.factory('Autocomplete', function($q) {
    var get = function(search) {
    var deferred = $q.defer();
    var autocompleteService = new google.maps.places.AutocompleteService();
    autocompleteService.getPlacePredictions({
        input: search,
        types: ['geocode'],
        componentRestrictions: {
            country: 'ES'
        }
    }, function(predictions, status) {
        if (status == google.maps.places.PlacesServiceStatus.OK) {
            deferred.resolve(predictions);
        } else {
            deferred.reject(status);
        }
    });
    return deferred.promise;
};

return {
    get: get
};
});

app.controller('myController', function($scope, Autocomplete) {
$scope.$watch('search', function(newValue, oldValue) {
    var promesa = Autocomplete.get(newValue);
    promesa.then(function(value) {
        $scope.directions = value;
    }, function(reason) {
        $scope.error = reason;
    });
 });

});

the question itself is to be made on:

deferred.resolve(varResult); 

when you have done well and the request:

deferred.reject(error); 

when there is an error, and then:

return deferred.promise;

Regular expression [Any number]

UPDATE: for your updated question

variable.match(/\[[0-9]+\]/);

Try this:

variable.match(/[0-9]+/);    // for unsigned integers
variable.match(/[-0-9]+/);   // for signed integers
variable.match(/[-.0-9]+/);  // for signed float numbers

Hope this helps!

PHP Notice: Undefined offset: 1 with array when reading data

The output of the error, is because you call an index of the Array that does not exist, for example

$arr = Array(1,2,3);
echo $arr[3]; 
// Error PHP Notice:  Undefined offset: 1 pointer 3 does not exist, the array only has 3 elements but starts at 0 to 2, not 3!

Auto increment in phpmyadmin

@AmitKB, Your procedure is correct. Although this error

Query error: #1075 - Incorrect table definition; there can be only one auto column and it must be defined as a key

can be solved by first marking the field as key(using the key icon with label primary),unless you have other key then it may not work.

How to handle-escape both single and double quotes in an SQL-Update statement

Use two single quotes to escape them in the sql statement. The double quotes should not be a problem:

SELECT 'How is my son''s school helping him learn?  "Not as good as Stack Overflow would!"'

Print:

How is my son's school helping him learn? "Not as good as Stack Overflow would!"

Use a loop to plot n charts Python

Use a dictionary!!

You can also use dictionaries that allows you to have more control over the plots:

import matplotlib.pyplot as plt
#   plot 0     plot 1    plot 2   plot 3
x=[[1,2,3,4],[1,4,3,4],[1,2,3,4],[9,8,7,4]]
y=[[3,2,3,4],[3,6,3,4],[6,7,8,9],[3,2,2,4]]

plots = zip(x,y)
def loop_plot(plots):
    figs={}
    axs={}
    for idx,plot in enumerate(plots):
        figs[idx]=plt.figure()
        axs[idx]=figs[idx].add_subplot(111)
        axs[idx].plot(plot[0],plot[1])
return figs, axs

figs, axs = loop_plot(plots)

Now you can select the plot that you want to modify easily:

axs[0].set_title("Now I can control it!")

Of course, is up to you to decide what to do with the plots. You can either save them to disk figs[idx].savefig("plot_%s.png" %idx) or show them plt.show(). Use the argument block=False only if you want to pop up all the plots together (this could be quite messy if you have a lot of plots). You can do this inside the loop_plot function or in a separate loop using the dictionaries that the function provided.

How to add display:inline-block in a jQuery show() function?

<style>
.demo-ele{display:inline-block}
</style>

<div class="demo-ele" style="display:none">...</div>

<script>
$(".demo-ele").show(1000);//hide first, show with inline-block
<script>

Django - what is the difference between render(), render_to_response() and direct_to_template()?

Just one note I could not find in the answers above. In this code:

context_instance = RequestContext(request)
return render_to_response(template_name, user_context, context_instance)

What the third parameter context_instance actually does? Being RequestContext it sets up some basic context which is then added to user_context. So the template gets this extended context. What variables are added is given by TEMPLATE_CONTEXT_PROCESSORS in settings.py. For instance django.contrib.auth.context_processors.auth adds variable user and variable perm which are then accessible in the template.

Unordered List (<ul>) default indent

If you don't want indention in your list and also don't care about or don't want bullets, there is the CSS-free option of using a "definition list" (HTML 4.01) or "description list" (HTML 5). Use only the non-indenting definition <dt> tags, but not the indenting description <dd> tags, neither of which produces a bullet.

<dl>
  <dt>Item 1</dt>
  <dt>Item 2</dt>
  <dt>Item 3</dt>
</dl>

The output looks like this:

Item 1
Item 2
Item 3

How do I use .woff fonts for my website?

You need to declare @font-face like this in your stylesheet

@font-face {
  font-family: 'Awesome-Font';
  font-style: normal;
  font-weight: 400;
  src: local('Awesome-Font'), local('Awesome-Font-Regular'), url(path/Awesome-Font.woff) format('woff');
}

Now if you want to apply this font to a paragraph simply use it like this..

p {
font-family: 'Awesome-Font', Arial;
}

More Reference

Why can't I center with margin: 0 auto?

An inline-block covers the whole line (from left to right), so a margin left and/or right won't work here. What you need is a block, a block has borders on the left and the right so can be influenced by margins.

This is how it works for me:

#content {
display: block;
margin: 0 auto;
}

Inserting one list into another list in java?

no... Once u have executed the statement anotherList.addAll(list) and after that if u change some list data it does not carry to another list

How to copy data from one table to another new table in MySQL?

If you don't want to list the fields, and the structure of the tables is the same, you can do:

INSERT INTO `table2` SELECT * FROM `table1`;

or if you want to create a new table with the same structure:

CREATE TABLE new_tbl [AS] SELECT * FROM orig_tbl;

Reference for insert select; Reference for create table select

Understanding the Linux oom-killer's logs

Sum of total_vm is 847170 and sum of rss is 214726, these two values are counted in 4kB pages, which means when oom-killer was running, you had used 214726*4kB=858904kB physical memory and swap space.

Since your physical memory is 1GB and ~200MB was used for memory mapping, it's reasonable for invoking oom-killer when 858904kB was used.

rss for process 2603 is 181503, which means 181503*4KB=726012 rss, was equal to sum of anon-rss and file-rss.

[11686.043647] Killed process 2603 (flasherav) total-vm:1498536kB, anon-rss:721784kB, file-rss:4228kB

Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes

Please note that PrimeFaces supports the standard JSF 2.0+ keywords:

  • @this Current component.
  • @all Whole view.
  • @form Closest ancestor form of current component.
  • @none No component.

and the standard JSF 2.3+ keywords:

  • @child(n) nth child.
  • @composite Closest composite component ancestor.
  • @id(id) Used to search components by their id ignoring the component tree structure and naming containers.
  • @namingcontainer Closest ancestor naming container of current component.
  • @parent Parent of the current component.
  • @previous Previous sibling.
  • @next Next sibling.
  • @root UIViewRoot instance of the view, can be used to start searching from the root instead the current component.

But, it also comes with some PrimeFaces specific keywords:

  • @row(n) nth row.
  • @widgetVar(name) Component with given widgetVar.

And you can even use something called "PrimeFaces Selectors" which allows you to use jQuery Selector API. For example to process all inputs in a element with the CSS class myClass:

process="@(.myClass :input)"

See:

How to set a header for a HTTP GET request, and trigger file download?

I'm adding another option. The answers above were very useful for me, but I wanted to use jQuery instead of ic-ajax (it seems to have a dependency with Ember when I tried to install through bower). Keep in mind that this solution only works on modern browsers.

In order to implement this on jQuery I used jQuery BinaryTransport. This is a nice plugin to read AJAX responses in binary format.

Then you can do this to download the file and send the headers:

$.ajax({
    url: url,
    type: 'GET',
    dataType: 'binary',
    headers: headers,
    processData: false,
    success: function(blob) {
        var windowUrl = window.URL || window.webkitURL;
        var url = windowUrl.createObjectURL(blob);
        anchor.prop('href', url);
        anchor.prop('download', fileName);
        anchor.get(0).click();
        windowUrl.revokeObjectURL(url);
    }
});

The vars in the above script mean:

  • url: the URL of the file
  • headers: a Javascript object with the headers to send
  • fileName: the filename the user will see when downloading the file
  • anchor: it is a DOM element that is needed to simulate the download that must be wrapped with jQuery in this case. For example $('a.download-link').

Cannot access mongodb through browser - It looks like you are trying to access MongoDB over HTTP on the native driver port

Before Mongo 3.6:

You may start mongodb with

mongod --httpinterface

And access it on

http://localhost:28017

Since version 2.6: MongoDB disables the HTTP interface by default.

Update

HTTP Interface and REST API

MongoDB 3.6 removes the deprecated HTTP interface and REST API to MongoDB.

See Mongo http interface and rest api

Calling a php function by onclick event

Use this html code it will surely help you

<input type="button" value="NEXT"  onclick="document.write('<?php //call a function here ex- 'fun();' ?>');" />

one limitation is that it is taking more time to run so wait for few seconds it will work

how do I query sql for a latest record date for each user

SELECT *
FROM ReportStatus c
inner join ( SELECT 
  MAX(Date) AS MaxDate
  FROM ReportStatus ) m
on  c.date = m.maxdate

"Please try running this command again as Root/Administrator" error when trying to install LESS

I kept having this problem because windows was setting my node_modules folder to Readonly. Make sure you uncheck this.

enter image description here

Disabling and enabling a html input button

You can do this fairly easily with just straight JavaScript, no libraries required.

Enable a button

document.getElementById("Button").disabled=false;

Disable a button

 document.getElementById("Button").disabled=true;

No external libraries necessary.

How to Change color of Button in Android when Clicked?

Refer this,

boolean check = false;
Button backward_img;
Button backward_img1;
backward_img = (Button) findViewById(R.id.bars_footer_backward);
backward_img1 = (Button) findViewById(R.id.bars_footer_backward1);
backward_img.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View arg0) {
        check = true;
        backward_img.setBackgroundColor(Color.BLUE);
    }
});

if (check == true) {
    backward_img1.setBackgroundColor(Color.RED);
    backward_img.setBackgroundColor(Color.BLUE);
}

getDate with Jquery Datepicker

Instead of parsing day, month and year you can specify date formats directly using datepicker's formatDate function. In my example I am using "yy-mm-dd", but you can use any format of your choice.

$("#datepicker").datepicker({
    dateFormat: 'yy-mm-dd',
    inline: true,
    minDate: new Date(2010, 1 - 1, 1),
    maxDate: new Date(2010, 12 - 1, 31),
    altField: '#datepicker_value',
    onSelect: function(){
        var fullDate = $.datepicker.formatDate("yy-mm-dd", $(this).datepicker('getDate'));
        var str_output = "<h1><center><img src=\"/images/a" + fullDate +".png\"></center></h1><br/><br>";
        $('#page_output').html(str_output);
    }
});

Could not open ServletContext resource [/WEB-INF/applicationContext.xml]

ContextLoaderListener has its own context which is shared by all servlets and filters. By default it will search /WEB-INF/applicationContext.xml

You can customize this by using

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/somewhere-else/root-context.xml</param-value>
</context-param>

on web.xml, or remove this listener if you don't need one.

Where is GACUTIL for .net Framework 4.0 in windows 7?

There actually is now a GAC Utility for .NET 4.0. It is found in the Microsoft Windows 7 and .NET 4.0 SDK (the SDK supports multiple OSs -- not just Windows 7 -- so if you are using a later OS from Microsoft the odds are good that it's supported).

This is the SDK. You can download the ISO or do a Web install. Kind-of overkill to download the entire thing if all you want is the GAC Util; however, it does work.

How can I view all historical changes to a file in SVN

There's no built-in command for it, so I usually just do something like this:

#!/bin/bash

# history_of_file
#
# Outputs the full history of a given file as a sequence of
# logentry/diff pairs.  The first revision of the file is emitted as
# full text since there's not previous version to compare it to.

function history_of_file() {
    url=$1 # current url of file
    svn log -q $url | grep -E -e "^r[[:digit:]]+" -o | cut -c2- | sort -n | {

#       first revision as full text
        echo
        read r
        svn log -r$r $url@HEAD
        svn cat -r$r $url@HEAD
        echo

#       remaining revisions as differences to previous revision
        while read r
        do
            echo
            svn log -r$r $url@HEAD
            svn diff -c$r $url@HEAD
            echo
        done
    }
}

Then, you can call it with:

history_of_file $1

Scala check if element is present in a list

this should work also with different predicate

myFunction(strings.find( _ == mystring ).isDefined)

Using DISTINCT along with GROUP BY in SQL Server

Use DISTINCT to remove duplicate GROUPING SETS from the GROUP BY clause

In a completely silly example using GROUPING SETS() in general (or the special grouping sets ROLLUP() or CUBE() in particular), you could use DISTINCT in order to remove the duplicate values produced by the grouping sets again:

SELECT DISTINCT actors
FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
GROUP BY CUBE(actors, actors)

With DISTINCT:

actors
------
NULL
a
b

Without DISTINCT:

actors
------
a
b
NULL
a
b
a
b

But why, apart from making an academic point, would you do that?

Use DISTINCT to find unique aggregate function values

In a less far-fetched example, you might be interested in the DISTINCT aggregated values, such as, how many different duplicate numbers of actors are there?

SELECT DISTINCT COUNT(*)
FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
GROUP BY actors

Answer:

count
-----
2

Use DISTINCT to remove duplicates with more than one GROUP BY column

Another case, of course, is this one:

SELECT DISTINCT actors, COUNT(*)
FROM (VALUES('a', 1), ('a', 1), ('b', 1), ('b', 2)) t(actors, id)
GROUP BY actors, id

With DISTINCT:

actors  count
-------------
a       2
b       1

Without DISTINCT:

actors  count
-------------
a       2
b       1
b       1

For more details, I've written some blog posts, e.g. about GROUPING SETS and how they influence the GROUP BY operation, or about the logical order of SQL operations (as opposed to the lexical order of operations).

What does AngularJS do better than jQuery?

Data-Binding

You go around making your webpage, and keep on putting {{data bindings}} whenever you feel you would have dynamic data. Angular will then provide you a $scope handler, which you can populate (statically or through calls to the web server).

This is a good understanding of data-binding. I think you've got that down.

DOM Manipulation

For simple DOM manipulation, which doesnot involve data manipulation (eg: color changes on mousehover, hiding/showing elements on click), jQuery or old-school js is sufficient and cleaner. This assumes that the model in angular's mvc is anything that reflects data on the page, and hence, css properties like color, display/hide, etc changes dont affect the model.

I can see your point here about "simple" DOM manipulation being cleaner, but only rarely and it would have to be really "simple". I think DOM manipulation is one the areas, just like data-binding, where Angular really shines. Understanding this will also help you see how Angular considers its views.

I'll start by comparing the Angular way with a vanilla js approach to DOM manipulation. Traditionally, we think of HTML as not "doing" anything and write it as such. So, inline js, like "onclick", etc are bad practice because they put the "doing" in the context of HTML, which doesn't "do". Angular flips that concept on its head. As you're writing your view, you think of HTML as being able to "do" lots of things. This capability is abstracted away in angular directives, but if they already exist or you have written them, you don't have to consider "how" it is done, you just use the power made available to you in this "augmented" HTML that angular allows you to use. This also means that ALL of your view logic is truly contained in the view, not in your javascript files. Again, the reasoning is that the directives written in your javascript files could be considered to be increasing the capability of HTML, so you let the DOM worry about manipulating itself (so to speak). I'll demonstrate with a simple example.

This is the markup we want to use. I gave it an intuitive name.

<div rotate-on-click="45"></div>

First, I'd just like to comment that if we've given our HTML this functionality via a custom Angular Directive, we're already done. That's a breath of fresh air. More on that in a moment.

Implementation with jQuery

live demo here (click).

function rotate(deg, elem) {
  $(elem).css({
    webkitTransform: 'rotate('+deg+'deg)', 
    mozTransform: 'rotate('+deg+'deg)', 
    msTransform: 'rotate('+deg+'deg)', 
    oTransform: 'rotate('+deg+'deg)', 
    transform: 'rotate('+deg+'deg)'    
  });
}

function addRotateOnClick($elems) {
  $elems.each(function(i, elem) {
    var deg = 0;
    $(elem).click(function() {
      deg+= parseInt($(this).attr('rotate-on-click'), 10);
      rotate(deg, this);
    });
  });
}

addRotateOnClick($('[rotate-on-click]'));

Implementation with Angular

live demo here (click).

app.directive('rotateOnClick', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      var deg = 0;
      element.bind('click', function() {
        deg+= parseInt(attrs.rotateOnClick, 10);
        element.css({
          webkitTransform: 'rotate('+deg+'deg)', 
          mozTransform: 'rotate('+deg+'deg)', 
          msTransform: 'rotate('+deg+'deg)', 
          oTransform: 'rotate('+deg+'deg)', 
          transform: 'rotate('+deg+'deg)'    
        });
      });
    }
  };
});

Pretty light, VERY clean and that's just a simple manipulation! In my opinion, the angular approach wins in all regards, especially how the functionality is abstracted away and the dom manipulation is declared in the DOM. The functionality is hooked onto the element via an html attribute, so there is no need to query the DOM via a selector, and we've got two nice closures - one closure for the directive factory where variables are shared across all usages of the directive, and one closure for each usage of the directive in the link function (or compile function).

Two-way data binding and directives for DOM manipulation are only the start of what makes Angular awesome. Angular promotes all code being modular, reusable, and easily testable and also includes a single-page app routing system. It is important to note that jQuery is a library of commonly needed convenience/cross-browser methods, but Angular is a full featured framework for creating single page apps. The angular script actually includes its own "lite" version of jQuery so that some of the most essential methods are available. Therefore, you could argue that using Angular IS using jQuery (lightly), but Angular provides much more "magic" to help you in the process of creating apps.

This is a great post for more related information: How do I “think in AngularJS” if I have a jQuery background?

General differences.

The above points are aimed at the OP's specific concerns. I'll also give an overview of the other important differences. I suggest doing additional reading about each topic as well.

Angular and jQuery can't reasonably be compared.

Angular is a framework, jQuery is a library. Frameworks have their place and libraries have their place. However, there is no question that a good framework has more power in writing an application than a library. That's exactly the point of a framework. You're welcome to write your code in plain JS, or you can add in a library of common functions, or you can add a framework to drastically reduce the code you need to accomplish most things. Therefore, a more appropriate question is:

Why use a framework?

Good frameworks can help architect your code so that it is modular (therefore reusable), DRY, readable, performant and secure. jQuery is not a framework, so it doesn't help in these regards. We've all seen the typical walls of jQuery spaghetti code. This isn't jQuery's fault - it's the fault of developers that don't know how to architect code. However, if the devs did know how to architect code, they would end up writing some kind of minimal "framework" to provide the foundation (achitecture, etc) I discussed a moment ago, or they would add something in. For example, you might add RequireJS to act as part of your framework for writing good code.

Here are some things that modern frameworks are providing:

  • Templating
  • Data-binding
  • routing (single page app)
  • clean, modular, reusable architecture
  • security
  • additional functions/features for convenience

Before I further discuss Angular, I'd like to point out that Angular isn't the only one of its kind. Durandal, for example, is a framework built on top of jQuery, Knockout, and RequireJS. Again, jQuery cannot, by itself, provide what Knockout, RequireJS, and the whole framework built on top them can. It's just not comparable.

If you need to destroy a planet and you have a Death Star, use the Death star.

Angular (revisited).

Building on my previous points about what frameworks provide, I'd like to commend the way that Angular provides them and try to clarify why this is matter of factually superior to jQuery alone.

DOM reference.

In my above example, it is just absolutely unavoidable that jQuery has to hook onto the DOM in order to provide functionality. That means that the view (html) is concerned about functionality (because it is labeled with some kind of identifier - like "image slider") and JavaScript is concerned about providing that functionality. Angular eliminates that concept via abstraction. Properly written code with Angular means that the view is able to declare its own behavior. If I want to display a clock:

<clock></clock>

Done.

Yes, we need to go to JavaScript to make that mean something, but we're doing this in the opposite way of the jQuery approach. Our Angular directive (which is in it's own little world) has "augumented" the html and the html hooks the functionality into itself.

MVW Architecure / Modules / Dependency Injection

Angular gives you a straightforward way to structure your code. View things belong in the view (html), augmented view functionality belongs in directives, other logic (like ajax calls) and functions belong in services, and the connection of services and logic to the view belongs in controllers. There are some other angular components as well that help deal with configuration and modification of services, etc. Any functionality you create is automatically available anywhere you need it via the Injector subsystem which takes care of Dependency Injection throughout the application. When writing an application (module), I break it up into other reusable modules, each with their own reusable components, and then include them in the bigger project. Once you solve a problem with Angular, you've automatically solved it in a way that is useful and structured for reuse in the future and easily included in the next project. A HUGE bonus to all of this is that your code will be much easier to test.

It isn't easy to make things "work" in Angular.

THANK GOODNESS. The aforementioned jQuery spaghetti code resulted from a dev that made something "work" and then moved on. You can write bad Angular code, but it's much more difficult to do so, because Angular will fight you about it. This means that you have to take advantage (at least somewhat) to the clean architecture it provides. In other words, it's harder to write bad code with Angular, but more convenient to write clean code.

Angular is far from perfect. The web development world is always growing and changing and there are new and better ways being put forth to solve problems. Facebook's React and Flux, for example, have some great advantages over Angular, but come with their own drawbacks. Nothing's perfect, but Angular has been and is still awesome for now. Just as jQuery once helped the web world move forward, so has Angular, and so will many to come.

Angular/RxJs When should I unsubscribe from `Subscription`

I like the last two answers, but I experienced an issue if the the subclass referenced "this" in ngOnDestroy.

I modified it to be this, and it looks like it resolved that issue.

export abstract class BaseComponent implements OnDestroy {
    protected componentDestroyed$: Subject<boolean>;
    constructor() {
        this.componentDestroyed$ = new Subject<boolean>();
        let f = this.ngOnDestroy;
        this.ngOnDestroy = function()  {
            // without this I was getting an error if the subclass had
            // this.blah() in ngOnDestroy
            f.bind(this)();
            this.componentDestroyed$.next(true);
            this.componentDestroyed$.complete();
        };
    }
    /// placeholder of ngOnDestroy. no need to do super() call of extended class.
    ngOnDestroy() {}
}

What is the non-jQuery equivalent of '$(document).ready()'?

A little thing I put together

domready.js

(function(exports, d) {
  function domReady(fn, context) {

    function onReady(event) {
      d.removeEventListener("DOMContentLoaded", onReady);
      fn.call(context || exports, event);
    }

    function onReadyIe(event) {
      if (d.readyState === "complete") {
        d.detachEvent("onreadystatechange", onReadyIe);
        fn.call(context || exports, event);
      }
    }

    d.addEventListener && d.addEventListener("DOMContentLoaded", onReady) ||
    d.attachEvent      && d.attachEvent("onreadystatechange", onReadyIe);
  }

  exports.domReady = domReady;
})(window, document);

How to use it

<script src="domready.js"></script>
<script>
  domReady(function(event) {
    alert("dom is ready!");
  });
</script>

You can also change the context in which the callback runs by passing a second argument

function init(event) {
  alert("check the console");
  this.log(event);
}

domReady(init, console);

How do I express "if value is not empty" in the VBA language?

Alexphi's suggestion is good. You can also hard code this by first creating a variable as a Variant and then assigning it to Empty. Then do an if/then with to possibly fill it. If it gets filled, it's not empty, if it doesn't, it remains empty. You check this then with IsEmpty.

Sub TestforEmpty()

    Dim dt As Variant
    dt = Empty

    Dim today As Date
    today = Date
    If today = Date Then
        dt = today
    End If

    If IsEmpty(dt) Then
        MsgBox "It not is today"
    Else
        MsgBox "It is today"
    End If

End Sub

When doing a MERGE in Oracle SQL, how can I update rows that aren't matched in the SOURCE?

The following answer is to merge data into same table

MERGE INTO YOUR_TABLE d
USING (SELECT 1 FROM DUAL) m
    ON ( d.USER_ID = '123' AND d.USER_NAME= 'itszaif') 
WHEN NOT MATCHED THEN
        INSERT ( d.USERS_ID, d.USER_NAME)
        VALUES ('123','itszaif');

This command checks if USER_ID and USER_NAME are matched, if not matched then it will insert.

Restful API service

Lets say I want to start the service on an event - onItemClicked() of a button. The Receiver mechanism would not work in that case because :-
a) I passed the Receiver to the service (as in Intent extra) from onItemClicked()
b) Activity moves to the background. In onPause() I set the receiver reference within the ResultReceiver to null to avoid leaking the Activity.
c) Activity gets destroyed.
d) Activity gets created again. However at this point the Service will not be able to make a callback to the Activity as that receiver reference is lost.
The mechanism of a limited broadcast or a PendingIntent seems to be more usefull in such scenarios- refer to Notify activity from service

Why does the program give "illegal start of type" error?

You have an extra '{' before return type. You may also want to put '==' instead of '=' in if and else condition.

Vue.js data-bind style backgroundImage not working

The accepted answer didn't seem to solve the problem for me, but this did

Ensure your backgroundImage declarations are wrapped in url( and quotes so the style works correctly, no matter the file name.

ES2015 Style:

<div :style="{ backgroundImage: `url('${image}')` }"></div>

Or without ES2015:

<div :style="{ backgroundImage: 'url(\'' + image + '\')' }"></div>

Source: vuejs/vue-loader issue #646

How to create an Excel File with Nodejs?

excel4node is a maintained, native Excel file creator built from the official specification. It's similar to, but more maintained than mxexcel-builder mentioned in the other answer.

// Require library
var excel = require('excel4node');

// Create a new instance of a Workbook class
var workbook = new excel.Workbook();

// Add Worksheets to the workbook
var worksheet = workbook.addWorksheet('Sheet 1');
var worksheet2 = workbook.addWorksheet('Sheet 2');

// Create a reusable style
var style = workbook.createStyle({
  font: {
    color: '#FF0800',
    size: 12
  },
  numberFormat: '$#,##0.00; ($#,##0.00); -'
});

// Set value of cell A1 to 100 as a number type styled with paramaters of style
worksheet.cell(1,1).number(100).style(style);

// Set value of cell B1 to 300 as a number type styled with paramaters of style
worksheet.cell(1,2).number(200).style(style);

// Set value of cell C1 to a formula styled with paramaters of style
worksheet.cell(1,3).formula('A1 + B1').style(style);

// Set value of cell A2 to 'string' styled with paramaters of style
worksheet.cell(2,1).string('string').style(style);

// Set value of cell A3 to true as a boolean type styled with paramaters of style but with an adjustment to the font size.
worksheet.cell(3,1).bool(true).style(style).style({font: {size: 14}});

workbook.write('Excel.xlsx');

Create a Bitmap/Drawable from file path

Create bitmap from file path:

File sd = Environment.getExternalStorageDirectory();
File image = new File(sd+filePath, imageName);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(),bmOptions);
bitmap = Bitmap.createScaledBitmap(bitmap,parent.getWidth(),parent.getHeight(),true);
imageView.setImageBitmap(bitmap);

If you want to scale the bitmap to the parent's height and width then use Bitmap.createScaledBitmap function.

I think you are giving the wrong file path. :) Hope this helps.

How to filter an array from all elements of another array

You can write a generic filterByIndex() function and make use of type inference in TS to save the hassle with the callback function:

let's say you have your array [1,2,3,4] that you want to filter() with the indices specified in the [2,4] array.

var filtered = [1,2,3,4,].filter(byIndex(element => element, [2,4]))

the byIndex function expects the element function and an array and looks like this:

byIndex = (getter: (e:number) => number, arr: number[]) => (x: number) => {
    var i = getter(x);
    return arr.indexOf(i); 
}

result is then

filtered = [1,3]

How to add a border just on the top side of a UIView

Convert DanShev answer to Swift 3

extension CALayer {

func addBorder(edge: UIRectEdge, color: UIColor, thickness: CGFloat) {

    let border = CALayer()

    switch edge {
    case .top:
        border.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: thickness)
        break
    case .bottom:
        border.frame = CGRect(x: 0, y: self.frame.height - thickness, width: self.frame.width, height: thickness)
        break
    case .left:
        border.frame = CGRect(x: 0, y: 0, width: thickness, height: self.frame.height)
        break
    case .right:
        border.frame = CGRect(x: self.frame.width - thickness, y: 0, width: thickness, height: self.frame.height)
        break
    default:
        break
    }

    border.backgroundColor = color.cgColor;

    self.addSublayer(border)
}
}

How to pass data in the ajax DELETE request other than headers

deleteRequest: function (url, Id, bolDeleteReq, callback, errorCallback) {
    $.ajax({
        url: urlCall,
        type: 'DELETE',
        data: {"Id": Id, "bolDeleteReq" : bolDeleteReq},
        success: callback || $.noop,
        error: errorCallback || $.noop
    });
}

Note: the use of headers was introduced in JQuery 1.5.:

A map of additional header key/value pairs to send along with the request. This setting is set before the beforeSend function is called; therefore, any values in the headers setting can be overwritten from within the beforeSend function.

How to integrate sourcetree for gitlab

Sourcetree 3.x has an option to accept gitLab. See here. I now use Sourcetree 3.0.15. In Settings, put your remote gitLab host and url, etc. If your existing git client version is not supported any more, the easiest way is perhaps to use Sourcetree embedded Git by Tools->Options->Git, in Git Version near the bottom, choose Embedded. A download may happen.

Tensorflow set CUDA_VISIBLE_DEVICES within jupyter

You can set environment variables in the notebook using os.environ. Do the following before initializing TensorFlow to limit TensorFlow to first GPU.

import os
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"   # see issue #152
os.environ["CUDA_VISIBLE_DEVICES"]="0"

You can double check that you have the correct devices visible to TF

from tensorflow.python.client import device_lib
print device_lib.list_local_devices()

I tend to use it from utility module like notebook_util

import notebook_util
notebook_util.pick_gpu_lowest_memory()
import tensorflow as tf

How do I tell matplotlib that I am done with a plot?

There is a clear figure command, and it should do it for you:

plt.clf()

If you have multiple subplots in the same figure

plt.cla()

clears the current axes.

How to Access Hive via Python?

You can use hive library,for that you want to import hive Class from hive import ThriftHive

Try This example:

import sys

from hive import ThriftHive
from hive.ttypes import HiveServerException

from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol

try:
  transport = TSocket.TSocket('localhost', 10000)
  transport = TTransport.TBufferedTransport(transport)
  protocol = TBinaryProtocol.TBinaryProtocol(transport)
  client = ThriftHive.Client(protocol)
  transport.open()
  client.execute("CREATE TABLE r(a STRING, b INT, c DOUBLE)")
  client.execute("LOAD TABLE LOCAL INPATH '/path' INTO TABLE r")
  client.execute("SELECT * FROM r")
  while (1):
    row = client.fetchOne()
    if (row == None):
       break
    print row

  client.execute("SELECT * FROM r")
  print client.fetchAll()
  transport.close()
except Thrift.TException, tx:
  print '%s' % (tx.message)

Round up to Second Decimal Place in Python

Note that the ceil(num * 100) / 100 trick will crash on some degenerate inputs, like 1e308. This may not come up often but I can tell you it just cost me a couple of days. To avoid this, "it would be nice if" ceil() and floor() took a decimal places argument, like round() does... Meanwhile, anyone know a clean alternative that won't crash on inputs like this? I had some hopes for the decimal package but it seems to die too:

>>> from math import ceil
>>> from decimal import Decimal, ROUND_DOWN, ROUND_UP
>>> num = 0.1111111111000
>>> ceil(num * 100) / 100
0.12
>>> float(Decimal(num).quantize(Decimal('.01'), rounding=ROUND_UP))
0.12
>>> num = 1e308
>>> ceil(num * 100) / 100
Traceback (most recent call last):
  File "<string>", line 301, in runcode
  File "<interactive input>", line 1, in <module>
OverflowError: cannot convert float infinity to integer
>>> float(Decimal(num).quantize(Decimal('.01'), rounding=ROUND_UP))
Traceback (most recent call last):
  File "<string>", line 301, in runcode
  File "<interactive input>", line 1, in <module>
decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>]

Of course one might say that crashing is the only sane behavior on such inputs, but I would argue that it's not the rounding but the multiplication that's causing the problem (that's why, eg, 1e306 doesn't crash), and a cleaner implementation of the round-up-nth-place fn would avoid the multiplication hack.

Oracle ORA-12154: TNS: Could not resolve service name Error?

It has nothing to do with a space embedded in the folder structure.

I had the same problem. But when I created an environmental variable (defined both at the system- and user-level) called TNS_HOME and made it to point to the folder where TNSNAMES.ORA existed, the problem was resolved. Voila!

venki

java.lang.ClassCastException

ClassA a = <something>;
ClassB b = (ClassB) a;

The 2nd line will fail if ClassA is not a subclass of ClassB, and will throw a ClassCastException.

How do I find the location of my Python site-packages directory?

Answer to old question. But use ipython for this.

pip install ipython
ipython 
import imaplib
imaplib?

This will give the following output about imaplib package -

Type:        module
String form: <module 'imaplib' from '/usr/lib/python2.7/imaplib.py'>
File:        /usr/lib/python2.7/imaplib.py
Docstring:  
IMAP4 client.

Based on RFC 2060.

Public class:           IMAP4
Public variable:        Debug
Public functions:       Internaldate2tuple
                        Int2AP
                        ParseFlags
                        Time2Internaldate

How to use in jQuery :not and hasClass() to get a specific element without a class

jQuery's hasClass() method returns a boolean (true/false) and not an element. Also, the parameter to be given to it is a class name and not a selector as such.

For ex: x.hasClass('error');

How to execute a shell script on a remote server using Ansible?

You can use template module to copy if script exists on local machine to remote machine and execute it.

 - name: Copy script from local to remote machine
   hosts: remote_machine
   tasks:
    - name: Copy  script to remote_machine
      template: src=script.sh.2 dest=<remote_machine path>/script.sh mode=755
    - name: Execute script on remote_machine
      script: sh <remote_machine path>/script.sh

SQL Order By Count

Q. List the name of each show, and the number of different times it has been held. List the show which has been held most often first.

event_id show_id event_name judge_id
0101    01  Dressage        01
0102    01  Jumping         02
0103    01  Led in          01
0201    02  Led in          02
0301    03  Led in          01
0401    04  Dressage        04
0501    05  Dressage        01
0502    05  Flag and Pole   02

Ans:

select event_name, count(show_id) as held_times from event 
group by event_name 
order by count(show_id) desc

Variable is accessed within inner class. Needs to be declared final

Here's a funny answer.

You can declare a final one-element array and change the elements of the array all you want apparently. I'm sure it breaks the very reason why this compiler rule was implemented in the first place but it's handy when you're in a time-bind as I was today.

I actually can't claim credit for this one. It was IntelliJ's recommendation! Feels a bit hacky. But doesn't seem as bad as a global variable so I thought it worth mentioning here. It's just one solution to the problem. Not necessarily the best one.

final int[] tapCount = {0};

addSiteButton.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
       tapCount[0]++;
    }

});

How to draw text using only OpenGL methods?

Theory

Why it is hard

Popular font formats like TrueType and OpenType are vector outline formats: they use Bezier curves to define the boundary of the letter.

Image source.

Transforming those formats into arrays of pixels (rasterization) is too specific and out of OpenGL's scope, specially because OpenGl does not have non-straight primitives (e.g. see Why is there no circle or ellipse primitive in OpenGL?)

The easiest approach is to first raster fonts ourselves on the CPU, and then give the array of pixels to OpenGL as a texture.

OpenGL then knows how to deal with arrays of pixels through textures very well.

Texture atlas

We could raster characters for every frame and re-create the textures, but that is not very efficient, specially if characters have a fixed size.

The more efficient approach is to raster all characters you plan on using and cram them on a single texture.

And then transfer that to the GPU once, and use it texture with custom uv coordinates to choose the right character.

This approach is called a texture atlas and it can be used not only for textures but also other repeatedly used textures, like tiles in a 2D game or web UI icons.

The Wikipedia picture of the full texture, which is itself taken from freetype-gl, illustrates this well:

I suspect that optimizing character placement to the smallest texture problem is an NP-hard problem, see: What algorithm can be used for packing rectangles of different sizes into the smallest rectangle possible in a fairly optimal way?

The same technique is used in web development to transmit several small images (like icons) at once, but there it is called "CSS Sprites": https://css-tricks.com/css-sprites/ and are used to hide the latency of the network instead of that of the CPU / GPU communication.

Non-CPU raster methods

There also exist methods which don't use the CPU raster to textures.

CPU rastering is simple because it uses the GPU as little as possible, but we also start thinking if it would be possible to use the GPU efficiency further.

This FOSDEM 2014 video explains other existing techniques:

Fonts inside of the 3D geometry with perspective

Rendering fonts inside of the 3D geometry with perspective (compared to an orthogonal HUD) is much more complicated, because perspective could make one part of the character much closer to the screen and larger than the other, making an uniform CPU discretization (e.g. raster, tesselation) look bad on the close part. This is actually an active research topic:

enter image description here

Distance fields are one of the popular techniques now.

Implementations

The examples that follow were all tested on Ubuntu 15.10.

Because this is a complex problem as discussed previously, most examples are large, and would blow up the 30k char limit of this answer, so just clone the respective Git repositories to compile.

They are all fully open source however, so you can just RTFS.

FreeType solutions

FreeType looks like the dominant open source font rasterization library, so it would allow us to use TrueType and OpenType fonts, making it the most elegant solution.

Examples / tutorials:

Other font rasterizers

Those seem less good than FreeType, but may be more lightweight:

Anton's OpenGL 4 Tutorials example 26 "Bitmap fonts"

The font was created by the author manually and stored in a single .png file. Letters are stored in an array form inside the image.

This method is of course not very general, and you would have difficulties with internationalization.

Build with:

make -f Makefile.linux64

Output preview:

enter image description here

opengl-tutorial chapter 11 "2D fonts"

Textures are generated from DDS files.

The tutorial explains how the DDS files were created, using CBFG and Paint.Net.

Output preview:

enter image description here

For some reason Suzanne is missing for me, but the time counter works fine: https://github.com/opengl-tutorials/ogl/issues/15

FreeGLUT

GLUT has glutStrokeCharacter and FreeGLUT is open source... https://github.com/dcnieho/FreeGLUT/blob/FG_3_0_0/src/fg_font.c#L255

OpenGLText

https://github.com/tlorach/OpenGLText

TrueType raster. By NVIDIA employee. Aims for reusability. Haven't tried it yet.

ARM Mali GLES SDK Sample

http://malideveloper.arm.com/resources/sample-code/simple-text-rendering/ seems to encode all characters on a PNG, and cut them from there.

SDL_ttf

enter image description here

Source: https://github.com/cirosantilli/cpp-cheat/blob/d36527fe4977bb9ef4b885b1ec92bd0cd3444a98/sdl/ttf.c

Lives in a separate tree to SDL, and integrates easily.

Does not provide a texture atlas implementation however, so performance will be limited: How to render fonts and text with SDL2 efficiently?

Related threads

Safely override C++ virtual functions

As far as I know, can't you just make it abstract?

class parent {
public:
  virtual void handle_event(int something) const = 0 {
    // boring default code
  }
};

I thought I read on www.parashift.com that you can actually implement an abstract method. Which makes sense to me personally, the only thing it does is force subclasses to implement it, no one said anything about it not being allowed to have an implementation itself.

What is makeinfo, and how do I get it?

For Centos , I solve it by installing these packages.

yum install texi2html texinfo 

Dont worry if there is no entry for makeinfo. Just run

make all

You can do it similarly for ubuntu using sudo.

Changing the position of Bootstrap popovers based on the popover's X position in relation to window edge?

For Bootstrap 3, there is

placement: 'auto right'

which is easier. By default, it will be right, but if the element is located in the right side of the screen, the popover will be left. So it should be:

$('.infopoint').popover({
   trigger:'hover',
   animation: false,
   placement: 'auto right'
});

jQuery same click event for multiple elements

Simply use $('.myclass1, .myclass2, .myclass3') for multiple selectors. Also, you dont need lambda functions to bind an existing function to the click event.

What is the difference between char s[] and char *s?

Just to add: you also get different values for their sizes.

printf("sizeof s[] = %zu\n", sizeof(s));  //6
printf("sizeof *s  = %zu\n", sizeof(s));  //4 or 8

As mentioned above, for an array '\0' will be allocated as the final element.

How to have jQuery restrict file types on upload?

For the front-end it is pretty convenient to put 'accept' attribute if you are using a file field.

Example:

<input id="file" type="file" name="file" size="30" 
       accept="image/jpg,image/png,image/jpeg,image/gif" 
/>

A couple of important notes:

How to put a jpg or png image into a button in HTML

You can use some inline CSS like this

<input type="submit" name="submit" style="background: url(images/stack.png); width:100px; height:25px;" />

Should do the magic, also you may wanna do a border:none; to get rid of the standard borders.

Can table columns with a Foreign Key be NULL?

Another way around this would be to insert a DEFAULT element in the other table. For example, any reference to uuid=00000000-0000-0000-0000-000000000000 on the other table would indicate no action. You also need to set all the values for that id to be "neutral", e.g. 0, empty string, null in order to not affect your code logic.

Format Date time in AngularJS

Here are a few popular examples:

<div>{{myDate | date:'M/d/yyyy'}}</div> 7/4/2014

<div>{{myDate | date:'yyyy-MM-dd'}}</div> 2014-07-04

<div>{{myDate | date:'M/d/yyyy HH:mm:ss'}}</div> 7/4/2014 12:01:59

Javascript | Set all values of an array

The other answers are Ok, but a while loop seems more appropriate:

function setAll(array, value) {
  var i = array.length;
  while (i--) {
    array[i] = value;
  }
}

A more creative version:

function replaceAll(array, value) {
  var re = new RegExp(value, 'g');
  return new Array(++array.length).toString().replace(/,/g, value).match(re);
}

May not work everywhere though. :-)

UL or DIV vertical scrollbar

Sometimes it is not eligible to set height to pixel values. However, it is possible to show vertical scrollbar through setting height of div to 100% and overflow to auto.

Let me show an example:

<div id="content" style="height: 100%; overflow: auto">
  <p>some text</p>
  <ul>
    <li>text</li>
    .....
    <li>text</li>
</div>

Substitute a comma with a line break in a cell

For some reason, none of the above worked for me. This DID however:

  1. Selected the range of cells I needed to replace.
  2. Go to Home > Find & Select > Replace or Ctrl + H
  3. Find what: ,
  4. Replace with: CTRL + SHIFT + J
  5. Click Replace All

Somehow CTRL + SHIFT + J is registered as a linebreak.

Mapping two integers to one, in a unique and deterministic way

If you want more control such as allocate X bits for the first number and Y bits for the second number, you can use this code:

class NumsCombiner
{

    int num_a_bits_size;
    int num_b_bits_size;

    int BitsExtract(int number, int k, int p)
    {
        return (((1 << k) - 1) & (number >> (p - 1)));
    }

public:
    NumsCombiner(int num_a_bits_size, int num_b_bits_size)
    {
        this->num_a_bits_size = num_a_bits_size;
        this->num_b_bits_size = num_b_bits_size;
    }

    int StoreAB(int num_a, int num_b)
    {
        return (num_b << num_a_bits_size) | num_a;
    }

    int GetNumA(int bnum)
    {
        return BitsExtract(bnum, num_a_bits_size, 1);
    }

    int GetNumB(int bnum)
    {
        return BitsExtract(bnum, num_b_bits_size, num_a_bits_size + 1);
    }
};

I use 32 bits in total. The idea here is that if you want for example that first number will be up to 10 bits and second number will be up to 12 bits, you can do this:

NumsCombiner nums_mapper(10/*bits for first number*/, 12/*bits for second number*/);

Now you can store in num_a the maximum number that is 2^10 - 1 = 1023 and in num_b naximum value of 2^12 - 1 = 4095.

To set value for num A and num B:

int bnum = nums_mapper.StoreAB(10/*value for a*/, 12 /*value from b*/);

Now bnum is all of the bits (32 bits in total. You can modify the code to use 64 bits) To get num a:

int a = nums_mapper.GetNumA(bnum);

To get num b:

int b = nums_mapper.GetNumB(bnum);

EDIT: bnum can be stored inside the class. I did not did it because my own needs I shared the code and hope that it will be helpful.

Thanks for source: https://www.geeksforgeeks.org/extract-k-bits-given-position-number/ for function to extract bits and thanks also to mouviciel answer in this post. Using these to sources I could figure out more advanced solution

foreach loop in angularjs

The angular.forEach() will iterate through your json object.

First iteration,

key = 0, value = { "name" : "Thomas", "password" : "thomasTheKing"}

Second iteration,

key = 1, value = { "name" : "Linda", "password" : "lindatheQueen" }

To get the value of your name, you can use value.name or value["name"]. Same with your password, you use value.password or value["password"].

The code below will give you what you want:

   angular.forEach(json, function (value, key)
         {
                //console.log(key);
                //console.log(value);
                if (value.password == "thomasTheKing") {
                    console.log("username is thomas");
                }
         });

How do I implement IEnumerable<T>

Why do you do it manually? yield return automates the entire process of handling iterators. (I also wrote about it on my blog, including a look at the compiler generated code).

If you really want to do it yourself, you have to return a generic enumerator too. You won't be able to use an ArrayList any more since that's non-generic. Change it to a List<MyObject> instead. That of course assumes that you only have objects of type MyObject (or derived types) in your collection.

Twitter Bootstrap Tabs: Go to Specific Tab on Page Reload or Hyperlink

I know this thread is very old, but I'll leave here my own implementation:

$(function () {
  // some initialization code

  addTabBehavior()
})

// Initialize events and change tab on first page load.
function addTabBehavior() {
  $('.nav-tabs a').on('show.bs.tab', e => {
    window.location.hash = e.target.hash.replace('nav-', '')
  })

  $(window).on('popstate', e => {
    changeTab()
  })

  changeTab()
}

// Change the current tab and URL hash; if don't have any hash
// in URL, so activate the first tab and update the URL hash.
function changeTab() {
  const hash = getUrlHash()

  if (hash) {
    $(`.nav-tabs a[href="#nav-${hash}"]`).tab('show')
  } else {
    $('.nav-tabs a').first().tab('show')
  }
}

// Get the hash from URL. Ex: www.example.com/#tab1
function getUrlHash() {
  return window.location.hash.slice(1)
}

Note that I'm using a nav- class prefix to nav links.

Check if a key exists inside a json object

Try this,

if(thisSession.hasOwnProperty('merchant_id')){

}

the JS Object thisSession should be like

{
amt: "10.00",
email: "[email protected]",
merchant_id: "sam",
mobileNo: "9874563210",
orderID: "123456",
passkey: "1234"
}

you can find the details here

Exporting to .xlsx using Microsoft.Office.Interop.Excel SaveAs Error

This is how you save the relevant file as a Excel12 (.xlsx) file... It is not as you would intuitively think i.e. using Excel.XlFileFormat.xlExcel12 but Excel.XlFileFormat.xlOpenXMLWorkbook. The actual C# command was

excelWorkbook.SaveAs(strFullFilePathNoExt, Excel.XlFileFormat.xlOpenXMLWorkbook, Missing.Value,
    Missing.Value, false, false, Excel.XlSaveAsAccessMode.xlNoChange, 
    Excel.XlSaveConflictResolution.xlUserResolution, true, 
    Missing.Value, Missing.Value, Missing.Value);

I hope this helps someone else in the future.


Missing.Value is found in the System.Reflection namespace.

Understanding the Gemfile.lock file

What does the exclamation mark after the gem name in the 'DEPENDECIES' group mean?

The exclamation mark appears when the gem was installed using a source other than "https://rubygems.org".

Datatables - Search Box outside datatable

This one helped me for DataTables Version 1.10.4, because its new API

var oTable = $('#myTable').DataTable();    
$('#myInputTextField').keyup(function(){
   oTable.search( $(this).val() ).draw();
})

Sending simple message body + file attachment using Linux Mailx

You can try this:

(cat ./body.txt)|mailx -s "subject text" -a "attchement file" [email protected]

How to choose between Hudson and Jenkins?

I've got two points to add. One, Hudson/Jenkins is all about the plugins. Plugin developers have moved to Jenkins and so should we, the users. Two, I am not personally a big fan of Oracle's products. In fact, I avoid them like the plague. For the money spent on licensing and hardware for an Oracle solution you can hire twice the engineering staff and still have some left over to buy beer every Friday :)

Messages Using Command prompt in Windows 7

Open Notepad and write this

@echo off
:A
Cls
echo MESSENGER
set /p n=User:
set /p m=Message:
net send %n% %m%
Pause
Goto A

and then save as "Messenger.bat" and close the Notepad
Step 1:

when you open that saved notepad file it will open as a file Messenger command prompt with this details.

Messenger
User:

after "User" write the ip of the computer you want to contact and then press enter.

pip installation /usr/local/opt/python/bin/python2.7: bad interpreter: No such file or directory

I had the same issue. I have both Python 2.7 & 3.6 installed. Python 2.7 had virtualenv working, but after installing Python3, virtualenv kept looking for version 2.7 and couldn't find it. Doing pip install virtualenv installed the Python3 version of virtualenv.

Then, for each command, if I want to use Python2, I would use virtualenv --python=python2.7 somecommand

Format bytes to kilobytes, megabytes, gigabytes

I did this converting all input to byte and so converting to any output needed. Also, I used a auxiliar function to get base 1000 or 1024, but left it flex to decide use 1024 on popular type (without 'i', like MB instead of MiB).

    public function converte_binario($size=0,$format_in='B',$format_out='MB',$force_in_1024=false,$force_out_1024=false,$precisao=5,$return_format=true,$decimal=',',$centena=''){
    $out = false;

    if( (is_numeric($size)) && ($size>0)){
        $in_data = $this->converte_binario_aux($format_in,$force_in_1024);
        $out_data = $this->converte_binario_aux($format_out,$force_out_1024);

        // se formato de entrada e saída foram encontrados
        if( ((isset($in_data['sucesso'])) && ($in_data['sucesso']==true)) && ((isset($out_data['sucesso'])) && ($out_data['sucesso']==true))){
            // converte formato de entrada para bytes.
            $size_bytes_in = $size * (pow($in_data['base'], $in_data['pot']));
            $size_byte_out = (pow($out_data['base'], $out_data['pot']));
            // transforma bytes na unidade de destino
            $out = number_format($size_bytes_in / $size_byte_out,$precisao,$decimal,$centena);
            if($return_format){
                $out .= $format_out;
            }
        }
    }
    return $out;
}

public function converte_binario_aux($format=false,$force_1024=false){
    $out = [];
    $out['sucesso'] = false;
    $out['base'] = 0;
    $out['pot'] = 0;
    if((is_string($format) && (strlen($format)>0))){
        $format = trim(strtolower($format));
        $units_1000 = ['b','kb' ,'mb' ,'gb' ,'tb' ,'pb' ,'eb' ,'zb' ,'yb' ];
        $units_1024 = ['b','kib','mib','gib','tib','pib','eib','zib','yib'];
        $pot = array_search($format,$units_1000);
        if( (is_numeric($pot)) && ($pot>=0)){
            $out['pot'] = $pot;
            $out['base'] = 1000;
            $out['sucesso'] = true;
        }
        else{
            $pot = array_search($format,$units_1024);
            if( (is_numeric($pot)) && ($pot>=0)){
                $out['pot'] = $pot;
                $out['base'] = 1024;
                $out['sucesso'] = true;
            }
        }
        if($force_1024){
            $out['base'] = 1024;
        }
    }
    return $out;
}

Can I use CASE statement in a JOIN condition?

A CASE expression returns a value from the THEN portion of the clause. You could use it thusly:

SELECT  * 
FROM    sys.indexes i 
    JOIN sys.partitions p 
        ON i.index_id = p.index_id  
    JOIN sys.allocation_units a 
        ON CASE 
           WHEN a.type IN (1, 3) AND a.container_id = p.hobt_id THEN 1
           WHEN a.type IN (2) AND a.container_id = p.partition_id THEN 1
           ELSE 0
           END = 1

Note that you need to do something with the returned value, e.g. compare it to 1. Your statement attempted to return the value of an assignment or test for equality, neither of which make sense in the context of a CASE/THEN clause. (If BOOLEAN was a datatype then the test for equality would make sense.)

javascript unexpected identifier

It looks like there is an extra curly bracket in the code.

function () {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        document.getElementById("content").innerHTML = xmlhttp.responseText;
    }
// extra bracket }
xmlhttp.open("GET", "data/" + id + ".html", true);
xmlhttp.send();
}

Superscript in markdown (Github flavored)?

<sup> and <sub> tags work and are your only good solution for arbitrary text. Other solutions include:

Unicode

If the superscript (or subscript) you need is of a mathematical nature, Unicode may well have you covered.

I've compiled a list of all the Unicode super and subscript characters I could identify in this gist. Some of the more common/useful ones are:

  • ° SUPERSCRIPT ZERO (U+2070)
  • ¹ SUPERSCRIPT ONE (U+00B9)
  • ² SUPERSCRIPT TWO (U+00B2)
  • ³ SUPERSCRIPT THREE (U+00B3)
  • n SUPERSCRIPT LATIN SMALL LETTER N (U+207F)

People also often reach for <sup> and <sub> tags in an attempt to render specific symbols like these:

  • TRADE MARK SIGN (U+2122)
  • ® REGISTERED SIGN (U+00AE)
  • ? SERVICE MARK (U+2120)

Assuming your editor supports Unicode, you can copy and paste the characters above directly into your document.

Alternatively, you could use the hex values above in an HTML character escape. Eg, &#x00B2; instead of ². This works with GitHub (and should work anywhere else your Markdown is rendered to HTML) but is less readable when presented as raw text/Markdown.

Images

If your requirements are especially unusual, you can always just inline an image. The GitHub supported syntax is:

![Alt text goes here, if you'd like](path/to/image.png) 

You can use a full path (eg. starting with https:// or http://) but it's often easier to use a relative path, which will load the image from the repo, relative to the Markdown document.

If you happen to know LaTeX (or want to learn it) you could do just about any text manipulation imaginable and render it to an image. Sites like Quicklatex make this quite easy.

Passing an array/list into a Python function

You can pass lists just like other types:

l = [1,2,3]

def stuff(a):
   for x in a:
      print a


stuff(l)

This prints the list l. Keep in mind lists are passed as references not as a deep copy.

How to kill a process running on particular port in Linux?

In Windows, it will be netstat -ano | grep "8080" and we get the following message TCP 0.0.0.0:8080 0.0.0.0:0 LISTENING 10076

WE can kill the PID using taskkill /F /PID 10076

Create own colormap using matplotlib and plot color scale

If you want to automate the creating of a custom divergent colormap commonly used for surface plots, this module combined with @unutbu method worked well for me.

def diverge_map(high=(0.565, 0.392, 0.173), low=(0.094, 0.310, 0.635)):
    '''
    low and high are colors that will be used for the two
    ends of the spectrum. they can be either color strings
    or rgb color tuples
    '''
    c = mcolors.ColorConverter().to_rgb
    if isinstance(low, basestring): low = c(low)
    if isinstance(high, basestring): high = c(high)
    return make_colormap([low, c('white'), 0.5, c('white'), high])

The high and low values can be either string color names or rgb tuples. This is the result using the surface plot demo: enter image description here

Any way to break if statement in PHP?

Because you can break out of a do/while loop, let us "do" one round. With a while(false) at the end, the condition is never true and will not repeat, again.

do
{
    $subjectText = trim(filter_input(INPUT_POST, 'subject'));
    if(!$subjectText)
    {
        $smallInfo = 'Please give a subject.';
        break;
    }

    $messageText = trim(filter_input(INPUT_POST, 'message'));
    if(!$messageText)
    {
        $smallInfo = 'Please supply a message.';
        break;
    }
} while(false);

C# Iterating through an enum? (Indexing a System.Array)

How about a dictionary list?

Dictionary<string, int> list = new Dictionary<string, int>();
foreach( var item in Enum.GetNames(typeof(MyEnum)) )
{
    list.Add(item, (int)Enum.Parse(typeof(MyEnum), item));
}

and of course you can change the dictionary value type to whatever your enum values are.

MySQL: selecting rows where a column is null

SELECT pid FROM planets WHERE userid IS NULL

Log record changes in SQL server in an audit table

I know this is old, but maybe this will help someone else.

Do not log "new" values. Your existing table, GUESTS, has the new values. You'll have double entry of data, plus your DB size will grow way too fast that way.

I cleaned this up and minimized it for this example, but here is the tables you'd need for logging off changes:

CREATE TABLE GUESTS (
      GuestID INT IDENTITY(1,1) PRIMARY KEY, 
      GuestName VARCHAR(50), 
      ModifiedBy INT, 
      ModifiedOn DATETIME
)

CREATE TABLE GUESTS_LOG (
      GuestLogID INT IDENTITY(1,1) PRIMARY KEY, 
      GuestID INT, 
      GuestName VARCHAR(50), 
      ModifiedBy INT, 
      ModifiedOn DATETIME
)

When a value changes in the GUESTS table (ex: Guest name), simply log off that entire row of data, as-is, to your Log/Audit table using the Trigger. Your GUESTS table has current data, the Log/Audit table has the old data.

Then use a select statement to get data from both tables:

SELECT 0 AS 'GuestLogID', GuestID, GuestName, ModifiedBy, ModifiedOn FROM [GUESTS] WHERE GuestID = 1
UNION
SELECT GuestLogID, GuestID, GuestName, ModifiedBy, ModifiedOn FROM [GUESTS_LOG] WHERE GuestID = 1
ORDER BY ModifiedOn ASC

Your data will come out with what the table looked like, from Oldest to Newest, with the first row being what was created & the last row being the current data. You can see exactly what changed, who changed it, and when they changed it.

Optionally, I used to have a function that looped through the RecordSet (in Classic ASP), and only displayed what values had changed on the web page. It made for a GREAT audit trail so that users could see what had changed over time.

Java string replace and the NUL (NULL, ASCII 0) character?

This does cause "funky characters":

System.out.println( "Mr. Foo".trim().replace('.','\0'));

produces:

Mr[] Foo

in my Eclipse console, where the [] is shown as a square box. As others have posted, use String.replace().

Codeigniter unset session

$session_data = array('username' =>"shashikant");
$this->session->set_userdata('logged_in', $session_data);

$this->session->unset_userdata('logged_in');

BootStrap : Uncaught TypeError: $(...).datetimepicker is not a function

I had the same problem, you have to load first the Moment.js file!

_x000D_
_x000D_
<script src="path/moment.js"></script>_x000D_
<script src="path/bootstrap-datetimepicker.js"></script>
_x000D_
_x000D_
_x000D_

check if array is empty (vba excel)

@jeminar has the best solution above.

I cleaned it up a bit though.

I recommend adding this to a FunctionsArray module

  • isInitialised=false is not needed because Booleans are false when created
  • On Error GoTo 0 wrap and indent code inside error blocks similar to with blocks for visibility. these methods should be avoided as much as possible but ... VBA ...
Function isInitialised(ByRef a() As Variant) As Boolean
    On Error Resume Next
    isInitialised = IsNumeric(UBound(a))
    On Error GoTo 0
End Function

Where is my .vimrc file?

Here are a few more tips:

  • In Arch Linux the global one is at /etc/vimrc. There are some comments in there with helpful details.

  • Since the filename starts with a ., it's hidden unless you use ls -a to show ALL files.

  • Typing :version while in Vim will show you a bunch of interesting information including the file location.

  • If you're not sure what ~/.vimrc means look at this question.

"Uncaught TypeError: Illegal invocation" in Chrome

When you execute a method (i.e. function assigned to an object), inside it you can use this variable to refer to this object, for example:

_x000D_
_x000D_
var obj = {_x000D_
  someProperty: true,_x000D_
  someMethod: function() {_x000D_
    console.log(this.someProperty);_x000D_
  }_x000D_
};_x000D_
obj.someMethod(); // logs true
_x000D_
_x000D_
_x000D_

If you assign a method from one object to another, its this variable refers to the new object, for example:

_x000D_
_x000D_
var obj = {_x000D_
  someProperty: true,_x000D_
  someMethod: function() {_x000D_
    console.log(this.someProperty);_x000D_
  }_x000D_
};_x000D_
_x000D_
var anotherObj = {_x000D_
  someProperty: false,_x000D_
  someMethod: obj.someMethod_x000D_
};_x000D_
_x000D_
anotherObj.someMethod(); // logs false
_x000D_
_x000D_
_x000D_

The same thing happens when you assign requestAnimationFrame method of window to another object. Native functions, such as this, has build-in protection from executing it in other context.

There is a Function.prototype.call() function, which allows you to call a function in another context. You just have to pass it (the object which will be used as context) as a first parameter to this method. For example alert.call({}) gives TypeError: Illegal invocation. However, alert.call(window) works fine, because now alert is executed in its original scope.

If you use .call() with your object like that:

support.animationFrame.call(window, function() {});

it works fine, because requestAnimationFrame is executed in scope of window instead of your object.

However, using .call() every time you want to call this method, isn't very elegant solution. Instead, you can use Function.prototype.bind(). It has similar effect to .call(), but instead of calling the function, it creates a new function which will always be called in specified context. For example:

_x000D_
_x000D_
window.someProperty = true;_x000D_
var obj = {_x000D_
  someProperty: false,_x000D_
  someMethod: function() {_x000D_
    console.log(this.someProperty);_x000D_
  }_x000D_
};_x000D_
_x000D_
var someMethodInWindowContext = obj.someMethod.bind(window);_x000D_
someMethodInWindowContext(); // logs true
_x000D_
_x000D_
_x000D_

The only downside of Function.prototype.bind() is that it's a part of ECMAScript 5, which is not supported in IE <= 8. Fortunately, there is a polyfill on MDN.

As you probably already figured out, you can use .bind() to always execute requestAnimationFrame in context of window. Your code could look like this:

var support = {
    animationFrame: (window.requestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        window.oRequestAnimationFrame).bind(window)
};

Then you can simply use support.animationFrame(function() {});.

Android open pdf file

The problem is that there is no app installed to handle opening the PDF. You should use the Intent Chooser, like so:

File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +"/"+ filename);
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file),"application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

Intent intent = Intent.createChooser(target, "Open File");
try {
    startActivity(intent);
} catch (ActivityNotFoundException e) {
    // Instruct the user to install a PDF reader here, or something
}   

Can't start Tomcat as Windows Service

Solution suggested by Prashant worked fine for me.

Tomcat9 Properties > Configure > Startup > Mode = Java Tomcat9 Properties > Configure > Shutdown > Mode = Java

Detect end of ScrollView

I found a simple way to detect this :

   scrollView.getViewTreeObserver()
       .addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
            @Override
            public void onScrollChanged() {
                if (scrollView.getChildAt(0).getBottom()
                     <= (scrollView.getHeight() + scrollView.getScrollY())) {
                    //scroll view is at bottom
                } else {
                    //scroll view is not at bottom
                }
            }
        });
  • Doesn't need to custom ScrollView.
  • Scrollview can host only one direct child, so scrollView.getChildAt(0) is okay.
  • This solution is right even the height of direct child of scroll view is match_parent or wrap_content.

How do I draw a shadow under a UIView?

Sketch Shadow Using IBDesignable and IBInspectable in Swift 4

HOW TO USE IT

DEMO

SKETCH AND XCODE SIDE BY SIDE

Shadow Exampl

CODE

@IBDesignable class ShadowView: UIView {

    @IBInspectable var shadowColor: UIColor? {
        get {
            if let color = layer.shadowColor {
                return UIColor(cgColor: color)
            }
            return nil
        }
        set {
            if let color = newValue {
                layer.shadowColor = color.cgColor
            } else {
                layer.shadowColor = nil
            }
        }
    }

    @IBInspectable var shadowOpacity: Float {
        get {
            return layer.shadowOpacity
        }
        set {
            layer.shadowOpacity = newValue
        }
    }

    @IBInspectable var shadowOffset: CGPoint {
        get {
            return CGPoint(x: layer.shadowOffset.width, y:layer.shadowOffset.height)
        }
        set {
            layer.shadowOffset = CGSize(width: newValue.x, height: newValue.y)
        }

     }

    @IBInspectable var shadowBlur: CGFloat {
        get {
            return layer.shadowRadius
        }
        set {
            layer.shadowRadius = newValue / 2.0
        }
    }

    @IBInspectable var shadowSpread: CGFloat = 0 {
        didSet {
            if shadowSpread == 0 {
                layer.shadowPath = nil
            } else {
                let dx = -shadowSpread
                let rect = bounds.insetBy(dx: dx, dy: dx)
                layer.shadowPath = UIBezierPath(rect: rect).cgPath
            }
        }
    }
}

OUTPUT

DEMO OUTPUT

How to check postgres user and password?

You will not be able to find out the password he chose. However, you may create a new user or set a new password to the existing user.

Usually, you can login as the postgres user:

Open a Terminal and do sudo su postgres. Now, after entering your admin password, you are able to launch psql and do

CREATE USER yourname WITH SUPERUSER PASSWORD 'yourpassword';

This creates a new admin user. If you want to list the existing users, you could also do

\du

to list all users and then

ALTER USER yourusername WITH PASSWORD 'yournewpass';

Get top n records for each group of grouped results

If the other answers are not fast enough Give this code a try:

SELECT
        province, n, city, population
    FROM
      ( SELECT  @prev := '', @n := 0 ) init
    JOIN
      ( SELECT  @n := if(province != @prev, 1, @n + 1) AS n,
                @prev := province,
                province, city, population
            FROM  Canada
            ORDER BY
                province   ASC,
                population DESC
      ) x
    WHERE  n <= 3
    ORDER BY  province, n;

Output:

+---------------------------+------+------------------+------------+
| province                  | n    | city             | population |
+---------------------------+------+------------------+------------+
| Alberta                   |    1 | Calgary          |     968475 |
| Alberta                   |    2 | Edmonton         |     822319 |
| Alberta                   |    3 | Red Deer         |      73595 |
| British Columbia          |    1 | Vancouver        |    1837970 |
| British Columbia          |    2 | Victoria         |     289625 |
| British Columbia          |    3 | Abbotsford       |     151685 |
| Manitoba                  |    1 | ...

angular-cli server - how to specify default port

There might be a situation when you want to use NodeJS environment variable to specify Angular CLI dev server port. One of the possible solution is to move CLI dev server running into a separate NodeJS script, which will read port value (e.g from .env file) and use it executing ng serve with port parameter:

// run-env.js
const dotenv = require('dotenv');
const child_process = require('child_process');

const config = dotenv.config()
const DEV_SERVER_PORT = process.env.DEV_SERVER_PORT || 4200;

const child = child_process.exec(`ng serve --port=${DEV_SERVER_PORT}`);
child.stdout.on('data', data => console.log(data.toString()));

Then you may a) run this script directly via node run-env, b) run it via npm by updating package.json, for example

"scripts": {
  "start": "node run-env"
}

run-env.js should be committed to the repo, .env should not. More details on the approach can be found in this post: How to change Angular CLI Development Server Port via .env.

JSON and XML comparison

The important thing about JSON is to keep data transfer encrypted for security reasons. No doubt that JSON is much much faster then XML. I have seen XML take 100ms where as JSON only took 60ms. JSON data is easy to manipulate.

why are there two different kinds of for loops in java?

The first is the original for loop. You initialize a variable, set a terminating condition, and provide a state incrementing/decrementing counter (There are exceptions, but this is the classic)

For that,

for (int i=0;i<myString.length;i++) { 
  System.out.println(myString[i]); 
}

is correct.

For Java 5 an alternative was proposed. Any thing that implements iterable can be supported. This is particularly nice in Collections. For example you can iterate the list like this

List<String> list = ....load up with stuff

for (String string : list) {
  System.out.println(string);
}

instead of

for (int i=0; i<list.size();i++) {
  System.out.println(list.get(i));
}

So it's just an alternative notation really. Any item that implements Iterable (i.e. can return an iterator) can be written that way.

What's happening behind the scenes is somethig like this: (more efficient, but I'm writing it explicitly)

Iterator<String> it = list.iterator();
while (it.hasNext()) {
  String string=it.next();
  System.out.println(string);
}

In the end it's just syntactic sugar, but rather convenient.

START_STICKY and START_NOT_STICKY

Both codes are only relevant when the phone runs out of memory and kills the service before it finishes executing. START_STICKY tells the OS to recreate the service after it has enough memory and call onStartCommand() again with a null intent. START_NOT_STICKY tells the OS to not bother recreating the service again. There is also a third code START_REDELIVER_INTENT that tells the OS to recreate the service and redeliver the same intent to onStartCommand().

This article by Dianne Hackborn explained the background of this a lot better than the official documentation.

Source: http://android-developers.blogspot.com.au/2010/02/service-api-changes-starting-with.html

The key part here is a new result code returned by the function, telling the system what it should do with the service if its process is killed while it is running:

START_STICKY is basically the same as the previous behavior, where the service is left "started" and will later be restarted by the system. The only difference from previous versions of the platform is that it if it gets restarted because its process is killed, onStartCommand() will be called on the next instance of the service with a null Intent instead of not being called at all. Services that use this mode should always check for this case and deal with it appropriately.

START_NOT_STICKY says that, after returning from onStartCreated(), if the process is killed with no remaining start commands to deliver, then the service will be stopped instead of restarted. This makes a lot more sense for services that are intended to only run while executing commands sent to them. For example, a service may be started every 15 minutes from an alarm to poll some network state. If it gets killed while doing that work, it would be best to just let it be stopped and get started the next time the alarm fires.

START_REDELIVER_INTENT is like START_NOT_STICKY, except if the service's process is killed before it calls stopSelf() for a given intent, that intent will be re-delivered to it until it completes (unless after some number of more tries it still can't complete, at which point the system gives up). This is useful for services that are receiving commands of work to do, and want to make sure they do eventually complete the work for each command sent.

"unmappable character for encoding" warning in Java

Most of the time this compile error comes when unicode(UTF-8 encoded) file compiling

javac -encoding UTF-8 HelloWorld.java

and also You can add this compile option to your IDE ex: Intellij idea
(File>settings>Java Compiler) add as additional command line parameter

enter image description here

-encoding : encoding Set the source file encoding name, such as EUC-JP and UTF-8.. If -encoding is not specified, the platform default converter is used. (DOC)

Write a mode method in Java to find the most frequently occurring element in an array

Here is my answer.

public static int mode(int[] arr) {
    int max = 0;
    int maxFreq = 0;

    Arrays.sort(arr);
    max = arr[arr.length-1];

    int[] count = new int[max + 1];

    for (int i = 0; i < arr.length; i++) {
        count[arr[i]]++;
    }

     for (int i = 0; i < count.length; i++) {
        if (count[i] > maxFreq) {
            maxFreq = count[i];
        }
    }

    for (int i = 0; i < count.length; i++) {
        if (count[i] == maxFreq) {
            return i;
        }
    }
    return -1;
}

Printing reverse of any String without using any predefined function?

Code will be as below:

public class RemoveString {

public static void main(String[] args) {

Scanner scanner=new Scanner(System.in);

String s=scanner.next();

String st="";

for(int i=s.length()-1;i>=0;i--){

st=st+s.charAt(i);


}

System.out.println(st);

}

}

Excel Formula which places date/time in cell when data is entered in another cell in the same row

Not sure if this works for cells with functions but I found this code elsewhere for single cell entries and modified it for my use. If done properly, you do not need to worry about entering a function in a cell or the file changing the dates to that day's date every time it is opened.

  • open Excel
  • press "Alt+F11"
  • Double-click on the worksheet that you want to apply the change to (listed on the left)
  • copy/paste the code below
  • adjust the Range(:) input to correspond to the column you will update
  • adjust the Offset(0,_) input to correspond to the column where you would like the date displayed (in the version below I am making updates to column D and I want the date displayed in column F, hence the input entry of "2" for 2 columns over from column D)
  • hit save
  • repeat steps above if there are other worksheets in your workbook that need the same code
  • you may have to change the number format of the column displaying the date to "General" and increase the column's width if it is displaying "####" after you make an updated entry

Copy/Paste Code below:


Private Sub Worksheet_Change(ByVal Target As Range)

If Intersect(Target, Range("D:D")) Is Nothing Then Exit Sub
Target.Offset(0, 2) = Date

End Sub


Good luck...

How to set background image in Java?

<script>
function SetBack(dir) {
    document.getElementById('body').style.backgroundImage=dir;
}
SetBack('url(myniftybg.gif)');
</script>

How to check if a String contains any of some strings

    static void Main(string[] args)
    {
        string illegalCharacters = "!@#$%^&*()\\/{}|<>,.~`?"; //We'll call these the bad guys
        string goodUserName = "John Wesson";                   //This is a good guy. We know it. We can see it!
                                                               //But what if we want the program to make sure?
        string badUserName = "*_Wesson*_John!?";                //We can see this has one of the bad guys. Underscores not restricted.

        Console.WriteLine("goodUserName " + goodUserName +
            (!HasWantedCharacters(goodUserName, illegalCharacters) ?
            " contains no illegal characters and is valid" :      //This line is the expected result
            " contains one or more illegal characters and is invalid"));
        string captured = "";
        Console.WriteLine("badUserName " + badUserName +
            (!HasWantedCharacters(badUserName, illegalCharacters, out captured) ?
            " contains no illegal characters and is valid" :
            //We can expect this line to print and show us the bad ones
            " is invalid and contains the following illegal characters: " + captured));  

    }

    //Takes a string to check for the presence of one or more of the wanted characters within a string
    //As soon as one of the wanted characters is encountered, return true
    //This is useful if a character is required, but NOT if a specific frequency is needed
    //ie. you wouldn't use this to validate an email address
    //but could use it to make sure a username is only alphanumeric
    static bool HasWantedCharacters(string source, string wantedCharacters)
    {
        foreach(char s in source) //One by one, loop through the characters in source
        {
            foreach(char c in wantedCharacters) //One by one, loop through the wanted characters
            {
                if (c == s)  //Is the current illegalChar here in the string?
                    return true;
            }
        }
        return false;
    }

    //Overloaded version of HasWantedCharacters
    //Checks to see if any one of the wantedCharacters is contained within the source string
    //string source ~ String to test
    //string wantedCharacters ~ string of characters to check for
    static bool HasWantedCharacters(string source, string wantedCharacters, out string capturedCharacters)
    {
        capturedCharacters = ""; //Haven't found any wanted characters yet

        foreach(char s in source)
        {
            foreach(char c in wantedCharacters) //Is the current illegalChar here in the string?
            {
                if(c == s)
                {
                    if(!capturedCharacters.Contains(c.ToString()))
                        capturedCharacters += c.ToString();  //Send these characters to whoever's asking
                }
            }
        }

        if (capturedCharacters.Length > 0)  
            return true;
        else
            return false;
    }

datetimepicker is not a function jquery

Keep in mind, the jQuery UI's datepicker is not initialized with datetimepicker(), there appears to be a plugin/addon here: http://trentrichardson.com/examples/timepicker/.

However, with just jquery-ui it's actually initialized as $("#example").datepicker(). See jQuery's demo site here: http://jqueryui.com/demos/datepicker/

   $(document).ready(function(){
        $("#example1").datepicker();
    });

To use the datetimepicker at the link referenced above, you will want to be certain that your scripts path is correct for the plugin.

How to check if click event is already bound - JQuery

The best way I see is to use live() or delegate() to capture the event in a parent and not in each child element.

If your button is inside a #parent element, you can replace:

$('#myButton').bind('click', onButtonClicked);

by

$('#parent').delegate('#myButton', 'click', onButtonClicked);

even if #myButton doesn't exist yet when this code is executed.

How do I increase the RAM and set up host-only networking in Vagrant?

I could not get any of these answers to work. Here's what I ended up putting at the very top of my Vagrantfile, before the Vagrant::Config.run do block:

Vagrant.configure("2") do |config|
  config.vm.provider "virtualbox" do |vb|
    vb.customize ["modifyvm", :id, "--memory", "1024"]
  end
end

I noticed that the shortcut accessor style, "vb.memory = 1024", didn't seem to work.

Flushing footer to bottom of the page, twitter bootstrap

Use the flex utilities built into Bootstrap 4! Here's what I've come up with using mostly Bootstrap 4 utilities.

<div class="d-flex flex-column" style="min-height: 100vh;">
  <header></header>
  <div class="container flex-grow-1">
    <div>Some Content</div>
  </div>
  <footer></footer>
</div>
  • .d-flex to make the main div a flex container
  • .flex-column on the main div to arrange your flex items in a column
  • min-height: 100vh to the main div, either with a style attribute or in your CSS, to fill the viewport vertically
  • .flex-grow-1 on the container, element to have the main content container take up all the space that remains in the viewport height.

How to find elements by class

The following should work

soup.find('span', attrs={'class':'totalcount'})

replace 'totalcount' with your class name and 'span' with tag you are looking for. Also, if your class contains multiple names with space, just choose one and use.

P.S. This finds the first element with given criteria. If you want to find all elements then replace 'find' with 'find_all'.

How to override a JavaScript function

You could override it or preferably extend it's implementation like this

parseFloat = (function(_super) {
    return function() {
        // Extend it to log the value for example that is passed
        console.log(arguments[0]);
        // Or override it by always subtracting 1 for example
        arguments[0] = arguments[0] - 1;
        return _super.apply(this, arguments);
    };         

})(parseFloat);

And call it as you would normally call it:

var result = parseFloat(1.345); // It should log the value 1.345 but get the value 0.345

Get values from an object in JavaScript

If you want to do this in a single line, try:

Object.keys(a).map(function(key){return a[key]})

Can a for loop increment/decrement by more than one?

for (var i = 0; i < 10; i = i + 2) {
    // code here
}?

How to use stringstream to separate comma separated strings

#include <iostream>
#include <sstream>

std::string input = "abc,def,ghi";
std::istringstream ss(input);
std::string token;

while(std::getline(ss, token, ',')) {
    std::cout << token << '\n';
}

abc
def
ghi

How to clear the entire array?

Find a better use for myself: I usually test if a variant is empty, and all of the above methods fail with the test. I found that you can actually set a variant to empty:

Dim aTable As Variant
If IsEmpty(aTable) Then
    'This is true
End If
ReDim aTable(2)
If IsEmpty(aTable) Then
    'This is False
End If
ReDim aTable(2)
aTable = Empty
If IsEmpty(aTable) Then
    'This is true
End If
ReDim aTable(2)
Erase aTable
If IsEmpty(aTable) Then
    'This is False
End If

this way i get the behaviour i want

InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately

If you are not able to upgrade your Python version to 2.7.9, and want to suppress warnings,

you can downgrade your 'requests' version to 2.5.3:

pip install requests==2.5.3

Bugfix disclosure / Warning introduced in 2.6.0

Why is there extra padding at the top of my UITableView with style UITableViewStyleGrouped in iOS7

if self.automaticallyAdjustsScrollViewInsets = NO; doesn't work for you, make sure the height of either tableview header or section header is CGFLOAT_MIN not 0.

For example if you want to make tableview header 0 high, you can do:

    CGRect frame = self.tableViewHeader.frame;
    frame.size.height = CGFLOAT_MIN; //not 0
    self.tableView.tableHeaderView.frame = frame;
    self.tableView.tableHeaderView = self.tableViewHeader;

Hope it helps.

How to use a ViewBag to create a dropdownlist?

@Html.DropDownListFor(m => m.Departments.id, (SelectList)ViewBag.Department, "Select", htmlAttributes: new { @class = "form-control" })

How to close Browser Tab After Submitting a Form?

That's because the event onsubmit is triggered before the form is submitted.

Remove your onSubmit and output that JavaScript in your PHP script after you have processed the request. You are closing the window right now, and cancelling the request to your server.

Generic XSLT Search and Replace template

Here's one way in XSLT 2

<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;','''')"/>   </xsl:template> </xsl:stylesheet> 

Doing it in XSLT1 is a little more problematic as it's hard to get a literal containing a single apostrophe, so you have to resort to a variable:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:variable name="apos">'</xsl:variable>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;',$apos)"/>   </xsl:template> </xsl:stylesheet> 

How do I navigate to another page when PHP script is done?

if ($done)
{
    header("Location: /url/to/the/other/page");
    exit;
}

How to match a line not containing a word

This should work:

/^((?!PART).)*$/

If you only wanted to exclude it from the beginning of the line (I know you don't, but just FYI), you could use this:

/^(?!PART)/

Edit (by request): Why this pattern works

The (?!...) syntax is a negative lookahead, which I've always found tough to explain. Basically, it means "whatever follows this point must not match the regular expression /PART/." The site I've linked explains this far better than I can, but I'll try to break this down:

^         #Start matching from the beginning of the string.    
(?!PART)  #This position must not be followed by the string "PART".
.         #Matches any character except line breaks (it will include those in single-line mode).
$         #Match all the way until the end of the string.

The ((?!xxx).)* idiom is probably hardest to understand. As we saw, (?!PART) looks at the string ahead and says that whatever comes next can't match the subpattern /PART/. So what we're doing with ((?!xxx).)* is going through the string letter by letter and applying the rule to all of them. Each character can be anything, but if you take that character and the next few characters after it, you'd better not get the word PART.

The ^ and $ anchors are there to demand that the rule be applied to the entire string, from beginning to end. Without those anchors, any piece of the string that didn't begin with PART would be a match. Even PART itself would have matches in it, because (for example) the letter A isn't followed by the exact string PART.

Since we do have ^ and $, if PART were anywhere in the string, one of the characters would match (?=PART). and the overall match would fail. Hope that's clear enough to be helpful.

Define global constants

The best way to create application wide constants in Angular 2 is by using environment.ts files. The advantage of declaring such constants is that you can vary them according to the environment as there can be a different environment file for each environment.

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}
    do
        echo $i $(( i - 2 ))
    done
    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}
    do
        digits="${digits}1234567890"
        tens_fmt="${tens_fmt}%10d"
        tens_args=("${tens_args[@]}" $i)
    done
    printf "$tens_fmt\n" "${tens_args[@]}"
    echo "$digits"
}

On postback, how can I check which control cause postback in Page_Init event

I see that there is already some great advice and methods suggest for how to get the post back control. However I found another web page (Mahesh blog) with a method to retrieve post back control ID.

I will post it here with a little modification, including making it an extension class. Hopefully it is more useful in that way.

/// <summary>
/// Gets the ID of the post back control.
/// 
/// See: http://geekswithblogs.net/mahesh/archive/2006/06/27/83264.aspx
/// </summary>
/// <param name = "page">The page.</param>
/// <returns></returns>
public static string GetPostBackControlId(this Page page)
{
    if (!page.IsPostBack)
        return string.Empty;

    Control control = null;
    // first we will check the "__EVENTTARGET" because if post back made by the controls
    // which used "_doPostBack" function also available in Request.Form collection.
    string controlName = page.Request.Params["__EVENTTARGET"];
    if (!String.IsNullOrEmpty(controlName))
    {
        control = page.FindControl(controlName);
    }
    else
    {
        // if __EVENTTARGET is null, the control is a button type and we need to
        // iterate over the form collection to find it

        // ReSharper disable TooWideLocalVariableScope
        string controlId;
        Control foundControl;
        // ReSharper restore TooWideLocalVariableScope

        foreach (string ctl in page.Request.Form)
        {
            // handle ImageButton they having an additional "quasi-property" 
            // in their Id which identifies mouse x and y coordinates
            if (ctl.EndsWith(".x") || ctl.EndsWith(".y"))
            {
                controlId = ctl.Substring(0, ctl.Length - 2);
                foundControl = page.FindControl(controlId);
            }
            else
            {
                foundControl = page.FindControl(ctl);
            }

            if (!(foundControl is IButtonControl)) continue;

            control = foundControl;
            break;
        }
    }

    return control == null ? String.Empty : control.ID;
}

Update (2016-07-22): Type check for Button and ImageButton changed to look for IButtonControl to allow postbacks from third party controls to be recognized.

Create space at the beginning of a UITextField

This is what I am using right now:

Swift 4.2

class TextField: UITextField {

    let padding = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)

    override open func textRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.inset(by: padding)
    }

    override open func placeholderRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.inset(by: padding)
    }

    override open func editingRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.inset(by: padding)
    }
}

Swift 4

class TextField: UITextField {

    let padding = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)

    override open func textRect(forBounds bounds: CGRect) -> CGRect {
        return UIEdgeInsetsInsetRect(bounds, padding)
    }

    override open func placeholderRect(forBounds bounds: CGRect) -> CGRect {
        return UIEdgeInsetsInsetRect(bounds, padding)
    }

    override open func editingRect(forBounds bounds: CGRect) -> CGRect {
        return UIEdgeInsetsInsetRect(bounds, padding)
    }
}

Swift 3:

class TextField: UITextField {

    let padding = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)

    override func textRect(forBounds bounds: CGRect) -> CGRect {
        return UIEdgeInsetsInsetRect(bounds, padding)
    }

    override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
        return UIEdgeInsetsInsetRect(bounds, padding)
    }

    override func editingRect(forBounds bounds: CGRect) -> CGRect {
        return UIEdgeInsetsInsetRect(bounds, padding)
    }
}

I never set a other padding but you can tweak. This class doesn't take care of the rightView and leftView on the textfield. If you want that to be handle correctly you can use something like (example in objc and I only needed the rightView:

- (CGRect)textRectForBounds:(CGRect)bounds {
    CGRect paddedRect = UIEdgeInsetsInsetRect(bounds, self.insets);

    if (self.rightViewMode == UITextFieldViewModeAlways || self.rightViewMode == UITextFieldViewModeUnlessEditing) {
        return [self adjustRectWithWidthRightView:paddedRect];
    }
    return paddedRect;
}

- (CGRect)placeholderRectForBounds:(CGRect)bounds {
    CGRect paddedRect = UIEdgeInsetsInsetRect(bounds, self.insets);

    if (self.rightViewMode == UITextFieldViewModeAlways || self.rightViewMode == UITextFieldViewModeUnlessEditing) {
        return [self adjustRectWithWidthRightView:paddedRect];
    }
    return paddedRect;
}

- (CGRect)editingRectForBounds:(CGRect)bounds {
    CGRect paddedRect = UIEdgeInsetsInsetRect(bounds, self.insets);

    if (self.rightViewMode == UITextFieldViewModeAlways || self.rightViewMode == UITextFieldViewModeWhileEditing) {
        return [self adjustRectWithWidthRightView:paddedRect];
    }
    return paddedRect;
}

- (CGRect)adjustRectWithWidthRightView:(CGRect)bounds {
    CGRect paddedRect = bounds;
    paddedRect.size.width -= CGRectGetWidth(self.rightView.frame);

    return paddedRect;
}

Selecting a Record With MAX Value

What do you mean costs too much? Too much what?

SELECT MAX(Balance) AS MaxBalance, CustomerID FROM CUSTOMERS GROUP BY CustomerID

If your table is properly indexed (Balance) and there has got to be an index on the PK than I am not sure what you mean about costs too much or seems unreliable? There is nothing unreliable about an aggregate that you are using and telling it to do. In this case, MAX() does exactly what you tell it to do - there's nothing magical about it.

Take a look at MAX() and if you want to filter it use the HAVING clause.

Python: SyntaxError: non-keyword after keyword arg

It's just what it says:

inputFile = open((x), encoding = "utf8", "r")

You have specified encoding as a keyword argument, but "r" as a positional argument. You can't have positional arguments after keyword arguments. Perhaps you wanted to do:

inputFile = open((x), "r", encoding = "utf8")

Calling multiple JavaScript functions on a button click

if there are more than 2 js function then following two ways can also be implemented:

  1. if you have more than two functions you can group them in if condition

    OR

  2. you can write two different if conditions.

1 OnClientClick="var b = validateView(); if (b) ShowDiv1(); if(b) testfunction(); return b">

OR

2 OnClientClick="var b = validateView(); if(b) {

ShowDiv1();

testfunction();

} return b">

How can I get the current directory name in Javascript?

This one-liner works:

var currentDirectory = window.location.pathname.split('/').slice(0, -1).join('/')

Is it possible in Java to check if objects fields are null and then add default value to all those attributes?

You can use reflection to iterate over the object's field, and set them. You'd obviously need some sort of mapping between types or even field names and required default values but this can be done quite easily in a loop. For example:

for (Field f : obj.getClass().getFields()) {
  f.setAccessible(true);
  if (f.get(obj) == null) {
     f.set(obj, getDefaultValueForType(f.getType()));
  }
}

[Update]

With modern Java, you can use annotations to set the default values for fields on a per class basis. A complete implementation might look like this:

// DefaultString.java:
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface DefaultString {
    String value();
}

// DefaultInteger.java:
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface DefaultInteger {
    int value();
}

// DefaultPojo.java:
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

public class DefaultPojo {

    public void setDefaults() {
        for (Field f : getClass().getFields()) {
            f.setAccessible(true);
            try {
                if (f.get(this) == null) {
                    f.set(this, getDefaultValueFromAnnotation(f.getAnnotations()));
                }
            } catch (IllegalAccessException e) { // shouldn't happen because I used setAccessible
            }
        }
    }

    private Object getDefaultValueFromAnnotation(Annotation[] annotations) {
        for (Annotation a : annotations) {
            if (a instanceof DefaultString)
                return ((DefaultString)a).value();
            if (a instanceof DefaultInteger)
                return ((DefaultInteger)a).value();
        }
        return null;
    }

}

// Test Pojo
public class TestPojo extends DefaultPojo {
    @DefaultString("Hello world!")
    public String stringValue;
    @DefaultInteger(42);
    public int integerValue;
}

Then default values for a TestPojo can be set just by running test.setDetaults()

HTML inside Twitter Bootstrap popover

Another way to specify the popover content in a reusable way is to create a new data attribute like data-popover-content and use it like this:

HTML:

<!-- Popover #1 -->
<a class="btn btn-primary" data-placement="top" data-popover-content="#a1" data-toggle="popover" data-trigger="focus" href="#" tabindex="0">Popover Example</a>

<!-- Content for Popover #1 -->
<div class="hidden" id="a1">
  <div class="popover-heading">
    This is the heading for #1
  </div>

  <div class="popover-body">
    This is the body for #1
  </div>
</div>

JS:

$(function(){
    $("[data-toggle=popover]").popover({
        html : true,
        content: function() {
          var content = $(this).attr("data-popover-content");
          return $(content).children(".popover-body").html();
        },
        title: function() {
          var title = $(this).attr("data-popover-content");
          return $(title).children(".popover-heading").html();
        }
    });
});

This can be useful when you have a lot of html to place into your popovers.

Here is an example fiddle: http://jsfiddle.net/z824fn6b/

How to find the difference in days between two dates?

Even if you don't have GNU date, you'll probably have Perl installed:

use Time::Local;
sub to_epoch {
  my ($t) = @_; 
  my ($y, $d, $m) = ($t =~ /(\d{4})-(\d{2})-(\d{2})/);
  return timelocal(0, 0, 0, $d+0, $m-1, $y-1900);
}
sub diff_days {
  my ($t1, $t2) = @_; 
  return (abs(to_epoch($t2) - to_epoch($t1))) / 86400;
}
print diff_days("2002-20-10", "2003-22-11"), "\n";

This returns 398.041666666667 -- 398 days and one hour due to daylight savings.


The question came back up on my feed. Here's a more concise method using a Perl bundled module

days=$(perl -MDateTime -le '
    sub parse_date { 
        @f = split /-/, shift;
        return DateTime->new(year=>$f[0], month=>$f[2], day=>$f[1]); 
    }
    print parse_date(shift)->delta_days(parse_date(shift))->in_units("days");
' $A $B)
echo $days   # => 398

Why does Oracle not find oci.dll?

I just installed Oracle Instant Client 18_3 with the SDK. The PATH and ENV variable is set as instructed on the install page but I get the OCl.dll not found error. I searched the entire drive recursively and no such DLL exists.

So now what?

With the install instructions (not updated for 18_3) and downloads there are MISTAKES at step 13, so watch out for that.

When you create the folder structure for the downloads just write them the old way "c:\oraclient". Then when you unzip the basic, SDK and instant Client install for Windows 10_x64 extract them to "C:\oraclient\", because they all write to the same default folder. Then, when you set the ENV variable (which is no longer ORACLE_HOME, but now is OCI_LIB64) and the PATH, you will point to "C:\oraclient\instantclient_18_3".

To be sure you got it all right drill down and look for any duplicate "instantclient_18_3" folders. If you do have those cut and paste the CONTENTS to the root folder "C:\oraclient\instantclient_18_3\" folder.

Whoever works on the documentation at Oracle needs to troubleshoot better. I've seen "C:\oreclient_dir_install", "c:\oracle", "c:\oreclient" and "c:\oraclient" all mentioned as install directories, all for Windows x64 installs

BTW, install the C++ redist it helps. The 18.3 Basic package requires the Microsoft Visual Studio 2013 Redistributable.

How to update a record using sequelize for node?

public static update(values: Object, options: Object): Promise>

check documentation once http://docs.sequelizejs.com/class/lib/model.js~Model.html#static-method-update

  Project.update(
    // Set Attribute values 
    { title:'a very different title now' },
  // Where clause / criteria 
     { _id : 1 }     
  ).then(function(result) { 

 //it returns an array as [affectedCount, affectedRows]

  })

Is there a simple, elegant way to define singletons?

The one time I wrote a singleton in Python I used a class where all the member functions had the classmethod decorator.

class foo:
  x = 1

  @classmethod
  def increment(cls, y = 1):
    cls.x += y

how to make a html iframe 100% width and height?

this code probable help you .

<iframe src="" onload="this.width=screen.width;this.height=screen.height;">

File to byte[] in Java

Simple way to do it:

File fff = new File("/path/to/file");
FileInputStream fileInputStream = new FileInputStream(fff);

// int byteLength = fff.length(); 

// In android the result of file.length() is long
long byteLength = fff.length(); // byte count of the file-content

byte[] filecontent = new byte[(int) byteLength];
fileInputStream.read(filecontent, 0, (int) byteLength);

What is the connection string for localdb for version 11

In Sql Server 2008 R2 database files you can connect with

Server=np:\\.\pipe\YourInstance\tsql\query;InitialCatalog=yourDataBase;Trusted_Connection=True;

only, but in sql Server 2012 you can use this:

Server=(localdb)\v11.0;Integrated Security=true;Database=DB1;

and it depended on your .mdf .ldf version.

for finding programmicaly i use this Method that explained in this post

How to use EditText onTextChanged event when I press the number?

To change the text;

multipleLine.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            MainActivity.myArray.set(pickId,String.valueOf(s));
            MainActivity.myAdapt.notifyDataSetChanged();
        }

        @Override
        public void afterTextChanged(Editable s) {

        }

Python socket.error: [Errno 111] Connection refused

The problem obviously was (as you figured it out) that port 36250 wasn't open on the server side at the time you tried to connect (hence connection refused). I can see the server was supposed to open this socket after receiving SEND command on another connection, but it apparently was "not opening [it] up in sync with the client side".

Well, the main reason would be there was no synchronisation whatsoever. Calling:

cs.send("SEND " + FILE)
cs.close()

would just place the data into a OS buffer; close would probably flush the data and push into the network, but it would almost certainly return before the data would reach the server. Adding sleep after close might mitigate the problem, but this is not synchronisation.

The correct solution would be to make sure the server has opened the connection. This would require server sending you some message back (for example OK, or better PORT 36250 to indicate where to connect). This would make sure the server is already listening.

The other thing is you must check the return values of send to make sure how many bytes was taken from your buffer. Or use sendall.

(Sorry for disturbing with this late answer, but I found this to be a high traffic question and I really didn't like the sleep idea in the comments section.)

How to maintain a Unique List in Java?

HashSet<String> (or) any Set implementation may does the job for you. Set don't allow duplicates.

Here is javadoc for HashSet.

HTML text-overflow ellipsis detection

All the solutions did not really work for me, what did work was compare the elements scrollWidth to the scrollWidth of its parent (or child, depending on which element has the trigger).

When the child's scrollWidth is higher than its parents, it means .text-ellipsis is active.


When event is the parent element

function isEllipsisActive(event) {
    let el          = event.currentTarget;
    let width       = el.offsetWidth;
    let widthChild  = el.firstChild.offsetWidth;
    return (widthChild >= width);
}

When event is the child element

function isEllipsisActive(event) {
    let el          = event.currentTarget;
    let width       = el.offsetWidth;
    let widthParent = el.parentElement.scrollWidth;
    return (width >= widthParent);
}

Algorithm to detect overlapping periods

I don't believe that the framework itself has this class. Maybe a third-party library...

But why not create a Period value-object class to handle this complexity? That way you can ensure other constraints, like validating start vs end datetimes. Something like:

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

namespace Whatever.Domain.Timing {
    public class Period {
        public DateTime StartDateTime {get; private set;}
        public DateTime EndDateTime {get; private set;}

        public Period(DateTime StartDateTime, DateTime EndDateTime) {
            if (StartDateTime > EndDateTime)
                throw new InvalidPeriodException("End DateTime Must Be Greater Than Start DateTime!");
            this.StartDateTime = StartDateTime;
            this.EndDateTime = EndDateTime;
        }


        public bool Overlaps(Period anotherPeriod){
            return (this.StartDateTime < anotherPeriod.EndDateTime && anotherPeriod.StartDateTime < this.EndDateTime)
        }

        public TimeSpan GetDuration(){
            return EndDateTime - StartDateTime;
        }

    }

    public class InvalidPeriodException : Exception {
        public InvalidPeriodException(string Message) : base(Message) { }    
    }
}

That way you will be able to individually compare each period...

How can I test a PDF document if it is PDF/A compliant?

A list of PDF/A validators is on the pdfa.org web site here:

verapdf

A free online PDF/A validator is available here:

http://www.validatepdfa.com/

A report on the accuracy of many of these PDF/A validators is available from PDFLib:

https://www.pdflib.com/fileadmin/pdflib/pdf/pdfa/2009-05-04-Bavaria-report-on-PDFA-validation-accuracy.pdf

Se as well:

https://www.pdflib.com/knowledge-base/pdfa/

Pandas: how to change all the values of a column?

You can do a column transformation by using apply

Define a clean function to remove the dollar and commas and convert your data to float.

def clean(x):
    x = x.replace("$", "").replace(",", "").replace(" ", "")
    return float(x)

Next, call it on your column like this.

data['Revenue'] = data['Revenue'].apply(clean)

Lodash - difference between .extend() / .assign() and .merge()

If you want a deep copy without override while retaining the same obj reference

obj = _.assign(obj, _.merge(obj, [source]))

Do Java arrays have a maximum size?

Going by this article http://en.wikipedia.org/wiki/Criticism_of_Java#Large_arrays:

Java has been criticized for not supporting arrays of more than 231-1 (about 2.1 billion) elements. This is a limitation of the language; the Java Language Specification, Section 10.4, states that:

Arrays must be indexed by int values... An attempt to access an array component with a long index value results in a compile-time error.

Supporting large arrays would also require changes to the JVM. This limitation manifests itself in areas such as collections being limited to 2 billion elements and the inability to memory map files larger than 2 GiB. Java also lacks true multidimensional arrays (contiguously allocated single blocks of memory accessed by a single indirection), which limits performance for scientific and technical computing.

How to unpack and pack pkg file?

Packages are just .xar archives with a different extension and a specified file hierarchy. Unfortunately, part of that file hierarchy is a cpio.gz archive of the actual installables, and usually that's what you want to edit. And there's also a Bom file that includes information on the files inside that cpio archive, and a PackageInfo file that includes summary information.

If you really do just need to edit one of the info files, that's simple:

mkdir Foo
cd Foo
xar -xf ../Foo.pkg
# edit stuff
xar -cf ../Foo-new.pkg *

But if you need to edit the installable files:

mkdir Foo
cd Foo
xar -xf ../Foo.pkg
cd foo.pkg
cat Payload | gunzip -dc |cpio -i
# edit Foo.app/*
rm Payload
find ./Foo.app | cpio -o | gzip -c > Payload
mkbom Foo.app Bom # or edit Bom
# edit PackageInfo
rm -rf Foo.app
cd ..
xar -cf ../Foo-new.pkg

I believe you can get mkbom (and lsbom) for most linux distros. (If you can get ditto, that makes things even easier, but I'm not sure if that's nearly as ubiquitously available.)

Difference between a class and a module

+-----------------------------------------------------------------------------+
¦               ¦ class                     ¦ module                          ¦
¦---------------+---------------------------+---------------------------------¦
¦ instantiation ¦ can be instantiated       ¦ can *not* be instantiated       ¦
¦---------------+---------------------------+---------------------------------¦
¦ usage         ¦ object creation           ¦ mixin facility. provide         ¦
¦               ¦                           ¦   a namespace.                  ¦
¦---------------+---------------------------+---------------------------------¦
¦ superclass    ¦ module                    ¦ object                          ¦
¦---------------+---------------------------+---------------------------------¦
¦ methods       ¦ class methods and         ¦ module methods and              ¦
¦               ¦   instance methods        ¦   instance methods              ¦
¦---------------+---------------------------+---------------------------------¦
¦ inheritance   ¦ inherits behaviour and can¦ No inheritance                  ¦
¦               ¦   be base for inheritance ¦                                 ¦
¦---------------+---------------------------+---------------------------------¦
¦ inclusion     ¦ cannot be included        ¦ can be included in classes and  ¦
¦               ¦                           ¦   modules by using the include  ¦
¦               ¦                           ¦   command (includes all         ¦
¦               ¦                           ¦   instance methods as instance  ¦
¦               ¦                           ¦   methods in a class/module)    ¦
¦---------------+---------------------------+---------------------------------¦
¦ extension     ¦ can not extend with       ¦ module can extend instance by   ¦
¦               ¦   extend command          ¦   using extend command (extends ¦
¦               ¦   (only with inheritance) ¦   given instance with singleton ¦
¦               ¦                           ¦   methods from module)          ¦
+-----------------------------------------------------------------------------+

How to clear Route Caching on server: Laravel 5.2.37

For your case solution is :

php artisan cache:clear
php artisan route:cache

Optimizing Route Loading is a must on production :

If you are building a large application with many routes, you should make sure that you are running the route:cache Artisan command during your deployment process:

php artisan route:cache

This command reduces all of your route registrations into a single method call within a cached file, improving the performance of route registration when registering hundreds of routes.

Since this feature uses PHP serialization, you may only cache the routes for applications that exclusively use controller based routes. PHP is not able to serialize Closures.

Laravel 5 clear cache from route, view, config and all cache data from application

I would like to share my experience and solution. when i was working on my laravel e commerce website with gitlab. I was fetching one issue suddenly my view cache with error during development. i did try lot to refresh and something other but i can't see any more change in my view, but at last I did resolve my problem using laravel command so, let's see i added several command for clear cache from view, route, config etc.

Reoptimized class loader:

php artisan optimize

Clear Cache facade value:

php artisan cache:clear

Clear Route cache:

php artisan route:cache

Clear View cache:

php artisan view:clear

Clear Config cache:

php artisan config:cache

How does strtok() split the string into tokens in C?

For those who are still having hard time understanding this strtok() function, take a look at this pythontutor example, it is a great tool to visualize your C (or C++, Python ...) code.

In case the link got broken, paste in:

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

int main()
{
    char s[] = "Hello, my name is? Matthew! Hey.";
    char* p;
    for (char *p = strtok(s," ,?!."); p != NULL; p = strtok(NULL, " ,?!.")) {
      puts(p);
    }
    return 0;
}

Credits go to Anders K.

How do I access an access array item by index in handlebars?

The following, with an additional dot before the index, works just as expected. Here, the square brackets are optional when the index is followed by another property:

{{people.[1].name}}
{{people.1.name}}

However, the square brackets are required in:

{{#with people.[1]}}
  {{name}}
{{/with}}

In the latter, using the index number without the square brackets would get one:

Error: Parse error on line ...:
...     {{#with people.1}}                
-----------------------^
Expecting 'ID', got 'INTEGER'

As an aside: the brackets are (also) used for segment-literal syntax, to refer to actual identifiers (not index numbers) that would otherwise be invalid. More details in What is a valid identifier?

(Tested with Handlebars in YUI.)

2.xx Update

You can now use the get helper for this:

(get people index)

although if you get an error about index needing to be a string, do:

(get people (concat index ""))

Java: splitting a comma-separated string but ignoring commas in quotes

You're in that annoying boundary area where regexps almost won't do (as has been pointed out by Bart, escaping the quotes would make life hard) , and yet a full-blown parser seems like overkill.

If you are likely to need greater complexity any time soon I would go looking for a parser library. For example this one

What is REST? Slightly confused

REST is not a specific web service but a design concept (architecture) for managing state information. The seminal paper on this was Roy Thomas Fielding's dissertation (2000), "Architectural Styles and the Design of Network-based Software Architectures" (available online from the University of California, Irvine).

First read Ryan Tomayko's post How I explained REST to my wife; it's a great starting point. Then read Fielding's actual dissertation. It's not that advanced, nor is it long (six chapters, 180 pages)! (I know you kids in school like it short).

EDIT: I feel it's pointless to try to explain REST. It has so many concepts like scalability, visibility (stateless) etc. that the reader needs to grasp, and the best source for understanding those are the actual dissertation. It's much more than POST/GET etc.

How do you copy the contents of an array to a std::vector in C++ without looping?

avoid the memcpy, I say. No reason to mess with pointer operations unless you really have to. Also, it will only work for POD types (like int) but would fail if you're dealing with types that require construction.

XML Parser for C

For C++ I suggest using CMarkup.

Deprecation warning in Moment.js - Not in a recognized ISO format

Parsing string with moment.js.

const date = '1231231231231' //Example String date
const parsed = moment(+date);

Calling a rest api with username and password - how to

If the API says to use HTTP Basic authentication, then you need to add an Authorization header to your request. I'd alter your code to look like this:

    WebRequest req = WebRequest.Create(@"https://sub.domain.com/api/operations?param=value&param2=value");
    req.Method = "GET";
    req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("username:password"));
    //req.Credentials = new NetworkCredential("username", "password");
    HttpWebResponse resp = req.GetResponse() as HttpWebResponse;

Replacing "username" and "password" with the correct values, of course.

What is the best way to return different types of ResponseEntity in Spring MVC or Spring-Boot

You can use a map with your object or string like bellow :

@RequestMapping(value = "/path", 
        method = RequestMethod.GET, 
        produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public ResponseEntity<Map<String,String>> getData(){

    Map<String,String> response = new HashMap<String, String>();

    boolean isValid = // some logic
    if (isValid){
        response.put("ok", "success saving data");
        return ResponseEntity.accepted().body(response);
    }
    else{
        response.put("error", "an error expected on processing file");
        return ResponseEntity.badRequest().body(response);
    }

}

How to make a HTTP PUT request?

How to use PUT method using WebRequest.

    //JsonResultModel class
    public class JsonResultModel
    {
       public string ErrorMessage { get; set; }
       public bool IsSuccess { get; set; }
       public string Results { get; set; }
    }
    // HTTP_PUT Function
    public static JsonResultModel HTTP_PUT(string Url, string Data)
    {
        JsonResultModel model = new JsonResultModel();
        string Out = String.Empty;
        string Error = String.Empty;
        System.Net.WebRequest req = System.Net.WebRequest.Create(Url);

        try
        {
            req.Method = "PUT";
            req.Timeout = 100000;
            req.ContentType = "application/json";
            byte[] sentData = Encoding.UTF8.GetBytes(Data);
            req.ContentLength = sentData.Length;

            using (System.IO.Stream sendStream = req.GetRequestStream())
            {
                sendStream.Write(sentData, 0, sentData.Length);
                sendStream.Close();

            }

            System.Net.WebResponse res = req.GetResponse();
            System.IO.Stream ReceiveStream = res.GetResponseStream();
            using (System.IO.StreamReader sr = new 
            System.IO.StreamReader(ReceiveStream, Encoding.UTF8))
            {

                Char[] read = new Char[256];
                int count = sr.Read(read, 0, 256);

                while (count > 0)
                {
                    String str = new String(read, 0, count);
                    Out += str;
                    count = sr.Read(read, 0, 256);
                }
            }
        }
        catch (ArgumentException ex)
        {
            Error = string.Format("HTTP_ERROR :: The second HttpWebRequest object has raised an Argument Exception as 'Connection' Property is set to 'Close' :: {0}", ex.Message);
        }
        catch (WebException ex)
        {
            Error = string.Format("HTTP_ERROR :: WebException raised! :: {0}", ex.Message);
        }
        catch (Exception ex)
        {
            Error = string.Format("HTTP_ERROR :: Exception raised! :: {0}", ex.Message);
        }

        model.Results = Out;
        model.ErrorMessage = Error;
        if (!string.IsNullOrWhiteSpace(Out))
        {
            model.IsSuccess = true;
        }
        return model;
    }

Uri not Absolute exception getting while calling Restful Webservice

An absolute URI specifies a scheme; a URI that is not absolute is said to be relative.

http://docs.oracle.com/javase/8/docs/api/java/net/URI.html

So, perhaps your URLEncoder isn't working as you're expecting (the https bit)?

    URLEncoder.encode(uri) 

How do I see which version of Swift I'm using?

From Xcode 8.3 onward Build Settings has key Swift Language Version with a value of swift version your target is using.

For older Xcodes use this solution, open terminal and type following command(s)

Case 1: You have installed only one Xcode App

swift -version

Case 2: You have installed multiple Xcode Apps

  • Switch active developer directory (Replace Xcode_7.3.app from following command with your Xcode app file name from Application directory for which you want to check swift version)

     sudo xcode-select --switch /Applications/Xcode_7.3.app/Contents/Developer
    
  • Then

     swift -version
    

NOTE: From Xcode 8 to Xcode 8.2.x you can use swift 2.3 even though Xcode 8 uses swift 3.x as default swift version. To use swift 2.3, just turn on flag Use Legacy Swift Language Version to YES from Build Setting and XCode will use Swift 2.3 for that project target.

How to replace NaNs by preceding values in pandas DataFrame?

ffill now has it's own method pd.DataFrame.ffill

df.ffill()

     0    1    2
0  1.0  2.0  3.0
1  4.0  2.0  3.0
2  4.0  2.0  9.0

Error while waiting for device: Time out after 300seconds waiting for emulator to come online

I had the same problem. I removed virtual device and run app on my phone - worked well. To remove virtual device: Click icon "AVD Manager" in Android Studio, select virtual device and in context menu click "Delete". Then turn on on the phone "Developer mode". Connect phone via USB to the laptop.

Convert HTML5 into standalone Android App

You can use https://appery.io/ It is the same phonegap but in very convinient wrapper

How do I install an R package from source?

From cran, you can install directly from a github repository address. So if you want the package at https://github.com/twitter/AnomalyDetection:

library(devtools)
install_github("twitter/AnomalyDetection")

does the trick.

Visual Studio Error: (407: Proxy Authentication Required)

My case is when using two factor auth, outlook account and VS12.

I found out I have to

  • open IE (my corporate default browser)
  • log in to visual studio online account (including two factor auth)
  • connect again in VS12 (do the auth again for some reason)

What is the size of an enum in C?

While the previous answers are correct, some compilers have options to break the standard and use the smallest type that will contain all values.

Example with GCC (documentation in the GCC Manual):

enum ord {
    FIRST = 1,
    SECOND,
    THIRD
} __attribute__ ((__packed__));
STATIC_ASSERT( sizeof(enum ord) == 1 )

Create a button programmatically and set a background image

Create Button and add image as its background swift 4

     let img = UIImage(named: "imgname")
     let myButton = UIButton(type: UIButtonType.custom)
     myButton.frame = CGRect.init(x: 10, y: 10, width: 100, height: 45)
     myButton.setImage(img, for: .normal)
     myButton.addTarget(self, action: #selector(self.buttonClicked(_:)), for: UIControlEvents.touchUpInside)
     self.view.addSubview(myButton)

How to detect query which holds the lock in Postgres?

From this excellent article on query locks in Postgres, one can get blocked query and blocker query and their information from the following query.

CREATE VIEW lock_monitor AS(
SELECT
  COALESCE(blockingl.relation::regclass::text,blockingl.locktype) as locked_item,
  now() - blockeda.query_start AS waiting_duration, blockeda.pid AS blocked_pid,
  blockeda.query as blocked_query, blockedl.mode as blocked_mode,
  blockinga.pid AS blocking_pid, blockinga.query as blocking_query,
  blockingl.mode as blocking_mode
FROM pg_catalog.pg_locks blockedl
JOIN pg_stat_activity blockeda ON blockedl.pid = blockeda.pid
JOIN pg_catalog.pg_locks blockingl ON(
  ( (blockingl.transactionid=blockedl.transactionid) OR
  (blockingl.relation=blockedl.relation AND blockingl.locktype=blockedl.locktype)
  ) AND blockedl.pid != blockingl.pid)
JOIN pg_stat_activity blockinga ON blockingl.pid = blockinga.pid
  AND blockinga.datid = blockeda.datid
WHERE NOT blockedl.granted
AND blockinga.datname = current_database()
);

SELECT * from lock_monitor;

As the query is long but useful, the article author has created a view for it to simplify it's usage.

How to make flexbox items the same size?

Set them so that their flex-basis is 0 (so all elements have the same starting point), and allow them to grow:

flex: 1 1 0px

Your IDE or linter might mention that the unit of measure 'px' is redundant. If you leave it out (like: flex: 1 1 0), IE will not render this correctly. So the px is required to support Internet Explorer, as mentioned in the comments by @fabb;

MySQL FULL JOIN?

Full join in mysql :(left union right) or (right unoin left)

 SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
    FROM Persons
    left JOIN Orders
    ON Persons.P_Id=Orders.P_Id
    ORDER BY Persons.LastName

    Union

    SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
    FROM Persons
    Right JOIN Orders
    ON Persons.P_Id=Orders.P_Id
    ORDER BY Persons.LastName

What is the difference between JVM, JDK, JRE & OpenJDK?

JVM is the Java Virtual Machine – it actually runs Java ByteCode.

JRE is the Java Runtime Environment – it contains a JVM, among other things, and is what you need to run a Java program.

JDK is the Java Development Kit – it is the JRE, but with javac (which is what you need to compile Java source code) and other programming tools added.

OpenJDK is a specific JDK implementation.

Select row on click react-table

There is a HOC included for React-Table that allows for selection, even when filtering and paginating the table, the setup is slightly more advanced than the basic table so read through the info in the link below first.


enter image description here



After importing the HOC you can then use it like this with the necessary methods:

/**
* Toggle a single checkbox for select table
*/
toggleSelection(key: number, shift: string, row: string) {
    // start off with the existing state
    let selection = [...this.state.selection];
    const keyIndex = selection.indexOf(key);

    // check to see if the key exists
    if (keyIndex >= 0) {
        // it does exist so we will remove it using destructing
        selection = [
            ...selection.slice(0, keyIndex),
            ...selection.slice(keyIndex + 1)
        ];
    } else {
        // it does not exist so add it
        selection.push(key);
    }
    // update the state
    this.setState({ selection });
}

/**
* Toggle all checkboxes for select table
*/
toggleAll() {
    const selectAll = !this.state.selectAll;
    const selection = [];

    if (selectAll) {
        // we need to get at the internals of ReactTable
        const wrappedInstance = this.checkboxTable.getWrappedInstance();
        // the 'sortedData' property contains the currently accessible records based on the filter and sort
        const currentRecords = wrappedInstance.getResolvedState().sortedData;
        // we just push all the IDs onto the selection array
        currentRecords.forEach(item => {
            selection.push(item._original._id);
        });
    }
    this.setState({ selectAll, selection });
}

/**
* Whether or not a row is selected for select table
*/
isSelected(key: number) {
    return this.state.selection.includes(key);
}

<CheckboxTable
    ref={r => (this.checkboxTable = r)}
    toggleSelection={this.toggleSelection}
    selectAll={this.state.selectAll}
    toggleAll={this.toggleAll}
    selectType="checkbox"
    isSelected={this.isSelected}
    data={data}
    columns={columns}
/>

See here for more information:
https://github.com/tannerlinsley/react-table/tree/v6#selecttable

Here is a working example:
https://codesandbox.io/s/react-table-select-j9jvw

Nginx not picking up site in sites-enabled?

Changing from:

include /etc/nginx/sites-enabled/*; 

to

include /etc/nginx/sites-enabled/*.*; 

fixed my issue

Android SDK manager won't open

Try adding the Java path (pointing to the JDK) to the System Environment Variables.

Right-click 'Computer' > Properties > Advanced system settings > Environment Variables

Then under System Variables, add a new variable.

Variable   Value
JAVA_PATH  C:\Program Files\Java\jdk1.7.0

Then edit the Path variable, prefix it with %JAVA_PATH%\bin;.

What are the ways to sum matrix elements in MATLAB?

The best practice is definitely to avoid loops or recursions in Matlab.

Between sum(A(:)) and sum(sum(A)). In my experience, arrays in Matlab seems to be stored in a continuous block in memory as stacked column vectors. So the shape of A does not quite matter in sum(). (One can test reshape() and check if reshaping is fast in Matlab. If it is, then we have a reason to believe that the shape of an array is not directly related to the way the data is stored and manipulated.)

As such, there is no reason sum(sum(A)) should be faster. It would be slower if Matlab actually creates a row vector recording the sum of each column of A first and then sum over the columns. But I think sum(sum(A)) is very wide-spread amongst users. It is likely that they hard-code sum(sum(A)) to be a single loop, the same to sum(A(:)).

Below I offer some testing results. In each test, A=rand(size) and size is specified in the displayed texts.

First is using tic toc.

Size 100x100
sum(A(:))
Elapsed time is 0.000025 seconds.
sum(sum(A))
Elapsed time is 0.000018 seconds.

Size 10000x1
sum(A(:))
Elapsed time is 0.000014 seconds.
sum(A)
Elapsed time is 0.000013 seconds.

Size 1000x1000
sum(A(:))
Elapsed time is 0.001641 seconds.
sum(A)
Elapsed time is 0.001561 seconds.

Size 1000000
sum(A(:))
Elapsed time is 0.002439 seconds.
sum(A)
Elapsed time is 0.001697 seconds.

Size 10000x10000
sum(A(:))
Elapsed time is 0.148504 seconds.
sum(A)
Elapsed time is 0.155160 seconds.

Size 100000000
Error using rand
Out of memory. Type HELP MEMORY for your options.

Error in test27 (line 70)
A=rand(100000000,1);

Below is using cputime

Size 100x100
The cputime for sum(A(:)) in seconds is 
0
The cputime for sum(sum(A)) in seconds is 
0

Size 10000x1
The cputime for sum(A(:)) in seconds is 
0
The cputime for sum(sum(A)) in seconds is 
0

Size 1000x1000
The cputime for sum(A(:)) in seconds is 
0
The cputime for sum(sum(A)) in seconds is 
0

Size 1000000
The cputime for sum(A(:)) in seconds is 
0
The cputime for sum(sum(A)) in seconds is 
0

Size 10000x10000
The cputime for sum(A(:)) in seconds is 
0.312
The cputime for sum(sum(A)) in seconds is 
0.312

Size 100000000
Error using rand
Out of memory. Type HELP MEMORY for your options.

Error in test27_2 (line 70)
A=rand(100000000,1);

In my experience, both timers are only meaningful up to .1s. So if you have similar experience with Matlab timers, none of the tests can discern sum(A(:)) and sum(sum(A)).

I tried the largest size allowed on my computer a few more times.

Size 10000x10000
sum(A(:))
Elapsed time is 0.151256 seconds.
sum(A)
Elapsed time is 0.143937 seconds.

Size 10000x10000
sum(A(:))
Elapsed time is 0.149802 seconds.
sum(A)
Elapsed time is 0.145227 seconds.

Size 10000x10000
The cputime for sum(A(:)) in seconds is 
0.2808
The cputime for sum(sum(A)) in seconds is 
0.312

Size 10000x10000
The cputime for sum(A(:)) in seconds is 
0.312
The cputime for sum(sum(A)) in seconds is 
0.312

Size 10000x10000
The cputime for sum(A(:)) in seconds is 
0.312
The cputime for sum(sum(A)) in seconds is 
0.312

They seem equivalent. Either one is good. But sum(sum(A)) requires that you know the dimension of your array is 2.

How to copy sheets to another workbook using vba?

I would like to slightly rewrite keytarhero's response:

Sub CopyWorkbook()

Dim sh as Worksheet,  wb as workbook

Set wb = workbooks("Target workbook")
For Each sh in workbooks("source workbook").Worksheets
   sh.Copy After:=wb.Sheets(wb.sheets.count) 
Next sh

End Sub

Edit: You can also build an array of sheet names and copy that at once.

Workbooks("source workbook").Worksheets(Array("sheet1","sheet2")).Copy _
         After:=wb.Sheets(wb.sheets.count)

Note: copying a sheet from an XLS? to an XLS will result into an error. The opposite works fine (XLS to XLSX)

Bloomberg Open API

This API has been available for a long time and enables to get access to market data (including live) if you are running a Bloomberg Terminal or have access to a Bloomberg Server, which is chargeable.

The only difference is that the API (not its code) has been open sourced, so it can now be used as a dependency in an open source project for example, without any copyrights issues, which was not the case before.

git pull while not in a git directory

You can write a script like this:

cd /X/Y
git pull

You can name it something like gitpull.
If you'd rather have it do arbitrary directories instead of /X/Y:

cd $1
git pull

Then you can call it with gitpull /X/Z
Lastly, you can try finding repositories. I have a ~/git folder which contains repositories, and you can use this to do a pull on all of them.

g=`find /X -name .git`
for repo in ${g[@]}
do
    cd ${repo}
    cd ..
    git pull
done

Close Android Application

I don't think you can do it in one line of code. Try opening your activities with startActivityForResult. As the result you can pass something like a CLOSE_FLAG, which will inform your parent activity that its child activity has finished.

That said, you should probably read this answer.

Prevent textbox autofill with previously entered values

For firefox

Either:

<asp:TextBox id="Textbox1" runat="server" autocomplete="off"></asp:TextBox>

Or from the CodeBehind:

Textbox1.Attributes.Add("autocomplete", "off");

Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed

It may be that the Windows Credential Manager is holding onto credentials for the network share.

Credential Manager - Windows Credentials

Load up Credential Manager (the easiest way is perhaps just to Search for that in the Start Menu), see if there are any Windows Credentials for your network share, and try deleting/updating them.

How to get a list of installed Jenkins plugins with name and version pair

Behe's answer with sorting plugins did not work on my Jenkins machine. I received the error java.lang.UnsupportedOperationException due to trying to sort an immutable collection i.e. Jenkins.instance.pluginManager.plugins. Simple fix for the code:

List<String> jenkinsPlugins = new ArrayList<String>(Jenkins.instance.pluginManager.plugins);
jenkinsPlugins.sort { it.displayName }
              .each { plugin ->
                   println ("${plugin.shortName}:${plugin.version}")
              }

Use the http://<jenkins-url>/script URL to run the code.

Best way to do multi-row insert in Oracle?

you can insert using loop if you want to insert some random values.

BEGIN 
    FOR x IN 1 .. 1000 LOOP
         INSERT INTO MULTI_INSERT_DEMO (ID, NAME)
         SELECT x, 'anyName' FROM dual;
    END LOOP;
END;

Post-increment and Pre-increment concept?

It's pretty simple. Both will increment the value of a variable. The following two lines are equal:

x++;
++x;

The difference is if you are using the value of a variable being incremented:

x = y++;
x = ++y;

Here, both lines increment the value of y by one. However, the first one assigns the value of y before the increment to x, and the second one assigns the value of y after the increment to x.

So there's only a difference when the increment is also being used as an expression. The post-increment increments after returning the value. The pre-increment increments before.

Tkinter: How to use threads to preventing main event loop from "freezing"

I have used RxPY which has some nice threading functions to solve this in a fairly clean manner. No queues, and I have provided a function that runs on the main thread after completion of the background thread. Here is a working example:

import rx
from rx.scheduler import ThreadPoolScheduler
import time
import tkinter as tk

class UI:
   def __init__(self):
      self.root = tk.Tk()
      self.pool_scheduler = ThreadPoolScheduler(1) # thread pool with 1 worker thread
      self.button = tk.Button(text="Do Task", command=self.do_task).pack()

   def do_task(self):
      rx.empty().subscribe(
         on_completed=self.long_running_task, 
         scheduler=self.pool_scheduler
      )

   def long_running_task(self):
      # your long running task here... eg:
      time.sleep(3)
      # if you want a callback on the main thread:
      self.root.after(5, self.on_task_complete)

   def on_task_complete(self):
       pass # runs on main thread

if __name__ == "__main__":
    ui = UI()
    ui.root.mainloop()

Another way to use this construct which might be cleaner (depending on preference):

tk.Button(text="Do Task", command=self.button_clicked).pack()

...

def button_clicked(self):

   def do_task(_):
      time.sleep(3) # runs on background thread
             
   def on_task_done():
      pass # runs on main thread

   rx.just(1).subscribe(
      on_next=do_task, 
      on_completed=lambda: self.root.after(5, on_task_done), 
      scheduler=self.pool_scheduler
   )

C# How do I click a button by hitting Enter whilst textbox has focus?

Most beginner friendly solution is:

  1. In your Designer, click on the text field you want this to happen. At the properties Window (default: bottom-right) click on the thunderbolt (Events). This icon is next to the alphabetical sort icon and the properties icon.

  2. Scroll down to keyDown. Click on the Dropdown field right to it. You'll notice there's nothing in there so simply press enter. Visual Studio will write you the following code:

    private void yourNameOfTextbox_KeyDown(object sender, KeyEventArgs e)
    {
    
    }
    
  3. Then simply paste this between the brackets:

    if (e.KeyCode == Keys.Enter)
    {
         yourNameOfButton.PerformClick();
    }
    

This will act as you would have clicked it.

How to get a random number between a float range?

Most commonly, you'd use:

import random
random.uniform(a, b) # range [a, b) or [a, b] depending on floating-point rounding

Python provides other distributions if you need.

If you have numpy imported already, you can used its equivalent:

import numpy as np
np.random.uniform(a, b) # range [a, b)

Again, if you need another distribution, numpy provides the same distributions as python, as well as many additional ones.

Extract only right most n letters from a string

Use this:

string mystr = "PER 343573"; int number = Convert.ToInt32(mystr.Replace("PER ",""));