Programs & Examples On #Linda

foreach loop in angularjs

Questions 1 & 2

So basically, first parameter is the object to iterate on. It can be an array or an object. If it is an object like this :

var values = {name: 'misko', gender: 'male'};

Angular will take each value one by one the first one is name, the second is gender.

If your object to iterate on is an array (also possible), like this :

[{ "Name" : "Thomas", "Password" : "thomasTheKing" },
 { "Name" : "Linda", "Password" : "lindatheQueen" }]

Angular.forEach will take one by one starting by the first object, then the second object.

For each of this object, it will so take them one by one and execute a specific code for each value. This code is called the iterator function. forEach is smart and behave differently if you are using an array of a collection. Here is some exemple :

var obj = {name: 'misko', gender: 'male'};
var log = [];
angular.forEach(obj, function(value, key) {
  console.log(key + ': ' + value);
});
// it will log two iteration like this
// name: misko
// gender: male

So key is the string value of your key and value is ... the value. You can use the key to access your value like this : obj['name'] = 'John'

If this time you display an array, like this :

var values = [{ "Name" : "Thomas", "Password" : "thomasTheKing" },
           { "Name" : "Linda", "Password" : "lindatheQueen" }];
angular.forEach(values, function(value, key){
     console.log(key + ': ' + value);
});
// it will log two iteration like this
// 0: [object Object]
// 1: [object Object]

So then value is your object (collection), and key is the index of your array since :

[{ "Name" : "Thomas", "Password" : "thomasTheKing" },
 { "Name" : "Linda", "Password" : "lindatheQueen" }]
// is equal to
{0: { "Name" : "Thomas", "Password" : "thomasTheKing" },
 1: { "Name" : "Linda", "Password" : "lindatheQueen" }}

I hope it answer your question. Here is a JSFiddle to run some code and test if you want : http://jsfiddle.net/ygahqdge/

Debugging your code

The problem seems to come from the fact $http.get() is an asynchronous request.

You send a query on your son, THEN when you browser end downloading it it execute success. BUT just after sending your request your perform a loop using angular.forEach without waiting the answer of your JSON.

You need to include the loop in the success function

var app = angular.module('testModule', [])
    .controller('testController', ['$scope', '$http', function($scope, $http){
    $http.get('Data/info.json').then(function(data){
         $scope.data = data;

         angular.forEach($scope.data, function(value, key){
         if(value.Password == "thomasTheKing")
           console.log("username is thomas");
         });
    });

});

This should work.

Going more deeply

The $http API is based on the deferred/promise APIs exposed by the $q service. While for simple usage patterns this doesn't matter much, for advanced usage it is important to familiarize yourself with these APIs and the guarantees they provide.

You can give a look at deferred/promise APIs, it is an important concept of Angular to make smooth asynchronous actions.

Group by with union mysql select query

Try this EDITED:

(SELECT COUNT(motorbike.owner_id),owner.name,transport.type FROM transport,owner,motorbike WHERE transport.type='motobike' AND owner.owner_id=motorbike.owner_id AND transport.type_id=motorbike.motorbike_id GROUP BY motorbike.owner_id)

UNION ALL

(SELECT COUNT(car.owner_id),owner.name,transport.type FROM transport,owner,car WHERE transport.type='car' AND owner.owner_id=car.owner_id AND transport.type_id=car.car_id GROUP BY car.owner_id)

SQL UPDATE all values in a field with appended string CONCAT not working

convert the NULL values with empty string by wrapping it in COALESCE

"UPDATE table SET data = CONCAT(COALESCE(`data`,''), 'a')"

OR

Use CONCAT_WS instead:

"UPDATE table SET data = CONCAT_WS(',',data, 'a')"

SQL SELECT from multiple tables

select p.pid, p.cid, c1.name,c2.name
from product p
left outer join customer1 c1 on c1.cid=p.cid
left outer join customer2 c2 on c2.cid=p.cid

sqlplus error on select from external table: ORA-29913: error in executing ODCIEXTTABLEOPEN callout

Our version of Oracle is running on Red Hat Enterprise Linux. We experimented with several different types of group permissions to no avail. The /defaultdir directory had a group that was a secondary group for the oracle user. When we updated the /defaultdir directory to have a group of "oinstall" (oracle's primary group), I was able to select from the external tables underneath that directory with no problem.

So, for others that come along and might have this issue, make the directory have oracle's primary group as the group and it might resolve it for you as it did us. We were able to set the permissions to 770 on the directory and files and selecting on the external tables works fine now.

how to remove css property using javascript?

element.style.height = null;

output:

<div style="height:100px;"> 
// results: 
<div style="">

MacOSX homebrew mysql root password

I stumbled across this too and the solution was unironically to simply run this:

mysql

How do I conditionally add attributes to React components?

In React you can conditionally render Components, but also their attributes, like props, className, id, and more.

In React it's very good practice to use the ternary operator which can help you conditionally render Components.

An example also shows how to conditionally render Component and its style attribute.

Here is a simple example:

_x000D_
_x000D_
class App extends React.Component {_x000D_
  state = {_x000D_
    isTrue: true_x000D_
  };_x000D_
_x000D_
  render() {_x000D_
    return (_x000D_
      <div>_x000D_
        {this.state.isTrue ? (_x000D_
          <button style={{ color: this.state.isTrue ? "red" : "blue" }}>_x000D_
            I am rendered if TRUE_x000D_
          </button>_x000D_
        ) : (_x000D_
          <button>I am rendered if FALSE</button>_x000D_
        )}_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<App />, document.getElementById("root"));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
_x000D_
<div id="root"></div>
_x000D_
_x000D_
_x000D_

Replace words in a string - Ruby

sentence.sub! 'Robert', 'Joe'

Won't cause an exception if the replaced word isn't in the sentence (the []= variant will).

How to replace all instances?

The above replaces only the first instance of "Robert".

To replace all instances use gsub/gsub! (ie. "global substitution"):

sentence.gsub! 'Robert', 'Joe'

The above will replace all instances of Robert with Joe.

Fit background image to div

You can achieve this with the background-size property, which is now supported by most browsers.

To scale the background image to fit inside the div:

background-size: contain;

To scale the background image to cover the whole div:

background-size: cover;

JSFiddle example

There also exists a filter for IE 5.5+ support, as well as vendor prefixes for some older browsers.

What is the difference between Bootstrap .container and .container-fluid classes?

.container has a max width pixel value, whereas .container-fluid is max-width 100%.

.container-fluid continuously resizes as you change the width of your window/browser by any amount.

.container resizes in chunks at several certain widths, controlled by media queries (technically we can say it’s “fixed width” because pixels values are specified, but if you stop there, people may get the impression that it can’t change size – i.e. not responsive.)

Why is "except: pass" a bad programming practice?

if it was bad practice "pass" would not be an option. if you have an asset that receives information from many places IE a form or userInput it comes in handy.

variable = False
try:
    if request.form['variable'] == '1':
       variable = True
except:
    pass

Difference between Git and GitHub

There are a number of obvious differences between Git and GitHub.

Git itself is really focused on the essential tasks of version control. It maintains a commit history, it allows you to reverse changes through reset and revert commands, and it allows you to share code with other developers through push and pull commands. I think those are the essential features every developer wants from a DVCS tool.

Git versus GitHub Comparison Chart

No Scope Creep with Git

But one thing about Git is that it is really just laser focused on source code control and nothing else. That's awesome, but it also means the tool lacks many features organizations want. For example, there is no built-in user management facilities to authenticate who is connecting and committing code. Integration with things like Jira or Jenkins are left up to developers to figure out through things like hooks. Basically, there are a load of places where features could be integrated. That's where organizations like GitHub and GitLab come in.

Additional GitHub Features

GitHub's primary 'value-add' is that it provides a cloud based platform for Git. That in itself is awesome. On top of that, GitHub also offers:

  • simple task tracking
  • a GitHub desktop app
  • online file editing
  • branch protection rules
  • pull request features
  • organizational tools
  • interaction limits for hotheads
  • emoji support!!! :octocat: :+1:

So GitHub really adds polish and refinement to an already popular DVCS tool.

Git and GitHub competitors

Sometimes when it comes to differentiating between Git and GitHub, I think it's good to look at who they compete against. Git competes on a plane with tools like Mercurial, Subversion and RTC, whereas GitHub is more in the SaaS space competing against cloud vendors such as GitLab and Atlassian's BitBucket.

No GitHub Required

One thing I always like to remind people of is that you don't need GitHub or GitLab or BitBucket to use Git. Git was released in what, 2005? GitHub didn't come on the scene until 2007 or 2008, so big organizations were doing distributed version control with Git long before the cloud hosting vendors came along. So Git is just fine on its own. It doesn't need a cloud hosting service to be effective. But at the same time, having a PaaS provider certainly doesn't hurt.

Working with GitHub Desktop

By the way, you mentioned the mismatch between the repositories in your GitHub account and the repos you have locally? That's understandable. Until you've connected and done a pull or a fetch, the local Git repo doesn't know about the remote GitHub repo. Having said that, GitHub provides a tool known as the GitHub desktop that allows you to connect to GitHub from a desktop client and easily load local Git repos to GitHub, or bring GitHub repos onto your local machine.

GitHub Desktop

I'm not overly impressed by the tool, as once you know Git, these things aren't that hard to do in the Bash shell, but it's an option.

The fight between Git and GitHub

Servlet Mapping using web.xml

It allows servlets to have multiple servlet mappings:

<servlet>
    <servlet-name>Servlet1</servlet-name>
    <servlet-path>foo.Servlet</servlet-path>
</servlet>
<servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/enroll</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/pay</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/bill</url-pattern>
</servlet-mapping>

It allows filters to be mapped on the particular servlet:

<filter-mapping>
    <filter-name>Filter1</filter-name>
    <servlet-name>Servlet1</servlet-name>
</filter-mapping>

Your proposal would support neither of them. Note that the web.xml is read and parsed only once during application's startup, not on every HTTP request as you seem to think.

Since Servlet 3.0, there's the @WebServlet annotation which minimizes this boilerplate:

@WebServlet("/enroll")
public class Servlet1 extends HttpServlet {

See also:

How to get source code of a Windows executable?

For Any *.Exe file written in any language .You can view the source code with hiew (otherwise Hackers view). You can download it at www.hiew.ru. It will be the demo version but still can view the code.

After this follow these steps:

  1. Press alt+f2 to navigate to the file.

  2. Press enter to see its assembly / c++ code.

How to use ng-if to test if a variable is defined

I edited your plunker to include ABOS's solution.

<body ng-controller="MainCtrl">
    <ul ng-repeat='item in items'>
      <li ng-if='item.color'>The color is {{item.color}}</li>
      <li ng-if='item.shipping !== undefined'>The shipping cost is {{item.shipping}}</li>
    </ul>
  </body>

plunkerFork

Simplest way to profile a PHP script

The PECL APD extension is used as follows:

<?php
apd_set_pprof_trace();

//rest of the script
?>

After, parse the generated file using pprofp.

Example output:

Trace for /home/dan/testapd.php
Total Elapsed Time = 0.00
Total System Time  = 0.00
Total User Time    = 0.00


Real         User        System             secs/    cumm
%Time (excl/cumm)  (excl/cumm)  (excl/cumm) Calls    call    s/call  Memory Usage Name
--------------------------------------------------------------------------------------
100.0 0.00 0.00  0.00 0.00  0.00 0.00     1  0.0000   0.0009            0 main
56.9 0.00 0.00  0.00 0.00  0.00 0.00     1  0.0005   0.0005            0 apd_set_pprof_trace
28.0 0.00 0.00  0.00 0.00  0.00 0.00    10  0.0000   0.0000            0 preg_replace
14.3 0.00 0.00  0.00 0.00  0.00 0.00    10  0.0000   0.0000            0 str_replace

Warning: the latest release of APD is dated 2004, the extension is no longer maintained and has various compability issues (see comments).

How to get PID of process by specifying process name and store it in a variable to use further?

use grep [n]ame to remove that grep -v name this is first... Sec using xargs in the way how it is up there is wrong to rnu whatever it is piped you have to use -i ( interactive mode) otherwise you may have issues with the command.

ps axf | grep | grep -v grep | awk '{print "kill -9 " $1}' ? ps aux |grep [n]ame | awk '{print "kill -9 " $2}' ? isnt that better ?

StringUtils.isBlank() vs String.isEmpty()

I am answering this because it's the top result in Google for "String isBlank() Method".

If you are using Java 11 or above, you can use the String class isBlank() method. This method does the same thing as Apache Commons StringUtils class.

I have written a small post on this method examples, read it here.

"SELECT ... IN (SELECT ...)" query in CodeIgniter

I think you can create a simple SQL query:

$sql="select username from user where id in (select id from idtables)";
$query=$this->db->query($sql);

and then you can use it normally.

Why does cURL return error "(23) Failed writing body"?

This happens when a piped program (e.g. grep) closes the read pipe before the previous program is finished writing the whole page.

In curl "url" | grep -qs foo, as soon as grep has what it wants it will close the read stream from curl. cURL doesn't expect this and emits the "Failed writing body" error.

A workaround is to pipe the stream through an intermediary program that always reads the whole page before feeding it to the next program.

E.g.

curl "url" | tac | tac | grep -qs foo

tac is a simple Unix program that reads the entire input page and reverses the line order (hence we run it twice). Because it has to read the whole input to find the last line, it will not output anything to grep until cURL is finished. Grep will still close the read stream when it has what it's looking for, but it will only affect tac, which doesn't emit an error.

Socket.io + Node.js Cross-Origin Request Blocked

This could be a certification issue with Firefox, not necessarily anything wrong with your CORS. Firefox CORS request giving 'Cross-Origin Request Blocked' despite headers

I was running into the same exact issue with Socketio and Nodejs throwing CORS error in Firefox. I had Certs for *.myNodeSite.com, but I was referencing the LAN IP address 192.168.1.10 for Nodejs. (WAN IP address might throw the same error as well.) Since the Cert didn't match the IP address reference, Firefox threw that error.

Oracle: How to filter by date and time in a where clause

In the example that you have provided there is nothing that would throw a SQL command not properly formed error. How are you executing this query? What are you not showing us?

This example script works fine:

create table tableName
(session_start_date_time DATE);

insert into tableName (session_start_date_time) 
values (sysdate+1);

select * from tableName
where session_start_date_time > to_date('12-Jan-2012 16:00', 'DD-MON-YYYY hh24:mi');

As does this example:

create table tableName2
(session_start_date_time TIMESTAMP);

insert into tableName2 (session_start_date_time) 
values (to_timestamp('01/12/2012 16:01:02.345678','mm/dd/yyyy hh24:mi:ss.ff'));

select * from tableName2
where session_start_date_time > to_date('12-Jan-2012 16:00', 'DD-MON-YYYY hh24:mi');

select * from tableName2
where session_start_date_time > to_timestamp('01/12/2012 14:01:02.345678','mm/dd/yyyy hh24:mi:ss.ff');

So there must be something else that is wrong.

Add image to layout in ruby on rails

When using the new ruby, the image folder will go to asset folder on folder app

after placing your images in image folder, use

<%=image_tag("example_image.png", alt: "Example Image")%>

IndexError: tuple index out of range ----- Python

This is because your row variable/tuple does not contain any value for that index. You can try printing the whole list like print(row) and check how many indexes there exists.

How to make div background color transparent in CSS

From https://developer.mozilla.org/en-US/docs/Web/CSS/background-color

To set background color:

/* Hexadecimal value with color and 100% transparency*/
background-color: #11ffee00;  /* Fully transparent */

/* Special keyword values */
background-color: transparent;

/* HSL value with color and 100% transparency*/
background-color: hsla(50, 33%, 25%, 1.00);  /* 100% transparent */

/* RGB value with color and 100% transparency*/
background-color: rgba(117, 190, 218, 1.0);  /* 100% transparent */

Get all child elements

Yes, you can use find_elements_by_ to retrieve children elements into a list. See the python bindings here: http://selenium-python.readthedocs.io/locating-elements.html

Example HTML:

<ul class="bar">
    <li>one</li>
    <li>two</li>
    <li>three</li>
</ul>

You can use the find_elements_by_ like so:

parentElement = driver.find_element_by_class_name("bar")
elementList = parentElement.find_elements_by_tag_name("li")

If you want help with a specific case, you can edit your post with the HTML you're looking to get parent and children elements from.

In AngularJS, what's the difference between ng-pristine and ng-dirty?

Both directives obviously serve the same purpose, and though it seems that the decision of the angular team to include both interfere with the DRY principle and adds to the payload of the page, it still is rather practical to have them both around. It is easier to style your input elements as you have both .ng-pristine and .ng-dirty available for styling in your css files. I guess this was the primary reason for adding both directives.

Why do I get a SyntaxError for a Unicode escape in my file path?

C:\\Users\\expoperialed\\Desktop\\Python This syntax worked for me.

How to get Python requests to trust a self signed SSL certificate?

try:

r = requests.post(url, data=data, verify='/path/to/public_key.pem')

Add days to JavaScript Date

A solution designed for the pipeline operator:

const addDays = days => date => {
  const result = new Date(date);

  result.setDate(result.getDate() + days);

  return result;
};

Usage:

// Without the pipeline operator...
addDays(7)(new Date());

// And with the pipeline operator...
new Date() |> addDays(7);

If you need more functionality, I suggest looking into the date-fns library.

Angular 1 - get current URL parameters

Better would have been generate url like

app.dev/backend?type=surveys&id=2

and then use

var type=$location.search().type;
var id=$location.search().id;

and inject $location in controller.

What is callback in Android?

You create an interface first, then define a method, which would act as a callback. In this example we would have two classes, one classA and another classB

Interface:

public interface OnCustomEventListener{
  public void onEvent();   //method, which can have parameters
}

the listener itself in classB (we only set the listener in classB)

private OnCustomEventListener mListener; //listener field

//setting the listener
public void setCustomEventListener(OnCustomEventListener eventListener) {
   this.mListener=eventListener;
}

in classA, how we start listening for whatever classB has to tell

classB.setCustomEventListener(new OnCustomEventListener(){
    public void onEvent(){
       //do whatever you want to do when the event is performed.
    }
});  

how do we trigger an event from classB (for example on button pressed)

if(this.mListener!=null){
   this.mListener.onEvent();
}

P.S. Your custom listener may have as many parameters as you want

Source

Force an Android activity to always use landscape mode

A quick and simple solution is for the AndroidManifest.xml file, add the following for each activity that you wish to force to landscape mode:

android:screenOrientation="landscape"

How can I display a pdf document into a Webview?

Here load with progressDialog. Need to give WebClient otherwise it force to open in browser:

final ProgressDialog pDialog = new ProgressDialog(context);
    pDialog.setTitle(context.getString(R.string.app_name));
    pDialog.setMessage("Loading...");
    pDialog.setIndeterminate(false);
    pDialog.setCancelable(false);
    WebView webView = (WebView) rootView.findViewById(R.id.web_view);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            pDialog.show();
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            pDialog.dismiss();
        }
    });
    String pdf = "http://www.adobe.com/devnet/acrobat/pdfs/pdf_open_parameters.pdf";
    webView.loadUrl("https://drive.google.com/viewerng/viewer?embedded=true&url=" + pdf);

How to create a date object from string in javascript

First extract the string like this

var dateString = str.match(/^(\d{2})\/(\d{2})\/(\d{4})$/);

Then,

var d = new Date( dateString[3], dateString[2]-1, dateString[1] );

og:type and valid values : constantly being parsed as og:type=website

Make sure your article:author data is a Facebook author URL. Unfortunately, that conflicts with what Pinterest is expecting. It's the best thing about standards, there are so many ways to implement them!

<meta property="article:author" content="https://www.facebook.com/mpatnode76">

But Pinterest wants to see something like this:

<meta property="article:author" content="Mike Patnode">

We ended up swapping the formats depending upon the user agent. Hopefully, that doesn't screw up your page cache. That fixed it for us.

Full disclosure. Found this here: https://surniaulula.com/2014/03/01/pinterest-articleauthor-incompatible-with-open-graph/

Printing result of mysql query from variable

From php docs:

For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.

For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.

The returned result resource should be passed to mysql_fetch_array(), and other functions for dealing with result tables, to access the returned data.

http://php.net/manual/en/function.mysql-query.php

Debug JavaScript in Eclipse

For Node.js there is Nodeclipse 0.2 with some bug fixes for chromedevtools

Which characters are valid/invalid in a JSON key name?

No. Any valid string is a valid key. It can even have " as long as you escape it:

{"The \"meaning\" of life":42}

There is perhaps a chance you'll encounter difficulties loading such values into some languages, which try to associate keys with object field names. I don't know of any such cases, however.

Exclude Blank and NA in R

Don't know exactly what kind of dataset you have, so I provide general answer.

x <- c(1,2,NA,3,4,5)
y <- c(1,2,3,NA,6,8)
my.data <- data.frame(x, y)
> my.data
   x  y
1  1  1
2  2  2
3 NA  3
4  3 NA
5  4  6
6  5  8
# Exclude rows with NA values
my.data[complete.cases(my.data),]
  x y
1 1 1
2 2 2
5 4 6
6 5 8

os.path.dirname(__file__) returns empty

os.path.split(os.path.realpath(__file__))[0]

os.path.realpath(__file__)return the abspath of the current script; os.path.split(abspath)[0] return the current dir

Resize height with Highcharts

I had a similar problem with height except my chart was inside a bootstrap modal popup, which I'm already controlling the size of with css. However, for some reason when the window was resized horizontally the height of the chart container would expand indefinitely. If you were to drag the window back and forth it would expand vertically indefinitely. I also don't like hard-coded height/width solutions.

So, if you're doing this in a modal, combine this solution with a window resize event.

// from link
$('#ChartModal').on('show.bs.modal', function() {
    $('.chart-container').css('visibility', 'hidden');
});

$('#ChartModal').on('shown.bs.modal.', function() {
    $('.chart-container').css('visibility', 'initial');
    $('#chartbox').highcharts().reflow()
    //added
    ratio = $('.chart-container').width() / $('.chart-container').height();
});

Where "ratio" becomes a height/width aspect ratio, that will you resize when the bootstrap modal resizes. This measurement is only taken when he modal is opened. I'm storing ratio as a global but that's probably not best practice.

$(window).on('resize', function() {
    //chart-container is only visible when the modal is visible.
    if ( $('.chart-container').is(':visible') ) {
        $('#chartbox').highcharts().setSize( 
            $('.chart-container').width(),
            ($('.chart-container').width() / ratio),
            doAnimation = true );
    }       
});

So with this, you can drag your screen to the side (resizing it) and your chart will maintain its aspect ratio.

Widescreen

enter image description here

vs smaller

enter image description here

(still fiddling around with vw units, so everything in the back is too small to read lol!)

Change the current directory from a Bash script

Declare your path:

PATH='/home/artemb'     
cd ${PATH}

How to get the last row of an Oracle a table

SELECT * FROM 
  MY_TABLE
WHERE 
  <your filters>
ORDER BY PRIMARY_KEY DESC FETCH FIRST ROW ONLY

map vs. hash_map in C++

The C++ spec doesn't say exactly what algorithm you must use for the STL containers. It does, however, put certain constraints on their performance, which rules out the use of hash tables for map and other associative containers. (They're most commonly implemented with red/black trees.) These constraints require better worst-case performance for these containers than hash tables can deliver.

Many people really do want hash tables, however, so hash-based STL associative containers have been a common extension for years. Consequently, they added unordered_map and such to later versions of the C++ standard.

Spring MVC - How to return simple String as JSON in Rest Controller

In one project we addressed this using JSONObject (maven dependency info). We chose this because we preferred returning a simple String rather than a wrapper object. An internal helper class could easily be used instead if you don't want to add a new dependency.

Example Usage:

@RestController
public class TestController
{
    @RequestMapping("/getString")
    public String getString()
    {
        return JSONObject.quote("Hello World");
    }
}

Sum the digits of a number

Here is the best solution I found:

function digitsum(n) {
    n = n.toString();
    let result = 0;
    for (let i = 0; i < n.length; i++) {
        result += parseInt(n[i]);
    }
    return result;
}
console.log(digitsum(192));

Convert JSON array to an HTML table in jQuery

One simple way of doing this is:

_x000D_
_x000D_
var data = [{_x000D_
  "Total": 34,_x000D_
  "Version": "1.0.4",_x000D_
  "Office": "New York"_x000D_
}, {_x000D_
  "Total": 67,_x000D_
  "Version": "1.1.0",_x000D_
  "Office": "Paris"_x000D_
}];_x000D_
_x000D_
drawTable(data);_x000D_
_x000D_
function drawTable(data) {_x000D_
_x000D_
  // Get Table headers and print_x000D_
  var head = $("<tr />")_x000D_
  $("#DataTable").append(head);_x000D_
  for (var j = 0; j < Object.keys(data[0]).length; j++) {_x000D_
    head.append($("<th>" + Object.keys(data[0])[j] + "</th>"));_x000D_
  }_x000D_
_x000D_
  // Print the content of rows in DataTable_x000D_
  for (var i = 0; i < data.length; i++) {_x000D_
    drawRow(data[i]);_x000D_
  }_x000D_
_x000D_
}_x000D_
_x000D_
function drawRow(rowData) {_x000D_
  var row = $("<tr />")_x000D_
  $("#DataTable").append(row);_x000D_
  row.append($("<td>" + rowData["Total"] + "</td>"));_x000D_
  row.append($("<td>" + rowData["Version"] + "</td>"));_x000D_
  row.append($("<td>" + rowData["Office"] + "</td>"));_x000D_
}
_x000D_
table {_x000D_
  border: 1px solid #666;_x000D_
  width: 100%;_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
th {_x000D_
  background: #f8f8f8;_x000D_
  font-weight: bold;_x000D_
  padding: 2px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<table id="DataTable"></table>
_x000D_
_x000D_
_x000D_

How do I get a substring of a string in Python?

A common way to achieve this is by string slicing.

MyString[a:b] gives you a substring from index a to (b - 1).

Set environment variables from file of key/value pairs

Modified from @Dan Kowalczyk

I put this in ~/.bashrc.

set -a
. ./.env >/dev/null 2>&1
set +a

Cross-compatible very well with Oh-my-Zsh's dotenv plugin. (There is Oh-my-bash, but it doesn't have dotenv plugin.)

How do I Search/Find and Replace in a standard string?

In C++11, you can do this as a one-liner with a call to regex_replace:

#include <string>
#include <regex>

using std::string;

string do_replace( string const & in, string const & from, string const & to )
{
  return std::regex_replace( in, std::regex(from), to );
}

string test = "Remove all spaces";
std::cout << do_replace(test, " ", "") << std::endl;

output:

Removeallspaces

GROUP BY without aggregate function

I know you said you want to understand group by if you have data like this:

COL-A  COL-B  COL-C  COL-D
  1      Ac      C1     D1
  2      Bd      C2     D2
  3      Ba      C1     D3
  4      Ab      C1     D4
  5      C       C2     D5

And you want to make the data appear like:

COL-A  COL-B  COL-C  COL-D
  4      Ab      C1     D4
  1      Ac      C1     D1
  3      Ba      C1     D3
  2      Bd      C2     D2
  5      C       C2     D5

You use:

select * from table_name
order by col-c,colb

Because I think this is what you intend to do.

What is the difference between response.sendRedirect() and request.getRequestDispatcher().forward(request,response)

forward

Control can be forward to resources available within the server from where the call is made. This transfer of control is done by the container internally and browser / client is not involved. This is the major difference between forward and sendRedirect. When the forward is done, the original request and response objects are transfered along with additional parameters if needed.

redirect

Control can be redirect to resources to different servers or domains. This transfer of control task is delegated to the browser by the container. That is, the redirect sends a header back to the browser / client. This header contains the resource url to be redirected by the browser. Then the browser initiates a new request to the given url. Since it is a new request, the old request and response object is lost.

For example, sendRedirect can transfer control from http://google.com to http://anydomain.com but forward cannot do this.

‘session’ is not lost in both forward and redirect.

To feel the difference between forward and sendRedirect visually see the address bar of your browser, in forward, you will not see the forwarded address (since the browser is not involved) in redirect, you can see the redirected address.

git push vs git push origin <branchname>

The first push should be a:

git push -u origin branchname

That would make sure:

Any future git push will, with that default policy, only push the current branch, and only if that branch has an upstream branch with the same name.
that avoid pushing all matching branches (previous default policy), where tons of test branches were pushed even though they aren't ready to be visible on the upstream repo.

How to set corner radius of imageView?

The easiest way is to create an UIImageView subclass (I have tried it and it's working perfectly on iPhone 7 and XCode 8):

class CIRoundedImageView: UIImageView {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func awakeFromNib() {

        self.layoutIfNeeded()
        layer.cornerRadius = self.frame.height / 2.0
        layer.masksToBounds = true
    }
}

and then you can also set a border:

imageView.layer.borderWidth = 2.0

imageView.layer.borderColor = UIColor.blackColor().CGColor

PHP Warning: Unknown: failed to open stream

This also happens (and is particularly confounding) if you forgot that you created a Windows symlink to a different directory, and that other directory doesn't have appropriate permissions.

RecyclerView: Inconsistency detected. Invalid item position

I've just fixed the same issue. I had a RecyclerView.Adapter with setHasStableIds(true) set to avoid items blinking.

I was using a duplicatable field in getItemId() (my model has no id field):

override fun getItemId(position: Int): Long {
    // Error-prone due to possibly duplicate name.
    return contacts[position].name.hashCode().toLong()
}

getItemId() should return a unique id for each item, so the solution was to do it:

override fun getItemId(position: Int): Long {
    // Contact's phone is unique, so I use it instead.
    return contacts[position].phone.hashCode().toLong()
}

Strtotime() doesn't work with dd/mm/YYYY format

fastest should probably be

false!== ($date !== $date=preg_replace(';[0-2]{2}/[0-2]{2}/[0-2]{2};','$3-$2-$1',$date))

this will return false if the format does not look like the proper one, but it wont-check wether the date is valid

Where to find the win32api module for Python?

I've found that UC Irvine has a great collection of python modules, pywin32 (win32api) being one of many listed there. I'm not sure how they do with keeping up with the latest versions of these modules but it hasn't let me down yet.

UC Irvine Python Extension Repository - http://www.lfd.uci.edu/~gohlke/pythonlibs

pywin32 module - http://www.lfd.uci.edu/~gohlke/pythonlibs/#pywin32

Groovy: How to check if a string contains any element of an array?

def valid = pointAddress.findAll { a ->
    validPointTypes.any { a.contains(it) }
}

Should do it

Getting unique values in Excel by using formulas only

Ok, I have two ideas for you. Hopefully one of them will get you where you need to go. Note that the first one ignores the request to do this as a formula since that solution is not pretty. I figured I make sure the easy way really wouldn't work for you ;^).

Use the Advanced Filter command

  1. Select the list (or put your selection anywhere inside the list and click ok if the dialog comes up complaining that Excel does not know if your list contains headers or not)
  2. Choose Data/Advanced Filter
  3. Choose either "Filter the list, in-place" or "Copy to another location"
  4. Click "Unique records only"
  5. Click ok
  6. You are done. A unique list is created either in place or at a new location. Note that you can record this action to create a one line VBA script to do this which could then possible be generalized to work in other situations for you (e.g. without the manual steps listed above).

Using Formulas (note that I'm building on Locksfree solution to end up with a list with no holes)

This solution will work with the following caveats:

  • The list must be sorted (ascending or descending does not matter). Actually that's quite accurate as the requirement is really that all like items must be contiguous but sorting is the easiest way to reach that state.
  • Three new columns are required (two new columns for calculations and one new column for the new list). The second and third columns could be combined but I'll leave that as an exercise to the reader.

    Here is the summary of the solution:

    1. For each item in the list, calculate the number of duplicates above it.
    2. For each place in the unique list, calculate the index of the next unique item.
    3. Finally, use the indexes to create a new list with only unique items.

    And here is a step by step example:

    1. Open a new spreadsheet
    2. In a1:a6 enter the example given in the original question ("red", "blue", "red", "green", "blue", "black")
    3. Sort the list: put the selection in the list and choose the sort command.
    4. In column B, calculate the duplicates:
      1. In B1, enter "=IF(COUNTIF($A$1:A1,A1) = 1,0,COUNTIF(A1:$A$6,A1))". Note that the "$" in the cell references are very important as it will make the next step (populating the rest of the column) much easier. The "$" indicates an absolute reference so that when the cell content is copy/pasted the reference will not update (as opposed to a relative reference which will update).
      2. Use smart copy to populate the rest of column B: Select B1. Move your mouse over the black square in the lower right hand corner of the selection. Click and drag down to the bottom of the list (B6). When you release, the formula will be copied into B2:B6 with the relative references updated.
      3. The value of B1:B6 should now be "0,0,1,0,0,1". Notice that the "1" entries indicate duplicates.
    5. In Column C, create an index of unique items:
      1. In C1, enter "=Row()". You really just want C1 = 1 but using Row() means this solution will work even if the list does not start in row 1.
      2. In C2, enter "=IF(C1+1<=ROW($B$6), C1+1+INDEX($B$1:$B$6,C1+1),C1+1)". The "if" is being used to stop a #REF from being produced when the index reaches the end of the list.
      3. Use smart copy to populate C3:C6.
      4. The value of C1:C6 should be "1,2,4,5,7,8"
    6. In column D, create the new unique list:
      1. In D1, enter "=IF(C1<=ROW($A$6), INDEX($A$1:$A$6,C1), "")". And, the "if" is being used to stop the #REF case when the index goes beyond the end of the list.
      2. Use smart copy to populate D2:D6.
      3. The values of D1:D6 should now be "black","blue","green","red","","".

    Hope this helps....

  • How to post raw body data with curl?

    curl's --data will by default send Content-Type: application/x-www-form-urlencoded in the request header. However, when using Postman's raw body mode, Postman sends Content-Type: text/plain in the request header.

    So to achieve the same thing as Postman, specify -H "Content-Type: text/plain" for curl:

    curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/
    

    Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network tab :

    enter image description here

    npm WARN ... requires a peer of ... but none is installed. You must install peer dependencies yourself

    I had a similar issue and solved after running these instructions!

    npm install npm -g
    npm install --save-dev @angular/cli@latest
    npm install
    npm start
    

    shell init issue when click tab, what's wrong with getcwd?

    By chance, is this occurring on a directory using OverlayFS (or some other special file system type)?

    I just had this issue where my cross-compiled version of bash would use an internal implementation of getcwd which has issues with OverlayFS. I found information about this here:

    It seems that this can be traced to an internal implementation of getcwd() in bash. When cross-compiled, it can't check for getcwd() use of malloc, so it is cautious and sets GETCWD_BROKEN and uses an internal implementation of getcwd(). This internal implementation doesn't seem to work well with OverlayFS.

    http://permalink.gmane.org/gmane.linux.embedded.yocto.general/25204

    You can configure and rebuild bash with bash_cv_getcwd_malloc=yes (if you're actually building bash and your C library does malloc a getcwd call).

    Is there any way to wait for AJAX response and halt execution?

    The simple answer is to turn off async. But that's the wrong thing to do. The correct answer is to re-think how you write the rest of your code.

    Instead of writing this:

    function functABC(){
        $.ajax({
            url: 'myPage.php',
            data: {id: id},
            success: function(data) {
                return data;
            }
        });
    }
    
    function foo () {
        var response = functABC();
        some_result = bar(response);
        // and other stuff and
        return some_result;
    }
    

    You should write it like this:

    function functABC(callback){
        $.ajax({
            url: 'myPage.php',
            data: {id: id},
            success: callback
        });
    }
    
    function foo (callback) {
        functABC(function(data){
            var response = data;
            some_result = bar(response);
            // and other stuff and
            callback(some_result);
        })
    }
    

    That is, instead of returning result, pass in code of what needs to be done as callbacks. As I've shown, callbacks can be nested to as many levels as you have function calls.


    A quick explanation of why I say it's wrong to turn off async:

    Turning off async will freeze the browser while waiting for the ajax call. The user cannot click on anything, cannot scroll and in the worst case, if the user is low on memory, sometimes when the user drags the window off the screen and drags it in again he will see empty spaces because the browser is frozen and cannot redraw. For single threaded browsers like IE7 it's even worse: all websites freeze! Users who experience this may think you site is buggy. If you really don't want to do it asynchronously then just do your processing in the back end and refresh the whole page. It would at least feel not buggy.

    Differences in boolean operators: & vs && and | vs ||

    I think you're talking about the logical meaning of both operators, here you have a table-resume:

    boolean a, b;
    
    Operation     Meaning                       Note
    ---------     -------                       ----
       a && b     logical AND                    short-circuiting
       a || b     logical OR                     short-circuiting
       a &  b     boolean logical AND            not short-circuiting
       a |  b     boolean logical OR             not short-circuiting
       a ^  b     boolean logical exclusive OR
      !a          logical NOT
    
    short-circuiting        (x != 0) && (1/x > 1)   SAFE
    not short-circuiting    (x != 0) &  (1/x > 1)   NOT SAFE
    

    Short-circuit evaluation, minimal evaluation, or McCarthy evaluation (after John McCarthy) is the semantics of some Boolean operators in some programming languages in which the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression: when the first argument of the AND function evaluates to false, the overall value must be false; and when the first argument of the OR function evaluates to true, the overall value must be true.

    Not Safe means the operator always examines every condition in the clause, so in the examples above, 1/x may be evaluated when the x is, in fact, a 0 value, raising an exception.

    Doctrine 2 ArrayCollection filter method

    The Collection#filter method really does eager load all members. Filtering at the SQL level will be added in doctrine 2.3.

    What is the difference between JDK and JRE?

    The difference between JDK and JRE is that JDK is the software development kit for java while JRE is the place where you run your programs.

    How do I display a MySQL error in PHP for a long query that depends on the user input?

    I use the following to turn all error reporting on for MySQLi

    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    

    *NOTE: don't use this in a production environment.

    Unable to Build using MAVEN with ERROR - Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile

    For me, I changed C:\apps\Java\jdk1.8_162\bin\javac.exe to C:\apps\Java\jdk1.8_162\bin\javacpl.exe Since there was no executable with that name in the bin folder. That worked.

    jQuery: go to URL with target="_blank"

    If you want to create the popup window through jQuery then you'll need to use a plugin. This one seems like it will do what you want:

    http://rip747.github.com/popupwindow/

    Alternately, you can always use JavaScript's window.open function.

    Note that with either approach, the new window must be opened in response to user input/action (so for instance, a click on a link or button). Otherwise the browser's popup blocker will just block the popup.

    Bootstrap 3 - How to load content in modal body via AJAX?

    I guess you're searching for this custom function. It takes a data-toggle attribute and creates dynamically the necessary div to place the remote content. Just place the data-toggle="ajaxModal" on any link you want to load via AJAX.

    The JS part:

    $('[data-toggle="ajaxModal"]').on('click',
                  function(e) {
                    $('#ajaxModal').remove();
                    e.preventDefault();
                    var $this = $(this)
                      , $remote = $this.data('remote') || $this.attr('href')
                      , $modal = $('<div class="modal" id="ajaxModal"><div class="modal-body"></div></div>');
                    $('body').append($modal);
                    $modal.modal({backdrop: 'static', keyboard: false});
                    $modal.load($remote);
                  }
                );
    

    Finally, in the remote content, you need to put the entire structure to work.

    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title"></h4>
            </div>
            <div class="modal-body">
            </div>
            <div class="modal-footer">
                <a href="#" class="btn btn-white" data-dismiss="modal">Close</a>
                <a href="#" class="btn btn-primary">Button</a>
                <a href="#" class="btn btn-primary">Another button...</a>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
    

    Is there a function to copy an array in C/C++?

    Since you asked for a C++ solution...

    #include <algorithm>
    #include <iterator>
    
    const int arr_size = 10;
    some_type src[arr_size];
    // ...
    some_type dest[arr_size];
    std::copy(std::begin(src), std::end(src), std::begin(dest));
    

    How to output a comma delimited list in jinja python template?

    And using the joiner from http://jinja.pocoo.org/docs/dev/templates/#joiner

    {% set comma = joiner(",") %}
    {% for user in userlist %}
        {{ comma() }}<a href="/profile/{{ user }}/">{{ user }}</a>
    {% endfor %}  
    

    It's made for this exact purpose. Normally a join or a check of forloop.last would suffice for a single list, but for multiple groups of things it's useful.

    A more complex example on why you would use it.

    {% set pipe = joiner("|") %}
    {% if categories %} {{ pipe() }}
        Categories: {{ categories|join(", ") }}
    {% endif %}
    {% if author %} {{ pipe() }}
        Author: {{ author() }}
    {% endif %}
    {% if can_edit %} {{ pipe() }}
        <a href="?action=edit">Edit</a>
    {% endif %}
    

    Trouble using ROW_NUMBER() OVER (PARTITION BY ...)

    A bit involved. Easiest would be to refer to this SQL Fiddle I created for you that produces the exact result. There are ways you can improve it for performance or other considerations, but this should hopefully at least be clearer than some alternatives.

    The gist is, you get a canonical ranking of your data first, then use that to segment the data into groups, then find an end date for each group, then eliminate any intermediate rows. ROW_NUMBER() and CROSS APPLY help a lot in doing it readably.


    EDIT 2019:

    The SQL Fiddle does in fact seem to be broken, for some reason, but it appears to be a problem on the SQL Fiddle site. Here's a complete version, tested just now on SQL Server 2016:

    CREATE TABLE Source
    (
      EmployeeID int,
      DateStarted date,
      DepartmentID int
    )
    
    INSERT INTO Source
    VALUES
    (10001,'2013-01-01',001),
    (10001,'2013-09-09',001),
    (10001,'2013-12-01',002),
    (10001,'2014-05-01',002),
    (10001,'2014-10-01',001),
    (10001,'2014-12-01',001)
    
    
    SELECT *, 
      ROW_NUMBER() OVER (PARTITION BY EmployeeID ORDER BY DateStarted) AS EntryRank,
      newid() as GroupKey,
      CAST(NULL AS date) AS EndDate
    INTO #RankedData
    FROM Source
    ;
    
    UPDATE #RankedData
    SET GroupKey = beginDate.GroupKey
    FROM #RankedData sup
      CROSS APPLY 
      (
        SELECT TOP 1 GroupKey
        FROM #RankedData sub 
        WHERE sub.EmployeeID = sup.EmployeeID AND
          sub.DepartmentID = sup.DepartmentID AND
          NOT EXISTS 
            (
              SELECT * 
              FROM #RankedData bot 
              WHERE bot.EmployeeID = sup.EmployeeID AND
                bot.EntryRank BETWEEN sub.EntryRank AND sup.EntryRank AND
                bot.DepartmentID <> sup.DepartmentID
            )
          ORDER BY DateStarted ASC
        ) beginDate (GroupKey);
    
    UPDATE #RankedData
    SET EndDate = nextGroup.DateStarted
    FROM #RankedData sup
      CROSS APPLY 
      (
        SELECT TOP 1 DateStarted
        FROM #RankedData sub
        WHERE sub.EmployeeID = sup.EmployeeID AND
          sub.DepartmentID <> sup.DepartmentID AND
          sub.EntryRank > sup.EntryRank
        ORDER BY EntryRank ASC
      ) nextGroup (DateStarted);
    
    SELECT * FROM 
    (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY GroupKey ORDER BY EntryRank ASC) AS GroupRank FROM #RankedData
    ) FinalRanking
    WHERE GroupRank = 1
    ORDER BY EntryRank;
    
    DROP TABLE #RankedData
    DROP TABLE Source
    

    MySQL SELECT last few days?

    Use for a date three days ago:

    WHERE t.date >= DATE_ADD(CURDATE(), INTERVAL -3 DAY);
    

    Check the DATE_ADD documentation.

    Or you can use:

    WHERE t.date >= ( CURDATE() - INTERVAL 3 DAY )
    

    How to reload current page?

    I have solved following this way

    import { Router, ActivatedRoute } from '@angular/router';
    
    constructor(private router: Router
              , private activeRoute: ActivatedRoute) {
    
    }
    reloadCurrentPage(){
       let currentUrl = this.router.url;
       this.router.navigateByUrl('/', {skipLocationChange: true}).then(() => {
       this.router.navigate([currentUrl]);
       });
     }
    

    How do disable paging by swiping with finger in ViewPager but still be able to swipe programmatically?

    Try overriding and returning true from either onInterceptTouchEvent() and/or onTouchEvent(), which will consume touch events on the pager.

    Redirecting to a page after submitting form in HTML

    You need to use the jQuery AJAX or XMLHttpRequest() for post the data to the server. After data posting you can redirect your page to another page by window.location.href.

    Example:

     var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          window.location.href = 'https://website.com/my-account';
        }
      };
      xhttp.open("POST", "demo_post.asp", true);
      xhttp.send();
    

    How to add files/folders to .gitignore in IntelliJ IDEA?

    Here is the screen print showing the options to ignore the file or folder after the installation of the .ignore plugin. The generated file name would be .gitignore enter image description here

    How can I do SELECT UNIQUE with LINQ?

    var uniqueColors = (from dbo in database.MainTable 
                        where dbo.Property == true
                        select dbo.Color.Name).Distinct();
    

    How to sort a list of strings numerically?

    Try this, it’ll sort the list in-place in descending order (there’s no need to specify a key in this case):

    Process

    listB = [24, 13, -15, -36, 8, 22, 48, 25, 46, -9]
    listC = sorted(listB, reverse=True) # listB remains untouched
    print listC
    

    output:

     [48, 46, 25, 24, 22, 13, 8, -9, -15, -36]
    

    How to generate unique IDs for form labels in React?

    You could use a library such as node-uuid for this to make sure you get unique ids.

    Install using:

    npm install node-uuid --save

    Then in your react component add the following:

    import {default as UUID} from "node-uuid";
    import {default as React} from "react";
    
    export default class MyComponent extends React.Component {   
      componentWillMount() {
        this.id = UUID.v4();
      }, 
      render() {
        return (
          <div>
            <label htmlFor={this.id}>My label</label>
            <input id={this.id} type="text"/>
          </div>
        );
      }   
    }
    

    Difference between readFile() and readFileSync()

    fs.readFile takes a call back which calls response.send as you have shown - good. If you simply replace that with fs.readFileSync, you need to be aware it does not take a callback so your callback which calls response.send will never get called and therefore the response will never end and it will timeout.

    You need to show your readFileSync code if you're not simply replacing readFile with readFileSync.

    Also, just so you're aware, you should never call readFileSync in a node express/webserver since it will tie up the single thread loop while I/O is performed. You want the node loop to process other requests until the I/O completes and your callback handling code can run.

    Spring Boot and multiple external configuration files

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

    My requirements:

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

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

    I came up with the following solution:

    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Bean;
    import org.springframework.core.io.ClassPathResource;
    import org.springframework.core.io.PathResource;
    import org.springframework.core.io.Resource;
    
    import java.io.IOException;
    import java.util.Properties;
    
    import static java.util.Arrays.stream;
    
    @Configuration
    public class PropertiesConfig {
    
        private static final Logger LOG = LoggerFactory.getLogger(PropertiesConfig.class);
    
        private final static String PROPERTIES_FILENAME = "user.properties";
    
        @Value("${properties.location:}")
        private String propertiesLocation;
    
        @Bean
        Properties userProperties() throws IOException {
            final Resource[] possiblePropertiesResources = {
                    new ClassPathResource(PROPERTIES_FILENAME),
                    new PathResource("config/" + PROPERTIES_FILENAME),
                    new PathResource(PROPERTIES_FILENAME),
                    new PathResource(getCustomPath())
            };
            // Find the last existing properties location to emulate spring boot application.properties discovery
            final Resource propertiesResource = stream(possiblePropertiesResources)
                    .filter(Resource::exists)
                    .reduce((previous, current) -> current)
                    .get();
            final Properties userProperties = new Properties();
    
            userProperties.load(propertiesResource.getInputStream());
    
            LOG.info("Using {} as user resource", propertiesResource);
    
            return userProperties;
        }
    
        private String getCustomPath() {
            return propertiesLocation.endsWith(".properties") ? propertiesLocation : propertiesLocation + PROPERTIES_FILENAME;
        }
    
    }
    

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

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

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

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

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

    EDIT

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

    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.core.io.ClassPathResource;
    import org.springframework.core.io.PathResource;
    import org.springframework.core.io.Resource;
    
    import java.io.IOException;
    import java.util.Map;
    import java.util.Properties;
    
    import static java.util.Arrays.stream;
    import static java.util.stream.Collectors.toMap;
    
    @Configuration
    class PropertiesConfig {
    
        private final static Logger LOG = LoggerFactory.getLogger(PropertiesConfig.class);
        private final static String[] PROPERTIES_FILENAMES = {"job1.properties", "job2.properties", "job3.properties"};
    
        @Value("${properties.location:}")
        private String propertiesLocation;
    
        @Bean
        Map<String, Properties> myProperties() {
            return stream(PROPERTIES_FILENAMES)
                    .collect(toMap(filename -> filename, this::loadProperties));
        }
    
        private Properties loadProperties(final String filename) {
            final Resource[] possiblePropertiesResources = {
                    new ClassPathResource(filename),
                    new PathResource("config/" + filename),
                    new PathResource(filename),
                    new PathResource(getCustomPath(filename))
            };
            final Resource resource = stream(possiblePropertiesResources)
                    .filter(Resource::exists)
                    .reduce((previous, current) -> current)
                    .get();
            final Properties properties = new Properties();
    
            try {
                properties.load(resource.getInputStream());
            } catch(final IOException exception) {
                throw new RuntimeException(exception);
            }
    
            LOG.info("Using {} as user resource", resource);
    
            return properties;
        }
    
        private String getCustomPath(final String filename) {
            return propertiesLocation.endsWith(".properties") ? propertiesLocation : propertiesLocation + filename;
        }
    
    }
    

    What's the best way to send a signal to all members of a process group?

    This script also work:

    #/bin/sh while true do echo "Enter parent process id [type quit for exit]" read ppid if [ $ppid -eq "quit" -o $ppid -eq "QUIT" ];then exit 0 fi for i in `ps -ef| awk '$3 == '$ppid' { print $2 }'` do echo killing $i kill $i done done

    What does 'Unsupported major.minor version 52.0' mean, and how do I fix it?

    Actually you have a code compiled targeting a higher JDK (JDK 1.8 in your case) but at runtime you are supplying a lower JRE(JRE 7 or below).

    you can fix this problem by adding target parameter while compilation
    e.g. if your runtime target is 1.7, you should use 1.7 or below

    javac -target 1.7 *.java
    

    if you are using eclipse, you can sent this parameter at Window -> Preferences -> Java -> Compiler -> set "Compiler compliance level" = choose your runtime jre version or lower.

    state provider and route provider in angularJS

    You shouldn't use both ngRoute and UI-router. Here's a sample code for UI-router:

    _x000D_
    _x000D_
    repoApp.config(function($stateProvider, $urlRouterProvider) {_x000D_
      _x000D_
      $stateProvider_x000D_
        .state('state1', {_x000D_
          url: "/state1",_x000D_
          templateUrl: "partials/state1.html",_x000D_
          controller: 'YourCtrl'_x000D_
        })_x000D_
        _x000D_
        .state('state2', {_x000D_
          url: "/state2",_x000D_
          templateUrl: "partials/state2.html",_x000D_
          controller: 'YourOtherCtrl'_x000D_
        });_x000D_
        $urlRouterProvider.otherwise("/state1");_x000D_
    });_x000D_
    //etc.
    _x000D_
    _x000D_
    _x000D_

    You can find a great answer on the difference between these two in this thread: What is the difference between angular-route and angular-ui-router?

    You can also consult UI-Router's docs here: https://github.com/angular-ui/ui-router

    Frontend tool to manage H2 database

    There's a shell client built in too which is handy.

    java -cp h2*.jar org.h2.tools.Shell
    

    http://opensource-soa.blogspot.com.au/2009/03/how-to-use-h2-shell.html

    $ java -cp h2.jar org.h2.tools.Shell -help
    Interactive command line tool to access a database using JDBC.
    Usage: java org.h2.tools.Shell <options>
    Options are case sensitive. Supported options are:
    [-help] or [-?]        Print the list of options
    [-url "<url>"]         The database URL (jdbc:h2:...)
    [-user <user>]         The user name
    [-password <pwd>]      The password
    [-driver <class>]      The JDBC driver class to use (not required in most cases)
    [-sql "<statements>"]  Execute the SQL statements and exit
    [-properties "<dir>"]  Load the server properties from this directory
    If special characters don't work as expected, you may need to use
     -Dfile.encoding=UTF-8 (Mac OS X) or CP850 (Windows).
    See also http://h2database.com/javadoc/org/h2/tools/Shell.html
    

    How to fix curl: (60) SSL certificate: Invalid certificate chain

    After updating to OS X 10.9.2, I started having invalid SSL certificate issues with Homebrew, Textmate, RVM, and Github.

    When I initiate a brew update, I was getting the following error:

    fatal: unable to access 'https://github.com/Homebrew/homebrew/': SSL certificate problem: Invalid certificate chain
    Error: Failure while executing: git pull -q origin refs/heads/master:refs/remotes/origin/master
    

    I was able to alleviate some of the issue by just disabling the SSL verification in Git. From the console (a.k.a. shell or terminal):

    git config --global http.sslVerify false
    

    I am leary to recommend this because it defeats the purpose of SSL, but it is the only advice I've found that works in a pinch.

    I tried rvm osx-ssl-certs update all which stated Already are up to date.

    In Safari, I visited https://github.com and attempted to set the certificate manually, but Safari did not present the options to trust the certificate.

    Ultimately, I had to Reset Safari (Safari->Reset Safari... menu). Then afterward visit github.com and select the certificate, and "Always trust" This feels wrong and deletes the history and stored passwords, but it resolved my SSL verification issues. A bittersweet victory.

    The ternary (conditional) operator in C

    Some of the other answers given are great. But I am surprised that no one mentioned that it can be used to help enforce const correctness in a compact way.

    Something like this:

    const int n = (x != 0) ? 10 : 20;
    

    so basically n is a const whose initial value is dependent on a condition statement. The easiest alternative is to make n not a const, this would allow an ordinary if to initialize it. But if you want it to be const, it cannot be done with an ordinary if. The best substitute you could make would be to use a helper function like this:

    int f(int x) {
        if(x != 0) { return 10; } else { return 20; }
    }
    
    const int n = f(x);
    

    but the ternary if version is far more compact and arguably more readable.

    Why is 1/1/1970 the "epoch time"?

    Epoch reference date

    An epoch reference date is a point on the timeline from which we count time. Moments before that point are counted with a negative number, moments after are counted with a positive number.

    Many epochs in use

    Why is 1 January 1970 00:00:00 considered the epoch time?

    No, not the epoch, an epoch. There are many epochs in use.

    This choice of epoch is arbitrary.

    Major computers systems and libraries use any of at least a couple dozen various epochs. One of the most popular epochs is commonly known as Unix Time, using the 1970 UTC moment you mentioned.

    While popular, Unix Time’s 1970 may not be the most common. Also in the running for most common would be January 0, 1900 for countless Microsoft Excel & Lotus 1-2-3 spreadsheets, or January 1, 2001 used by Apple’s Cocoa framework in over a billion iOS/macOS machines worldwide in countless apps. Or perhaps January 6, 1980 used by GPS devices?

    Many granularities

    Different systems use different granularity in counting time.

    Even the so-called “Unix Time” varies, with some systems counting whole seconds and some counting milliseconds. Many database such as Postgres use microseconds. Some, such as the modern java.time framework in Java 8 and later, use nanoseconds. Some use still other granularities.

    ISO 8601

    Because there is so much variance in the use of an epoch reference and in the granularities, it is generally best to avoid communicating moments as a count-from-epoch. Between the ambiguity of epoch & granularity, plus the inability of humans to perceive meaningful values (and therefore miss buggy values), use plain text instead of numbers.

    The ISO 8601 standard provides an extensive set of practical well-designed formats for expressing date-time values as text. These formats are easy to parse by machine as well as easy to read by humans across cultures.

    These include:

    How to convert milliseconds into a readable date?

    This is a solution. Later you can split by ":" and take the values of the array

     /**
     * Converts milliseconds to human readeable language separated by ":"
     * Example: 190980000 --> 2:05:3 --> 2days 5hours 3min
     */
    function dhm(t){
        var cd = 24 * 60 * 60 * 1000,
            ch = 60 * 60 * 1000,
            d = Math.floor(t / cd),
            h = '0' + Math.floor( (t - d * cd) / ch),
            m = '0' + Math.round( (t - d * cd - h * ch) / 60000);
        return [d, h.substr(-2), m.substr(-2)].join(':');
    }
    
    //Example
    var delay = 190980000;                   
    var fullTime = dhm(delay);
    console.log(fullTime);
    

    String was not recognized as a valid DateTime " format dd/MM/yyyy"

    Change Manually :

    string s = date.Substring(3, 2) +"/" + date.Substring(0, 2) + "/" + date.Substring(6, 4);
    

    From 11/22/2015 it will be converted in 22/11/2015

    How do I pass command line arguments to a Node.js program?

    I extended the getArgs function just to get also commands, as well as flags (-f, --anotherflag) and named args (--data=blablabla):

    1. The module
    /**
     * @module getArgs.js
     * get command line arguments (commands, named arguments, flags)
     *
     * @see https://stackoverflow.com/a/54098693/1786393
     *
     * @return {Object}
     *
     */
    function getArgs () {
      const commands = []
      const args = {}
      process.argv
        .slice(2, process.argv.length)
        .forEach( arg => {
          // long arg
          if (arg.slice(0,2) === '--') {
            const longArg = arg.split('=')
            const longArgFlag = longArg[0].slice(2,longArg[0].length)
            const longArgValue = longArg.length > 1 ? longArg[1] : true
            args[longArgFlag] = longArgValue
         }
         // flags
          else if (arg[0] === '-') {
            const flags = arg.slice(1,arg.length).split('')
            flags.forEach(flag => {
              args[flag] = true
            })
          }
         else {
          // commands
          commands.push(arg)
         } 
        })
      return { args, commands }
    }
    
    
    // test
    if (require.main === module) {
      // node getArgs test --dir=examples/getUserName --start=getUserName.askName
      console.log( getArgs() )
    }
    
    module.exports = { getArgs }
    
    
    1. Usage example:
    $ node lib/getArgs test --dir=examples/getUserName --start=getUserName.askName
    {
      args: { dir: 'examples/getUserName', start: 'getUserName.askName' },
      commands: [ 'test' ]
    }
    
    $ node lib/getArgs --dir=examples/getUserName --start=getUserName.askName test tutorial
    {
      args: { dir: 'examples/getUserName', start: 'getUserName.askName' },
      commands: [ 'test', 'tutorial' ]
    }
    
    

    function is not defined error in Python

    In python functions aren't accessible magically from everywhere (like they are in say, php). They have to be declared first. So this will work:

    def pyth_test (x1, x2):
        print x1 + x2
    
    pyth_test(1, 2)
    

    But this won't:

    pyth_test(1, 2)
    
    def pyth_test (x1, x2):
        print x1 + x2
    

    image size (drawable-hdpi/ldpi/mdpi/xhdpi)

    you can use Android Asset in android studio , and android Asset will give you image in this size as a drawable and the application will automatically use the size based on screen of device or emulate

    Why can I not create a wheel in python?

    Install the wheel package first:

    pip install wheel
    

    The documentation isn't overly clear on this, but "the wheel project provides a bdist_wheel command for setuptools" actually means "the wheel package...".

    Fastest way(s) to move the cursor on a terminal command line?

    Use Meta-b / Meta-f to move backward/forward by a word respectively.

    In OSX, Meta translates as ESC, which sucks.

    But alternatively, you can open terminal preferences -> settings -> profile -> keyboard and check "use option as meta key"

    How to find the size of a table in SQL?

    I know that in SQL 2012 (may work in other versions) you can do the following:

    1. Right click on the database name in the Object Explorer.
    2. Select Reports > Standard Reports > Disk Usage by Top Tables.

    That will give you a list of the top 1000 tables and then you can order it by data size etc.

    Styling every 3rd item of a list using CSS?

    :nth-child is the answer you are looking for.

    Redirect from a view to another view

    It's because your statement does not produce output.

    Besides all the warnings of Darin and lazy (they are right); the question still offerst something to learn.

    If you want to execute methods that don't directly produce output, you do:

    @{ Response.Redirect("~/Account/LogIn?returnUrl=Products");}
    

    This is also true for rendering partials like:

    @{ Html.RenderPartial("_MyPartial"); }
    

    find first sequence item that matches a criterion

    If you don't have any other indexes or sorted information for your objects, then you will have to iterate until such an object is found:

    next(obj for obj in objs if obj.val == 5)
    

    This is however faster than a complete list comprehension. Compare these two:

    [i for i in xrange(100000) if i == 1000][0]
    
    next(i for i in xrange(100000) if i == 1000)
    

    The first one needs 5.75ms, the second one 58.3µs (100 times faster because the loop 100 times shorter).

    Python "expected an indented block"

    The body of the loop is indented: indentation is Python’s way of grouping statements. At the interactive prompt, you have to type a tab or space(s) for each indented line. In practice you will prepare more complicated input for Python with a text editor; all decent text editors have an auto-indent facility. When a compound statement is entered interactively, it must be followed by a blank line to indicate completion (since the parser cannot guess when you have typed the last line). Note that each line within a basic block must be indented by the same amount.

    src: ##

    ##https://docs.python.org/3/tutorial/introduction.html#using-python-as-a-calculator

    React Native TextInput that only accepts numeric characters

    A kind reminder to those who encountered the problem that "onChangeText" cannot change the TextInput value as expected on iOS: that is actually a bug in ReactNative and had been fixed in version 0.57.1. Refer to: https://github.com/facebook/react-native/issues/18874

    What are the minimum margins most printers can handle?

    The margins vary depending on the printer. In Windows GDI, you call the following functions to get the built-in margins, the "no-print zone":

    GetDeviceCaps(hdc, PHYSICALWIDTH);
    GetDeviceCaps(hdc, PHYSICALHEIGHT);
    GetDeviceCaps(hdc, PHYSICALOFFSETX);
    GetDeviceCaps(hdc, PHYSICALOFFSETY);
    

    Printing right to the edge is called a "bleed" in the printing industry. The only laser printer I ever knew to print right to the edge was the Xerox 9700: 120 ppm, $500K in 1980.

    How to move columns in a MySQL table?

    I had to run this for a column introduced in the later stages of a product, on 10+ tables. So wrote this quick untidy script to generate the alter command for all 'relevant' tables.

    SET @NeighboringColumn = '<YOUR COLUMN SHOULD COME AFTER THIS COLUMN>';
    
    SELECT CONCAT("ALTER TABLE `",t.TABLE_NAME,"` CHANGE COLUMN `",COLUMN_NAME,"` 
    `",COLUMN_NAME,"` ", c.DATA_TYPE, CASE WHEN c.CHARACTER_MAXIMUM_LENGTH IS NOT 
    NULL THEN CONCAT("(", c.CHARACTER_MAXIMUM_LENGTH, ")") ELSE "" END ,"  AFTER 
    `",@NeighboringColumn,"`;")
    FROM information_schema.COLUMNS c, information_schema.TABLES t
    WHERE c.TABLE_SCHEMA = '<YOUR SCHEMA NAME>'
    AND c.COLUMN_NAME = '<COLUMN TO MOVE>'
    AND c.TABLE_SCHEMA = t.TABLE_SCHEMA
    AND c.TABLE_NAME = t.TABLE_NAME
    AND t.TABLE_TYPE = 'BASE TABLE'
    AND @NeighboringColumn IN (SELECT COLUMN_NAME 
        FROM information_schema.COLUMNS c2 
        WHERE c2.TABLE_NAME = t.TABLE_NAME);
    

    SSIS Text was truncated with status value 4

    I suspect the or one or more characters had no match in the target code page part of the error.

    If you remove the rows with values in that column, does it load? Can you identify, in other words, the rows which cause the package to fail? It could be the data is too long, or it could be that there's some funky character in there SQL Server doesn't like.

    html table cell width for different rows

    As far as i know that is impossible and that makes sense since what you are trying to do is against the idea of tabular data presentation. You could however put the data in multiple tables and remove any padding and margins in between them to achieve the same result, at least visibly. Something along the lines of:

    _x000D_
    _x000D_
    <html>_x000D_
    _x000D_
    <head>_x000D_
      <style type="text/css">_x000D_
        .mytable {_x000D_
          border-collapse: collapse;_x000D_
          width: 100%;_x000D_
          background-color: white;_x000D_
        }_x000D_
        .mytable-head {_x000D_
          border: 1px solid black;_x000D_
          margin-bottom: 0;_x000D_
          padding-bottom: 0;_x000D_
        }_x000D_
        .mytable-head td {_x000D_
          border: 1px solid black;_x000D_
        }_x000D_
        .mytable-body {_x000D_
          border: 1px solid black;_x000D_
          border-top: 0;_x000D_
          margin-top: 0;_x000D_
          padding-top: 0;_x000D_
          margin-bottom: 0;_x000D_
          padding-bottom: 0;_x000D_
        }_x000D_
        .mytable-body td {_x000D_
          border: 1px solid black;_x000D_
          border-top: 0;_x000D_
        }_x000D_
        .mytable-footer {_x000D_
          border: 1px solid black;_x000D_
          border-top: 0;_x000D_
          margin-top: 0;_x000D_
          padding-top: 0;_x000D_
        }_x000D_
        .mytable-footer td {_x000D_
          border: 1px solid black;_x000D_
          border-top: 0;_x000D_
        }_x000D_
      </style>_x000D_
    </head>_x000D_
    _x000D_
    <body>_x000D_
      <table class="mytable mytable-head">_x000D_
        <tr>_x000D_
          <td width="25%">25</td>_x000D_
          <td width="50%">50</td>_x000D_
          <td width="25%">25</td>_x000D_
        </tr>_x000D_
      </table>_x000D_
      <table class="mytable mytable-body">_x000D_
        <tr>_x000D_
          <td width="50%">50</td>_x000D_
          <td width="30%">30</td>_x000D_
          <td width="20%">20</td>_x000D_
        </tr>_x000D_
      </table>_x000D_
      <table class="mytable mytable-body">_x000D_
        <tr>_x000D_
          <td width="16%">16</td>_x000D_
          <td width="68%">68</td>_x000D_
          <td width="16%">16</td>_x000D_
        </tr>_x000D_
      </table>_x000D_
      <table class="mytable mytable-footer">_x000D_
        <tr>_x000D_
          <td width="20%">20</td>_x000D_
          <td width="30%">30</td>_x000D_
          <td width="50%">50</td>_x000D_
        </tr>_x000D_
      </table>_x000D_
    </body>_x000D_
    _x000D_
    </html>
    _x000D_
    _x000D_
    _x000D_

    JSFIDDLE

    I don't know your requirements but i'm sure there's a more elegant solution.

    How to delete a localStorage item when the browser window/tab is closed?

    why not used sessionStorage?

    "The sessionStorage object is equal to the localStorage object, except that it stores the data for only one session. The data is deleted when the user closes the browser window."

    http://www.w3schools.com/html/html5_webstorage.asp

    Android Service needs to run always (Never pause or stop)

    I had overcome this issue, and my sample code is as follows.

    Add the below line in your Main Activity, here BackGroundClass is the service class.You can create this class in New -> JavaClass (In this class, add the process (tasks) in which you needs to occur at background). For Convenience, first denote them with notification ringtone as background process.

     startService(new Intent(this, BackGroundClass .class));
    

    In the BackGroundClass, just include my codings and you may see the result.

    import android.app.Service;
    import android.content.Intent;
    import android.media.MediaPlayer;
    import android.os.IBinder;
    import android.provider.Settings;
    import android.support.annotation.Nullable;
    import android.widget.Toast;
    
    public class BackgroundService  extends Service {
        private MediaPlayer player;
        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
    @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
         player = MediaPlayer.create(this,Settings.System.DEFAULT_RINGTONE_URI);
            player.setLooping(true);
             player.start();
            return START_STICKY;
        }
     @Override
        public void onDestroy() {
            super.onDestroy();
             player.stop();
        }
    }
    

    And in AndroidManifest.xml, try to add this.

    <service android:name=".BackgroundService"/>
    

    Run the program, just open the application, you may find the notification alert at the background. Even, you may exit the application but still you might have hear the ringtone alert unless and until if you switched off the application or Uninstall the application. This denotes that the notification alert is at the background process. Like this you may add some process for background.

    Kind Attention: Please, Don't verify with TOAST as it will run only once even though it was at background process.

    Hope it will helps...!!

    Get the value of input text when enter key pressed

    Something like this (not tested, but should work)

    Pass this as parameter in Html:

    <input type="text" placeholder="some text" class="search" onkeydown="search(this)"/>
    

    And alert the value of the parameter passed into the search function:

    function search(e){
      alert(e.value);
    }
    

    Concatenating Files And Insert New Line In Between Files

    If you have few enough files that you can list each one, then you can use process substitution in Bash, inserting a newline between each pair of files:

    cat File1.txt <(echo) File2.txt <(echo) File3.txt > finalfile.txt
    

    Sync data between Android App and webserver

    @Grantismo provides a great explanation on the overall. If you wish to know who people are actually doing this things i suggest you to take a look at how google did for the Google IO App of 2014 (it's always worth taking a deep look at the source code of these apps that they release. There's a lot to learn from there).

    Here's a blog post about it: http://android-developers.blogspot.com.br/2014/09/conference-data-sync-gcm-google-io.html

    Essentially, on the application side: GCM for signalling, Sync Adapter for data fetching and talking properly with Content Provider that will make things persistent (yeah, it isolates the DB from direct access from other parts of the app).

    Also, if you wish to take a look at the 2015's code: https://github.com/google/iosched

    Python OpenCV2 (cv2) wrapper to get image size?

    import cv2
    img=cv2.imread('my_test.jpg')
    img_info = img.shape
    print("Image height :",img_info[0])
    print("Image Width :", img_info[1])
    print("Image channels :", img_info[2])
    

    Ouput :- enter image description here

    My_test.jpg link ---> https://i.pinimg.com/originals/8b/ca/f5/8bcaf5e60433070b3210431e9d2a9cd9.jpg

    How to check that a string is parseable to a double?

    Apache, as usual, has a good answer from Apache Commons-Lang in the form of NumberUtils.isCreatable(String).

    Handles nulls, no try/catch block required.

    Generating a UUID in Postgres for Insert statement?

    ALTER TABLE table_name ALTER COLUMN id SET DEFAULT uuid_in((md5((random())::text))::cstring);
    

    After reading @ZuzEL's answer, i used the above code as the default value of the column id and it's working fine.

    How to use vim in the terminal?

    Get started quickly

    You simply type vim into the terminal to open it and start a new file.

    You can pass a filename as an option and it will open that file, e.g. vim main.c. You can open multiple files by passing multiple file arguments.

    Vim has different modes, unlike most editors you have probably used. You begin in NORMAL mode, which is where you will spend most of your time once you become familiar with vim.

    To return to NORMAL mode after changing to a different mode, press Esc. It's a good idea to map your Caps Lock key to Esc, as it's closer and nobody really uses the Caps Lock key.

    The first mode to try is INSERT mode, which is entered with a for append after cursor, or i for insert before cursor.

    To enter VISUAL mode, where you can select text, use v. There are many other variants of this mode, which you will discover as you learn more about vim.

    To save your file, ensure you're in NORMAL mode and then enter the command :w. When you press :, you will see your command appear in the bottom status bar. To save and exit, use :x. To quit without saving, use :q. If you had made a change you wanted to discard, use :q!.

    Configure vim to your liking

    You can edit your ~/.vimrc file to configure vim to your liking. It's best to look at a few first (here's mine) and then decide which options suits your style.

    This is how mine looks:

    vim screenshot

    To get the file explorer on the left, use NERDTree. For the status bar, use vim-airline. Finally, the color scheme is solarized.

    Further learning

    You can use man vim for some help inside the terminal. Alternatively, run vimtutor which is a good hands-on starting point.

    It's a good idea to print out a Vim Cheatsheet and keep it in front of you while you're learning vim.

    Good luck!

    subtract two times in python

    I had similar situation as you and I ended up with using external library called arrow.

    Here is what it looks like:

    >>> import arrow
    >>> enter = arrow.get('12:30:45', 'HH:mm:ss')
    >>> exit = arrow.now()
    >>> duration = exit - enter
    >>> duration
    datetime.timedelta(736225, 14377, 757451)
    

    Unsetting array values in a foreach loop

    Try that:

    foreach ($images[1] as $key => &$image) {
        if (yourConditionGoesHere) {
            unset($images[1][$key])
        }
    }
    unset($image); // detach reference after loop  
    

    Normally, foreach operates on a copy of your array so any changes you make, are made to that copy and don't affect the actual array.

    So you need to unset the values via $images[$key];

    The reference on &$image prevents the loop from creating a copy of the array which would waste memory.

    Take the content of a list and append it to another list

    Using the map() and reduce() built-in functions

    def file_to_list(file):
         #stuff to parse file to a list
         return list
    
    files = [...list of files...]
    
    L = map(file_to_list, files)
    
    flat_L = reduce(lambda x,y:x+y, L)
    

    Minimal "for looping" and elegant coding pattern :)

    What is the difference between Python's list methods append and extend?

    extend(L) extends the list by appending all the items in the given list L.

    >>> a
    [1, 2, 3]
    a.extend([4])  #is eqivalent of a[len(a):] = [4]
    >>> a
    [1, 2, 3, 4]
    a = [1, 2, 3]
    >>> a
    [1, 2, 3]
    >>> a[len(a):] = [4]
    >>> a
    [1, 2, 3, 4]
    

    Change the name of a key in dictionary

    Method if anyone wants to replace all occurrences of the key in a multi-level dictionary.

    Function checks if the dictionary has a specific key and then iterates over sub-dictionaries and invokes the function recursively:

    def update_keys(old_key,new_key,d):
        if isinstance(d,dict):
            if old_key in d:
                d[new_key] = d[old_key]
                del d[old_key]
            for key in d:
                updateKey(old_key,new_key,d[key])
    
    update_keys('old','new',dictionary)
    

    Android: Access child views from a ListView

    A quick search of the docs for the ListView class has turned up getChildCount() and getChildAt() methods inherited from ViewGroup. Can you iterate through them using these? I'm not sure but it's worth a try.

    Found it here

    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.

    Get first element from a dictionary

    Dictionary<string, Dictionary<string, string>> like = new Dictionary<string, Dictionary<string, string>>();
    Dictionary<string, string> first = like.Values.First();
    

    Zooming MKMapView to fit annotation pins?

    As Abhishek Bedi points out in a comment, For iOS7 forward the best way to do this is:

    //from API docs: 
    //- (void)showAnnotations:(NSArray *)annotations animated:(BOOL)animated NS_AVAILABLE(10_9, 7_0);
    [self.mapView showAnnotations:self.mapView.annotations animated:YES];
    

    For my personal project (prior to iOS7) I simply added a category on the MKMapView class to encapsulate the "visible area" functionality for a very common operation: setting it to be able to see all the currently-loaded annotations on the MKMapView instance (this includes as many pins as you might have placed, as well as the user's location). the result was this:

    .h file

    #import <MapKit/MapKit.h>
    
    @interface MKMapView (Extensions)
    
    -(void)ij_setVisibleRectToFitAllLoadedAnnotationsAnimated:(BOOL)animated;
    -(void)ij_setVisibleRectToFitAnnotations:(NSArray *)annotations animated:(BOOL)animated;
    
    
    @end
    

    .m file

    #import "MKMapView+Extensions.h"
    
    @implementation MKMapView (Extensions)
    
    /**
     *  Changes the currently visible portion of the map to a region that best fits all the currently loadded annotations on the map, and it optionally animates the change.
     *
     *  @param animated is the change should be perfomed with an animation.
     */
    -(void)ij_setVisibleRectToFitAllLoadedAnnotationsAnimated:(BOOL)animated
    {
        MKMapView * mapView = self;
    
        NSArray * annotations = mapView.annotations;
    
        [self ij_setVisibleRectToFitAnnotations:annotations animated:animated];
    
    }
    
    
    /**
     *  Changes the currently visible portion of the map to a region that best fits the provided annotations array, and it optionally animates the change.
        All elements from the array must conform to the <MKAnnotation> protocol in order to fetch the coordinates to compute the visible region of the map.
     *
     *  @param annotations an array of elements conforming to the <MKAnnotation> protocol, holding the locations for which the visible portion of the map will be set.
     *  @param animated    wether or not the change should be perfomed with an animation.
     */
    -(void)ij_setVisibleRectToFitAnnotations:(NSArray *)annotations animated:(BOOL)animated
    {
        MKMapView * mapView = self;
    
        MKMapRect r = MKMapRectNull;
        for (id<MKAnnotation> a in annotations) {
            ZAssert([a conformsToProtocol:@protocol(MKAnnotation)], @"ERROR: All elements of the array MUST conform to the MKAnnotation protocol. Element (%@) did not fulfill this requirement", a);
            MKMapPoint p = MKMapPointForCoordinate(a.coordinate);
            //MKMapRectUnion performs the union between 2 rects, returning a bigger rect containing both (or just one if the other is null). here we do it for rects without a size (points)
            r = MKMapRectUnion(r, MKMapRectMake(p.x, p.y, 0, 0));
        }
    
        [mapView setVisibleMapRect:r animated:animated];
    
    }
    
    @end
    

    As you can see, I've added 2 methods so far: one for setting the visible region of the map to the one that fits all currently-loaded annotations on the MKMapView instance, and another method to set it to any array of objects. So to set the mapView's visible region the code would then be as simple as:

       //the mapView instance  
        [self.mapView ij_setVisibleRectToFitAllLoadedAnnotationsAnimated:animated]; 
    

    I hope it helps =)

    iOS 8 removed "minimal-ui" viewport property, are there other "soft fullscreen" solutions?

    Just say goodbye to minimal-ui (for now)

    It's true, minimal-ui could be both useful and harmful, and I suppose the trade-off now has another balance, in favor of newer, bigger iPhones.

    I've been dealing with the issue while working with my js framework for HTML5 apps. After many attempted solutions, each with their drawbacks, I surrendered to considering that space lost on iPhones previous than 6. Given the situation, I think that the only solid and predictable behavior is a pre-determined one.

    In short, I ended up preventing any form of minimal-ui, so at least my screen height is always the same and you always know what actual space you have for your app.

    With the help of time, enough users will have more room.


    EDIT

    How I do it

    This is a little simplified, for demo purpose, but should work for you. Assuming you have a main container

    html, body, #main {
      height: 100%;
      width: 100%;
      overflow: hidden;
    }
    .view {
      width: 100%;
      height: 100%;
      overflow: scroll;
    }
    

    Then:

    1. then with js, I set #main's height to the window's available height. This also helps dealing with other scrolling bugs found in both iOS and Android. It also means that you need to deal on how to update it, just note that;

    2. I block over-scrolling when reaching the boundaries of the scroll. This one is a bit more deep in my code, but I think you can as well follow the principle of this answer for basic functionality. I think it could flickr a little, but will do the job.


    See the demo (on a iPhone)

    As a sidenote: this app too is bookmarkable, as it uses an internal routing to hashed addresses, but I also added a prompt iOS users to add to home. I feel this way helps loyalty and returning visitors (and so the lost space is back).

    How can I iterate through a string and also know the index (current position)?

    You can use standard STL function distance as mentioned before

    index = std::distance(s.begin(), it);
    

    Also, you can access string and some other containers with the c-like interface:

    for (i=0;i<string1.length();i++) string1[i];
    

    How do I reference a local image in React?

    import React from "react";   
    import image from './img/one.jpg';
    
    class Image extends React.Component{
      render(){
        return(
          <img className='profile-image' alt='icon' src={image}/>
       );
      }
    }
    

    export default Image

    Eclipse Indigo - Cannot install Android ADT Plugin

    Ensure you have the option "Contact all update sites during install to find required software". This option is located in the lower left corner on the first screen after choosing Help/Add New Software. This is unchecked by default. This WILL FIX the issue if it was unchecked.

    The plugin will install in 3.7 32bit and 64bit.

    Algorithm for solving Sudoku

    Here is a much faster solution based on hari's answer. The basic difference is that we keep a set of possible values for cells that don't have a value assigned. So when we try a new value, we only try valid values and we also propagate what this choice means for the rest of the sudoku. In the propagation step, we remove from the set of valid values for each cell the values that already appear in the row, column, or the same block. If only one number is left in the set, we know that the position (cell) has to have that value.

    This method is known as forward checking and look ahead (http://ktiml.mff.cuni.cz/~bartak/constraints/propagation.html).

    The implementation below needs one iteration (calls of solve) while hari's implementation needs 487. Of course my code is a bit longer. The propagate method is also not optimal.

    import sys
    from copy import deepcopy
    
    def output(a):
        sys.stdout.write(str(a))
    
    N = 9
    
    field = [[5,1,7,6,0,0,0,3,4],
             [2,8,9,0,0,4,0,0,0],
             [3,4,6,2,0,5,0,9,0],
             [6,0,2,0,0,0,0,1,0],
             [0,3,8,0,0,6,0,4,7],
             [0,0,0,0,0,0,0,0,0],
             [0,9,0,0,0,0,0,7,8],
             [7,0,3,4,0,0,5,6,0],
             [0,0,0,0,0,0,0,0,0]]
    
    def print_field(field):
        if not field:
            output("No solution")
            return
        for i in range(N):
            for j in range(N):
                cell = field[i][j]
                if cell == 0 or isinstance(cell, set):
                    output('.')
                else:
                    output(cell)
                if (j + 1) % 3 == 0 and j < 8:
                    output(' |')
    
                if j != 8:
                    output(' ')
            output('\n')
            if (i + 1) % 3 == 0 and i < 8:
                output("- - - + - - - + - - -\n")
    
    def read(field):
        """ Read field into state (replace 0 with set of possible values) """
    
        state = deepcopy(field)
        for i in range(N):
            for j in range(N):
                cell = state[i][j]
                if cell == 0:
                    state[i][j] = set(range(1,10))
    
        return state
    
    state = read(field)
    
    
    def done(state):
        """ Are we done? """
    
        for row in state:
            for cell in row:
                if isinstance(cell, set):
                    return False
        return True
    
    
    def propagate_step(state):
        """
        Propagate one step.
    
        @return:  A two-tuple that says whether the configuration
                  is solvable and whether the propagation changed
                  the state.
        """
    
                new_units = False
    
        # propagate row rule
        for i in range(N):
            row = state[i]
            values = set([x for x in row if not isinstance(x, set)])
            for j in range(N):
                if isinstance(state[i][j], set):
                    state[i][j] -= values
                    if len(state[i][j]) == 1:
                        val = state[i][j].pop()
                        state[i][j] = val
                        values.add(val)
                        new_units = True
                    elif len(state[i][j]) == 0:
                        return False, None
    
        # propagate column rule
        for j in range(N):
            column = [state[x][j] for x in range(N)]
            values = set([x for x in column if not isinstance(x, set)])
            for i in range(N):
                if isinstance(state[i][j], set):
                    state[i][j] -= values
                    if len(state[i][j]) == 1:
                        val = state[i][j].pop()
                        state[i][j] = val
                        values.add(val)
                        new_units = True
                    elif len(state[i][j]) == 0:
                        return False, None
    
        # propagate cell rule
        for x in range(3):
            for y in range(3):
                values = set()
                for i in range(3 * x, 3 * x + 3):
                    for j in range(3 * y, 3 * y + 3):
                        cell = state[i][j]
                        if not isinstance(cell, set):
                            values.add(cell)
                for i in range(3 * x, 3 * x + 3):
                    for j in range(3 * y, 3 * y + 3):
                        if isinstance(state[i][j], set):
                            state[i][j] -= values
                            if len(state[i][j]) == 1:
                                val = state[i][j].pop()
                                state[i][j] = val
                                values.add(val)
                                new_units = True
                            elif len(state[i][j]) == 0:
                                return False, None
    
        return True, new_units
    
    def propagate(state):
        """ Propagate until we reach a fixpoint """
        while True:
            solvable, new_unit = propagate_step(state)
            if not solvable:
                return False
            if not new_unit:
                return True
    
    
    def solve(state):
        """ Solve sudoku """
    
        solvable = propagate(state)
    
        if not solvable:
            return None
    
        if done(state):
            return state
    
        for i in range(N):
            for j in range(N):
                cell = state[i][j]
                if isinstance(cell, set):
                    for value in cell:
                        new_state = deepcopy(state)
                        new_state[i][j] = value
                        solved = solve(new_state)
                        if solved is not None:
                            return solved
                    return None
    
    print_field(solve(state))
    

    Clear form fields with jQuery

    the code I see here and on related SO questions seems incomplete.

    Resetting a form means setting the original values from the HTML, so I put this together for a little project I was doing based on the above code:

                $(':input', this)
                    .not(':button, :submit, :reset, :hidden')
                    .each(function(i,e) {
                        $(e).val($(e).attr('value') || '')
                            .prop('checked',  false)
                            .prop('selected', false)
                    })
    
                $('option[selected]', this).prop('selected', true)
                $('input[checked]',   this).prop('checked',  true)
                $('textarea',         this).each(function(i,e) { $(e).val($(e).html()) })
    

    Please let me know if I'm missing anything or anything can be improved.

    The Android emulator is not starting, showing "invalid command-line parameter"

    This don't work since Andoid SDK R12 update. I think is because SDK don't find the Java SDK Path. You can solve that by adding the Java SDK Path in your PATH environment variable.

    The Import android.support.v7 cannot be resolved

    I fixed it adding these lines in the build.grandle (App Module)

    dependencies {
       compile fileTree(dir: 'libs', include: ['*.jar']) //it was there
       compile "com.android.support:support-v4:21.0.+" //Added
       compile "com.android.support:appcompat-v7:21.0.+" //Added
    }
    

    iPad Multitasking support requires these orientations

    Unchecked all Device orientation and checked only "Requires full screen". Its working properly

    Why is the Java main method static?

    static - When the JVM makes a call to the main method there is no object that exists for the class being called therefore it has to have static method to allow invocation from class.

    How to draw a circle with text in the middle?

    Of course, you have to use to tags to do that. One to create the circle and other for the text.

    Here some code may help you

    #circle {
        background: #f00;
        width: 200px;
        height: 200px;
        border-radius: 50%;
        color:black;
    
    }
    .innerTEXT{
        position:absolute;
        top:80px;
        left:60px;
    }
    
    <div id="circle">
        <span class="innerTEXT"> Here a text</span>
    </div>
    

    Live example here http://jsbin.com/apumik/1/edit

    Update

    Here less smaller with a few changes

    http://jsbin.com/apumik/3/edit

    Python: Figure out local timezone

    In Python 3.x, local timezone can be figured out like this:

    import datetime
    LOCAL_TIMEZONE = datetime.datetime.now(datetime.timezone.utc).astimezone().tzinfo
    

    It's a tricky use of datetime's code .

    For python >= 3.6, you'll need

    import datetime
    LOCAL_TIMEZONE = datetime.datetime.now(datetime.timezone(datetime.timedelta(0))).astimezone().tzinfo
    

    PHP convert date format dd/mm/yyyy => yyyy-mm-dd

    I can see great answers, so there's no need to repeat here, so I'd like to offer some advice:

    I would recommend using a Unix Timestamp integer instead of a human-readable date format to handle time internally, then use PHP's date() function to convert the timestamp value into a human-readable date format for user display. Here's a crude example of how it should be done:

    // Get unix timestamp in seconds
    $current_time = date();
    
    // Or if you need millisecond precision
    
    // Get unix timestamp in milliseconds
    $current_time = microtime(true);
    

    Then use $current_time as needed in your app (store, add or subtract, etc), then when you need to display the date value it to your users, you can use date() to specify your desired date format:

    // Display a human-readable date format
    echo date('d-m-Y', $current_time);
    

    This way you'll avoid much headache dealing with date formats, conversions and timezones, as your dates will be in a standardized format (Unix Timestamp) that is compact, timezone-independent (always in UTC) and widely supported in programming languages and databases.

    Show datalist labels but submit the actual value

    Note that datalist is not the same as a select. It allows users to enter a custom value that is not in the list, and it would be impossible to fetch an alternate value for such input without defining it first.

    Possible ways to handle user input are to submit the entered value as is, submit a blank value, or prevent submitting. This answer handles only the first two options.

    If you want to disallow user input entirely, maybe select would be a better choice.


    To show only the text value of the option in the dropdown, we use the inner text for it and leave out the value attribute. The actual value that we want to send along is stored in a custom data-value attribute:

    To submit this data-value we have to use an <input type="hidden">. In this case we leave out the name="answer" on the regular input and move it to the hidden copy.

    <input list="suggestionList" id="answerInput">
    <datalist id="suggestionList">
        <option data-value="42">The answer</option>
    </datalist>
    <input type="hidden" name="answer" id="answerInput-hidden">
    

    This way, when the text in the original input changes we can use javascript to check if the text also present in the datalist and fetch its data-value. That value is inserted into the hidden input and submitted.

    document.querySelector('input[list]').addEventListener('input', function(e) {
        var input = e.target,
            list = input.getAttribute('list'),
            options = document.querySelectorAll('#' + list + ' option'),
            hiddenInput = document.getElementById(input.getAttribute('id') + '-hidden'),
            inputValue = input.value;
    
        hiddenInput.value = inputValue;
    
        for(var i = 0; i < options.length; i++) {
            var option = options[i];
    
            if(option.innerText === inputValue) {
                hiddenInput.value = option.getAttribute('data-value');
                break;
            }
        }
    });
    

    The id answer and answer-hidden on the regular and hidden input are needed for the script to know which input belongs to which hidden version. This way it's possible to have multiple inputs on the same page with one or more datalists providing suggestions.

    Any user input is submitted as is. To submit an empty value when the user input is not present in the datalist, change hiddenInput.value = inputValue to hiddenInput.value = ""


    Working jsFiddle examples: plain javascript and jQuery

    Make page to tell browser not to cache/preserve input values

    Another approach would be to reset the form using JavaScript right after the form in the HTML:

    <form id="myForm">
      <input type="text" value="" name="myTextInput" />
    </form>
    
    <script type="text/javascript">
      document.getElementById("myForm").reset();
    </script>
    

    What is the difference between background, backgroundTint, backgroundTintMode attributes in android layout xml?

    I won't stress much on the difference as it is already covered, but notice the below:

    • android:backgroundTint android:backgroundTintMode are only available at API 21
    • If you have a widget that has a png/vector drawable background set by android:background, and you want to change its default color, then you can use android:backgroundTint to add a shade to it.

    example

    <Button
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:background="@android:drawable/ic_dialog_email" />
    

    enter image description here

    <Button
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:background="@android:drawable/ic_dialog_email"
        android:backgroundTint="@color/colorAccent" />
    

    enter image description here

    Another example

    If you try to change the accent color of the FloatingActionButton using android:background you won't notice a change, that is because it's already utilizes app:srcCompat, so in order to do that you can use android:backgroundTint instead

    How do I prompt a user for confirmation in bash script?

    read -p "Are you sure? " -n 1 -r
    echo    # (optional) move to a new line
    if [[ $REPLY =~ ^[Yy]$ ]]
    then
        # do dangerous stuff
    fi
    

    I incorporated levislevis85's suggestion (thanks!) and added the -n option to read to accept one character without the need to press Enter. You can use one or both of these.

    Also, the negated form might look like this:

    read -p "Are you sure? " -n 1 -r
    echo    # (optional) move to a new line
    if [[ ! $REPLY =~ ^[Yy]$ ]]
    then
        [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1 # handle exits from shell or function but don't exit interactive shell
    fi
    

    However, as pointed out by Erich, under some circumstances such as a syntax error caused by the script being run in the wrong shell, the negated form could allow the script to continue to the "dangerous stuff". The failure mode should favor the safest outcome so only the first, non-negated if should be used.

    Explanation:

    The read command outputs the prompt (-p "prompt") then accepts one character (-n 1) and accepts backslashes literally (-r) (otherwise read would see the backslash as an escape and wait for a second character). The default variable for read to store the result in is $REPLY if you don't supply a name like this: read -p "my prompt" -n 1 -r my_var

    The if statement uses a regular expression to check if the character in $REPLY matches (=~) an upper or lower case "Y". The regular expression used here says "a string starting (^) and consisting solely of one of a list of characters in a bracket expression ([Yy]) and ending ($)". The anchors (^ and $) prevent matching longer strings. In this case they help reinforce the one-character limit set in the read command.

    The negated form uses the logical "not" operator (!) to match (=~) any character that is not "Y" or "y". An alternative way to express this is less readable and doesn't as clearly express the intent in my opinion in this instance. However, this is what it would look like: if [[ $REPLY =~ ^[^Yy]$ ]]

    Drop all tables command

    To delete also views add 'view' keyword:

    delete from sqlite_master where type in ('view', 'table', 'index', 'trigger');
    

    Is there any quick way to get the last two characters in a string?

    theString.substring(theString.length() - 2)
    

    Include another HTML file in a HTML file

    Using ES6 backticks ``: template literals!

    _x000D_
    _x000D_
    let nick = "Castor", name = "Moon", nuts = 1_x000D_
    _x000D_
    more.innerHTML = `_x000D_
    _x000D_
    <h1>Hello ${nick} ${name}!</h1>_x000D_
    _x000D_
    You collected ${nuts} nuts so far!_x000D_
    _x000D_
    <hr>_x000D_
    _x000D_
    Double it and get ${nuts + nuts} nuts!!_x000D_
    _x000D_
    ` 
    _x000D_
    <div id="more"></div>
    _x000D_
    _x000D_
    _x000D_

    This way we can include html without encoding quotes, include variables from the DOM, and so on.

    It is a powerful templating engine, we can use separate js files and use events to load the content in place, or even separate everything in chunks and call on demand:

    let inject = document.createElement('script');
    inject.src= '//....com/template/panel45.js';
    more.appendChild(inject);
    

    https://caniuse.com/#feat=template-literals

    replacing NA's with 0's in R dataframe

    Here are two quickie approaches I know of:

    In base

    AQ1 <- airquality
    AQ1[is.na(AQ1 <- airquality)] <- 0
    AQ1
    

    Not in base

    library(qdap)
    NAer(airquality)
    

    PS P.S. Does my command above create a new dataframe called AQ1?

    Look at AQ1 and see

    Keyboard shortcut to clear cell output in Jupyter notebook

    I just looked and found cell|all output|clear which worked with:

    Server Information: You are using Jupyter notebook.

    The version of the notebook server is: 6.1.5 The server is running on this version of Python: Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)]

    Current Kernel Information: Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)] Type 'copyright', 'credits' or 'license' for more information IPython 7.19.0 -- An enhanced Interactive Python. Type '?' for help.

    How to import set of icons into Android Studio project

    For custom images you created yourself, you can do without the plugin:

    Right click on res folder, selecting New > Image Asset. browse image file. Select the largest image you have.

    It will create all densities for you. Make sure you select an original image, not an asset studio image with an alpha, or you will semi-transpartent it twice.

    Capture the Screen into a Bitmap

    // Use this version to capture the full extended desktop (i.e. multiple screens)
    
    Bitmap screenshot = new Bitmap(SystemInformation.VirtualScreen.Width, 
                                   SystemInformation.VirtualScreen.Height, 
                                   PixelFormat.Format32bppArgb);
    Graphics screenGraph = Graphics.FromImage(screenshot);
    screenGraph.CopyFromScreen(SystemInformation.VirtualScreen.X, 
                               SystemInformation.VirtualScreen.Y, 
                               0, 
                               0, 
                               SystemInformation.VirtualScreen.Size, 
                               CopyPixelOperation.SourceCopy);
    
    screenshot.Save("Screenshot.png", System.Drawing.Imaging.ImageFormat.Png);
    

    Fastest way of finding differences between two files in unix?

    You could try..

    comm -13 <(sort file1) <(sort file2) > file3
    

    or

    grep -Fxvf file1 file2 > file3
    

    or

    diff file1 file2 | grep "<" | sed 's/^<//g'  > file3
    

    or

    join -v 2 <(sort file1) <(sort file2) > file3
    

    Convert DateTime to String PHP

    Its worked for me

    $start_time   = date_create_from_format('Y-m-d H:i:s', $start_time);
    $current_date = new DateTime();
    $diff         = $start_time->diff($current_date);
    $aa           = (string)$diff->format('%R%a');
    echo gettype($aa);
    

    CFLAGS, CCFLAGS, CXXFLAGS - what exactly do these variables control?

    As you noticed, these are Makefile {macros or variables}, not compiler options. They implement a set of conventions. (Macros is an old name for them, still used by some. GNU make doc calls them variables.)

    The only reason that the names matter is the default make rules, visible via make -p, which use some of them.

    If you write all your own rules, you get to pick all your own macro names.

    In a vanilla gnu make, there's no such thing as CCFLAGS. There are CFLAGS, CPPFLAGS, and CXXFLAGS. CFLAGS for the C compiler, CXXFLAGS for C++, and CPPFLAGS for both.

    Why is CPPFLAGS in both? Conventionally, it's the home of preprocessor flags (-D, -U) and both c and c++ use them. Now, the assumption that everyone wants the same define environment for c and c++ is perhaps questionable, but traditional.


    P.S. As noted by James Moore, some projects use CPPFLAGS for flags to the C++ compiler, not flags to the C preprocessor. The Android NDK, for one huge example.

    Blurry text after using CSS transform: scale(); in Chrome

    Just to add to the fix craze, putting {border:1px solid #???} around the badly looking object fixes the issue for me. In case you have a stable background colour, consider this too. This is so dumb noone thought about mentioning I guess, eh eh.

    VB.Net: Dynamically Select Image from My.Resources

    Make sure you don't include extension of the resource, nor path to it. It's only the resource file name.

    PictureBoxName.Image = My.Resources.ResourceManager.GetObject("object_name") 
    

    Return an empty Observable

    In my case with Angular2 and rxjs, it worked with:

    import {EmptyObservable} from 'rxjs/observable/EmptyObservable';
    ...
    return new EmptyObservable();
    ...
    

    Copy data from another Workbook through VBA

    Are you looking for the syntax to open them:

    Dim wkbk As Workbook
    
    Set wkbk = Workbooks.Open("C:\MyDirectory\mysheet.xlsx")
    

    Then, you can use wkbk.Sheets(1).Range("3:3") (or whatever you need)

    How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception

    Since you are running it in servlet, you need to have the jar accessible by the servlet container. You either include the connector as part of your application war or put it as part of the servlet container's extended library and datasource management stuff, if it has one. The second part is totally depend on the container that you have.

    Pandas every nth row

    df.drop(labels=df[df.index % 3 != 0].index, axis=0) #  every 3rd row (mod 3)
    

    MySQL: is a SELECT statement case sensitive?

    You can lowercase the value and the passed parameter :

    SELECT * FROM `table` WHERE LOWER(`Value`) = LOWER("IAreSavage")
    

    Another (better) way would be to use the COLLATE operator as said in the documentation

    Can't get value of input type="file"?

    You can get it by using document.getElementById();

    var fileVal=document.getElementById("some Id");
    alert(fileVal.value);
    

    will give the value of file,but it gives with fakepath as follows

    c:\fakepath\filename
    

    How to clear a textbox once a button is clicked in WPF?

    There is one possible pitfall with using textBoxName.Text = string.Empty; and that is if you are using Text binding for your TextBox (i.e. <TextBox Text="{Binding Path=Description}"></TextBox>). In this case, setting an empty string will actually override and break your binding.

    To prevent this behavior you have to use the Clear method:

    textBoxName.Clear();
    

    This way the TextBox will be cleared, but the binding will be kept intact.

    Splitting string with pipe character ("|")

    split takes regex as a parameter.| has special meaning in regex.. use \\| instead of | to escape it.

    How to convert date into this 'yyyy-MM-dd' format in angular 2

    A simple solution would be to just write

    this.date = new Date().toLocaleDateString();
    

    date .toLocaleDateString() time .toLocaleTimeString() both .toLocaleString()

    Hope this helps.

    Getting distance between two points based on latitude/longitude

    You can use Uber's H3,point_dist() function to compute the spherical distance between two (lat, lng) points. We can set return unit ('km', 'm', or 'rads'). The default unit is Km.

    Example :

    import H3
    
    coords_1 = (52.2296756, 21.0122287)
    coords_2 = (52.406374, 16.9251681)
    distance = h3.point_dist(coords_1,coords_2) #278.4584889328128
    

    Hope this will usefull!

    Unpacking a list / tuple of pairs into two lists / tuples

    >>> source_list = ('1','a'),('2','b'),('3','c'),('4','d')
    >>> list1, list2 = zip(*source_list)
    >>> list1
    ('1', '2', '3', '4')
    >>> list2
    ('a', 'b', 'c', 'd')
    

    Edit: Note that zip(*iterable) is its own inverse:

    >>> list(source_list) == zip(*zip(*source_list))
    True
    

    When unpacking into two lists, this becomes:

    >>> list1, list2 = zip(*source_list)
    >>> list(source_list) == zip(list1, list2)
    True
    

    Addition suggested by rocksportrocker.

    Convert an array to string

    You can join your array using the following:

    string.Join(",", Client);
    

    Then you can output anyway you want. You can change the comma to what ever you want, a space, a pipe, or whatever.

    Android Intent Cannot resolve constructor

    You may use this:

    Intent intent = new Intent(getApplicationContext(), ClassName.class);
    

    Array.size() vs Array.length

    Array.size() is not a valid method

    Always use the length property

    There is a library or script adding the size method to the array prototype since this is not a native array method. This is commonly done to add support for a custom getter. An example of using this would be when you want to get the size in memory of an array (which is the only thing I can think of that would be useful for this name).

    Underscore.js unfortunately defines a size method which actually returns the length of an object or array. Since unfortunately the length property of a function is defined as the number of named arguments the function declares they had to use an alternative and size was chosen (count would have been a better choice).

    Upload file to SFTP using PowerShell

    I am able to sftp using PowerShell as below:

    PS C:\Users\user\Desktop> sftp [email protected]                                                     
    [email protected]'s password:
    Connected to [email protected].
    sftp> ls
    testFolder
    sftp> cd testFolder
    sftp> ls
    taj_mahal.jpeg
    sftp> put taj_mahal_1.jpeg
    Uploading taj_mahal_1.jpeg to /home/user/testFolder/taj_mahal_1.jpeg
    taj_mahal_1.jpeg                                                                      100%   11KB  35.6KB/s   00:00
    sftp> ls
    taj_mahal.jpeg      taj_mahal_1.jpeg
    sftp>
    

    I do not have installed Posh-SSH or anything like that. I am using Windows 10 Pro PowerShell. No additional modules installed.

    How to use UIScrollView in Storyboard

    i wanna put my 5 cents to accepted answer: i've been researching topic for 2 days and finally found a solution that i will be using always from now on

    go up to item 4 in accepted answer and forget about adding attributes of frames and contentsizes and so on

    to make everything automatic just use solution from this link

    everything is clear, easy, elegant and works like a charm on ios 7. i'm pretty glad with all that lol

    Reminder - \r\n or \n\r?

    \r\n for Windows will do just fine.

    mysql-python install error: Cannot open include file 'config-win.h'

    for 64-bit windows

    Can I calculate z-score with R?

    if x is a vector with raw scores then scale(x) is a vector with standardized scores.

    Or manually: (x-mean(x))/sd(x)

    clear javascript console in Google Chrome

    Update: As of November 6, 2012, console.clear() is now available in Chrome Canary.


    If you type clear() into the console it clears it.

    I don't think there is a way to programmatically do it, as it could be misused. (console is cleared by some web page, end user can't access error information)

    one possible workaround:

    in the console type window.clear = clear, then you'll be able to use clear in any script on your page.

    Twig for loop for arrays with keys

    These are extended operations (e.g., sort, reverse) for one dimensional and two dimensional arrays in Twig framework:

    1D Array

    Without Key Sort and Reverse

    {% for key, value in array_one_dimension %}
        <div>{{ key }}</div>
        <div>{{ value }}</div>
    {% endfor %}
    

    Key Sort

    {% for key, value in array_one_dimension|keys|sort %}
        <div>{{ key }}</div>
        <div>{{ value }}</div>
    {% endfor %}
    

    Key Sort and Reverse

    {% for key, value in array_one_dimension|keys|sort|reverse %}
        <div>{{ key }}</div>
        <div>{{ value }}</div>
    {% endfor %}
    

    2D Arrays

    Without Key Sort and Reverse

    {% for key_a, value_a in array_two_dimension %}
        {% for key_b, value_b in array_two_dimension[key_a] %}
            <div>{{ key_b }}</div>
            <div>{{ value_b }}</div>
        {% endfor %}
    {% endfor %}
    

    Key Sort on Outer Array

    {% for key_a, value_a in array_two_dimension|keys|sort %}
        {% for key_b, value_b in array_two_dimension[key_a] %}
            <div>{{ key_b }}</div>
            <div>{{ value_b }}</div>
        {% endfor %}
    {% endfor %}
    

    Key Sort on Both Outer and Inner Arrays

    {% for key_a, value_a in array_two_dimension|keys|sort %}
        {% for key_b, value_b in array_two_dimension[key_a]|keys|sort %}
            <div>{{ key_b }}</div>
            <div>{{ value_b }}</div>
        {% endfor %}
    {% endfor %}
    

    Key Sort on Outer Array & Key Sort and Reverse on Inner Array

    {% for key_a, value_a in array_two_dimension|keys|sort %}
        {% for key_b, value_b in array_two_dimension[key_a]|keys|sort|reverse %}
            <div>{{ key_b }}</div>
            <div>{{ value_b }}</div>
        {% endfor %}
    {% endfor %}
    

    Key Sort and Reverse on Outer Array & Key Sort on Inner Array

    {% for key_a, value_a in array_two_dimension|keys|sort|reverse %}
        {% for key_b, value_b in array_two_dimension[key_a]|keys|sort %}
            <div>{{ key_b }}</div>
            <div>{{ value_b }}</div>
        {% endfor %}
    {% endfor %}
    

    Key Sort and Reverse on Both Outer and Inner Array

    {% for key_a, value_a in array_two_dimension|keys|sort|reverse %}
        {% for key_b, value_b in array_two_dimension[key_a]|keys|sort|reverse %}
            <div>{{ key_b }}</div>
            <div>{{ value_b }}</div>
        {% endfor %}
    {% endfor %}
    

    Fill formula down till last row in column

    It's a one liner actually. No need to use .Autofill

    Range("M3:M" & LastRow).Formula = "=G3&"",""&L3"
    

    What is the MySQL JDBC driver connection string?

    Here's the documentation:

    https://dev.mysql.com/doc/connector-j/en/connector-j-reference-configuration-properties.html

    A basic connection string looks like:

    jdbc:mysql://localhost:3306/dbname
    

    The class.forName string is "com.mysql.jdbc.Driver", which you can find (edit: now on the same page).

    jQuery scrollTop() doesn't seem to work in Safari or Chrome (Windows)

    I was facing this problem, I created this link at the bottom and implemented the jQuery scrollTop code and it worked perfectly in Firefox, IE, Opera but didn't work in Chrome and Safari. I'm learning jQuery so I don't know if this solution is technically perfect but this worked for me. I just implemented 2 ScrollTop codes the first one uses $('html') which works for Firefox, etc. The second one uses $('html body') this works for Chrome and Safari.

    $('a#top').click(function() {
    
        $('html').animate({scrollTop: 0}, 'slow');
        return false;
    
        $('html body').animate({scrollTop: 0}, 'slow');
        return false;
    });
    

    How to iterate over a JavaScript object?

    var Dictionary = {
      If: {
        you: {
          can: '',
          make: ''
        },
        sense: ''
      },
      of: {
        the: {
          sentence: {
            it: '',
            worked: ''
          }
        }
      }
    };
    
    function Iterate(obj) {
      for (prop in obj) {
        if (obj.hasOwnProperty(prop) && isNaN(prop)) {
          console.log(prop + ': ' + obj[prop]);
          Iterate(obj[prop]);
        }
      }
    }
    Iterate(Dictionary);
    

    Illegal mix of collations (utf8_unicode_ci,IMPLICIT) and (utf8_general_ci,IMPLICIT) for operation '='

    I spent half a day searching for answers to an identical "Illegal mix of collations" error with conflicts between utf8_unicode_ci and utf8_general_ci.

    I found that some columns in my database were not specifically collated utf8_unicode_ci. It seems mysql implicitly collated these columns utf8_general_ci.

    Specifically, running a 'SHOW CREATE TABLE table1' query outputted something like the following:

    | table1 | CREATE TABLE `table1` (
    `id` int(11) NOT NULL,
    `col1` varchar(4) CHARACTER SET utf8 NOT NULL,
    `col2` int(11) NOT NULL,
    PRIMARY KEY (`col1`,`col2`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci |
    

    Note the line 'col1' varchar(4) CHARACTER SET utf8 NOT NULL does not have a collation specified. I then ran the following query:

    ALTER TABLE table1 CHANGE col1 col1 VARCHAR(4) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL;

    This solved my "Illegal mix of collations" error. Hope this might help someone else out there.

    Laravel Query Builder where max id

    You should be able to perform a select on the orders table, using a raw WHERE to find the max(id) in a subquery, like this:

     \DB::table('orders')->where('id', \DB::raw("(select max(`id`) from orders)"))->get();
    

    If you want to use Eloquent (for example, so you can convert your response to an object) you will want to use whereRaw, because some functions such as toJSON or toArray will not work without using Eloquent models.

     $order = Order::whereRaw('id = (select max(`id`) from orders)')->get();
    

    That, of course, requires that you have a model that extends Eloquent.

     class Order extends Eloquent {}
    

    As mentioned in the comments, you don't need to use whereRaw, you can do the entire query using the query builder without raw SQL.

     // Using the Query Builder
     \DB::table('orders')->find(\DB::table('orders')->max('id'));
    
     // Using Eloquent
     $order = Order::find(\DB::table('orders')->max('id'));
    

    (Note that if the id field is not unique, you will only get one row back - this is because find() will only return the first result from the SQL server.).

    How does one extract each folder name from a path?

    There are a few ways that a file path can be represented. You should use the System.IO.Path class to get the separators for the OS, since it can vary between UNIX and Windows. Also, most (or all if I'm not mistaken) .NET libraries accept either a '\' or a '/' as a path separator, regardless of OS. For this reason, I'd use the Path class to split your paths. Try something like the following:

    string originalPath = "\\server\\folderName1\\another\ name\\something\\another folder\\";
    string[] filesArray = originalPath.Split(Path.AltDirectorySeparatorChar,
                                  Path.DirectorySeparatorChar);
    

    This should work regardless of the number of folders or the names.

    Git removing upstream from local repository

    In git version 2.14.3,

    You can remove upstream using

    git branch --unset-upstream
    

    The above command will also remove the tracking stream branch, hence if you want to rebase from repository you have use

    git rebase origin master 
    

    instead of git pull --rebase

    Sending a file over TCP sockets in Python

    You can send some flag to stop while loop in server

    for example

    Server side:

    import socket
    s = socket.socket()
    s.bind(("localhost", 5000))
    s.listen(1)
    c,a = s.accept()
    filetodown = open("img.png", "wb")
    while True:
       print("Receiving....")
       data = c.recv(1024)
       if data == b"DONE":
               print("Done Receiving.")
               break
       filetodown.write(data)
    filetodown.close()
    c.send("Thank you for connecting.")
    c.shutdown(2)
    c.close()
    s.close()
    #Done :)
    

    Client side:

    import socket
    s = socket.socket()
    s.connect(("localhost", 5000))
    filetosend = open("img.png", "rb")
    data = filetosend.read(1024)
    while data:
        print("Sending...")
        s.send(data)
        data = filetosend.read(1024)
    filetosend.close()
    s.send(b"DONE")
    print("Done Sending.")
    print(s.recv(1024))
    s.shutdown(2)
    s.close()
    #Done :)
    

    Check if ADODB connection is open

    This topic is old but if other people like me search a solution, this is a solution that I have found:

    Public Function DBStats() As Boolean
        On Error GoTo errorHandler
            If Not IsNull(myBase.Version) Then 
                DBStats = True
            End If
            Exit Function
        errorHandler:
            DBStats = False  
    End Function
    

    So "myBase" is a Database Object, I have made a class to access to database (class with insert, update etc...) and on the module the class is use declare in an object (obviously) and I can test the connection with "[the Object].DBStats":

    Dim BaseAccess As New myClass
    BaseAccess.DBOpen 'I open connection
    Debug.Print BaseAccess.DBStats ' I test and that tell me true
    BaseAccess.DBClose ' I close the connection
    Debug.Print BaseAccess.DBStats ' I test and tell me false
    

    Edit : In DBOpen I use "OpenDatabase" and in DBClose I use ".Close" and "set myBase = nothing" Edit 2: In the function, if you are not connect, .version give you an error so if aren't connect, the errorHandler give you false

    Where is nodejs log file?

    If you use docker in your dev you can do this in another shell: docker attach running_node_app_container_name

    That will show you STDOUT and STDERR.

    Laravel Eloquent LEFT JOIN WHERE NULL

    I would dump your query so you can take a look at the SQL that was actually executed and see how that differs from what you wrote.

    You should be able to do that with the following code:

    $queries = DB::getQueryLog();
    $last_query = end($queries);
    var_dump($last_query);
    die();
    

    Hopefully that should give you enough information to allow you to figure out what's gone wrong.

    Download image from the site in .NET/C#

    Also possible to use DownloadData method

        private byte[] GetImage(string iconPath)
        {
            using (WebClient client = new WebClient())
            {
                byte[] pic = client.DownloadData(iconPath);
                //string checkPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) +@"\1.png";
                //File.WriteAllBytes(checkPath, pic);
                return pic;
            }
        }
    

    Why does git status show branch is up-to-date when changes exist upstream?

    I have faced a similar problem, I searched everywhere online for solutions and I tried to follow them. None worked for me. These were the steps I took to the problem.

    Make new repo and push the existing code again to the new repo

    git init doesn’t initialize if you already have a .git/ folder in your repository. So, for your case, do -

    (1) rm -rf .git/

    (2) git init

    (3) git remote add origin https://repository.remote.url

    (4) git commit -m “Commit message”

    (5) git push -f origin master

    Note that all git configs like remote repositories for this repository are cleared in step 1. So, you have to set up all remote repository URLs again.

    Also, take care of the -f in step 5: The remote already has some code base with n commits, and you’re trying to make all those changes into a single commit. So, force-pushing the changes to remote is necessary.

    Eloquent ORM laravel 5 Get Array of ids

    read about the lists() method

    $test=test::select('id')->where('id' ,'>' ,0)->lists('id')->toArray()
    

    How to extract year and month from date in PostgreSQL without using to_char() function?

    date_part(text, timestamp)
    

    e.g.

    date_part('month', timestamp '2001-02-16 20:38:40'),
    date_part('year', timestamp '2001-02-16 20:38:40') 
    

    http://www.postgresql.org/docs/8.0/interactive/functions-datetime.html

    How to prevent line breaks in list items using CSS

    Bootstrap 4 has a class named text-nowrap. It is just what you need.

    Carousel with Thumbnails in Bootstrap 3.0

    @Skelly 's answer is correct. It won't let me add a comment (<50 rep)... but to answer your question on his answer: In the example he linked, if you add

    col-xs-3 
    

    class to each of the thumbnails, like this:

    class="col-md-3 col-xs-3"
    

    then it should stay the way you want it when sized down to phone width.

    What is a NullPointerException, and how do I fix it?

    A null pointer is one that points to nowhere. When you dereference a pointer p, you say "give me the data at the location stored in "p". When p is a null pointer, the location stored in p is nowhere, you're saying "give me the data at the location 'nowhere'". Obviously, it can't do this, so it throws a null pointer exception.

    In general, it's because something hasn't been initialized properly.

    Invalid use side-effecting operator Insert within a function

    You can't use a function to insert data into a base table. Functions return data. This is listed as the very first limitation in the documentation:

    User-defined functions cannot be used to perform actions that modify the database state.

    "Modify the database state" includes changing any data in the database (though a table variable is an obvious exception the OP wouldn't have cared about 3 years ago - this table variable only lives for the duration of the function call and does not affect the underlying tables in any way).

    You should be using a stored procedure, not a function.