Programs & Examples On #Syscache

How can I trigger a Bootstrap modal programmatically?

You should't write data-toggle="modal" in the element which triggered the modal (like a button), and you manually can show the modal with:

$('#myModal').modal('show');

and hide with:

$('#myModal').modal('hide');

Transform char array into String

If you have the char array null terminated, you can assign the char array to the string:

char[] chArray = "some characters";
String String(chArray);

As for your loop code, it looks right, but I will try on my controller to see if I get the same problem.

"Expected BEGIN_OBJECT but was STRING at line 1 column 1"

if your json format and variables are okay then check your database queries...even if data is saved in db correctly the actual problem might be in there...recheck your queries and try again.. Hope it helps

What characters are valid for JavaScript variable names?

Javascript Variables

You can start a variable with any letter, $, or _ character. As long as it doesn't start with a number, you can include numbers as well.

Start: [a-z], $, _

Contain: [a-z], [0-9], $, _

jQuery

You can use _ for your library so that it will stand side-by-side with jQuery. However, there is a configuration you can set so that jQuery will not use $. It will instead use jQuery. To do this, simply set:

jQuery.noConflict();

This page explains how to do this.

How to read a single character from the user?

A comment in one of the other answers mentioned cbreak mode, which is important for Unix implementations because you generally don't want ^C (KeyboardError) to be consumed by getchar (as it will when you set the terminal to raw mode, as done by most other answers).

Another important detail is that if you're looking to read one character and not one byte, you should read 4 bytes from the input stream, as that's the maximum number of bytes a single character will consist of in UTF-8 (Python 3+). Reading only a single byte will produce unexpected results for multi-byte characters such as keypad arrows.

Here's my changed implementation for Unix:

import contextlib
import os
import sys
import termios
import tty


_MAX_CHARACTER_BYTE_LENGTH = 4


@contextlib.contextmanager
def _tty_reset(file_descriptor):
    """
    A context manager that saves the tty flags of a file descriptor upon
    entering and restores them upon exiting.
    """
    old_settings = termios.tcgetattr(file_descriptor)
    try:
        yield
    finally:
        termios.tcsetattr(file_descriptor, termios.TCSADRAIN, old_settings)


def get_character(file=sys.stdin):
    """
    Read a single character from the given input stream (defaults to sys.stdin).
    """
    file_descriptor = file.fileno()
    with _tty_reset(file_descriptor):
        tty.setcbreak(file_descriptor)
        return os.read(file_descriptor, _MAX_CHARACTER_BYTE_LENGTH)

Maven: How to rename the war file for the project?

You need to configure the war plugin:

<project>
  ...
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.3</version>
        <configuration>
          <warName>bird.war</warName>
        </configuration>
      </plugin>
    </plugins>
  </build>
  ...
</project>

More info here

Using jQuery, Restricting File Size Before Uploading

I tried it this way and I am getting the results in IE*, and Mozilla 3.6.16, didnt check in older versions.

<img id="myImage" src="" style="display:none;"><br>
<button onclick="findSize();">Image Size</button>
<input type="file" id="loadfile" />
<input type="button" value="find size" onclick="findSize()" />
<script type="text/javascript">
function findSize() {
    if ( $.browser.msie ) {
       var a = document.getElementById('loadfile').value;
           $('#myImage').attr('src',a);
           var imgbytes = document.getElementById('myImage').size;
           var imgkbytes = Math.round(parseInt(imgbytes)/1024);
           alert(imgkbytes+' KB');
    }else {
           var fileInput = $("#loadfile")[0];
           var imgbytes = fileInput.files[0].fileSize; // Size returned in bytes.
           var imgkbytes = Math.round(parseInt(imgbytes)/1024);
                   alert(imgkbytes+' KB');
     }
}    
</script>

Add Jquery library also.

SQL Server Text type vs. varchar data type

There has been some major changes in ms 2008 -> Might be worth considering the following article when making a decisions on what data type to use. http://msdn.microsoft.com/en-us/library/ms143432.aspx

Bytes per

  1. varchar(max), varbinary(max), xml, text, or image column 2^31-1 2^31-1
  2. nvarchar(max) column 2^30-1 2^30-1

How do I run a program from command prompt as a different user and as an admin

Start -> shift + command Prompt right click will helps to use as another user or as Admin

Git Cherry-pick vs Merge Workflow

In my opinion cherry-picking should be reserved for rare situations where it is required, for example if you did some fix on directly on 'master' branch (trunk, main development branch) and then realized that it should be applied also to 'maint'. You should base workflow either on merge, or on rebase (or "git pull --rebase").

Please remember that cherry-picked or rebased commit is different from the point of view of Git (has different SHA-1 identifier) than the original, so it is different than the commit in remote repository. (Rebase can usually deal with this, as it checks patch id i.e. the changes, not a commit id).

Also in git you can merge many branches at once: so called octopus merge. Note that octopus merge has to succeed without conflicts. Nevertheless it might be useful.

HTH.

How can I set a proxy server for gem?

For http/https proxy with or without authentication:

Run one of the following commands in cmd.exe

set http_proxy=http://your_proxy:your_port
set http_proxy=http://username:password@your_proxy:your_port
set https_proxy=https://your_proxy:your_port
set https_proxy=https://username:password@your_proxy:your_port

Make an image follow mouse pointer

Ok, here's a simple box that follows the cursor

Doing the rest is a simple case of remembering the last cursor position and applying a formula to get the box to move other than exactly where the cursor is. A timeout would also be handy if the box has a limited acceleration and must catch up to the cursor after it stops moving. Replacing the box with an image is simple CSS (which can replace most of the setup code for the box). I think the actual thinking code in the example is about 8 lines.

Select the right image (use a sprite) to orientate the rocket.

Yeah, annoying as hell. :-)

_x000D_
_x000D_
function getMouseCoords(e) {
  var e = e || window.event;
  document.getElementById('container').innerHTML = e.clientX + ', ' +
    e.clientY + '<br>' + e.screenX + ', ' + e.screenY;
}


var followCursor = (function() {
  var s = document.createElement('div');
  s.style.position = 'absolute';
  s.style.margin = '0';
  s.style.padding = '5px';
  s.style.border = '1px solid red';
  s.textContent = ""

  return {
    init: function() {
      document.body.appendChild(s);
    },

    run: function(e) {
      var e = e || window.event;
      s.style.left = (e.clientX - 5) + 'px';
      s.style.top = (e.clientY - 5) + 'px';
      getMouseCoords(e);
    }
  };
}());

window.onload = function() {
  followCursor.init();
  document.body.onmousemove = followCursor.run;
}
_x000D_
#container {
  width: 1000px;
  height: 1000px;
  border: 1px solid blue;
}
_x000D_
<div id="container"></div>
_x000D_
_x000D_
_x000D_

Show/hide widgets in Flutter programmatically

Try the Offstage widget

if attribute offstage:true the not occupy the physical space and invisible,

if attribute offstage:false it will occupy the physical space and visible

Offstage(
   offstage: true,
   child: Text("Visible"),
),

'git status' shows changed files, but 'git diff' doesn't

I had this same problem described in the following way: If I typed

$ git diff

Git simply returned to the prompt with no error.

If I typed

$ git diff <filename>

Git simply returned to the prompt with no error.

Finally, by reading around I noticed that git diff actually calls the mingw64\bin\diff.exe to do the work.

Here's the deal. I'm running Windows and had installed another Bash utility and it changed my path so it no longer pointed to my mingw64\bin directory.

So if you type:

git diff

and it just returns to the prompt you may have this problem.

The actual diff.exe which is run by git is located in your mingw64\bin directory

Finally, to fix this, I actually copied my mingw64\bin directory to the location Git was looking for it in. I tried it and it still didn't work.

Then, I closed my Git Bash window and opened it again went to my same repository that was failing and now it works.

Select default option value from typescript angular 6

HTML

<select class='form-control'>
    <option *ngFor="let option of options"
    [selected]="option === nrSelect"
    [value]="option">
        {{ option }}
    </option>
</select>

Typescript

nrSelect = 47;
options = [41, 42, 47, 48];

how to delete the content of text file without deleting itself

Write an empty string to the file, flush, and close. Make sure that the file writer is not in append-mode. I think that should do the trick.

Remove duplicates from a list of objects based on property in Java 8

The easiest way to do it directly in the list is

HashSet<Object> seen=new HashSet<>();
employee.removeIf(e->!seen.add(e.getID()));
  • removeIf will remove an element if it meets the specified criteria
  • Set.add will return false if it did not modify the Set, i.e. already contains the value
  • combining these two, it will remove all elements (employees) whose id has been encountered before

Of course, it only works if the list supports removal of elements.

How to shut down the computer from C#

If you want to shut down computer remotely then you can use

Using System.Diagnostics;

on any button click

{
    Process.Start("Shutdown","-i");
}

How do I create HTML table using jQuery dynamically?

FOR EXAMPLE YOU HAVE RECIEVED JASON DATA FROM SERVER.

                var obj = JSON.parse(msg);
                var tableString ="<table id='tbla'>";
                tableString +="<th><td>Name<td>City<td>Birthday</th>";


                for (var i=0; i<obj.length; i++){
                    //alert(obj[i].name);
                    tableString +=gg_stringformat("<tr><td>{0}<td>{1}<td>{2}</tr>",obj[i].name, obj[i].age, obj[i].birthday);
                }
                tableString +="</table>";
                alert(tableString);
                $('#divb').html(tableString);

HERE IS THE CODE FOR gg_stringformat

function gg_stringformat() {
var argcount = arguments.length,
    string,
    i;

if (!argcount) {
    return "";
}
if (argcount === 1) {
    return arguments[0];
}
string = arguments[0];
for (i = 1; i < argcount; i++) {
    string = string.replace(new RegExp('\\{' + (i - 1) + '}', 'gi'), arguments[i]);
}
return string;

}

Java HTML Parsing

Another library that might be useful for HTML processing is jsoup. Jsoup tries to clean malformed HTML and allows html parsing in Java using jQuery like tag selector syntax.

http://jsoup.org/

Is there a Python equivalent of the C# null-coalescing operator?

In addition to Juliano's answer about behavior of "or": it's "fast"

>>> 1 or 5/0
1

So sometimes it's might be a useful shortcut for things like

object = getCachedVersion() or getFromDB()

JWT refresh token flow

Based in this implementation with Node.js of JWT with refresh token:

1) In this case they use a uid and it's not a JWT. When they refresh the token they send the refresh token and the user. If you implement it as a JWT, you don't need to send the user, because it would inside the JWT.

2) They implement this in a separated document (table). It has sense to me because a user can be logged in in different client applications and it could have a refresh token by app. If the user lose a device with one app installed, the refresh token of that device could be invalidated without affecting the other logged in devices.

3) In this implementation it response to the log in method with both, access token and refresh token. It seams correct to me.

How to Git stash pop specific stash in 1.8.3?

On Windows Powershell I run this:

git stash apply "stash@{1}"

BitBucket - download source as ZIP

Direct download:

Go to the project repository from the dashboard of bitbucket. Select downloads from the left menu. Choose Download repository.

enter image description here

Adding click event handler to iframe

iframe doesn't have onclick event but we can implement this by using iframe's onload event and javascript like this...

function iframeclick() {
document.getElementById("theiframe").contentWindow.document.body.onclick = function() {
        document.getElementById("theiframe").contentWindow.location.reload();
    }
}


<iframe id="theiframe" src="youriframe.html" style="width: 100px; height: 100px;" onload="iframeclick()"></iframe>

I hope it will helpful to you....

Using CSS :before and :after pseudo-elements with inline CSS?

You can't specify inline styles for pseudo-elements.

This is because pseudo-elements, like pseudo-classes (see my answer to this other question), are defined in CSS using selectors as abstractions of the document tree that can't be expressed in HTML. An inline style attribute, on the other hand, is specified within HTML for a particular element.

Since inline styles can only occur in HTML, they will only apply to the HTML element that they're defined on, and not to any pseudo-elements it generates.

As an aside, the main difference between pseudo-elements and pseudo-classes in this aspect is that properties that are inherited by default will be inherited by :before and :after from the generating element, whereas pseudo-class styles just don't apply at all. In your case, for example, if you place text-align: justify in an inline style attribute for a td element, it will be inherited by td:after. The caveat is that you can't declare td:after with the inline style attribute; you must do it in the stylesheet.

jsonify a SQLAlchemy result set in Flask

I was working with a sql query defaultdict of lists of RowProxy objects named jobDict It took me a while to figure out what Type the objects were.

This was a really simple quick way to resolve to some clean jsonEncoding just by typecasting the row to a list and by initially defining the dict with a value of list.

    jobDict = defaultdict(list)
    def set_default(obj):
        # trickyness needed here via import to know type
        if isinstance(obj, RowProxy):
            return list(obj)
        raise TypeError


    jsonEncoded = json.dumps(jobDict, default=set_default)

Compare 2 arrays which returns difference

use underscore as :

_.difference(array1,array2)

MongoDB: How to update multiple documents with a single command?

I had the same problem , and i found the solution , and it works like a charm

just set the flag multi to true like this :

 db.Collection.update(
                {_id_receiver: id_receiver},
               {$set: {is_showed: true}},
                {multi: true}   /* --> multiple update */
            , function (err, updated) {...});

i hope that helps :)

Code for a simple JavaScript countdown timer?

Here is another one if anyone needs one for minutes and seconds:

    var mins = 10;  //Set the number of minutes you need
    var secs = mins * 60;
    var currentSeconds = 0;
    var currentMinutes = 0;
    /* 
     * The following line has been commented out due to a suggestion left in the comments. The line below it has not been tested. 
     * setTimeout('Decrement()',1000);
     */
    setTimeout(Decrement,1000); 

    function Decrement() {
        currentMinutes = Math.floor(secs / 60);
        currentSeconds = secs % 60;
        if(currentSeconds <= 9) currentSeconds = "0" + currentSeconds;
        secs--;
        document.getElementById("timerText").innerHTML = currentMinutes + ":" + currentSeconds; //Set the element id you need the time put into.
        if(secs !== -1) setTimeout('Decrement()',1000);
    }

How can I submit a form using JavaScript?

You can use...

document.getElementById('theForm').submit();

...but don't replace the innerHTML. You could hide the form and then insert a processing... span which will appear in its place.

var form = document.getElementById('theForm');

form.style.display = 'none';

var processing = document.createElement('span');

processing.appendChild(document.createTextNode('processing ...'));

form.parentNode.insertBefore(processing, form);

Angular update object in object array

In angular/typescript we can avoid mutation of the objects in the array.

An example using your item arr as a BehaviorSubject:

// you can initialize the items$ with the default array
this.items$ = new BehaviorSubject<any>([user1, user2, ...])

updateUser(user){
   this.myservice.getUpdate(user.id).subscribe(newitem => {

     // remove old item
     const items = this.items$.value.filter((item) => item.id !== newitem.id);

     // add a the newItem and broadcast a new table
     this.items$.next([...items, newItem])
   });
}

And in the template you can subscribe on the items$

<tr *ngFor="let u of items$ | async; let i = index">
   <td>{{ u.id }}</td>
   <td>{{ u.name }}</td>
   <td>
        <input type="checkbox" checked="u.accepted" (click)="updateUser(u)">
        <label for="singleCheckbox-{{i}}"></label>
   </td>
</tr>

How to convert JSON to CSV format and store in a variable

I wanted to riff off @Christian Landgren's answer above. I was confused why my CSV file only had 3 columns/headers. This was because the first element in my json only had 3 keys. So you need to be careful with the const header = Object.keys(json[0]) line. It's assuming that the first element in the array is representative. I had messy JSON that with some objects having more or less.

So I added an array.sort to this which will order the JSON by number of keys. So that way your CSV file will have the max number of columns.

This is also a function that you can use in your code. Just feed it JSON!

function convertJSONtocsv(json) {
    if (json.length === 0) {
        return;
    }

    json.sort(function(a,b){ 
       return Object.keys(b).length - Object.keys(a).length;
    });

    const replacer = (key, value) => value === null ? '' : value // specify how you want to handle null values here
    const header = Object.keys(json[0])
    let csv = json.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','))
    csv.unshift(header.join(','))
    csv = csv.join('\r\n')

    fs.writeFileSync('awesome.csv', csv)
}

How to find the type of an object in Go?

You can check the type of any variable/instance at runtime either using the "reflect" packages TypeOf function or by using fmt.Printf():

package main

import (
   "fmt"
   "reflect"
)

func main() {
    value1 := "Have a Good Day"
    value2 := 50
    value3 := 50.78

    fmt.Println(reflect.TypeOf(value1 ))
    fmt.Println(reflect.TypeOf(value2))
    fmt.Println(reflect.TypeOf(value3))
    fmt.Printf("%T",value1)
    fmt.Printf("%T",value2)
    fmt.Printf("%T",value3)
}

How do I release memory used by a pandas dataframe?

It seems there is an issue with glibc that affects the memory allocation in Pandas: https://github.com/pandas-dev/pandas/issues/2659

The monkey patch detailed on this issue has resolved the problem for me:

# monkeypatches.py

# Solving memory leak problem in pandas
# https://github.com/pandas-dev/pandas/issues/2659#issuecomment-12021083
import pandas as pd
from ctypes import cdll, CDLL
try:
    cdll.LoadLibrary("libc.so.6")
    libc = CDLL("libc.so.6")
    libc.malloc_trim(0)
except (OSError, AttributeError):
    libc = None

__old_del = getattr(pd.DataFrame, '__del__', None)

def __new_del(self):
    if __old_del:
        __old_del(self)
    libc.malloc_trim(0)

if libc:
    print('Applying monkeypatch for pd.DataFrame.__del__', file=sys.stderr)
    pd.DataFrame.__del__ = __new_del
else:
    print('Skipping monkeypatch for pd.DataFrame.__del__: libc or malloc_trim() not found', file=sys.stderr)

How to remove an element slowly with jQuery?

You mean like

$target.hide('slow')

?

How can I plot data with confidence intervals?

Here is part of my program related to plotting confidence interval.

1. Generate the test data

ads = 1
require(stats); require(graphics)
library(splines)
x_raw <- seq(1,10,0.1)
y <- cos(x_raw)+rnorm(len_data,0,0.1)
y[30] <- 1.4 # outlier point
len_data = length(x_raw)
N <- len_data
summary(fm1 <- lm(y~bs(x_raw, df=5), model = TRUE, x =T, y = T))
ht <-seq(1,10,length.out = len_data)
plot(x = x_raw, y = y,type = 'p')
y_e <- predict(fm1, data.frame(height = ht))
lines(x= ht, y = y_e)

Result

enter image description here

2. Fitting the raw data using B-spline smoother method

sigma_e <- sqrt(sum((y-y_e)^2)/N)
print(sigma_e)
H<-fm1$x
A <-solve(t(H) %*% H)
y_e_minus <- rep(0,N)
y_e_plus <- rep(0,N)
y_e_minus[N]
for (i in 1:N)
{
    tmp <-t(matrix(H[i,])) %*% A %*% matrix(H[i,])
    tmp <- 1.96*sqrt(tmp)
    y_e_minus[i] <- y_e[i] - tmp
    y_e_plus[i] <- y_e[i] + tmp
}
plot(x = x_raw, y = y,type = 'p')
polygon(c(ht,rev(ht)),c(y_e_minus,rev(y_e_plus)),col = rgb(1, 0, 0,0.5), border = NA)
#plot(x = x_raw, y = y,type = 'p')
lines(x= ht, y = y_e_plus, lty = 'dashed', col = 'red')
lines(x= ht, y = y_e)
lines(x= ht, y = y_e_minus, lty = 'dashed', col = 'red')

Result

enter image description here

SQL Server: how to select records with specific date from datetime column

The easiest way is to convert to a date:

SELECT *
FROM dbo.LogRequests
WHERE cast(dateX as date) = '2014-05-09';

Often, such expressions preclude the use of an index. However, according to various sources on the web, the above is sargable (meaning it will use an index), such as this and this.

I would be inclined to use the following, just out of habit:

SELECT *
FROM dbo.LogRequests
WHERE dateX >= '2014-05-09' and dateX < '2014-05-10';

what is the difference between XSD and WSDL

XSD defines a schema which is a definition of how an XML document can be structured. You can use it to check that a given XML document is valid and follows the rules you've laid out in the schema.

WSDL is a XML document that describes a web service. It shows which operations are available and how data should be structured to send to those operations.

WSDL documents have an associated XSD that show what is valid to put in a WSDL document.

How do you get AngularJS to bind to the title attribute of an A tag?

Look at the fiddle here for a quick answer

data-ng-attr-title="{{d.age > 5 ? 'My age is greater than threshold': ''}}"

Displays Title over elements conditionally using Angular JS

urllib and "SSL: CERTIFICATE_VERIFY_FAILED" Error

On Windows, Python does not look at the system certificate, it uses its own located at ?\lib\site-packages\certifi\cacert.pem.

The solution to your problem:

  1. download the domain validation certificate as *.crt or *pem file
  2. open the file in editor and copy it's content to clipboard
  3. find your cacert.pem location: from requests.utils import DEFAULT_CA_BUNDLE_PATH; print(DEFAULT_CA_BUNDLE_PATH)
  4. edit the cacert.pem file and paste your domain validation certificate at the end of the file.
  5. Save the file and enjoy requests!

How to send a “multipart/form-data” POST in Android with Volley

This is my way of doing it. It may be useful to others :

private void updateType(){
    // Log.i(TAG,"updateType");
     StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {

         @Override
         public void onResponse(String response) {
             // running on main thread-------
             try {
                 JSONObject res = new JSONObject(response);
                 res.getString("result");
                 System.out.println("Response:" + res.getString("result"));

                 }else{
                     CustomTast ct=new CustomTast(context);
                     ct.showCustomAlert("Network/Server Disconnected",R.drawable.disconnect);
                 }

             } catch (Exception e) {
                 e.printStackTrace();

                 //Log.e("Response", "==> " + e.getMessage());
             }
         }
     }, new Response.ErrorListener() {
         @Override
         public void onErrorResponse(VolleyError volleyError) {
             // running on main thread-------
             VolleyLog.d(TAG, "Error: " + volleyError.getMessage());

         }
     }) {
         protected Map<String, String> getParams() {
             HashMap<String, String> hashMapParams = new HashMap<String, String>();
             hashMapParams.put("key", "value");
             hashMapParams.put("key", "value");
             hashMapParams.put("key", "value"));
             hashMapParams.put("key", "value");
             System.out.println("Hashmap:" + hashMapParams);
             return hashMapParams;
         }
     };
     AppController.getInstance().addToRequestQueue(request);

 }

Get textarea text with javascript or Jquery

You could use val().

var value = $('#area1').val();
$('#VAL_DISPLAY').html(value);

How does Subquery in select statement work in oracle

It's simple-

SELECT empname,
       empid,
       (SELECT COUNT (profileid)
          FROM profile
         WHERE profile.empid = employee.empid)
           AS number_of_profiles
  FROM employee;

It is even simpler when you use a table join like this:

  SELECT e.empname, e.empid, COUNT (p.profileid) AS number_of_profiles
    FROM employee e LEFT JOIN profile p ON e.empid = p.empid
GROUP BY e.empname, e.empid;

Explanation for the subquery:

Essentially, a subquery in a select gets a scalar value and passes it to the main query. A subquery in select is not allowed to pass more than one row and more than one column, which is a restriction. Here, we are passing a count to the main query, which, as we know, would always be only a number- a scalar value. If a value is not found, the subquery returns null to the main query. Moreover, a subquery can access columns from the from clause of the main query, as shown in my query where employee.empid is passed from the outer query to the inner query.


Edit:

When you use a subquery in a select clause, Oracle essentially treats it as a left join (you can see this in the explain plan for your query), with the cardinality of the rows being just one on the right for every row in the left.


Explanation for the left join

A left join is very handy, especially when you want to replace the select subquery due to its restrictions. There are no restrictions here on the number of rows of the tables in either side of the LEFT JOIN keyword.

For more information read Oracle Docs on subqueries and left join or left outer join.

Python Sets vs Lists

Sets are faster, morover you get more functions with sets, such as lets say you have two sets :

set1 = {"Harry Potter", "James Bond", "Iron Man"}
set2 = {"Captain America", "Black Widow", "Hulk", "Harry Potter", "James Bond"}

We can easily join two sets:

set3 = set1.union(set2)

Find out what is common in both:

set3 = set1.intersection(set2)

Find out what is different in both:

set3 = set1.difference(set2)

And much more! Just try them out, they are fun! Moreover if you have to work on the different values within 2 list or common values within 2 lists, I prefer to convert your lists to sets, and many programmers do in that way. Hope it helps you :-)

nano error: Error opening terminal: xterm-256color

I, too, have this problem on an older Mac that I upgraded to Lion.

Before reading the terminfo tip, I was able to get vi and less working by doing "export TERM=xterm".

After reading the tip, I grabbed /usr/share/terminfo from a newer Mac that has fresh install of Lion and does not exhibit this problem.

Now, even though echo $TERM still yields xterm-256color, vi and less now work fine.

How to set Java SDK path in AndroidStudio?

Click "use embedded JDK" on version Android Studio 3.2.1

click this box

Where to find the complete definition of off_t type?

Since this answer still gets voted up, I want to point out that you should almost never need to look in the header files. If you want to write reliable code, you're much better served by looking in the standard. A better question than "how is off_t defined on my machine" is "how is off_t defined by the standard?". Following the standard means that your code will work today and tomorrow, on any machine.

In this case, off_t isn't defined by the C standard. It's part of the POSIX standard, which you can browse here.

Unfortunately, off_t isn't very rigorously defined. All I could find to define it is on the page on sys/types.h:

blkcnt_t and off_t shall be signed integer types.

This means that you can't be sure how big it is. If you're using GNU C, you can use the instructions in the answer below to ensure that it's 64 bits. Or better, you can convert to a standards defined size before putting it on the wire. This is how projects like Google's Protocol Buffers work (although that is a C++ project).


So, I think "where do I find the definition in my header files" isn't the best question. But, for completeness here's the answer:

On my machine (and most machines using glibc) you'll find the definition in bits/types.h (as a comment says at the top, never directly include this file), but it's obscured a bit in a bunch of macros. An alternative to trying to unravel them is to look at the preprocessor output:

#include <stdio.h>
#include <sys/types.h>

int main(void) {
  off_t blah;

  return 0;
}

And then:

$ gcc -E sizes.c  | grep __off_t
typedef long int __off_t;
....

However, if you want to know the size of something, you can always use the sizeof() operator.

Edit: Just saw the part of your question about the __. This answer has a good discussion. The key point is that names starting with __ are reserved for the implementation (so you shouldn't start your own definitions with __).

Python import csv to list

Extending your requirements a bit and assuming you do not care about the order of lines and want to get them grouped under categories, the following solution may work for you:

>>> fname = "lines.txt"
>>> from collections import defaultdict
>>> dct = defaultdict(list)
>>> with open(fname) as f:
...     for line in f:
...         text, cat = line.rstrip("\n").split(",", 1)
...         dct[cat].append(text)
...
>>> dct
defaultdict(<type 'list'>, {' CatA': ['This is the first line', 'This is the another line'], ' CatC': ['This is the third line'], ' CatB': ['This is the second line', 'This is the last line']})

This way you get all relevant lines available in the dictionary under key being the category.

Resource interpreted as stylesheet but transferred with MIME type text/html (seems not related with web server)

Based on the other answers it seems like this message has a lot of causes, I thought I'd just share my individual solution in case anyone has my exact problem in the future.

Our site loads the CSS files from an AWS Cloudfront distribution, which uses an S3 bucket as the origin. This particular S3 bucket was kept synced to a Linux server running Jenkins. The sync command via s3cmd sets the Content-Type for the S3 object automatically based on what the OS says (presumably based on the file extension). For some reason, in our server, all the types were being set correctly except .css files, which it gave the type text/plain. In S3, when you check the metadata in the properties of a file, you can set the type to whatever you want. Setting it to text/css allowed our site to correctly interpret the files as CSS and load correctly.

Excel formula is only showing the formula rather than the value within the cell in Office 2010

Make sure you include the = sign in addition to passing the arguments to the function. I.E.

=SUM(A1:A3) //this would give you the sum of cells A1, A2, and A3.

How to check if directory exist using C++ and winAPI

Here is a simple function which does exactly this :

#include <windows.h>
#include <string>

bool dirExists(const std::string& dirName_in)
{
  DWORD ftyp = GetFileAttributesA(dirName_in.c_str());
  if (ftyp == INVALID_FILE_ATTRIBUTES)
    return false;  //something is wrong with your path!

  if (ftyp & FILE_ATTRIBUTE_DIRECTORY)
    return true;   // this is a directory!

  return false;    // this is not a directory!
}

Directory index forbidden by Options directive

In my case, it's a typo caused this issue:

<VirtualHost *.8080>

should be

<VirtualHost *:8080>

super() fails with error: TypeError "argument 1 must be type, not classobj" when parent does not inherit from object

Your problem is that class B is not declared as a "new-style" class. Change it like so:

class B(object):

and it will work.

super() and all subclass/superclass stuff only works with new-style classes. I recommend you get in the habit of always typing that (object) on any class definition to make sure it is a new-style class.

Old-style classes (also known as "classic" classes) are always of type classobj; new-style classes are of type type. This is why you got the error message you saw:

TypeError: super() argument 1 must be type, not classobj

Try this to see for yourself:

class OldStyle:
    pass

class NewStyle(object):
    pass

print type(OldStyle)  # prints: <type 'classobj'>

print type(NewStyle) # prints <type 'type'>

Note that in Python 3.x, all classes are new-style. You can still use the syntax from the old-style classes but you get a new-style class. So, in Python 3.x you won't have this problem.

jQuery AJAX single file upload

After hours of searching and looking for answer, finally I made it!!!!! Code is below :))))

HTML:

<form id="fileinfo" enctype="multipart/form-data" method="post" name="fileinfo">
    <label>File to stash:</label>
    <input type="file" name="file" required />
</form>
<input type="button" value="Stash the file!"></input>
<div id="output"></div>

jQuery:

$(function(){
    $('#uploadBTN').on('click', function(){ 
        var fd = new FormData($("#fileinfo"));
        //fd.append("CustomField", "This is some extra data");
        $.ajax({
            url: 'upload.php',  
            type: 'POST',
            data: fd,
            success:function(data){
                $('#output').html(data);
            },
            cache: false,
            contentType: false,
            processData: false
        });
    });
});

In the upload.php file you can access the data passed with $_FILES['file'].

Thanks everyone for trying to help:)

I took the answer from here (with some changes) MDN

What is a web service endpoint?

A web service endpoint is the URL that another program would use to communicate with your program. To see the WSDL you add ?wsdl to the web service endpoint URL.

Web services are for program-to-program interaction, while web pages are for program-to-human interaction.

So: Endpoint is: http://www.blah.com/myproject/webservice/webmethod

Therefore, WSDL is: http://www.blah.com/myproject/webservice/webmethod?wsdl


To expand further on the elements of a WSDL, I always find it helpful to compare them to code:

A WSDL has 2 portions (physical & abstract).

Physical Portion:

Definitions - variables - ex: myVar, x, y, etc.

Types - data types - ex: int, double, String, myObjectType

Operations - methods/functions - ex: myMethod(), myFunction(), etc.

Messages - method/function input parameters & return types

  • ex: public myObjectType myMethod(String myVar)

Porttypes - classes (i.e. they are a container for operations) - ex: MyClass{}, etc.

Abstract Portion:

Binding - these connect to the porttypes and define the chosen protocol for communicating with this web service. - a protocol is a form of communication (so text/SMS, vs. phone vs. email, etc.).

Service - this lists the address where another program can find your web service (i.e. your endpoint).

Get Absolute Position of element within the window in wpf

I think what BrandonS wants is not the position of the mouse relative to the root element, but rather the position of some descendant element.

For that, there is the TransformToAncestor method:

Point relativePoint = myVisual.TransformToAncestor(rootVisual)
                              .Transform(new Point(0, 0));

Where myVisual is the element that was just double-clicked, and rootVisual is Application.Current.MainWindow or whatever you want the position relative to.

How to get jQuery to wait until an effect is finished?

if its something you wish to switch, fading one out and fading another in the same place, you can place a {position:absolute} attribute on the divs, so both the animations play on top of one another, and you don't have to wait for one animation to be over before starting up the next.

Put spacing between divs in a horizontal row?

Another idea: Compensate for your margin on the opposite side of the div.

For the side with the spacing you are looking to achieve as an example: 10px, and for the opposing side, compensate with a -10px. It works for me. This likely won't work in all scenarios, but depending on your layout and spacing of other elements, it might work great.

Android Shared preferences for creating one time activity (example)

How to Intialize?

// 0 - for private mode`
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); 

Editor editor = pref.edit();

How to Store Data In Shared Preference?

editor.putString("key_name", "string value"); // Storing string

OR

editor.putInt("key_name", "int value"); //Storing integer

And don't forget to apply :

editor.apply();

How to retrieve Data From Shared Preferences ?

pref.getString("key_name", null); // getting String

pref.getInt("key_name", 0); // getting Integer

Hope this will Help U :)

Multiple INSERT statements vs. single INSERT with multiple VALUES

It is not too surprising: the execution plan for the tiny insert is computed once, and then reused 1000 times. Parsing and preparing the plan is quick, because it has only four values to del with. A 1000-row plan, on the other hand, needs to deal with 4000 values (or 4000 parameters if you parameterized your C# tests). This could easily eat up the time savings you gain by eliminating 999 roundtrips to SQL Server, especially if your network is not overly slow.

"Could not run curl-config: [Errno 2] No such file or directory" when installing pycurl

Be advised that if you're using nodejs there's (at the time of writing) a dependency on libssl 1.0.* - so installing an alternative SSL library will break your nodejs installation.

An alternative solution to installing a different SSL library is that posted in this answer here: https://stackoverflow.com/a/59927568/13564342 to instead install libcurl4-gnutls-dev

sudo apt install libcurl4-gnutls-dev

websocket closing connection automatically

Since @Doua Beri is experiencing connection close even when there are 1 Hz SENDs, it may be instead be due to size limits on messages.

This passage from Spring's WebSockets may be useful, with my emphasis ...

Although in theory a WebSocket message can be almost unlimited in size, in practice WebSocket servers impose limits — for example, 8K on Tomcat and 64K on Jetty. For this reason STOMP clients such as stomp.js split larger STOMP messages at 16K boundaries and send them as multiple WebSocket messages thus requiring the server to buffer and re-assemble.

Angles between two n-dimensional vectors in Python

David Wolever's solution is good, but

If you want to have signed angles you have to determine if a given pair is right or left handed (see wiki for further info).

My solution for this is:

def unit_vector(vector):
    """ Returns the unit vector of the vector"""
    return vector / np.linalg.norm(vector)

def angle(vector1, vector2):
    """ Returns the angle in radians between given vectors"""
    v1_u = unit_vector(vector1)
    v2_u = unit_vector(vector2)
    minor = np.linalg.det(
        np.stack((v1_u[-2:], v2_u[-2:]))
    )
    if minor == 0:
        raise NotImplementedError('Too odd vectors =(')
    return np.sign(minor) * np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))

It's not perfect because of this NotImplementedError but for my case it works well. This behaviour could be fixed (cause handness is determined for any given pair) but it takes more code that I want and have to write.

What is the default encoding of the JVM?

You can use this to print out the JVM defaults

import java.nio.charset.Charset;
import java.io.InputStreamReader;
import java.io.FileInputStream;

public class PrintCharSets {
        public static void main(String[] args) throws Exception {
                System.out.println("file.encoding=" + System.getProperty("file.encoding"));
                System.out.println("Charset.defaultCharset=" + Charset.defaultCharset());
                System.out.println("InputStreamReader.getEncoding=" + new InputStreamReader(new FileInputStream("./PrintCharSets.java")).getEncoding());
        }
}

Compile and Run

javac PrintCharSets.java && java PrintCharSets

Programmatically getting the MAC of an Android device

You can no longer get the hardware MAC address of a android device. WifiInfo.getMacAddress() and BluetoothAdapter.getAddress() methods will return 02:00:00:00:00:00. This restriction was introduced in Android 6.0.

But Rob Anderson found a solution which is working for < Marshmallow : https://stackoverflow.com/a/35830358

Loop through properties in JavaScript object with Lodash

For your stated desire to "check if a property exists" you can directly use Lo-Dash's has.

var exists = _.has(myObject, propertyNameToCheck);

Which mime type should I use for mp3

mp3 files sometimes throw strange mime types as per this answer: https://stackoverflow.com/a/2755288/14482130

If you are doing some user validation do not allow 'application/octet-stream' or 'application/x-zip-compressed' as suggested above since they can contain be .exe or other potentially dangerous files.

In order to validate when mime type gives a false negative you can use fleep as per this answer https://stackoverflow.com/a/52570299/14482130 to finish the validation.

How to use java.String.format in Scala?

Also note that Scala extends String with a number of methods (via implicit conversion to a WrappedString brought in by Predef) so you could also do the following:

val formattedString = "Hello %s, isn't %s cool?".format("Ivan", "Scala")

How to get the jQuery $.ajax error response text?

you can try it too:

$(document).ajaxError(
    function (event, jqXHR, ajaxSettings, thrownError) {
        alert('[event:' + event + '], [jqXHR:' + jqXHR + '], [ajaxSettings:' + ajaxSettings + '], [thrownError:' + thrownError + '])');
    });

How to reset index in a pandas dataframe?

data1.reset_index(inplace=True)

How can I see if a Perl hash already has a certain key?

You can just go with:

if(!$strings{$string}) ....

How to reload the datatable(jquery) data?

For the newer versions use:

var datatable = $('#table').dataTable().api();

$.get('myUrl', function(newDataArray) {
    datatable.clear();
    datatable.rows.add(newDataArray);
    datatable.draw();
});

Taken from: https://stackoverflow.com/a/27781459/4059810

What's the difference between deadlock and livelock?

Maybe these two examples illustrate you the difference between a deadlock and a livelock:


Java-Example for a deadlock:

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class DeadlockSample {

    private static final Lock lock1 = new ReentrantLock(true);
    private static final Lock lock2 = new ReentrantLock(true);

    public static void main(String[] args) {
        Thread threadA = new Thread(DeadlockSample::doA,"Thread A");
        Thread threadB = new Thread(DeadlockSample::doB,"Thread B");
        threadA.start();
        threadB.start();
    }

    public static void doA() {
        System.out.println(Thread.currentThread().getName() + " : waits for lock 1");
        lock1.lock();
        System.out.println(Thread.currentThread().getName() + " : holds lock 1");

        try {
            System.out.println(Thread.currentThread().getName() + " : waits for lock 2");
            lock2.lock();
            System.out.println(Thread.currentThread().getName() + " : holds lock 2");

            try {
                System.out.println(Thread.currentThread().getName() + " : critical section of doA()");
            } finally {
                lock2.unlock();
                System.out.println(Thread.currentThread().getName() + " : does not hold lock 2 any longer");
            }
        } finally {
            lock1.unlock();
            System.out.println(Thread.currentThread().getName() + " : does not hold lock 1 any longer");
        }
    }

    public static void doB() {
        System.out.println(Thread.currentThread().getName() + " : waits for lock 2");
        lock2.lock();
        System.out.println(Thread.currentThread().getName() + " : holds lock 2");

        try {
            System.out.println(Thread.currentThread().getName() + " : waits for lock 1");
            lock1.lock();
            System.out.println(Thread.currentThread().getName() + " : holds lock 1");

            try {
                System.out.println(Thread.currentThread().getName() + " : critical section of doB()");
            } finally {
                lock1.unlock();
                System.out.println(Thread.currentThread().getName() + " : does not hold lock 1 any longer");
            }
        } finally {
            lock2.unlock();
            System.out.println(Thread.currentThread().getName() + " : does not hold lock 2 any longer");
        }
    }
}

Sample output:

Thread A : waits for lock 1
Thread B : waits for lock 2
Thread A : holds lock 1
Thread B : holds lock 2
Thread B : waits for lock 1
Thread A : waits for lock 2

Java-Example for a livelock:


import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LivelockSample {

    private static final Lock lock1 = new ReentrantLock(true);
    private static final Lock lock2 = new ReentrantLock(true);

    public static void main(String[] args) {
        Thread threadA = new Thread(LivelockSample::doA, "Thread A");
        Thread threadB = new Thread(LivelockSample::doB, "Thread B");
        threadA.start();
        threadB.start();
    }

    public static void doA() {
        try {
            while (!lock1.tryLock()) {
                System.out.println(Thread.currentThread().getName() + " : waits for lock 1");
                Thread.sleep(100);
            }
            System.out.println(Thread.currentThread().getName() + " : holds lock 1");

            try {
                while (!lock2.tryLock()) {
                    System.out.println(Thread.currentThread().getName() + " : waits for lock 2");
                    Thread.sleep(100);
                }
                System.out.println(Thread.currentThread().getName() + " : holds lock 2");

                try {
                    System.out.println(Thread.currentThread().getName() + " : critical section of doA()");
                } finally {
                    lock2.unlock();
                    System.out.println(Thread.currentThread().getName() + " : does not hold lock 2 any longer");
                }
            } finally {
                lock1.unlock();
                System.out.println(Thread.currentThread().getName() + " : does not hold lock 1 any longer");
            }
        } catch (InterruptedException e) {
            // can be ignored here for this sample
        }
    }

    public static void doB() {
        try {
            while (!lock2.tryLock()) {
                System.out.println(Thread.currentThread().getName() + " : waits for lock 2");
                Thread.sleep(100);
            }
            System.out.println(Thread.currentThread().getName() + " : holds lock 2");

            try {
                while (!lock1.tryLock()) {
                    System.out.println(Thread.currentThread().getName() + " : waits for lock 1");
                    Thread.sleep(100);
                }
                System.out.println(Thread.currentThread().getName() + " : holds lock 1");

                try {
                    System.out.println(Thread.currentThread().getName() + " : critical section of doB()");
                } finally {
                    lock1.unlock();
                    System.out.println(Thread.currentThread().getName() + " : does not hold lock 1 any longer");
                }
            } finally {
                lock2.unlock();
                System.out.println(Thread.currentThread().getName() + " : does not hold lock 2 any longer");
            }
        } catch (InterruptedException e) {
            // can be ignored here for this sample
        }
    }
}

Sample output:

Thread B : holds lock 2
Thread A : holds lock 1
Thread A : waits for lock 2
Thread B : waits for lock 1
Thread B : waits for lock 1
Thread A : waits for lock 2
Thread A : waits for lock 2
Thread B : waits for lock 1
Thread B : waits for lock 1
Thread A : waits for lock 2
Thread A : waits for lock 2
Thread B : waits for lock 1
...

Both examples force the threads to aquire the locks in different orders. While the deadlock waits for the other lock, the livelock does not really wait - it desperately tries to acquire the lock without the chance of getting it. Every try consumes CPU cycles.

HTML table with fixed headers and a fixed column?

In this answer there is also the best answer I found to your question:

HTML table with fixed headers?

and based on pure CSS.

Remove last character from string. Swift language

Swift 4.2

I also delete my last character from String (i.e. UILabel text) in IOS app

@IBOutlet weak var labelText: UILabel! // Do Connection with UILabel

@IBAction func whenXButtonPress(_ sender: UIButton) { // Do Connection With X Button

    labelText.text = String((labelText.text?.dropLast())!) // Delete the last caracter and assign it

}

IOS APP StoryBoard

How to install PyQt5 on Windows?

It can be installed with below simple command:

pip3 install pyqt5

How to wait until an element is present in Selenium?

You need to call ignoring with exception to ignore while the WebDriver will wait.

FluentWait<WebDriver> fluentWait = new FluentWait<>(driver)
        .withTimeout(30, TimeUnit.SECONDS)
        .pollingEvery(200, TimeUnit.MILLISECONDS)
        .ignoring(NoSuchElementException.class);

See the documentation of FluentWait for more info. But beware that this condition is already implemented in ExpectedConditions so you should use

WebElement element = (new WebDriverWait(driver, 10))
   .until(ExpectedConditions.elementToBeClickable(By.id("someid")));

*Update for newer versions of Selenium:

withTimeout(long, TimeUnit) has become withTimeout(Duration)
pollingEvery(long, TimeUnit) has become pollingEvery(Duration)

So the code will look as such:

FluentWait<WebDriver> fluentWait = new FluentWait<>(driver)
        .withTimeout(Duration.ofSeconds(30)
        .pollingEvery(Duration.ofMillis(200)
        .ignoring(NoSuchElementException.class);

Basic tutorial for waiting can be found here.

Using Laravel Homestead: 'no input file specified'

Restart your homestead. Worked for me.

homestead destroy
homestead up

Can I get div's background-image url?

Here is a simple regex which will remove the url(" and ") from the returned string.

var css = $("#myElem").css("background-image");
var img = css.replace(/(?:^url\(["']?|["']?\)$)/g, "");

Float sum with javascript

Once you read what What Every Computer Scientist Should Know About Floating-Point Arithmetic you could use the .toFixed() function:

var result = parseFloat('2.3') + parseFloat('2.4');
alert(result.toFixed(2));?

using OR and NOT in solr query

Putting together comments from a couple different answers here, in the Solr docs and on the other SO question, I found that the following syntax produces the correct result for my use case

(my_field=my_value or my_field is null):

(my_field:"my_value" OR (*:* NOT my_field:*))

This works for solr 4.1.0. This is slightly different than the use case in the OP; but, I thought that others would find it useful.

Notification not showing in Oreo

This is bug in firebase api version 11.8.0, So if you reduce API version you will not face this issue.

How to remove title bar from the android activity?

In your Android Manifest file make sure that the activity is using this (or a) theme (that is based on) @style/Theme.AppCompat.NoActionBar This removes the ActionBar completely, but won't make your activity fullscreen. If you want to make your activity fullscreen only use this theme

@android:style/Theme.NoTitleBar.Fullscreen

Or you could change

this.requestWindowFeature(Window.FEATURE_NO_TITLE);

to

requestWindowFeature(Window.FEATURE_NO_TITLE);
 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

This is what I use to get fullscreen at runtime

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                mDecorView = getWindow().getDecorView();
                mDecorView.setSystemUiVisibility(
                        View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                                | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                                | View.SYSTEM_UI_FLAG_IMMERSIVE);
            }

To exit fullscreen I use this

mDecorView = getWindow().getDecorView();
mDecorView.setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);

Javascript format date / time

Yes, you can use the native javascript Date() object and its methods.

For instance you can create a function like:

function formatDate(date) {
  var hours = date.getHours();
  var minutes = date.getMinutes();
  var ampm = hours >= 12 ? 'pm' : 'am';
  hours = hours % 12;
  hours = hours ? hours : 12; // the hour '0' should be '12'
  minutes = minutes < 10 ? '0'+minutes : minutes;
  var strTime = hours + ':' + minutes + ' ' + ampm;
  return (date.getMonth()+1) + "/" + date.getDate() + "/" + date.getFullYear() + "  " + strTime;
}

var d = new Date();
var e = formatDate(d);

alert(e);

And display also the am / pm and the correct time.

Remember to use getFullYear() method and not getYear() because it has been deprecated.

DEMO http://jsfiddle.net/a_incarnati/kqo10jLb/4/

Add timer to a Windows Forms application

Bit more detail:

    private void Form1_Load(object sender, EventArgs e)
    {
        Timer MyTimer = new Timer();
        MyTimer.Interval = (45 * 60 * 1000); // 45 mins
        MyTimer.Tick += new EventHandler(MyTimer_Tick);
        MyTimer.Start();
    }

    private void MyTimer_Tick(object sender, EventArgs e)
    {
        MessageBox.Show("The form will now be closed.", "Time Elapsed");
        this.Close();
    }

How to kill an application with all its activities?

You are correct: calling finish() will only exit the current activity, not the entire application. however, there is a workaround for this:

Every time you start an Activity, start it using startActivityForResult(...). When you want to close the entire app, you can do something like this:

setResult(RESULT_CLOSE_ALL);
finish();

Then define every activity's onActivityResult(...) callback so when an activity returns with the RESULT_CLOSE_ALL value, it also calls finish():

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch(resultCode)
    {
    case RESULT_CLOSE_ALL:
        setResult(RESULT_CLOSE_ALL);
        finish();
    }
    super.onActivityResult(requestCode, resultCode, data);
}

This will cause a cascade effect closing all activities.

Also, I support CommonsWare in his suggestion: store the password in a variable so that it will be destroyed when the application is closed.

ImportError: No Module named simplejson

Sometimes there is permission errors. Try:

sudo pip install simplejson

Hope it helps.

error while loading shared libraries: libncurses.so.5:

For Redhat Linux 8 try this:

sudo yum install libncurses*

How do I detect whether a Python variable is a function?

An Exact Function Checker

callable is a very good solution. However, I wanted to treat this the opposite way of John Feminella. Instead of treating it like this saying:

The proper way to check properties of duck-typed objects is to ask them if they quack, not to see if they fit in a duck-sized container. The "compare it directly" approach will give the wrong answer for many functions, like builtins.

We'll treat it like this:

The proper way to check if something is a duck is not to see if it can quack, but rather to see if it truly is a duck through several filters, instead of just checking if it seems like a duck from the surface.

How Would We Implement It

The 'types' module has plenty of classes to detect functions, the most useful being types.FunctionType, but there are also plenty of others, like a method type, a built in type, and a lambda type. We also will consider a 'functools.partial' object as being a function.

The simple way we check if it is a function is by using an isinstance condition on all of these types. Previously, I wanted to make a base class which inherits from all of the above, but I am unable to do that, as Python does not allow us to inherit from some of the above classes.

Here's a table of what classes can classify what functions:

Functions table from kinght-? Above function table by kinght-?

The Code Which Does It

Now, this is the code which does all of the work we described from above.

from types import BuiltinFunctionType, BuiltinMethodType,  FunctionType, MethodType, LambdaType
from functools import partial

def is_function(obj):
  return isinstance(obj, (BuiltinFunctionType, BuiltinMethodType,  FunctionType, MethodType, LambdaType, partial))

#-------------------------------------------------

def my_func():
  pass

def add_both(x, y):
  return x + y

class a:
  def b(self):
    pass

check = [

is_function(lambda x: x + x),
is_function(my_func),
is_function(a.b),
is_function(partial),
is_function(partial(add_both, 2))

]

print(check)
>>> [True, True, True, False, True]

The one false was is_function(partial), because that's a class, not a function, and this is exactly functions, not classes. Here is a preview for you to try out the code from.

Conclusion

callable(obj) is the preferred method to check if an object is a function if you want to go by duck-typing over absolutes.

Our custom is_function(obj), maybe with some edits is the preferred method to check if an object is a function if you don't any count callable class instance as a function, but only functions defined built-in, or with lambda, def, or partial.

And I think that wraps it all up. Have a good day!

PHP filesize MB/KB conversion

I think this is a better approach. Simple and straight forward.

public function sizeFilter( $bytes )
{
    $label = array( 'B', 'KB', 'MB', 'GB', 'TB', 'PB' );
    for( $i = 0; $bytes >= 1024 && $i < ( count( $label ) -1 ); $bytes /= 1024, $i++ );
    return( round( $bytes, 2 ) . " " . $label[$i] );
}

Properties order in Margin

Just because @MartinCapodici 's comment is awesome I write here as an answer to give visibility.

All clockwise:

  • WPF start West (left->top->right->bottom)
  • Netscape (ie CSS) start North (top->right->bottom->left)

Detecting request type in PHP (GET, POST, PUT or DELETE)

Since this is about REST, just getting the request method from the server is not enough. You also need to receive RESTful route parameters. The reason for separating RESTful parameters and GET/POST/PUT parameters is that a resource needs to have its own unique URL for identification.

Here's one way of implementing RESTful routes in PHP using Slim:

https://github.com/codeguy/Slim

$app = new \Slim\Slim();
$app->get('/hello/:name', function ($name) {
  echo "Hello, $name";
});
$app->run();

And configure the server accordingly.

Here's another example using AltoRouter:

https://github.com/dannyvankooten/AltoRouter

$router = new AltoRouter();
$router->setBasePath('/AltoRouter'); // (optional) the subdir AltoRouter lives in

// mapping routes
$router->map('GET|POST','/', 'home#index', 'home');
$router->map('GET','/users', array('c' => 'UserController', 'a' => 'ListAction'));
$router->map('GET','/users/[i:id]', 'users#show', 'users_show');
$router->map('POST','/users/[i:id]/[delete|update:action]', 'usersController#doAction', 'users_do');

What is the difference between vmalloc and kmalloc?

What are the advantages of having a contiguous block of memory? Specifically, why would I need to have a contiguous physical block of memory in a system call? Is there any reason I couldn't just use vmalloc?

From Google's "I'm Feeling Lucky" on vmalloc:

kmalloc is the preferred way, as long as you don't need very big areas. The trouble is, if you want to do DMA from/to some hardware device, you'll need to use kmalloc, and you'll probably need bigger chunk. The solution is to allocate memory as soon as possible, before memory gets fragmented.

How does a ArrayList's contains() method evaluate objects?

Just wanted to note that the following implementation is wrong when value is not a primitive type:

public class Thing
{
    public Object value;  

    public Thing (Object x)
    {
        this.value = x;
    }

    @Override
    public boolean equals(Object object)
    {
        boolean sameSame = false;

        if (object != null && object instanceof Thing)
        {
            sameSame = this.value == ((Thing) object).value;
        }

        return sameSame;
    }
}

In that case I propose the following:

public class Thing {
    public Object value;  

    public Thing (Object x) {
        value = x;
    }

    @Override
    public boolean equals(Object object) {

        if (object != null && object instanceof Thing) {
            Thing thing = (Thing) object;
            if (value == null) {
                return (thing.value == null);
            }
            else {
                return value.equals(thing.value);
            }
        }

        return false;
    }
}

React proptype array with shape

This was my solution to protect against an empty array as well:

import React, { Component } from 'react';
import { arrayOf, shape, string, number } from 'prop-types';

ReactComponent.propTypes = {
  arrayWithShape: (props, propName, componentName) => {
    const arrayWithShape = props[propName]
    PropTypes.checkPropTypes({ arrayWithShape:
        arrayOf(
          shape({
            color: string.isRequired,
            fontSize: number.isRequired,
          }).isRequired
      ).isRequired
    }, {arrayWithShape}, 'prop', componentName);
    if(arrayWithShape.length < 1){
      return new Error(`${propName} is empty`)
    }
  }
}

Check if a div exists with jquery

If you are simply checking for the existence of an ID, there is no need to go into jQuery, you could simply:

if(document.getElementById("yourid") !== null)
{
}

getElementById returns null if it can't be found.

Reference.

If however you plan to use the jQuery object later i'd suggest:

$(document).ready(function() {
    var $myDiv = $('#DivID');

    if ( $myDiv.length){
        //you can now reuse  $myDiv here, without having to select it again.
    }


});

A selector always returns a jQuery object, so there shouldn't be a need to check against null (I'd be interested if there is an edge case where you need to check for null - but I don't think there is).

If the selector doesn't find anything then length === 0 which is "falsy" (when converted to bool its false). So if it finds something then it should be "truthy" - so you don't need to check for > 0. Just for it's "truthyness"

What exactly is the function of Application.CutCopyMode property in Excel

Normally, When you copy a cell you will find the below statement written down in the status bar (in the bottom of your sheet)

"Select destination and Press Enter or Choose Paste"

Then you press whether Enter or choose paste to paste the value of the cell.

If you didn't press Esc afterwards you will be able to paste the value of the cell several times

Application.CutCopyMode = False does the same like the Esc button, if you removed it from your code you will find that you are able to paste the cell value several times again.

And if you closed the Excel without pressing Esc you will get the warning 'There is a large amount of information on the Clipboard....'

Loading all images using imread from a given folder

Why not just try loading all the files in the folder? If OpenCV can't open it, oh well. Move on to the next. cv2.imread() returns None if the image can't be opened. Kind of weird that it doesn't raise an exception.

import cv2
import os

def load_images_from_folder(folder):
    images = []
    for filename in os.listdir(folder):
        img = cv2.imread(os.path.join(folder,filename))
        if img is not None:
            images.append(img)
    return images

Getting min and max Dates from a pandas dataframe

'Date' is your index so you want to do,

print (df.index.min())
print (df.index.max())

2014-03-13 00:00:00
2014-03-31 00:00:00

Styling text input caret

It is enough to use color property alongside with -webkit-text-fill-color this way:

_x000D_
_x000D_
    input {_x000D_
        color: red; /* color of caret */_x000D_
        -webkit-text-fill-color: black; /* color of text */_x000D_
    }
_x000D_
<input type="text"/>
_x000D_
_x000D_
_x000D_

Works in WebKit browsers (but not in iOS Safari, where is still used system color for caret) and also in Firefox.

The -webkit-text-fill-color CSS property specifies the fill color of characters of text. If this property is not set, the value of the color property is used. MDN

So this means we set text color with text-fill-color and caret color with standard color property. In unsupported browser, caret and text will have same color – color of the caret.

PIG how to count a number of rows in alias

Be careful, with COUNT your first item in the bag must not be null. Else you can use the function COUNT_STAR to count all rows.

Add CSS or JavaScript files to layout head from views or partial views

I had a similar problem, and ended up applying Kalman's excellent answer with the code below (not quite as neat, but arguably more expansible):

namespace MvcHtmlHelpers
{
    //http://stackoverflow.com/questions/5110028/add-css-or-js-files-to-layout-head-from-views-or-partial-views#5148224
    public static partial class HtmlExtensions
    {
        public static AssetsHelper Assets(this HtmlHelper htmlHelper)
        {
            return AssetsHelper.GetInstance(htmlHelper);
        }
    }
    public enum BrowserType { Ie6=1,Ie7=2,Ie8=4,IeLegacy=7,W3cCompliant=8,All=15}
    public class AssetsHelper
    {
        public static AssetsHelper GetInstance(HtmlHelper htmlHelper)
        {
            var instanceKey = "AssetsHelperInstance";
            var context = htmlHelper.ViewContext.HttpContext;
            if (context == null) {return null;}
            var assetsHelper = (AssetsHelper)context.Items[instanceKey];
            if (assetsHelper == null){context.Items.Add(instanceKey, assetsHelper = new AssetsHelper(htmlHelper));}
            return assetsHelper;
        }
        private readonly List<string> _styleRefs = new List<string>();
        public AssetsHelper AddStyle(string stylesheet)
        {
            _styleRefs.Add(stylesheet);
            return this;
        }
        private readonly List<string> _scriptRefs = new List<string>();
        public AssetsHelper AddScript(string scriptfile)
        {
            _scriptRefs.Add(scriptfile);
            return this;
        }
        public IHtmlString RenderStyles()
        {
            ItemRegistrar styles = new ItemRegistrar(ItemRegistrarFormatters.StyleFormat,_urlHelper);
            styles.Add(Libraries.UsedStyles());
            styles.Add(_styleRefs);
            return styles.Render();
        }
        public IHtmlString RenderScripts()
        {
            ItemRegistrar scripts = new ItemRegistrar(ItemRegistrarFormatters.ScriptFormat, _urlHelper);
            scripts.Add(Libraries.UsedScripts());
            scripts.Add(_scriptRefs);
            return scripts.Render();
        }
        public LibraryRegistrar Libraries { get; private set; }
        private UrlHelper _urlHelper;
        public AssetsHelper(HtmlHelper htmlHelper)
        {
            _urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
            Libraries = new LibraryRegistrar();
        }
    }
    public class LibraryRegistrar
    {
        public class Component
        {
            internal class HtmlReference
            {
                internal string Url { get; set; }
                internal BrowserType ServeTo { get; set; }
            }
            internal List<HtmlReference> Styles { get; private set; }
            internal List<HtmlReference> Scripts { get; private set; }
            internal List<string> RequiredLibraries { get; private set; }

            public Component()
            {
                Styles = new List<HtmlReference>();
                Scripts = new List<HtmlReference>();
                RequiredLibraries = new List<string>();
            }
            public Component Requires(params string[] libraryNames)
            {
                foreach (var lib in libraryNames)
                {
                    if (!RequiredLibraries.Contains(lib))
                        { RequiredLibraries.Add(lib); }
                }
                return this;
            }
            public Component AddStyle(string url, BrowserType serveTo = BrowserType.All)
            {
                Styles.Add(new HtmlReference { Url = url, ServeTo=serveTo });
                return this;
            }
            public Component AddScript(string url, BrowserType serveTo = BrowserType.All)
            {
                Scripts.Add(new HtmlReference { Url = url, ServeTo = serveTo });
                return this;
            }
        }
        private readonly Dictionary<string, Component> _allLibraries = new Dictionary<string, Component>();
        private List<string> _usedLibraries = new List<string>();
        internal IEnumerable<string> UsedScripts()
        {
            SetOrder();
            var returnVal = new List<string>();
            foreach (var key in _usedLibraries)
            {
                returnVal.AddRange(from s in _allLibraries[key].Scripts
                                   where IncludesCurrentBrowser(s.ServeTo)
                                   select s.Url);
            }
            return returnVal;
        }
        internal IEnumerable<string> UsedStyles()
        {
            SetOrder();
            var returnVal = new List<string>();
            foreach (var key in _usedLibraries)
            {
                returnVal.AddRange(from s in _allLibraries[key].Styles
                                   where IncludesCurrentBrowser(s.ServeTo)
                                   select s.Url);
            }
            return returnVal;
        }
        public void Uses(params string[] libraryNames)
        {
            foreach (var name in libraryNames)
            {
                if (!_usedLibraries.Contains(name)){_usedLibraries.Add(name);}
            }
        }
        public bool IsUsing(string libraryName)
        {
            SetOrder();
            return _usedLibraries.Contains(libraryName);
        }
        private List<string> WalkLibraryTree(List<string> libraryNames)
        {
            var returnList = new List<string>(libraryNames);
            int counter = 0;
            foreach (string libraryName in libraryNames)
            {
                WalkLibraryTree(libraryName, ref returnList, ref counter);
            }
            return returnList;
        }
        private void WalkLibraryTree(string libraryName, ref List<string> libBuild, ref int counter)
        {
            if (counter++ > 1000) { throw new System.Exception("Dependancy library appears to be in infinate loop - please check for circular reference"); }
            Component library;
            if (!_allLibraries.TryGetValue(libraryName, out library))
                { throw new KeyNotFoundException("Cannot find a definition for the required style/script library named: " + libraryName); }
            foreach (var childLibraryName in library.RequiredLibraries)
            {
                int childIndex = libBuild.IndexOf(childLibraryName);
                if (childIndex!=-1)
                {
                    //child already exists, so move parent to position before child if it isn't before already
                    int parentIndex = libBuild.LastIndexOf(libraryName);
                    if (parentIndex>childIndex)
                    {
                        libBuild.RemoveAt(parentIndex);
                        libBuild.Insert(childIndex, libraryName);
                    }
                }
                else
                {
                    libBuild.Add(childLibraryName);
                    WalkLibraryTree(childLibraryName, ref libBuild, ref counter);
                }
            }
            return;
        }
        private bool _dependenciesExpanded;
        private void SetOrder()
        {
            if (_dependenciesExpanded){return;}
            _usedLibraries = WalkLibraryTree(_usedLibraries);
            _usedLibraries.Reverse();
            _dependenciesExpanded = true;
        }
        public Component this[string index]
        {
            get
            {
                if (_allLibraries.ContainsKey(index))
                    { return _allLibraries[index]; }
                var newComponent = new Component();
                _allLibraries.Add(index, newComponent);
                return newComponent;
            }
        }
        private BrowserType _requestingBrowser;
        private BrowserType RequestingBrowser
        {
            get
            {
                if (_requestingBrowser == 0)
                {
                    var browser = HttpContext.Current.Request.Browser.Type;
                    if (browser.Length > 2 && browser.Substring(0, 2) == "IE")
                    {
                        switch (browser[2])
                        {
                            case '6':
                                _requestingBrowser = BrowserType.Ie6;
                                break;
                            case '7':
                                _requestingBrowser = BrowserType.Ie7;
                                break;
                            case '8':
                                _requestingBrowser = BrowserType.Ie8;
                                break;
                            default:
                                _requestingBrowser = BrowserType.W3cCompliant;
                                break;
                        }
                    }
                    else
                    {
                        _requestingBrowser = BrowserType.W3cCompliant;
                    }
                }
                return _requestingBrowser;
            }
        }
        private bool IncludesCurrentBrowser(BrowserType browserType)
        {
            if (browserType == BrowserType.All) { return true; }
            return (browserType & RequestingBrowser) != 0;
        }
    }
    public class ItemRegistrar
    {
        private readonly string _format;
        private readonly List<string> _items;
        private readonly UrlHelper _urlHelper;

        public ItemRegistrar(string format, UrlHelper urlHelper)
        {
            _format = format;
            _items = new List<string>();
            _urlHelper = urlHelper;
        }
        internal void Add(IEnumerable<string> urls)
        {
            foreach (string url in urls)
            {
                Add(url);
            }
        }
        public ItemRegistrar Add(string url)
        {
            url = _urlHelper.Content(url);
            if (!_items.Contains(url))
                { _items.Add( url); }
            return this;
        }
        public IHtmlString Render()
        {
            var sb = new StringBuilder();
            foreach (var item in _items)
            {
                var fmt = string.Format(_format, item);
                sb.AppendLine(fmt);
            }
            return new HtmlString(sb.ToString());
        }
    }
    public class ItemRegistrarFormatters
    {
        public const string StyleFormat = "<link href=\"{0}\" rel=\"stylesheet\" type=\"text/css\" />";
        public const string ScriptFormat = "<script src=\"{0}\" type=\"text/javascript\"></script>";
    }
}

The project contains a static AssignAllResources method:

assets.Libraries["jQuery"]
        .AddScript("~/Scripts/jquery-1.10.0.min.js", BrowserType.IeLegacy)
        .AddScript("~/Scripts//jquery-2.0.1.min.js",BrowserType.W3cCompliant);
        /* NOT HOSTED YET - CHECK SOON 
        .AddScript("//ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js",BrowserType.W3cCompliant);
        */
    assets.Libraries["jQueryUI"].Requires("jQuery")
        .AddScript("//ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js",BrowserType.Ie6)
        .AddStyle("//ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/themes/eggplant/jquery-ui.css",BrowserType.Ie6)
        .AddScript("//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js", ~BrowserType.Ie6)
        .AddStyle("//ajax.aspnetcdn.com/ajax/jquery.ui/1.10.3/themes/eggplant/jquery-ui.css", ~BrowserType.Ie6);
    assets.Libraries["TimePicker"].Requires("jQueryUI")
        .AddScript("~/Scripts/jquery-ui-sliderAccess.min.js")
        .AddScript("~/Scripts/jquery-ui-timepicker-addon-1.3.min.js")
        .AddStyle("~/Content/jQueryUI/jquery-ui-timepicker-addon.css");
    assets.Libraries["Validation"].Requires("jQuery")
        .AddScript("//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js")
        .AddScript("~/Scripts/jquery.validate.unobtrusive.min.js")
        .AddScript("~/Scripts/mvcfoolproof.unobtrusive.min.js")
        .AddScript("~/Scripts/CustomClientValidation-1.0.0.min.js");
    assets.Libraries["MyUtilityScripts"].Requires("jQuery")
        .AddScript("~/Scripts/GeneralOnLoad-1.0.0.min.js");
    assets.Libraries["FormTools"].Requires("Validation", "MyUtilityScripts");
    assets.Libraries["AjaxFormTools"].Requires("FormTools", "jQueryUI")
        .AddScript("~/Scripts/jquery.unobtrusive-ajax.min.js");
    assets.Libraries["DataTables"].Requires("MyUtilityScripts")
        .AddScript("//ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js")
        .AddStyle("//ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css")
        .AddStyle("//ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables_themeroller.css");
    assets.Libraries["MvcDataTables"].Requires("DataTables", "jQueryUI")
        .AddScript("~/Scripts/jquery.dataTables.columnFilter.min.js");
    assets.Libraries["DummyData"].Requires("MyUtilityScripts")
        .AddScript("~/Scripts/DummyData.js")
        .AddStyle("~/Content/DummyData.css");     

in the _layout page

@{
    var assets = Html.Assets();
    CurrentResources.AssignAllResources(assets);
    Html.Assets().RenderStyles()
}
</head>
...
    @Html.Assets().RenderScripts()
</body>

and in the partial(s) and views

Html.Assets().Libraries.Uses("DataTables");
Html.Assets().AddScript("~/Scripts/emailGridUtilities.js");

How to host a Node.Js application in shared hosting

A2 Hosting permits node.js on their shared hosting accounts. I can vouch that I've had a positive experience with them.

Here are instructions in their KnowledgeBase for installing node.js using Apache/LiteSpeed as a reverse proxy: https://www.a2hosting.com/kb/installable-applications/manual-installations/installing-node-js-on-managed-hosting-accounts . It takes about 30 minutes to set up the configuration, and it'll work with npm, Express, MySQL, etc.

See a2hosting.com.

How do I write a method to calculate total cost for all items in an array?

The total of 7 numbers in an array can be created as:

import java.util.*;
class Sum
{
   public static void main(String arg[])
   {
     int a[]=new int[7];
     int total=0;
     Scanner n=new Scanner(System.in);
     System.out.println("Enter the no. for total");

     for(int i=0;i<=6;i++) 
     {
       a[i]=n.nextInt();
       total=total+a[i];
      }
       System.out.println("The total is :"+total);
    }
}

Iterator over HashMap in Java

Can we see your import block? because it seems that you have imported the wrong Iterator class.

The one you should use is java.util.Iterator

To make sure, try:

java.util.Iterator iter = hm.keySet().iterator();

I personally suggest the following:

Map Declaration using Generics and declaration using the Interface Map<K,V> and instance creation using the desired implementation HashMap<K,V>

Map<Integer, String> hm = new HashMap<>();

and for the loop:

for (Integer key : hm.keySet()) {
    System.out.println("Key = " + key + " - " + hm.get(key));
}

UPDATE 3/5/2015

Found out that iterating over the Entry set will be better performance wise:

for (Map.Entry<Integer, String> entry : hm.entrySet()) {
    Integer key = entry.getKey();
    String value = entry.getValue();

}

UPDATE 10/3/2017

For Java8 and streams, your solution will be (Thanks @Shihe Zhang)

 hm.forEach((key, value) -> System.out.println(key + ": " + value))

How do I solve this "Cannot read property 'appendChild' of null" error?

Your condition id !== 0 will always be different that zero because you are assigning a string value. On pages where the element with id views_slideshow_controls_text_next_slideshow-block is not found, you will still try to append the img element, which causes the Cannot read property 'appendChild' of null error.

Instead of assigning a string value, you can assign the DOM element and verify if it exists within the page.

window.onload = function loadContIcons() {
    var elem = document.createElement("img");
    elem.src = "http://arno.agnian.com/sites/all/themes/agnian/images/up.png";
    elem.setAttribute("class", "up_icon");

    var container = document.getElementById("views_slideshow_controls_text_next_slideshow-block");
    if (container !== null) {
        container.appendChild(elem);
    } else console.log("aaaaa");

    var elem1 = document.createElement("img");
    elem1.src = "http://arno.agnian.com/sites/all/themes/agnian/images/down.png";
    elem1.setAttribute("class", "down_icon");

    container = document.getElementById("views_slideshow_controls_text_previous_slideshow-block");
    if (container !== null) {
        container.appendChild(elem1);
    } else console.log("aaaaa");
}

Drop view if exists

Regarding the error

'CREATE VIEW' must be the first statement in a query batch.

Microsoft SQL Server has a quirky reqirement that CREATE VIEW be the only statement in a batch. This is also true of a few other statements, such as CREATE FUNCTION. It is not true of CREATE TABLE, so go figure …

The solution is to send your script to the server in small batches. One way to do this is to select a single statement and execute it. This is clearly inconvenient.

The more convenient solution is to get the client to send the script in small isolated batches.

The GO keyword is not strictly an SQL command, which is why you can’t end it with a semicolon like real SQL commands. Instead it is an instruction to the client to break the script at this point and to send the portion as a batch.

As a result, you end up writing something like:

DROP VIEW IF EXISTS … ;
GO
CREATE VIEW … AS … ;
GO

None of the other database servers I have encountered (PostgreSQL, MySQL, Oracle, SQLite) have this quirk, so the requirement appears to be Microsoft Only.

ReferenceError: document is not defined (in plain JavaScript)

This happened with me because I was using Next JS which has server side rendering. When you are using server side rendering there is no browser. Hence, there will not be any variable window or document. Hence this error shows up.

Work around :

If you are using Next JS you can use the dynamic rendering to prevent server side rendering for the component.

import dynamic from 'next/dynamic'

const DynamicComponentWithNoSSR = dynamic(() => import('../components/List'), {
  ssr: false
})

export default () => <DynamicComponentWithNoSSR />

If you are using any other server side rendering library. Then add the code that you want to run at the client side in componentDidMount. If you are using React Hooks then use useEffects in the place of componentsDidMount.

import React, {useState, useEffects} from 'react';

const DynamicComponentWithNoSSR = <>Some JSX</>

export default function App(){

[a,setA] = useState();
useEffect(() => {
    setA(<DynamicComponentWithNoSSR/>)
  });


return (<>{a}<>)
}

References :

  1. https://nextjs.org/docs/advanced-features/dynamic-import#with-no-ssr
  2. https://reactjs.org/docs/hooks-effect.html

Array versus linked-list

While many of you have touched upon major adv./dis of linked list vs array, most of the comparisons are how one is better/ worse than the other.Eg. you can do random access in array but not possible in linked list and others. However, this is assuming link lists and array are going to be applied in a similar application. However a correct answer should be how link list would be preferred over array and vice-versa in a particular application deployment. Suppose you want to implement a dictionary application, what would you use ? Array : mmm it would allow easy retrieval through binary search and other search algo .. but lets think how link list can be better..Say you want to search "Blob" in dictionary. Would it make sense to have a link list of A->B->C->D---->Z and then each list element also pointing to an array or another list of all words starting with that letter ..

A -> B -> C -> ...Z
|    |    |
|    |    [Cat, Cave]
|    [Banana, Blob]
[Adam, Apple]

Now is the above approach better or a flat array of [Adam,Apple,Banana,Blob,Cat,Cave] ? Would it even be possible with array ? So a major advantage of link list is you can have an element not just pointing to the next element but also to some other link list/array/ heap/ or any other memory location. Array is a one flat contigous memory sliced into blocks size of the element it is going to store.. Link list on the other hand is a chunks of non-contigous memory units (can be any size and can store anything) and pointing to each other the way you want. Similarly lets say you are making a USB drive. Now would you like files to be saved as any array or as a link list ? I think you get the idea what I am pointing to :)

How do I convert a float to an int in Objective C?

what's wrong with:

int myInt = myFloat;

bear in mind this'll use the default rounding rule, which is towards zero (i.e. -3.9f becomes -3)

SMTP Connect() failed. Message was not sent.Mailer error: SMTP Connect() failed

If it works on your localhost but not on your web host:

Some hosting sites block certain outbound SMTP ports. Commenting out the line $mail->IsSMTP(); as noted in the accepted answer may make it work, but it is simply disabling your SMTP configuration, and using the hosting site's email config.

If you are using GoDaddy, there is no way to send mail using a different SMTP. I was using SiteGround, and found that they were allowing SMTP access from ports 25 and 465 only, with an SSL encryption type, so I would look up documentation for your host and go from there.

Fatal error: "No Target Architecture" in Visual Studio

Another reason for the error (amongst many others that cropped up when changing the target build of a Win32 project to X64) was not having the C++ 64 bit compilers installed as noted at the top of this page.
Further to philipvr's comment on child headers, (in my case) an explicit include of winnt.h being unnecessary when windows.h was being used.

SQL Server command line backup statement

You can use sqlcmd to run a backup, or any other T-SQL script. You can find the detailed instructions and examples on various useful sqlcmd switches in this article: Working with the SQL Server command line (sqlcmd)

How to explicitly obtain post data in Spring MVC?

Spring MVC runs on top of the Servlet API. So, you can use HttpServletRequest#getParameter() for this:

String value1 = request.getParameter("value1");
String value2 = request.getParameter("value2");

The HttpServletRequest should already be available to you inside Spring MVC as one of the method arguments of the handleRequest() method.

How to skip the first n rows in sql query

try below query it's work

SELECT * FROM `my_table` WHERE id != (SELECT id From my_table LIMIT 1)

Hope this will help

What's the difference between UTF-8 and UTF-8 without BOM?

The UTF-8 BOM is a sequence of bytes at the start of a text stream (0xEF, 0xBB, 0xBF) that allows the reader to more reliably guess a file as being encoded in UTF-8.

Normally, the BOM is used to signal the endianness of an encoding, but since endianness is irrelevant to UTF-8, the BOM is unnecessary.

According to the Unicode standard, the BOM for UTF-8 files is not recommended:

2.6 Encoding Schemes

... Use of a BOM is neither required nor recommended for UTF-8, but may be encountered in contexts where UTF-8 data is converted from other encoding forms that use a BOM or where the BOM is used as a UTF-8 signature. See the “Byte Order Mark” subsection in Section 16.8, Specials, for more information.

How can I know if Object is String type object?

 object instanceof Type

is true if the object is a Type or a subclass of Type

 object.getClass().equals(Type.class) 

is true only if the object is a Type

Add MIME mapping in web.config for IIS Express

Putting it in the "web.config" works fine. The problem was that I got the MIME type wrong. Instead of font/x-woff or font/x-font-woff it must be application/font-woff:

<system.webServer>
  ...
  <staticContent>
    <remove fileExtension=".woff" />
    <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
  </staticContent>
</system.webServer>

See also this answer regarding the MIME type: https://stackoverflow.com/a/5142316/135441

Update 4/10/2013

Spec is now a recommendation and the MIME type is officially: application/font-woff

What is useState() in React?

useState is one of build-in react hooks available in 0.16.7 version.

useState should be used only inside functional components. useState is the way if we need an internal state and don't need to implement more complex logic such as lifecycle methods.

const [state, setState] = useState(initialState);

Returns a stateful value, and a function to update it.

During the initial render, the returned state (state) is the same as the value passed as the first argument (initialState).

The setState function is used to update the state. It accepts a new state value and enqueues a re-render of the component.

Please note that useState hook callback for updating the state behaves differently than components this.setState. To show you the difference I prepared two examples.

_x000D_
_x000D_
class UserInfoClass extends React.Component {_x000D_
  state = { firstName: 'John', lastName: 'Doe' };_x000D_
  _x000D_
  render() {_x000D_
    return <div>_x000D_
      <p>userInfo: {JSON.stringify(this.state)}</p>_x000D_
      <button onClick={() => this.setState({ _x000D_
        firstName: 'Jason'_x000D_
      })}>Update name to Jason</button>_x000D_
    </div>;_x000D_
  }_x000D_
}_x000D_
_x000D_
// Please note that new object is created when setUserInfo callback is used_x000D_
function UserInfoFunction() {_x000D_
  const [userInfo, setUserInfo] = React.useState({ _x000D_
    firstName: 'John', lastName: 'Doe',_x000D_
  });_x000D_
_x000D_
  return (_x000D_
    <div>_x000D_
      <p>userInfo: {JSON.stringify(userInfo)}</p>_x000D_
      <button onClick={() => setUserInfo({ firstName: 'Jason' })}>Update name to Jason</button>_x000D_
    </div>_x000D_
  );_x000D_
}_x000D_
_x000D_
ReactDOM.render(_x000D_
  <div>_x000D_
    <UserInfoClass />_x000D_
    <UserInfoFunction />_x000D_
  </div>_x000D_
, document.querySelector('#app'));
_x000D_
<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>_x000D_
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>_x000D_
_x000D_
<div id="app"></div>
_x000D_
_x000D_
_x000D_

New object is created when setUserInfo callback is used. Notice we lost lastName key value. To fixed that we could pass function inside useState.

setUserInfo(prevState => ({ ...prevState, firstName: 'Jason' })

See example:

_x000D_
_x000D_
// Please note that new object is created when setUserInfo callback is used_x000D_
function UserInfoFunction() {_x000D_
  const [userInfo, setUserInfo] = React.useState({ _x000D_
    firstName: 'John', lastName: 'Doe',_x000D_
  });_x000D_
_x000D_
  return (_x000D_
    <div>_x000D_
      <p>userInfo: {JSON.stringify(userInfo)}</p>_x000D_
      <button onClick={() => setUserInfo(prevState => ({_x000D_
        ...prevState, firstName: 'Jason' }))}>_x000D_
        Update name to Jason_x000D_
      </button>_x000D_
    </div>_x000D_
  );_x000D_
}_x000D_
_x000D_
ReactDOM.render(_x000D_
    <UserInfoFunction />_x000D_
, document.querySelector('#app'));
_x000D_
<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>_x000D_
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>_x000D_
_x000D_
<div id="app"></div>
_x000D_
_x000D_
_x000D_

Unlike the setState method found in class components, useState does not automatically merge update objects. You can replicate this behavior by combining the function updater form with object spread syntax:

setState(prevState => {
  // Object.assign would also work
  return {...prevState, ...updatedValues};
});

For more about useState see official documentation.

jquery function val() is not equivalent to "$(this).value="?

One thing you can do is this:

$(this)[0].value = "Something";

This allows jQuery to return the javascript object for that element, and you can bypass jQuery Functions.

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in

mysql_fetch_array() expects parameter 1 to be resource boolean given in php error on server if you get this error : please select all privileges on your server. u will get the answer..

Favicon not showing up in Google Chrome

Cache

Clear your cache. http://support.google.com/chrome/bin/answer.py?hl=en&answer=95582 And test another browser.

Some where able to get an updated favicon by adding an URL parameter: ?v=1 after the link href which changes the resource link and therefore loads the favicon without cache (thanks @Stanislav).

<link rel="icon" type="image/x-icon" href="favicon.ico?v=2"  />

Favicon Usage

How did you import the favicon? How you should add it.

Normal favicon:

<link rel="icon" href="favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />

PNG/GIF favicon:

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

in the <head> Tag.

Chrome local problem

Another thing could be the problem that chrome can't display favicons, if it's local (not uploaded to a webserver). Only if the file/icon would be in the downloads directory chrome is allowed to load this data - more information about this can be found here: local (file://) website favicon works in Firefox, not in Chrome or Safari- why?

Renaming

Try to rename it from favicon.{whatever} to {yourfaviconname}.{whatever} but I would suggest you to still have the normal favicon. This has solved my issue on IE.

Base64 approach

Found another solution for this which works great! I simply added my favicon as Base64 Encoded Image directly inside the tag like this:

<link href="data:image/x-icon;base64,AAABAAIAEBAAAAEAIABoBAAAJgAAACAgAAABACAAqBAAAI4EAAAoAAAAEAAAACAAAAABACAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AIaDgv+Gg4L/hoOC/4aDgv+Gg4L/hoOC/4aDgv+Gg4L/hoOC/4aDgv////8A////AP///wD///8A////AP///wCGg4L/////AP///wD///8A////AP///wD///8A////AP///wCGg4L/////AP///wD///8A////AP///wD///8AhoOC/////wCGg4L/hoOC/4aDgv+Gg4L/hoOC/4aDgv////8AhoOC/////wD///8A////AP///wD///8A////AIaDgv////8A////AP///wD///8A////AP///wD///8A////AIaDgv////8A////AP///wD///8A////AP///wCGg4L/////AHCMqP9wjKj/cIyo/3CMqP9wjKj/cIyo/////wCGg4L/////AP///wD///8A////AP///wD///8AhoOC/////wBTlsIAU5bCAFOWwgBTlsIAU5bCM1OWwnP///8AhoOC/////wD///8A////AP///wD///8A////AP///wD///8AU5bCBlOWwndTlsLHU5bC+FOWwv1TlsLR////AP///wD///8A////AP///wD///8A////AP///wD///8A////AFOWwvtTlsLuU5bCu1OWwlc2k9cANpPXqjaT19H///8A////AP///wD///8A////AP///wD///8A////AP///wBTlsIGNpPXADaT1wA2k9dINpPX8TaT1+40ktpDH4r2tB+K9hL///8A////AP///wD///8A////AP///wD///8A////ADaT1wY2k9e7NpPX/TaT16AfivYGH4r23R+K9u4tg/WQLoL1mP///wD///8A////AP///wD///8A////AP///wA2k9fuNpPX5zaT1zMfivYGH4r23R+K9uwjiPYXLoL1+S6C9W7///8A////AP///wD///8A////AP///wD///8ANpPXLjaT1wAfivYGH4r22x+K9usfivYSLoL1oC6C9esugvUA////AP///wD///8A////AP///wD///8A////AP///wD///8AH4r2zx+K9usfivYSLoL1DC6C9fwugvVXLoL1AP///wD///8A////AP///wD///8A////AP///wD///8A////AB+K9kgfivYMH4r2AC6C9bEugvXhLoL1AC6C9QD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAugvXyLoL1SC6C9QAugvUA////AP//AADgBwAA7/cAAOgXAADv9wAA6BcAAO+XAAD4HwAA+E8AAPsDAAD8AQAA/AEAAP0DAAD/AwAA/ycAAP/nAAAoAAAAIAAAAEAAAAABACAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/////wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AISEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP////8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP////8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/////wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/////wD///8AhISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP8AAAAA////AISEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AISEhP+EhIT/////AP///wCEhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/wAAAAD///8AhISE/4SEhP////8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP/4+vsA4ujuAOLo7gDi6O4A4ujuAN3k6wDZ4OgA2eDoANng6ADZ4OgA2eDoANng6ADW3uYAJS84APj6+wCEhIT/hISE/////wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/9Xd5QBwjKgAcIyoRnCMqGRwjKhxcIyogHCMqI9wjKidcIyoq3CMqLlwjKjHcIyo1HCMqLhogpwA/f7+AISEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AISEhP+EhIT/xtHcAHCMqABwjKjAcIyo/3CMqP9wjKj/cIyo/3CMqP9wjKj/cIyo/3CMqP9wjKj/cIyo4EdZawD///8AhISE/4SEhP////8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP+2xNMAcIyoAHCMqJhwjKjPcIyowHCMqLFwjKijcoymlXSMpIh0jKR6co2mbG+OqGFqj61zXZO4AeXv9gCEhIT/hISE/////wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/6i5ygDF0dwAIiozACQyPQAoP1AALlBmADhlggBblLkGVJbBPFOWwnxTlsK5U5bC9FOWwv9TlsIp3erzAISEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAALztHAAAAAAAuU2sAU5bCClOWwkNTlsKAU5bCwFOWwvhTlsL/U5bC/1OWwv9TlsL/U5bC/ViVvVcXOFAAAAAAAAAAAAD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AAAAAAAAAAAALDhEALVFoAFOWwjpTlsL6U5bC/1OWwv9TlsL/U5bC/1OWwvxTlsLIV5W+i2CRs0xHi71TKYzUnyuM0gIJHi4AAAAAAAAAAAAAAAAA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAAAAACtNZABTlsIAU5bCD1OWwv1TlsL6U5bCxFOWwoRVlsBHZJKwDCNObAA8icJAKYzUwimM1P8pjNT/KYzUWCaCxgALLUsAAAAAAAAAAAD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAApS2EAU5bCAFOWwgBTlsIAU5bCNVOWwgg+cJEAIT1QABU/XQA1isg4KYzUuymM1P8pjNT/KYzU/ymM1LAti9E0JYvmDhdouAAAAAAAAAAAAP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AFyk1AE+PuQBTlsIAU5bCAER7nwAmRVoADBojABRFaQAwi80xKYzUsymM1P8pjNT/KYzU/ymM1LgsjNE2MovXFB+K9MUfivbBH4r2BgcdNAARQH8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAQIDABIgKgAPGiIABRMcABdQeQAti9AqKYzUrCmM1P8pjNT/KYzU/ymM1MAqjNM9HmqmACWK7SIfivbZH4r2/x+K9vsuiudAFE2YACB69AD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAABhQfABtejgAoitEAKYzUACmM1JQpjNT/KYzU/ymM1MgpjNREH2mgABlosQAfivY0H4r26R+K9v8fivbyKIrtR0CB1SggevTQIHr0Nv///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AAAAAAAAAAAACBwsAJX2+ACmM1AApjNQAKYzUGSmM1MYpjNRMInWxABNHdQAcfuEAH4r2Sx+K9vUfivb/H4r25iGK9DE2gt4EIHr0yyB69P8gevTQ////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAAAAAAAAAAAOMUsAKYzUACmM1AApjNQAJX6/ABE7WgAUWJwAH4r2AB+K9mYfivb9H4r2/x+K9tYfivYfG27RACB69HsgevT/IHr0+yB69DL///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAAAAAAAAAAAAAfaJ4AJ4XKABVGagAKKkoAG3raAB+K9gEfivaEH4r2/x+K9v8fivbCH4r2EB133wAgevQsIHr0+SB69P8gevSAIHr0AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AAAAAAAAAAAAAAAAAAAAAAAUSGwAFERwAElCOAB+J9QAfivYAH4r2lx+K9v8fivb/H4r2qR+K9gYefuoAIHr0BSB69M4gevT/IHr00CB69AUgevQA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAkqSgAfivYAH4r2AB+K9gAfivZLH4r2/R+K9osfivYBH4PwACB69AAgevSAIHr0/yB69PkgevQwIHr0ACB69AD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAAAAAAAAAAAAAAAAAAEEiAAB+K9gAfivYAH4r2AB+K9gAfivYsH4r2AB+G8wAge/QAIHr0MCB69PsgevT/IHr0eyB69AAgevQAIHr0AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AAAAAAAAAAAAAAAAAAAAAAAAAAAAXZrYAH4r2AB+K9gAfivYAH4r2AB+K9gAfifUAIHz0ACB69AcgevTQIHr0/yB69MwgevQEIHr0ACB69AAgevQA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAAAAAAAAAAAAAAAAAAIDAB6E6gAfivYAH4r2AB+K9gAfivYAH4r2ACB+9QAgevQAIHr0fCB69P8gevT5IHr0LCB69AAgevQAIHr0ACB69AD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAAAAAAAAAAAAABBAcAEUqDAB6E6wAfivYAH4r2AB+K9gAggPUAIHr0ACB69AAgevQTIHr0qCB69HYgevQAIHr0ACB69AAgevQAIHr0AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP////////////////wAAH/8AAB//P/+f/z//n/8wAZ//MAGf/z//n/8wAZ//MAGf/zAAn/8/gJ//+AD///AAf//wEH//+cA///8AH//8BB///BgH//xwB///4If//4EP//+CD///hh///9w////4P///+H////j////////////" rel="icon" type="image/x-icon" />

Used this page here for this: http://www.motobit.com/util/base64-decoder-encoder.asp

Generate favicons

I can really suggest you this page: http://www.favicon-generator.org/ to create all types of favicons you need.

Using Excel VBA to run SQL query

Below is code that I currently use to pull data from a MS SQL Server 2008 into VBA. You need to make sure you have the proper ADODB reference [VBA Editor->Tools->References] and make sure you have Microsoft ActiveX Data Objects 2.8 Library checked, which is the second from the bottom row that is checked (I'm using Excel 2010 on Windows 7; you might have a slightly different ActiveX version, but it will still begin with Microsoft ActiveX):

References required for SQL

Sub Module for Connecting to MS SQL with Remote Host & Username/Password

Sub Download_Standard_BOM()
'Initializes variables
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String

'Setup the connection string for accessing MS SQL database
   'Make sure to change:
       '1: PASSWORD
       '2: USERNAME
       '3: REMOTE_IP_ADDRESS
       '4: DATABASE
    ConnectionString = "Provider=SQLOLEDB.1;Password=PASSWORD;Persist Security Info=True;User ID=USERNAME;Data Source=REMOTE_IP_ADDRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DATABASE"

    'Opens connection to the database
    cnn.Open ConnectionString
    'Timeout error in seconds for executing the entire query; this will run for 15 minutes before VBA timesout, but your database might timeout before this value
    cnn.CommandTimeout = 900

    'This is your actual MS SQL query that you need to run; you should check this query first using a more robust SQL editor (such as HeidiSQL) to ensure your query is valid
    StrQuery = "SELECT TOP 10 * FROM tbl_table"

    'Performs the actual query
    rst.Open StrQuery, cnn
    'Dumps all the results from the StrQuery into cell A2 of the first sheet in the active workbook
    Sheets(1).Range("A2").CopyFromRecordset rst
End Sub

Assign an initial value to radio button as checked

You can use the checked attribute for this:

<input type="radio" checked="checked">

What is a thread exit code?

As Sayse mentioned, exit code 259 (0x103) has special meaning, in this case the process being debugged is still running.

I saw this a lot with debugging web services, because the thread continues to run after executing each web service call (as it is still listening for further calls).

How do I specify C:\Program Files without a space in it for programs that can't handle spaces in file paths?

The Windows shell (assuming you're using CMD.exe) uses %ProgramFiles% to point to the Program Files folder, no matter where it is. Since the default Windows file opener accounts for environment variables like this, if the program was well-written, it should support this.

Also, it could be worth using relative addresses. If the program you're using is installed correctly, it should already be in the Program Files folder, so you could just refer to the configuration file as .\config_file.txt if its in the same directory as the program, or ..\other_program\config_file.txt if its in a directory different than the other program. This would apply not only on Windows but on almost every modern operating system, and will work properly if you have the "Start In" box properly set, or you run it directly from its folder.

Does IMDB provide an API?

Here is a Python module providing API's to get data from IMDB website

http://techdiary-viki.blogspot.com/2011/03/imdb-api.html

Why are my PowerShell scripts not running?

We can bypass execution policy in a nice way (inside command prompt):

type file.ps1 | powershell -command -

Or inside powershell:

gc file.ps1|powershell -c -

How to set selected value on select using selectpicker plugin from bootstrap

Well another way to do it is, with this keyword, you can simply get the object in this and manipulate it's value. Eg :

$("select[name=selValue]").click(
    function() {
        $(this).val(1);
    });

AngularJS $http, CORS and http authentication

For making a CORS request one must add headers to the request along with the same he needs to check of mode_header is enabled in Apache.

For enabling headers in Ubuntu:

sudo a2enmod headers

For php server to accept request from different origin use:

Header set Access-Control-Allow-Origin *
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"

Login to Microsoft SQL Server Error: 18456

you can do in linux for mssql change password for sa account

sudo /opt/mssql/bin/mssql-conf setup

The license terms for this product can be downloaded from
 http://go.microsoft.com/fwlink/?LinkId=746388 Jump Jump
and found in /usr/share/doc/mssql-server/LICENSE.TXT.
Do you accept the license terms? [Yes/No]:yes
  Setting up Microsoft SQL Server
Enter the new SQL Server system administrator password:  --Enter strong password
Confirm the new SQL Server system administrator password: --Enter strong password
 starting Microsoft SQL Server...
 Enabling Microsoft SQL Server to run at boot...
Setup completed successfully.

Vertical alignment of text and icon in button

Alternativly if your using bootstrap then you can just add align-middle to vertical align the element.

<button id="whaever" class="btn btn-large btn-primary" style="padding: 20px;" name="Continue" type="submit">Continue
    <i class="icon-ok align-middle" style="font-size:40px;"></i>
</button>

How to override trait function and call it from the overridden function?

Your last one was almost there:

trait A {
    function calc($v) {
        return $v+1;
    }
}

class MyClass {
    use A {
        calc as protected traitcalc;
    }

    function calc($v) {
        $v++;
        return $this->traitcalc($v);
    }
}

The trait is not a class. You can't access its members directly. It's basically just automated copy and paste...

Is 'bool' a basic datatype in C++?

Allthough it's now a native type, it's still defined behind the scenes as an integer (int I think) where the literal false is 0 and true is 1. But I think all logic still consider anything but 0 as true, so strictly speaking the true literal is probably a keyword for the compiler to test if something is not false.

if(someval == true){

probably translates to:

if(someval !== false){ // e.g. someval !== 0

by the compiler

FFmpeg: How to split video efficiently?

In my experience, don't use ffmpeg for splitting/join. MP4Box, is faster and light than ffmpeg. Please tryit. Eg if you want to split a 1400mb MP4 file into two parts a 700mb you can use the following cmdl: MP4Box -splits 716800 input.mp4 eg for concatenating two files you can use:

MP4Box -cat file1.mp4 -cat file2.mp4 output.mp4

Or if you need split by time, use -splitx StartTime:EndTime:

MP4Box -add input.mp4 -splitx 0:15 -new split.mp4

line breaks in a textarea

My recommendation is to save the data to database with Line breaks instead parsing it with nl2br. You should use nl2br in output not input.

For your question, you can use php or javascript:

PHP:

str_replace('<br />', "\n", $textarea);

jQuery:

$('#myTextArea').val($('#myTextArea').val().replace(@<br />@, "\N"));

How to declare a global variable in JavaScript

If this is the only application where you're going to use this variable, Felix's approach is excellent. However, if you're writing a jQuery plugin, consider "namespacing" (details on the quotes later...) variables and functions needed under the jQuery object. For example, I'm currently working on a jQuery popup menu that I've called miniMenu. Thus, I've defined a "namespace" miniMenu under jQuery, and I place everything there.

The reason I use quotes when I talk about JavaScript namespaces is that they aren't really namespaces in the normal sense. Instead, I just use a JavaScript object and place all my functions and variables as properties of this object.

Also, for convenience, I usually sub-space the plugin namespace with an i namespace for stuff that should only be used internally within the plugin, so as to hide it from users of the plugin.

This is how it works:

// An object to define utility functions and global variables on:
$.miniMenu = new Object();
// An object to define internal stuff for the plugin:
$.miniMenu.i = new Object();

Now I can just do $.miniMenu.i.globalVar = 3 or $.miniMenu.i.parseSomeStuff = function(...) {...} whenever I need to save something globally, and I still keep it out of the global namespace.

Fit Image into PictureBox

Use the following lines of codes and you will find the solution...

pictureBox1.ImageLocation = @"C:\Users\Desktop\mypicture.jpg";
pictureBox1.SizeMode =PictureBoxSizeMode.StretchImage;

Html.DropdownListFor selected value not being set

I had a similar issue, I was using the ViewBag and Element name as same. (Typing mistake)

How can I tell jaxb / Maven to generate multiple schema packages?

I encountered a lot of problems when using jaxb in Maven but i managed to solve your problem by doing the following

First create a schema.xjc file

<?xml version="1.0" encoding="UTF-8"?>
<jaxb:bindings xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
               xmlns:xsd="http://www.w3.org/2001/XMLSchema"
               jaxb:version="2.0">
    <jaxb:bindings schemaLocation="YOUR_URL?wsdl#types?schema1">
        <jaxb:schemaBindings>
            <jaxb:package name="your.package.name.schema1"/>
        </jaxb:schemaBindings>
    </jaxb:bindings>
    <jaxb:bindings schemaLocation="YOUR_URL??wsdl#types?schema2">
        <jaxb:schemaBindings>
            <jaxb:package name="your.package.name.schema2"/>
        </jaxb:schemaBindings>
    </jaxb:bindings>
</jaxb:bindings>

The package name can be anything you want it to be, as long as it doesn't contain any reserved keywords in Java

Next you have to create the wsimport.bat script to generate your packaged and code at the preferred location.

cd C:\YOUR\PATH\TO\PLACE\THE\PACKAGES
wsimport -keep -verbose -b "C:\YOUR\PATH\TO\schema.xjb" YOUR_URL?wsdl
pause

If you do not want to use cd, you can put the wsimport.bat in "C:\YOUR\PATH\TO\PLACE\THE\PACKAGES"

If you run it without -keep -verbose it will only generate the packages but not the .java files.

The -b will make sure the schema.xjc is used when generating

Finding first blank row, then writing to it

Function firstBlankRow() As Long
Dim emptyCells As Boolean

    For Each rowinC In Sheet7.Range("A" & currentEmptyRow & ":A5000")   ' (row,col)

        If rowinC.Value = "" Then
            currentEmptyRow = rowinC.row
            'firstBlankRow = rowinC.row 'define class variable to simplify computing complexity for other functions i.e. no need to call function again
            Exit Function   
        End If
    Next

End Function

Extract source code from .jar file

-Covert .jar file to .zip (In windows just change the extension) -Unzip the .zip folder -You will get complete .java files

Is it possible to use raw SQL within a Spring Repository

It is also possible to use Spring Data JDBC repository, which is a community project built on top of Spring Data Commons to access to databases with raw SQL, without using JPA.

It is less powerful than Spring Data JPA, but if you want lightweight solution for simple projects without using a an ORM like Hibernate, that a solution worth to try.

Using putty to scp from windows to Linux

Use scp priv_key.pem source user@host:target if you need to connect using a private key.

or if using pscp then use pscp -i priv_key.ppk source user@host:target

DynamoDB vs MongoDB NoSQL

I know this is old, but it still comes up when you search for the comparison. We were using Mongo, have moved almost entirely to Dynamo, which is our first choice now. Not because it has more features, it doesn't. Mongo has a better query language, you can index within a structure, there's lots of little things. The superiority of Dynamo is in what the OP stated in his comment: it's easy. You don't have to take care of any servers. When you start to set up a Mongo sharded solution, it gets complicated. You can go to one of the hosting companies, but that's not cheap either. With Dynamo, if you need more throughput, you just click a button. You can write scripts to scale automatically. When it's time to upgrade Dynamo, it's done for you. That is all a lot of precious stress and time not spent. If you don't have dedicated ops people, Dynamo is excellent.

So we are now going on Dynamo by default. Mongo maybe, if the data structure is complicated enough to warrant it, but then we'd probably go back to a SQL database. Dynamo is obtuse, you really need to think about how you're going to build it, and likely you'll use Redis in Elasticcache to make it work for complex stuff. But it sure is nice to not have to take care of it. You code. That's it.

If a folder does not exist, create it

Use the below code. I use this code for file copy and creating a new folder.

string fileToCopy = "filelocation\\file_name.txt";
String server = Environment.UserName;
string newLocation = "C:\\Users\\" + server + "\\Pictures\\Tenders\\file_name.txt";
string folderLocation = "C:\\Users\\" + server + "\\Pictures\\Tenders\\";
bool exists = System.IO.Directory.Exists(folderLocation);

if (!exists)
{
   System.IO.Directory.CreateDirectory(folderLocation);
   if (System.IO.File.Exists(fileToCopy))
   {
     MessageBox.Show("file copied");
     System.IO.File.Copy(fileToCopy, newLocation, true);
   }
   else
   {
      MessageBox.Show("no such files");
   }
}

C - error: storage size of ‘a’ isn’t known

1)declare the structs before the main function. it worked for me. 2) And also fix the spelling mistake of that variable name if any e

Converting time stamps in excel to dates

This worked for me:

=(col_name]/60/60/24)+(col_name-1)

CSS for the "down arrow" on a <select> element?

You can achieve this with just CSS and your down arrow as an image positioned absolute with a "pointer-events: none;" see my example below:

<select>
  <option value="1">1 Person</option>
  <option value="2">2 People</option>
</select>
<img class="passthrough" src="downarrow.png" />

.passthrough {
    pointer-events: none;
    position: absolute;
    right: 0;
}

nil detection in Go

I have created some sample code which creates new variables using a variety of ways that I can think of. It looks like the first 3 ways create values, and the last two create references.

package main

import "fmt"

type Config struct {
    host string
    port float64
}

func main() {
    //value
    var c1 Config
    c2 := Config{}
    c3 := *new(Config)

    //reference
    c4 := &Config{}
    c5 := new(Config)

    fmt.Println(&c1 == nil)
    fmt.Println(&c2 == nil)
    fmt.Println(&c3 == nil)
    fmt.Println(c4 == nil)
    fmt.Println(c5 == nil)

    fmt.Println(c1, c2, c3, c4, c5)
}

which outputs:

false
false
false
false
false
{ 0} { 0} { 0} &{ 0} &{ 0}

How do I obtain the frequencies of each value in an FFT?

Take a look at my answer here.

Answer to comment:

The FFT actually calculates the cross-correlation of the input signal with sine and cosine functions (basis functions) at a range of equally spaced frequencies. For a given FFT output, there is a corresponding frequency (F) as given by the answer I posted. The real part of the output sample is the cross-correlation of the input signal with cos(2*pi*F*t) and the imaginary part is the cross-correlation of the input signal with sin(2*pi*F*t). The reason the input signal is correlated with sin and cos functions is to account for phase differences between the input signal and basis functions.

By taking the magnitude of the complex FFT output, you get a measure of how well the input signal correlates with sinusoids at a set of frequencies regardless of the input signal phase. If you are just analyzing frequency content of a signal, you will almost always take the magnitude or magnitude squared of the complex output of the FFT.

The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties

Another solution could be:

var eventsCustom = eventCustomRepository.FindAllEventsCustomByUniqueStudentReference(userDevice.UniqueStudentReference).AsEnumerable()
   .Where(x => x.DateTimeStart.Date == currentDate.Date).AsQueryable();

Java image resize, maintain aspect ratio

I have found the selected answer to have problems with upscaling, and so I have made (yet) another version (which I have tested):

public static Point scaleFit(Point src, Point bounds) {
  int newWidth = src.x;
  int newHeight = src.y;
  double boundsAspectRatio = bounds.y / (double) bounds.x;
  double srcAspectRatio = src.y / (double) src.x;

  // first check if we need to scale width
  if (boundsAspectRatio < srcAspectRatio) {
    // scale width to fit
    newWidth = bounds.x;
    //scale height to maintain aspect ratio
    newHeight = (newWidth * src.y) / src.x;
  } else {
    //scale height to fit instead
    newHeight = bounds.y;
    //scale width to maintain aspect ratio
    newWidth = (newHeight * src.x) / src.y;
  }

  return new Point(newWidth, newHeight);
}

Written in Android terminology :-)

as for the tests:

@Test public void scaleFit() throws Exception {
  final Point displaySize = new Point(1080, 1920);
  assertEquals(displaySize, Util.scaleFit(displaySize, displaySize));
  assertEquals(displaySize, Util.scaleFit(new Point(displaySize.x / 2, displaySize.y / 2), displaySize));
  assertEquals(displaySize, Util.scaleFit(new Point(displaySize.x * 2, displaySize.y * 2), displaySize));
  assertEquals(new Point(displaySize.x, displaySize.y * 2), Util.scaleFit(new Point(displaySize.x / 2, displaySize.y), displaySize));
  assertEquals(new Point(displaySize.x * 2, displaySize.y), Util.scaleFit(new Point(displaySize.x, displaySize.y / 2), displaySize));
  assertEquals(new Point(displaySize.x, displaySize.y * 3 / 2), Util.scaleFit(new Point(displaySize.x / 3, displaySize.y / 2), displaySize));
}

Generating a drop down list of timezones with PHP

I wanted to have something simpler for my users, the way Google does it..

$timezones = [
    "AF" => [
        "name" => "Afghanistan" 
    ],
    "AL" => [
        "name" => "Albania" 
    ],
    "DZ" => [
        "name" => "Algeria" 
    ],
    "AS" => [
        "name" => "American Samoa" 
    ],
    "AD" => [
        "name" => "Andorra" 
    ],
    "AQ" => [
        "name" => "Antarctica" 
    ],
    "AG" => [
        "name" => "Antigua & Barbuda" 
    ],
    "AR" => [
        "name" => "Argentina" 
    ],
    "AM" => [
        "name" => "Armenia" 
    ],
    "AU" => [
        "name" => "Australia" 
    ],
    "AT" => [
        "name" => "Austria" 
    ],
    "AZ" => [
        "name" => "Azerbaijan" 
    ],
    "BS" => [
        "name" => "Bahamas" 
    ],
    "BD" => [
        "name" => "Bangladesh" 
    ],
    "BB" => [
        "name" => "Barbados" 
    ],
    "BY" => [
        "name" => "Belarus" 
    ],
    "BE" => [
        "name" => "Belgium" 
    ],
    "BZ" => [
        "name" => "Belize" 
    ],
    "BM" => [
        "name" => "Bermuda" 
    ],
    "BT" => [
        "name" => "Bhutan" 
    ],
    "BO" => [
        "name" => "Bolivia" 
    ],
    "BA" => [
        "name" => "Bosnia & Herzegovina" 
    ],
    "BR" => [
        "name" => "Brazil" 
    ],
    "IO" => [
        "name" => "British Indian Ocean Territory" 
    ],
    "BN" => [
        "name" => "Brunei" 
    ],
    "BG" => [
        "name" => "Bulgaria" 
    ],
    "CA" => [
        "name" => "Canada" 
    ],
    "CV" => [
        "name" => "Cape Verde" 
    ],
    "KY" => [
        "name" => "Cayman Islands" 
    ],
    "TD" => [
        "name" => "Chad" 
    ],
    "CL" => [
        "name" => "Chile" 
    ],
    "CN" => [
        "name" => "China" 
    ],
    "CX" => [
        "name" => "Christmas Island" 
    ],
    "CC" => [
        "name" => "Cocos (Keeling) Islands" 
    ],
    "CO" => [
        "name" => "Colombia" 
    ],
    "CK" => [
        "name" => "Cook Islands" 
    ],
    "CR" => [
        "name" => "Costa Rica" 
    ],
    "CI" => [
        "name" => "Côte d’Ivoire" 
    ],
    "HR" => [
        "name" => "Croatia" 
    ],
    "CU" => [
        "name" => "Cuba" 
    ],
    "CW" => [
        "name" => "Curaçao" 
    ],
    "CY" => [
        "name" => "Cyprus" 
    ],
    "CZ" => [
        "name" => "Czech Republic" 
    ],
    "DK" => [
        "name" => "Denmark" 
    ],
    "DO" => [
        "name" => "Dominican Republic" 
    ],
    "EC" => [
        "name" => "Ecuador" 
    ],
    "EG" => [
        "name" => "Egypt" 
    ],
    "SV" => [
        "name" => "El Salvador" 
    ],
    "EE" => [
        "name" => "Estonia" 
    ],
    "FK" => [
        "name" => "Falkland Islands (Islas Malvinas)" 
    ],
    "FO" => [
        "name" => "Faroe Islands" 
    ],
    "FJ" => [
        "name" => "Fiji" 
    ],
    "FI" => [
        "name" => "Finland" 
    ],
    "FR" => [
        "name" => "France" 
    ],
    "GF" => [
        "name" => "French Guiana" 
    ],
    "PF" => [
        "name" => "French Polynesia" 
    ],
    "TF" => [
        "name" => "French Southern Territories" 
    ],
    "GE" => [
        "name" => "Georgia" 
    ],
    "DE" => [
        "name" => "Germany" 
    ],
    "GH" => [
        "name" => "Ghana" 
    ],
    "GI" => [
        "name" => "Gibraltar" 
    ],
    "GR" => [
        "name" => "Greece" 
    ],
    "GL" => [
        "name" => "Greenland" 
    ],
    "GU" => [
        "name" => "Guam" 
    ],
    "GT" => [
        "name" => "Guatemala" 
    ],
    "GW" => [
        "name" => "Guinea-Bissau" 
    ],
    "GY" => [
        "name" => "Guyana" 
    ],
    "HT" => [
        "name" => "Haiti" 
    ],
    "HN" => [
        "name" => "Honduras" 
    ],
    "HK" => [
        "name" => "Hong Kong" 
    ],
    "HU" => [
        "name" => "Hungary" 
    ],
    "IS" => [
        "name" => "Iceland" 
    ],
    "IN" => [
        "name" => "India" 
    ],
    "ID" => [
        "name" => "Indonesia" 
    ],
    "IR" => [
        "name" => "Iran" 
    ],
    "IQ" => [
        "name" => "Iraq" 
    ],
    "IE" => [
        "name" => "Ireland" 
    ],
    "IL" => [
        "name" => "Israel" 
    ],
    "IT" => [
        "name" => "Italy" 
    ],
    "JM" => [
        "name" => "Jamaica" 
    ],
    "JP" => [
        "name" => "Japan" 
    ],
    "JO" => [
        "name" => "Jordan" 
    ],
    "KZ" => [
        "name" => "Kazakhstan" 
    ],
    "KE" => [
        "name" => "Kenya" 
    ],
    "KI" => [
        "name" => "Kiribati" 
    ],
    "KG" => [
        "name" => "Kyrgyzstan" 
    ],
    "LV" => [
        "name" => "Latvia" 
    ],
    "LB" => [
        "name" => "Lebanon" 
    ],
    "LR" => [
        "name" => "Liberia" 
    ],
    "LY" => [
        "name" => "Libya" 
    ],
    "LT" => [
        "name" => "Lithuania" 
    ],
    "LU" => [
        "name" => "Luxembourg" 
    ],
    "MO" => [
        "name" => "Macau" 
    ],
    "MK" => [
        "name" => "Macedonia (FYROM)" 
    ],
    "MY" => [
        "name" => "Malaysia" 
    ],
    "MV" => [
        "name" => "Maldives" 
    ],
    "MT" => [
        "name" => "Malta" 
    ],
    "MH" => [
        "name" => "Marshall Islands" 
    ],
    "MQ" => [
        "name" => "Martinique" 
    ],
    "MU" => [
        "name" => "Mauritius" 
    ],
    "MX" => [
        "name" => "Mexico" 
    ],
    "FM" => [
        "name" => "Micronesia" 
    ],
    "MD" => [
        "name" => "Moldova" 
    ],
    "MC" => [
        "name" => "Monaco" 
    ],
    "MN" => [
        "name" => "Mongolia" 
    ],
    "MA" => [
        "name" => "Morocco" 
    ],
    "MZ" => [
        "name" => "Mozambique" 
    ],
    "MM" => [
        "name" => "Myanmar (Burma)" 
    ],
    "NA" => [
        "name" => "Namibia" 
    ],
    "NR" => [
        "name" => "Nauru" 
    ],
    "NP" => [
        "name" => "Nepal" 
    ],
    "NL" => [
        "name" => "Netherlands" 
    ],
    "NC" => [
        "name" => "New Caledonia" 
    ],
    "NZ" => [
        "name" => "New Zealand" 
    ],
    "NI" => [
        "name" => "Nicaragua" 
    ],
    "NG" => [
        "name" => "Nigeria" 
    ],
    "NU" => [
        "name" => "Niue" 
    ],
    "NF" => [
        "name" => "Norfolk Island" 
    ],
    "KP" => [
        "name" => "North Korea" 
    ],
    "MP" => [
        "name" => "Northern Mariana Islands" 
    ],
    "NO" => [
        "name" => "Norway" 
    ],
    "PK" => [
        "name" => "Pakistan" 
    ],
    "PW" => [
        "name" => "Palau" 
    ],
    "PS" => [
        "name" => "Palestine" 
    ],
    "PA" => [
        "name" => "Panama" 
    ],
    "PG" => [
        "name" => "Papua New Guinea" 
    ],
    "PY" => [
        "name" => "Paraguay" 
    ],
    "PE" => [
        "name" => "Peru" 
    ],
    "PH" => [
        "name" => "Philippines" 
    ],
    "PN" => [
        "name" => "Pitcairn Islands" 
    ],
    "PL" => [
        "name" => "Poland" 
    ],
    "PT" => [
        "name" => "Portugal" 
    ],
    "PR" => [
        "name" => "Puerto Rico" 
    ],
    "QA" => [
        "name" => "Qatar" 
    ],
    "RE" => [
        "name" => "Réunion" 
    ],
    "RO" => [
        "name" => "Romania" 
    ],
    "RU" => [
        "name" => "Russia" 
    ],
    "WS" => [
        "name" => "Samoa" 
    ],
    "SM" => [
        "name" => "San Marino" 
    ],
    "SA" => [
        "name" => "Saudi Arabia" 
    ],
    "RS" => [
        "name" => "Serbia" 
    ],
    "SC" => [
        "name" => "Seychelles" 
    ],
    "SG" => [
        "name" => "Singapore" 
    ],
    "SK" => [
        "name" => "Slovakia" 
    ],
    "SI" => [
        "name" => "Slovenia" 
    ],
    "SB" => [
        "name" => "Solomon Islands" 
    ],
    "ZA" => [
        "name" => "South Africa" 
    ],
    "GS" => [
        "name" => "South Georgia & South Sandwich Islands" 
    ],
    "KR" => [
        "name" => "South Korea" 
    ],
    "ES" => [
        "name" => "Spain" 
    ],
    "LK" => [
        "name" => "Sri Lanka" 
    ],
    "PM" => [
        "name" => "St. Pierre & Miquelon" 
    ],
    "SD" => [
        "name" => "Sudan" 
    ],
    "SR" => [
        "name" => "Suriname" 
    ],
    "SJ" => [
        "name" => "Svalbard & Jan Mayen" 
    ],
    "SE" => [
        "name" => "Sweden" 
    ],
    "CH" => [
        "name" => "Switzerland" 
    ],
    "SY" => [
        "name" => "Syria" 
    ],
    "TW" => [
        "name" => "Taiwan" 
    ],
    "TJ" => [
        "name" => "Tajikistan" 
    ],
    "TH" => [
        "name" => "Thailand" 
    ],
    "TL" => [
        "name" => "Timor-Leste" 
    ],
    "TK" => [
        "name" => "Tokelau" 
    ],
    "TO" => [
        "name" => "Tonga" 
    ],
    "TT" => [
        "name" => "Trinidad & Tobago" 
    ],
    "TN" => [
        "name" => "Tunisia" 
    ],
    "TR" => [
        "name" => "Turkey" 
    ],
    "TM" => [
        "name" => "Turkmenistan" 
    ],
    "TC" => [
        "name" => "Turks & Caicos Islands" 
    ],
    "TV" => [
        "name" => "Tuvalu" 
    ],
    "UM" => [
        "name" => "U.S. Outlying Islands" 
    ],
    "UA" => [
        "name" => "Ukraine" 
    ],
    "AE" => [
        "name" => "United Arab Emirates" 
    ],
    "GB" => [
        "name" => "United Kingdom" 
    ],
    "US" => [
        "name" => "United States" 
    ],
    "UY" => [
        "name" => "Uruguay" 
    ],
    "UZ" => [
        "name" => "Uzbekistan" 
    ],
    "VU" => [
        "name" => "Vanuatu" 
    ],
    "VA" => [
        "name" => "Vatican City" 
    ],
    "VE" => [
        "name" => "Venezuela" 
    ],
    "VN" => [
        "name" => "Vietnam" 
    ],
    "WF" => [
        "name" => "Wallis & Futuna" 
    ],
    "EH" => [
        "name" => "Western Sahara" 
    ],
];

// taken from Toland Hon's Answer
function prettyOffset($offset) {
    $offset_prefix = $offset < 0 ? '-' : '+';
    $offset_formatted = gmdate( 'H:i', abs($offset) );

    $pretty_offset = "UTC${offset_prefix}${offset_formatted}";

    return $pretty_offset;
}

foreach ($timezones as $k => $v) {
    $tz = DateTimeZone::listIdentifiers(DateTimeZone::PER_COUNTRY, $k);

    foreach ($tz as $value) {
        $t = new DateTimeZone($value);
        $offset = (new DateTime("now", $t))->getOffset();
        $timezones[$k]['timezones'][$value] = prettyOffset($offset);
    }   
}

This gives me an array grouped by countries:

["US"]=>
  array(2) {
    ["name"]=>
    string(13) "United States"
    ["timezones"]=>
    array(29) {
      ["America/Adak"]=>
      string(9) "UTC-10:00"
      ["America/Anchorage"]=>
      string(9) "UTC-09:00"
      ["America/Boise"]=>
      string(9) "UTC-07:00"
      ["America/Chicago"]=>
      string(9) "UTC-06:00"
      ["America/Denver"]=>
      string(9) "UTC-07:00"
      ["America/Detroit"]=>
      string(9) "UTC-05:00"
      ["America/Indiana/Indianapolis"]=>
      string(9) "UTC-05:00"
      ["America/Indiana/Knox"]=>
      string(9) "UTC-06:00"
      ["America/Indiana/Marengo"]=>
      string(9) "UTC-05:00"
      ["America/Indiana/Petersburg"]=>
      string(9) "UTC-05:00"
      ["America/Indiana/Tell_City"]=>
      string(9) "UTC-06:00"
      ["America/Indiana/Vevay"]=>
      string(9) "UTC-05:00"
      ["America/Indiana/Vincennes"]=>
      string(9) "UTC-05:00"
      ["America/Indiana/Winamac"]=>
      string(9) "UTC-05:00"
      ["America/Juneau"]=>
      string(9) "UTC-09:00"
      ["America/Kentucky/Louisville"]=>
      string(9) "UTC-05:00"
      ["America/Kentucky/Monticello"]=>
      string(9) "UTC-05:00"
      ["America/Los_Angeles"]=>
      string(9) "UTC-08:00"
      ["America/Menominee"]=>
      string(9) "UTC-06:00"
      ["America/Metlakatla"]=>
      string(9) "UTC-08:00"
      ["America/New_York"]=>
      string(9) "UTC-05:00"
      ["America/Nome"]=>
      string(9) "UTC-09:00"
      ["America/North_Dakota/Beulah"]=>
      string(9) "UTC-06:00"
      ["America/North_Dakota/Center"]=>
      string(9) "UTC-06:00"
      ["America/North_Dakota/New_Salem"]=>
      string(9) "UTC-06:00"
      ["America/Phoenix"]=>
      string(9) "UTC-07:00"
      ["America/Sitka"]=>
      string(9) "UTC-09:00"
      ["America/Yakutat"]=>
      string(9) "UTC-09:00"
      ["Pacific/Honolulu"]=>
      string(9) "UTC-10:00"
    }
  }

Which means now I can do something like below (of course with some javaScript trickery): Google Analytics Timezone Settings

How to condense if/else into one line in Python?

An example of Python's way of doing "ternary" expressions:

i = 5 if a > 7 else 0

translates into

if a > 7:
   i = 5
else:
   i = 0

This actually comes in handy when using list comprehensions, or sometimes in return statements, otherwise I'm not sure it helps that much in creating readable code.

The readability issue was discussed at length in this recent SO question better way than using if-else statement in python.

It also contains various other clever (and somewhat obfuscated) ways to accomplish the same task. It's worth a read just based on those posts.

UIImageView aspect fit and center

Just pasting the solution:

Just like @manohar said

imageView.contentMode = UIViewContentModeCenter;
if (imageView.bounds.size.width > ((UIImage*)imagesArray[i]).size.width && imageView.bounds.size.height > ((UIImage*)imagesArray[i]).size.height) {
       imageView.contentMode = UIViewContentModeScaleAspectFit;
}

solved my problem

What are the differences between .so and .dylib on osx?

The file .so is not a UNIX file extension for shared library.

It just happens to be a common one.

Check line 3b at ArnaudRecipes sharedlib page

Basically .dylib is the mac file extension used to indicate a shared lib.

Windows XP or later Windows: How can I run a batch file in the background with no window displayed?

In the other question I suggested autoexnt. That is also possible in this situation. Just set the service to run manually (ie not automatic at startup). When you want to run your batch, modify the autoexnt.bat file to call the batch file you want, and start the autoexnt service.

The batchfile to start this, can look like this (untested):

echo call c:\path\to\batch.cmd %* > c:\windows\system32\autoexnt.bat
net start autoexnt

Note that batch files started this way run as the system user, which means you do not have access to network shares automatically. But you can use net use to connect to a remote server.

You have to download the Windows 2003 Resource Kit to get it. The Resource Kit can also be installed on other versions of windows, like Windows XP.

Fastest JavaScript summation

I tried using performance.now() to analyze the performance of the different types of loops. I took a very large array and found the sum of all elements of the array. I ran the code three times every time and found forEach and reduce to be a clear winner.

// For loop

let arr = [...Array(100000).keys()]
function addUsingForLoop(ar){
  let sum = 0;
  for(let i = 0; i < ar.length; i++){
    sum += ar[i];
  }
   console.log(`Sum: ${sum}`);
   return sum;
}
let t1 = performance.now();
addUsingForLoop(arr);
let t2 = performance.now();
console.log(`Time Taken ~ ${(t2 - t1)} milliseconds`)

// "Sum: 4999950000"
// "Time Taken ~ 42.17500000959262 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 44.41999999107793 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 49.845000030472875 milliseconds"

// While loop

let arr = [...Array(100000).keys()]
function addUsingWhileLoop(ar){
let sum = 0;
let index = 0;
while (index < ar.length) {
  sum += ar[index];
  index++;
}
  console.log(`Sum: ${sum}`)
  return sum;
}
let t1 = performance.now();
addUsingWhileLoop(arr);
let t2 = performance.now();
console.log(`Time Taken ~ ${(t2 - t1)} milliseconds`)

// "Sum: 4999950000"
// "Time Taken ~ 44.2499999771826 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 44.01999997207895 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 41.71000001952052 milliseconds"

// do-while

let arr = [...Array(100000).keys()]
function addUsingDoWhileLoop(ar){
let sum = 0;
let index = 0;
do {
   sum += index;
   index++;
} while (index < ar.length);
   console.log(`Sum: ${sum}`);
   return sum;
}
let t1 = performance.now();
addUsingDoWhileLoop(arr);
let t2 = performance.now();
console.log(`Time Taken ~ ${(t2 - t1)} milliseconds`)

// "Sum: 4999950000"
// "Time Taken ~ 43.79500000504777 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 43.47500001313165 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 47.535000019706786 milliseconds"

// Reverse loop

let arr = [...Array(100000).keys()]
function addUsingReverseLoop(ar){
   var sum=0;
   for (var i=ar.length; i--;) {
     sum+=arr[i];
   }
   console.log(`Sum: ${sum}`);
   return sum;
}
let t1 = performance.now();
addUsingReverseLoop(arr);
let t2 = performance.now();
console.log(`Time Taken ~ ${(t2 - t1)} milliseconds`)

// "Sum: 4999950000"
// "Time Taken ~ 46.199999982491136 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 44.96500000823289 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 43.880000011995435 milliseconds"

// Reverse while loop

let arr = [...Array(100000).keys()]
function addUsingReverseWhileLoop(ar){
    var sum = 0;
    var i = ar.length; 
    while (i--) {
        sum += ar[i];
    }
    console.log(`Sum: ${sum}`);
    return sum;
}
var t1 = performance.now();
addUsingReverseWhileLoop(arr);
var t2 = performance.now();
console.log(`Time Taken ~ ${(t2 - t1)} milliseconds`)

// "Sum: 4999950000"
// "Time Taken ~ 46.26999999163672 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 42.97000000951812 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 44.31500000646338 milliseconds"

// reduce

let arr = [...Array(100000).keys()]
let t1 = performance.now();
sum = arr.reduce((pv, cv) => pv + cv, 0);
console.log(`Sum: ${sum}`)
let t2 = performance.now();
console.log(`Time Taken ~ ${(t2 - t1)} milliseconds`)

// "Sum: 4999950000"
// "Time Taken ~ 4.654999997001141 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 5.040000018198043 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 4.835000028833747 milliseconds"

// forEach

let arr = [...Array(100000).keys()]
function addUsingForEach(ar){
  let sum = 0;
  ar.forEach(item => {
    sum += item;
  })
    console.log(`Sum: ${sum}`);
    return sum
}
let t1 = performance.now();
addUsingForEach(arr)
let t2 = performance.now();
console.log(`Time Taken ~ ${(t2 - t1)} milliseconds`)

// "Sum: 4999950000"
// "Time Taken ~ 5.315000016707927 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 5.869999993592501 mienter code herelliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 5.405000003520399 milliseconds"

Dynamically Dimensioning A VBA Array?

You have to use the ReDim statement to dynamically size arrays.

Public Sub Test()
    Dim NumberOfZombies As Integer
    NumberOfZombies = 20000
    Dim Zombies() As New Zombie
    ReDim Zombies(NumberOfZombies)

End Sub

This can seem strange when you already know the size of your array, but there you go!

Write a file on iOS

Your code is working at my end, i have just tested it. Where are you checking your changes? Use Documents directory path. To get path -

NSLog(@"%@",documentsDirectory);

and copy path from console and then open finder and press Cmd+shift+g and paste path here and then open your file

MySQL/SQL: Group by date only on a Datetime column

Cast the datetime to a date, then GROUP BY using this syntax:

SELECT SUM(foo), DATE(mydate) FROM a_table GROUP BY DATE(a_table.mydate);

Or you can GROUP BY the alias as @orlandu63 suggested:

SELECT SUM(foo), DATE(mydate) DateOnly FROM a_table GROUP BY DateOnly;

Though I don't think it'll make any difference to performance, it is a little clearer.

How do you get the currently selected <option> in a <select> via JavaScript?

This will do it for you:

var yourSelect = document.getElementById( "your-select-id" );
alert( yourSelect.options[ yourSelect.selectedIndex ].value )

How to update value of a key in dictionary in c#?

Dictionary is a key value pair. Catch Key by

dic["cat"] 

and assign its value like

dic["cat"] = 5

Django - filtering on foreign key properties

Asset.objects.filter( project__name__contains="Foo" )

The specified child already has a parent. You must call removeView() on the child's parent first (Android)

simply pass the argument

attachtoroot = false

View view = inflater.inflate(R.layout.child_layout_to_merge, parent_layout, false);

How do I convert certain columns of a data frame to become factors?

Here's an example:

#Create a data frame
> d<- data.frame(a=1:3, b=2:4)
> d
  a b
1 1 2
2 2 3
3 3 4

#currently, there are no levels in the `a` column, since it's numeric as you point out.
> levels(d$a)
NULL

#Convert that column to a factor
> d$a <- factor(d$a)
> d
  a b
1 1 2
2 2 3
3 3 4

#Now it has levels.
> levels(d$a)
[1] "1" "2" "3"

You can also handle this when reading in your data. See the colClasses and stringsAsFactors parameters in e.g. readCSV().

Note that, computationally, factoring such columns won't help you much, and may actually slow down your program (albeit negligibly). Using a factor will require that all values are mapped to IDs behind the scenes, so any print of your data.frame requires a lookup on those levels -- an extra step which takes time.

Factors are great when storing strings which you don't want to store repeatedly, but would rather reference by their ID. Consider storing a more friendly name in such columns to fully benefit from factors.

Check if a variable is between two numbers with Java

<<= is like +=, but for a left shift. x <<= 1 means x = x << 1. That's why 90 >>= angle doesn't parse. And, like others have said, Java doesn't have an elegant syntax for checking if a number is an an interval, so you have to do it the long way. It also can't do if (x == 0 || 1), and you're stuck writing it out the long way.

Code Sign error: The identity 'iPhone Developer' doesn't match any valid certificate/private key pair in the default keychain

Check if you are building for device instead of simulator. Go to Xcode menu 'Project' -> 'Set Active SDK' change from 'Device' to 'Simulator'

Under Xcode 4.1 Check your build settings for the project and your targets. For each check under 'Code Signing' check 'Code Signing Identity' and change over to 'Don't Code Sign'

How to force NSLocalizedString to use a specific language

The trick to use specific language by selecting it from the app is to force the NSLocalizedString to use specific bundle depending on the selected language ,

here is the post i have written for this learning advance localization in ios apps

and here is the code of one sample app advance localization in ios apps

Check if int is between two numbers

Because the < operator (and most others) are binary operators (they take two arguments), and (true true) is not a valid boolean expression.

The Java language designers could have designed the language to allow syntax like the type you prefer, but (I'm guessing) they decided that it was not worth the more complex parsing rules.

Synchronous request in Node.js

It seems solutions for this problem is never-ending, here's one more :)

// do it once.
sync(fs, 'readFile')

// now use it anywhere in both sync or async ways.
var data = fs.readFile(__filename, 'utf8')

http://alexeypetrushin.github.com/synchronize

MySQL LIMIT on DELETE statement

There is a workaround to solve this problem by using a derived table.

DELETE t1 FROM test t1 JOIN (SELECT t.id FROM test LIMIT 1) t2 ON t1.id = t2.id

Because the LIMIT is inside the derived table the join will match only 1 row and thus the query will delete only this row.

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81

If you are getting this error when you run stuffs on automated cluster and you are downloading the stable version of the google chrome every time then you can use the below shell script to download the compatible version of the chrome driver dynamically every time even if the stable version of the chrome gets updated.

%sh
#downloading compatible chrome driver version
#getting the current chrome browser version
**chromeVersion=$(google-chrome --product-version)**
#getting the major version value from the full version
**chromeMajorVersion=${chromeVersion%%.*}**
# setting the base url for getting the release url for the chrome driver
**baseDriverLatestReleaseURL=https://chromedriver.storage.googleapis.com/LATEST_RELEASE_**
#creating the latest release driver url based on the major version of the chrome
**latestDriverReleaseURL=$baseDriverLatestReleaseURL$chromeMajorVersion**
**echo $latestDriverReleaseURL**
#file name of the file that gets downloaded which would contain the full version of the chrome driver to download
**latestDriverVersionFileName="LATEST_RELEASE_"$chromeMajorVersion**
#downloading the file that would contain the full release version compatible with the major release of the chrome browser version
**wget $latestDriverReleaseURL** 
#reading the file to get the version of the chrome driver that we should download
**latestFullDriverVersion=$(cat $latestDriverVersionFileName)**
**echo $latestFullDriverVersion**
#creating the final URL by passing the compatible version of the chrome driver that we should download
**finalURL="https://chromedriver.storage.googleapis.com/"$latestFullDriverVersion"/chromedriver_linux64.zip"**
**echo $finalURL**
**wget $finalURL**

I was able to get the compatible version of chrome browser and chrome driver using the above approach when running scheduled job on the databricks environment and it worked like a charm without any issues.

Hope it helps others in one way or other.

PHP: Count a stdClass object

Just use this

$i=0;
foreach ($object as $key =>$value)
{
$i++;
}

the variable $i is number of keys.

how to make a cell of table hyperlink

Try this:

HTML:

<table width="200" border="1" class="table">
    <tr>
        <td><a href="#">&nbsp;</a></td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
    </tr>
</table>

CSS:

.table a
{
    display:block;
    text-decoration:none;
}

I hope it will work fine.

Select data between a date/time range

You can either user STR_TO_DATE function and pass your own date parameters based on the format you have posted :

select * from hockey_stats where game_date 
  between STR_TO_DATE('11/3/2012 00:00:00', '%c/%e/%Y %H:%i:%s')
  and STR_TO_DATE('11/5/2012 23:59:00', '%c/%e/%Y %H:%i:%s') 
order by game_date desc;

Or just use the format which MySQL handles dates YYYY:MM:DD HH:mm:SS and have the query as

select * from hockey_stats where game_date between '2012-03-11 00:00:00' and'2012-05-11 23:59:00' order by game_date desc;

SQL Server - How to lock a table until a stored procedure finishes

Use the TABLOCKX lock hint for your transaction. See this article for more information on locking.

CASCADE DELETE just once

You can use to automate this, you could define the foreign key constraint with ON DELETE CASCADE.
I quote the the manual of foreign key constraints:

CASCADE specifies that when a referenced row is deleted, row(s) referencing it should be automatically deleted as well.

Create a one to many relationship using SQL Server

This is a simple example of a classic Order example. Each Customer can have multiple Orders, and each Order can consist of multiple OrderLines.

You create a relation by adding a foreign key column. Each Order record has a CustomerID in it, that points to the ID of the Customer. Similarly, each OrderLine has an OrderID value. This is how the database diagram looks:

enter image description here

In this diagram, there are actual foreign key constraints. They are optional, but they ensure integrity of your data. Also, they make the structure of your database clearer to anyone using it.

I assume you know how to create the tables themselves. Then you just need to define the relationships between them. You can of course define constraints in T-SQL (as posted by several people), but they're also easily added using the designer. Using SQL Management Studio, you can right-click the Order table, click Design (I think it may be called Edit under 2005). Then anywhere in the window that opens right-click and select Relationships.

You will get another dialog, on the right there should be a grid view. One of the first lines reads "Tables and Columns Specification". Click that line, then click again on the little [...] button that appears on the right. You will get this dialog:

Foreign key constraint

The Order table should already be selected on the right. Select the Customer table on the left dropdown. Then in the left grid, select the ID column. In the right grid, select the CustomerID column. Close the dialog, and the next. Press Ctrl+S to save.

Having this constraint will ensure that no Order records can exist without an accompanying Customer record.

To effectively query a database like this, you might want to read up on JOINs.

Cloning a private Github repo

Private clone URLs take the form [email protected]:username/repo.git - perhaps you needed to use git@ rather than git://?

git:// URLs are read only, and it looks like private repos do not allow this form of access.

Adding div element to body or document in JavaScript

Try doing

document.body.innerHTML += '<div style="position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;"></div>'

Javascript : natural sort of alphanumerical strings

The most fully-featured library to handle this as of 2019 seems to be natural-orderby.

const { orderBy } = require('natural-orderby')

const unordered = [
  '123asd',
  '19asd',
  '12345asd',
  'asd123',
  'asd12'
]

const ordered = orderBy(unordered)

// [ '19asd',
//   '123asd',
//   '12345asd',
//   'asd12',
//   'asd123' ]

It not only takes arrays of strings, but also can sort by the value of a certain key in an array of objects. It can also automatically identify and sort strings of: currencies, dates, currency, and a bunch of other things.

Surprisingly, it's also only 1.6kB when gzipped.

How to add option to select list in jQuery

Your code fails because you are executing a method (addOption) on the jQuery object (and this object does not support the method)

You can use the standard Javascript function like this:

$("#dropListBuilding")[0].options.add( new Option("My Text","My Value") )

Entry point for Java applications: main(), init(), or run()?

This is a peculiar question because it's not supposed to be a matter of choice.

When you launch the JVM, you specify a class to run, and it is the main() of this class where your program starts.

By init(), I assume you mean the JApplet method. When an applet is launched in the browser, the init() method of the specified applet is executed as the first order of business.

By run(), I assume you mean the method of Runnable. This is the method invoked when a new thread is started.

  • main: program start
  • init: applet start
  • run: thread start

If Eclipse is running your run() method even though you have no main(), then it is doing something peculiar and non-standard, but not infeasible. Perhaps you should post a sample class that you've been running this way.

ASP.NET MVC - Extract parameter of an URL

You can get these parameter list in ControllerContext.RoutValues object as key-value pair.

You can store it in some variable and you make use of that variable in your logic.

Slide div left/right using jQuery

You can easy get that effect without using jQueryUI, for example:

$(document).ready(function(){
    $('#slide').click(function(){
    var hidden = $('.hidden');
    if (hidden.hasClass('visible')){
        hidden.animate({"left":"-1000px"}, "slow").removeClass('visible');
    } else {
        hidden.animate({"left":"0px"}, "slow").addClass('visible');
    }
    });
});

Try this working Fiddle:

http://jsfiddle.net/ZQTFq/

docker run <IMAGE> <MULTIPLE COMMANDS>

You can also pipe commands inside Docker container, bash -c "<command1> | <command2>" for example:

docker run img /bin/bash -c "ls -1 | wc -l"

But, without invoking the shell in the remote the output will be redirected to the local terminal.

Conditional logic in AngularJS template

You can use ng-show on every div element in the loop. Is this what you've wanted: http://jsfiddle.net/pGwRu/2/ ?

<div class="from" ng-show="message.from">From: {{message.from.name}}</div>

Converting a SimpleXML Object to an Array

I found this in the PHP manual comments:

/**
 * function xml2array
 *
 * This function is part of the PHP manual.
 *
 * The PHP manual text and comments are covered by the Creative Commons 
 * Attribution 3.0 License, copyright (c) the PHP Documentation Group
 *
 * @author  k dot antczak at livedata dot pl
 * @date    2011-04-22 06:08 UTC
 * @link    http://www.php.net/manual/en/ref.simplexml.php#103617
 * @license http://www.php.net/license/index.php#doc-lic
 * @license http://creativecommons.org/licenses/by/3.0/
 * @license CC-BY-3.0 <http://spdx.org/licenses/CC-BY-3.0>
 */
function xml2array ( $xmlObject, $out = array () )
{
    foreach ( (array) $xmlObject as $index => $node )
        $out[$index] = ( is_object ( $node ) ) ? xml2array ( $node ) : $node;

    return $out;
}

It could help you. However, if you convert XML to an array you will loose all attributes that might be present, so you cannot go back to XML and get the same XML.

How can I make SMTP authenticated in C#

Set the Credentials property before sending the message.

How to give a pattern for new line in grep?

try pcregrep instead of regular grep:

pcregrep -M "pattern1.*\n.*pattern2" filename

the -M option allows it to match across multiple lines, so you can search for newlines as \n.

What is the difference between a web API and a web service?

The basic difference between Web Services and Web APIs

Web Service:

1) It is a SOAP-based service and returns data as XML.

2) It only supports the HTTP protocol.

3) It is not open source but can be used by any client that understands XML.

5) It requires a SOAP protocol to receive and send data over the network, so it is not a light-weight architecture.

Web API:

1) A Web API is an HTTP based service and returns JSON or XML data by default.

2) It supports the HTTP protocol.

3) It can be hosted within an application or IIS.

4) It is open source and it can be used by any client that understands JSON or XML.

5) It has light-weight architecture and good for devices which have limited bandwidth, like mobile devices.

Sending emails in Node.js?

@JimBastard's accepted answer appears to be dated, I had a look and that mailer lib hasn't been touched in over 7 months, has several bugs listed, and is no longer registered in npm.

nodemailer certainly looks like the best option, however the url provided in other answers on this thread are all 404'ing.

nodemailer claims to support easy plugins into gmail, hotmail, etc. and also has really beautiful documentation.

java.lang.IllegalAccessError: tried to access method

I was getting same error because of configuration issue in intellij. As shown in screenshot. Main and test module was pointing to two different JDK. (Press F12 on the intellij project to open module settings)

Also all my dto's were using @lombok.Builder which I changed it to @Data.

enter image description here

enter image description here

uint8_t vs unsigned char

The whole point is to write implementation-independent code. unsigned char is not guaranteed to be an 8-bit type. uint8_t is (if available).