Programs & Examples On #Process exit

Pyspark: Exception: Java gateway process exited before sending the driver its port number

After spending hours and hours trying many different solutions, I can confirm that Java 10 SDK causes this error. On Mac, please navigate to /Library/Java/JavaVirtualMachines then run this command to uninstall Java JDK 10 completely:

sudo rm -rf jdk-10.jdk/

After that, please download JDK 8 then the problem will be solved.

Fatal error: Call to undefined function mysql_connect()

You upgraded to PHP 7, and now mysql_connect is deprecated. Check yours with:

php -version

Change it to mysqli_connect as in:

$host = "127.0.0.1";
$username = "root";
$pass = "foobar";
$con = mysqli_connect($host, $username, $pass, "your_database");

If you're upgrading legacy PHP, now you're faced with the task of upgrading all your mysql_* functions with mysqli_* functions.

Different ways of loading a file as an InputStream

There are subtle differences as to how the fileName you are passing is interpreted. Basically, you have 2 different methods: ClassLoader.getResourceAsStream() and Class.getResourceAsStream(). These two methods will locate the resource differently.

In Class.getResourceAsStream(path), the path is interpreted as a path local to the package of the class you are calling it from. For example calling, String.class.getResourceAsStream("myfile.txt") will look for a file in your classpath at the following location: "java/lang/myfile.txt". If your path starts with a /, then it will be considered an absolute path, and will start searching from the root of the classpath. So calling String.class.getResourceAsStream("/myfile.txt") will look at the following location in your class path ./myfile.txt.

ClassLoader.getResourceAsStream(path) will consider all paths to be absolute paths. So calling String.class.getClassLoader().getResourceAsStream("myfile.txt") and String.class.getClassLoader().getResourceAsStream("/myfile.txt") will both look for a file in your classpath at the following location: ./myfile.txt.

Everytime I mention a location in this post, it could be a location in your filesystem itself, or inside the corresponding jar file, depending on the Class and/or ClassLoader you are loading the resource from.

In your case, you are loading the class from an Application Server, so your should use Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName) instead of this.getClass().getClassLoader().getResourceAsStream(fileName). this.getClass().getResourceAsStream() will also work.

Read this article for more detailed information about that particular problem.


Warning for users of Tomcat 7 and below

One of the answers to this question states that my explanation seems to be incorrect for Tomcat 7. I've tried to look around to see why that would be the case.

So I've looked at the source code of Tomcat's WebAppClassLoader for several versions of Tomcat. The implementation of findResource(String name) (which is utimately responsible for producing the URL to the requested resource) is virtually identical in Tomcat 6 and Tomcat 7, but is different in Tomcat 8.

In versions 6 and 7, the implementation does not attempt to normalize the resource name. This means that in these versions, classLoader.getResourceAsStream("/resource.txt") may not produce the same result as classLoader.getResourceAsStream("resource.txt") event though it should (since that what the Javadoc specifies). [source code]

In version 8 though, the resource name is normalized to guarantee that the absolute version of the resource name is the one that is used. Therefore, in Tomcat 8, the two calls described above should always return the same result. [source code]

As a result, you have to be extra careful when using ClassLoader.getResourceAsStream() or Class.getResourceAsStream() on Tomcat versions earlier than 8. And you must also keep in mind that class.getResourceAsStream("/resource.txt") actually calls classLoader.getResourceAsStream("resource.txt") (the leading / is stripped).

Using IF ELSE statement based on Count to execute different Insert statements

There are many, many ways to code this, but here is one possible way. I'm assuming MS SQL

We'll start by getting row count (Another Quick Example) and then do if/else

-- Let's get our row count and assign it to a var that will be used
--    in our if stmt 
DECLARE @HasExistingRows int -- I'm assuming it can fit into an int
SELECT @HasExistingRows = Count(*) 
   ELSE 0 -- false
FROM
   INCIDENTS
WHERE {Your Criteria}
GROUP BY {Required Grouping}

Now we can do the If / Else Logic MSDN Docs

-- IF / Else / Begin / END Syntax
IF @HasExistingRows = 0 -- No Existing Rows
   BEGIN
      {Insert Logic for No Existing Rows}
   END
ELSE -- existing rows are found
   BEGIN
      {Insert logic for existing rows}
   END

Another faster way (inspired by Mahmoud Gamal's comment):

Forget the whole variable creation / assignment - look up "EXISTS" - MSDN Docs 2.

IF EXISTS ({SELECT Query})
   BEGIN
      {INSERT Version 1}
   END
ELSE
   BEGIN
      {INSERT version 2}
   END

Only on Firefox "Loading failed for the <script> with source"

I had the same issue with firefox, when I searched for a solution I didn't find anything, but then I tried to load the script from a cdn, it worked properly, so I think you should try loading it from a cdn link, I mean if you are trying to load a script that you havn't created. because in my case, when tried to load a script that is mine, it worked and imported successfully, for now I don't know why, but I think there is something in the scripts from network, so just try cdn, you won't lose anything.

I wish it help you.

Github Windows 'Failed to sync this branch'

This error also occurs if the branch you're trying to sync has been deleted.

git status won't tell you that, but you'll get a "no such ref was fetched" message if you try git pull.

What's the best way to center your HTML email content in the browser window (or email client preview pane)?

For googlers and completeness sake:

Here's a reference I always use when I need to go through the pain of implementing html email-templates or signatures: http://www.campaignmonitor.com/css/

I'ts a list of CSS support for most, if not all, CSS options, nicely compared between some of the most used email clients.

For centering, feel free to just use CSS (as the align attribute is deprecated in HTML 4.01).

<table width="100%" border="0" cellspacing="0" cellpadding="0">
    <tr>
        <td style="text-align: center;">
            Your Content
        </td>
    </tr>
</table>

how to sort an ArrayList in ascending order using Collections and Comparator

This might work?

Comparator mycomparator = 
    Collections.reverseOrder(Collections.reverseOrder());

Datatables - Search Box outside datatable

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

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

CSS text-align: center; is not centering things

To make a inline-block element align center horizontally in its parent, add text-align:center to its parent.

How to call a JavaScript function, declared in <head>, in the body when I want to call it

You can also put the JavaScript code in script tags, rather than a separate function. <script>//JS Code</script> This way the code will get executes on Page Load.

"Comparison method violates its general contract!"

Your comparator is not transitive.

Let A be the parent of B, and B be the parent of C. Since A > B and B > C, then it must be the case that A > C. However, if your comparator is invoked on A and C, it would return zero, meaning A == C. This violates the contract and hence throws the exception.

It's rather nice of the library to detect this and let you know, rather than behave erratically.

One way to satisfy the transitivity requirement in compareParents() is to traverse the getParent() chain instead of only looking at the immediate ancestor.

Print time in a batch file (milliseconds)

Maybe this tool (archived version ) could help? It doesn't return the time, but it is a good tool to measure the time a command takes.

Best data type for storing currency values in a MySQL database

It is also important to work out how many decimal places maybe required for your calculations.

I worked on a share price application that required the calculation of the price of one million shares. The quoted share price had to be stored to 7 digits of accuracy.

SQL Server 2008: how do I grant privileges to a username?

Like the following. It will make the user database owner.

EXEC sp_addrolemember N'db_owner', N'USerNAme'

How to return a value from pthread threads in C?

#include<stdio.h>
#include<pthread.h>
void* myprint(void *x)
{
 int k = *((int *)x);
 printf("\n Thread created.. value of k [%d]\n",k);
 //k =11;
 pthread_exit((void *)k);

}
int main()
{
 pthread_t th1;
 int x =5;
 int *y;
 pthread_create(&th1,NULL,myprint,(void*)&x);
 pthread_join(th1,(void*)&y);
 printf("\n Exit value is [%d]\n",y);
}  

How to increase the vertical split window size in Vim

I have these mapped in my .gvimrc to let me hit command-[arrow] to move the height and width of my current window around:

" resize current buffer by +/- 5 
nnoremap <D-left> :vertical resize -5<cr>
nnoremap <D-down> :resize +5<cr>
nnoremap <D-up> :resize -5<cr>
nnoremap <D-right> :vertical resize +5<cr>

For MacVim, you have to put them in your .gvimrc (and not your .vimrc) as they'll otherwise get overwritten by the system .gvimrc

Aggregate a dataframe on a given column and display another column

First, you split the data using split:

split(z,z$Group)

Than, for each chunk, select the row with max Score:

lapply(split(z,z$Group),function(chunk) chunk[which.max(chunk$Score),])

Finally reduce back to a data.frame do.calling rbind:

do.call(rbind,lapply(split(z,z$Group),function(chunk) chunk[which.max(chunk$Score),]))

Result:

  Group Score Info
1     1     3    c
2     2     4    d

One line, no magic spells, fast, result has good names =)

Android getText from EditText field

Try this -

EditText myEditText =  (EditText) findViewById(R.id.vnosEmaila);

String text = myEditText.getText().toString();

fork() child and parent processes

This is the correct way for getting the correct output.... However, childs parent id maybe sometimes printed as 1 because parent process gets terminated and the root process with pid = 1 controls this orphan process.

 pid_t  pid;
 pid = fork();
 if (pid == 0) 
    printf("This is the child process. My pid is %d and my parent's id 
      is %d.\n", getpid(), getppid());
 else 
     printf("This is the parent process. My pid is %d and my parent's 
         id is %d.\n", getpid(), pid);

How to get a shell environment variable in a makefile?

for those who want some official document to confirm the behavior

Variables in make can come from the environment in which make is run. Every environment variable that make sees when it starts up is transformed into a make variable with the same name and value. However, an explicit assignment in the makefile, or with a command argument, overrides the environment. (If the ‘-e’ flag is specified, then values from the environment override assignments in the makefile.

https://www.gnu.org/software/make/manual/html_node/Environment.html

Facebook key hash does not match any stored key hashes

This worked for me

  1. Go to Google Play Console
  2. Select Release Management
  3. Choose App Signing
  4. Convert App-Signing Certificate SHA-1 to Base64 (this will be different than your current upload certificate) using this tool: http://tomeko.net/online_tools/hex_to_base64.php?lang=en
  5. Enter Base64 converted SHA-1 into your Facebook Developer dashboard settings and try again.

your Google Play SHA-1

ASP.NET MVC Ajax Error handling

Unfortunately, neither of answers are good for me. Surprisingly the solution is much simpler. Return from controller:

return new HttpStatusCodeResult(HttpStatusCode.BadRequest, e.Response.ReasonPhrase);

And handle it as standard HTTP error on client as you like.

Need to combine lots of files in a directory

Yes , A plugin is available named "combine" for notepad++.Link: .>> Combine Plugin for Notepad++

You can install it via plugin manager. Extra benifit of this plugin is: "You can maintain the sequence of files while merging, it's according to the sequence of opened files are opened (see tabs)".

Identify duplicate values in a list in Python

You can print duplicate and Unqiue using below logic using list.

def dup(x):
    duplicate = []
    unique = []
    for i in x:
        if i in unique:
            duplicate.append(i)
        else:
            unique.append(i)
    print("Duplicate values: ",duplicate)
    print("Unique Values: ",unique)

list1 = [1, 2, 1, 3, 2, 5]
dup(list1)

xxxxxx.exe is not a valid Win32 application

There are at least two solutions:

  1. You need Visual Studio 2010 installed, then from Visual Studio 2010, View -> Solution Explorer -> Right Click on your project -> Choose Properties from the context menu, you'll get the windows "your project name" Property Pages -> Configuration Properties -> General -> Platform toolset, choose "Visual Studio 2010 (v100)".
  2. You need the Visual Studio 2012 Update 1 described in Windows XP Targeting with C++ in Visual Studio 2012

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.

How can I undo a `git commit` locally and on a remote after `git push`

You can do an interactive rebase:

git rebase -i <commit>

This will bring up your default editor. Just delete the line containing the commit you want to remove to delete that commit.

You will, of course, need access to the remote repository to apply this change there too.

See this question: Git: removing selected commits from repository

Passing an array to a query using a WHERE clause

Because the original question relates to an array of numbers and I am using an array of strings I couldn't make the given examples work.

I found that each string needed to be encapsulated in single quotes to work with the IN() function.

Here is my solution

foreach($status as $status_a) {
        $status_sql[] = '\''.$status_a.'\'';
    }
    $status = implode(',',$status_sql);

$sql = mysql_query("SELECT * FROM table WHERE id IN ($status)");

As you can see the first function wraps each array variable in single quotes (\') and then implodes the array.

NOTE: $status does not have single quotes in the SQL statement.

There is probably a nicer way to add the quotes but this works.

In Jinja2, how do you test if a variable is undefined?

Consider using default filter if it is what you need. For example:

{% set host = jabber.host | default(default.host) -%}

or use more fallback values with "hardcoded" one at the end like:

{% set connectTimeout = config.stackowerflow.connect.timeout | default(config.stackowerflow.timeout) | default(config.timeout) | default(42) -%}

Access: Move to next record until EOF

If you want cmd buttons that loop through the form's records, try adding this code to your cmdNext_Click and cmdPrevious_Click VBA. I have found it works well and copes with BOF / EOF issues:

On Error Resume Next

DoCmd.GoToRecord , , acNext

On Error Goto 0


On Error Resume Next

DoCmd.GoToRecord , , acPrevious

On Error Goto 0

Good luck! PT

Html code as IFRAME source rather than a URL

use html5's new attribute srcdoc (srcdoc-polyfill) Docs

<iframe srcdoc="<html><body>Hello, <b>world</b>.</body></html>"></iframe>

Browser support - Tested in the following browsers:

Microsoft Internet Explorer
6, 7, 8, 9, 10, 11
Microsoft Edge
13, 14
Safari
4, 5.0, 5.1 ,6, 6.2, 7.1, 8, 9.1, 10
Google Chrome
14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24.0.1312.5 (beta), 25.0.1364.5 (dev), 55
Opera
11.1, 11.5, 11.6, 12.10, 12.11 (beta) , 42
Mozilla FireFox
3.0, 3.6, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 (beta), 50

How to filter multiple values (OR operation) in angularJS

I've spent some time on it and thanks to @chrismarx, I saw that angular's default filterFilter allows you to pass your own comparator. Here's the edited comparator for multiple values:

  function hasCustomToString(obj) {
        return angular.isFunction(obj.toString) && obj.toString !== Object.prototype.toString;
  }
  var comparator = function (actual, expected) {
    if (angular.isUndefined(actual)) {
      // No substring matching against `undefined`
      return false;
    }
    if ((actual === null) || (expected === null)) {
      // No substring matching against `null`; only match against `null`
      return actual === expected;
    }
    // I edited this to check if not array
    if ((angular.isObject(expected) && !angular.isArray(expected)) || (angular.isObject(actual) && !hasCustomToString(actual))) {
      // Should not compare primitives against objects, unless they have custom `toString` method
      return false;
    }
    // This is where magic happens
    actual = angular.lowercase('' + actual);
    if (angular.isArray(expected)) {
      var match = false;
      expected.forEach(function (e) {
        e = angular.lowercase('' + e);
        if (actual.indexOf(e) !== -1) {
          match = true;
        }
      });
      return match;
    } else {
      expected = angular.lowercase('' + expected);
      return actual.indexOf(expected) !== -1;
    }
  };

And if we want to make a custom filter for DRY:

angular.module('myApp')
    .filter('filterWithOr', function ($filter) {
      var comparator = function (actual, expected) {
        if (angular.isUndefined(actual)) {
          // No substring matching against `undefined`
          return false;
        }
        if ((actual === null) || (expected === null)) {
          // No substring matching against `null`; only match against `null`
          return actual === expected;
        }
        if ((angular.isObject(expected) && !angular.isArray(expected)) || (angular.isObject(actual) && !hasCustomToString(actual))) {
          // Should not compare primitives against objects, unless they have custom `toString` method
          return false;
        }
        console.log('ACTUAL EXPECTED')
        console.log(actual)
        console.log(expected)

        actual = angular.lowercase('' + actual);
        if (angular.isArray(expected)) {
          var match = false;
          expected.forEach(function (e) {
            console.log('forEach')
            console.log(e)
            e = angular.lowercase('' + e);
            if (actual.indexOf(e) !== -1) {
              match = true;
            }
          });
          return match;
        } else {
          expected = angular.lowercase('' + expected);
          return actual.indexOf(expected) !== -1;
        }
      };
      return function (array, expression) {
        return $filter('filter')(array, expression, comparator);
      };
    });

And then we can use it anywhere we want:

$scope.list=[
  {name:'Jack Bauer'},
  {name:'Chuck Norris'},
  {name:'Superman'},
  {name:'Batman'},
  {name:'Spiderman'},
  {name:'Hulk'}
];


<ul>
  <li ng-repeat="item in list | filterWithOr:{name:['Jack','Chuck']}">
    {{item.name}}
  </li>
</ul>

Finally here's a plunkr.

Note: Expected array should only contain simple objects like String, Number etc.

Django model "doesn't declare an explicit app_label"

as a noob using Python3 ,I find it might be an import error instead of a Django error

wrong:

from someModule import someClass

right:

from .someModule import someClass

this happens a few days ago but I really can't reproduce it...I think only people new to Django may encounter this.here's what I remember:

try to register a model in admin.py:

from django.contrib import admin
from user import User
admin.site.register(User)

try to run server, error looks like this

some lines...
File "/path/to/admin.py" ,line 6
tell you there is an import error
some lines...
Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label

change user to .user ,problem solved

Parsing HTML using Python

I recommend using justext library:

https://github.com/miso-belica/jusText

Usage: Python2:

import requests
import justext

response = requests.get("http://planet.python.org/")
paragraphs = justext.justext(response.content, justext.get_stoplist("English"))
for paragraph in paragraphs:
    print paragraph.text

Python3:

import requests
import justext

response = requests.get("http://bbc.com/")
paragraphs = justext.justext(response.content, justext.get_stoplist("English"))
for paragraph in paragraphs:
    print (paragraph.text)

How to get current formatted date dd/mm/yyyy in Javascript and append it to an input

<input type="hidden" id="date"/>
<script>document.getElementById("date").value = new Date().toJSON().slice(0,10)</script>

Generate an integer that is not among four billion given ones

I think this is a solved problem (see above), but there's an interesting side case to keep in mind because it might get asked:

If there are exactly 4,294,967,295 (2^32 - 1) 32-bit integers with no repeats, and therefore only one is missing, there is a simple solution.

Start a running total at zero, and for each integer in the file, add that integer with 32-bit overflow (effectively, runningTotal = (runningTotal + nextInteger) % 4294967296). Once complete, add 4294967296/2 to the running total, again with 32-bit overflow. Subtract this from 4294967296, and the result is the missing integer.

The "only one missing integer" problem is solvable with only one run, and only 64 bits of RAM dedicated to the data (32 for the running total, 32 to read in the next integer).

Corollary: The more general specification is extremely simple to match if we aren't concerned with how many bits the integer result must have. We just generate a big enough integer that it cannot be contained in the file we're given. Again, this takes up absolutely minimal RAM. See the pseudocode.

# Grab the file size
fseek(fp, 0L, SEEK_END);
sz = ftell(fp);
# Print a '2' for every bit of the file.
for (c=0; c<sz; c++) {
  for (b=0; b<4; b++) {
    print "2";
  }
}

Retrieve list of tasks in a queue in Celery

To retrieve tasks from backend, use this

from amqplib import client_0_8 as amqp
conn = amqp.Connection(host="localhost:5672 ", userid="guest",
                       password="guest", virtual_host="/", insist=False)
chan = conn.channel()
name, jobs, consumers = chan.queue_declare(queue="queue_name", passive=True)

What does an exclamation mark mean in the Swift language?

IN SIMPLE WORDS

USING Exclamation mark indicates that variable must consists non nil value (it never be nil)

Calculating average of an array list?

List.stream().mapToDouble(a->a).average()

Is it possible to read from a InputStream with a timeout?

I have not used the classes from the Java NIO package, but it seems they might be of some help here. Specifically, java.nio.channels.Channels and java.nio.channels.InterruptibleChannel.

How to prevent a browser from storing passwords

I just change the type attribute of the field password to hidden before the click event:

document.getElementById("password").setAttribute("type", "hidden");
document.getElementById("save").click();

How to line-break from css, without using <br />?

Use <br/> as normal, but hide it with display: none when you don't want it.

I would expect most people finding this question want to use css / responsive design to decide whether or not a line-break appears in a specific place. (and don't have anything personal against <br/>)

While not immediately obvious, you can actually apply display:none to a <br/> tag to hide it, which enables the use of media queries in tandem with semantic BR tags.

<div>
  The quick brown fox<br />
  jumps over the lazy dog
</div>
@media screen and (min-width: 20em) {
  br {
    display: none; /* hide the BR tag for wider screens (i.e. disable the line break) */
  }
}

This is useful in responsive design where you need to force text into two lines at an exact break.

jsfiddle example

How to overwrite the previous print to stdout in python?

This works on Windows and python 3.6

import time
for x in range(10):
    time.sleep(0.5)
    print(str(x)+'\r',end='')

Is there a way for non-root processes to bind to "privileged" ports on Linux?

TLDR: For "the answer" (as I see it), jump down to the >>TLDR<< part in this answer.

OK, I've figured it out (for real this time), the answer to this question, and this answer of mine is also a way of apologizing for promoting another answer (both here and on twitter) that I thought was "the best", but after trying it, discovered that I was mistaken about that. Learn from my mistake kids: don't promote something until you've actually tried it yourself!

Again, I reviewed all the answers here. I've tried some of them (and chose not to try others because I simply didn't like the solutions). I thought that the solution was to use systemd with its Capabilities= and CapabilitiesBindingSet= settings. After wrestling with this for some time, I discovered that this is not the solution because:

Capabilities are intended to restrict root processes!

As the OP wisely stated, it is always best to avoid that (for all your daemons if possible!).

You cannot use the Capabilities related options with User= and Group= in systemd unit files, because capabilities are ALWAYS reset when execev (or whatever the function is) is called. In other words, when systemd forks and drops its perms, the capabilities are reset. There is no way around this, and all that binding logic in the kernel is basic around uid=0, not capabilities. This means that it is unlikely that Capabilities will ever be the right answer to this question (at least any time soon). Incidentally, setcap, as others have mentioned, is not a solution. It didn't work for me, it doesn't work nicely with scripts, and those are reset anyways whenever the file changes.

In my meager defense, I did state (in the comment I've now deleted), that James' iptables suggestion (which the OP also mentions), was the "2nd best solution". :-P

>>TLDR<<

The solution is to combine systemd with on-the-fly iptables commands, like this (taken from DNSChain):

[Unit]
Description=dnschain
After=network.target
Wants=namecoin.service

[Service]
ExecStart=/usr/local/bin/dnschain
Environment=DNSCHAIN_SYSD_VER=0.0.1
PermissionsStartOnly=true
ExecStartPre=/sbin/sysctl -w net.ipv4.ip_forward=1
ExecStartPre=-/sbin/iptables -D INPUT -p udp --dport 5333 -j ACCEPT
ExecStartPre=-/sbin/iptables -t nat -D PREROUTING -p udp --dport 53 -j REDIRECT --to-ports 5333
ExecStartPre=/sbin/iptables -A INPUT -p udp --dport 5333 -j ACCEPT
ExecStartPre=/sbin/iptables -t nat -A PREROUTING -p udp --dport 53 -j REDIRECT --to-ports 5333
ExecStopPost=/sbin/iptables -D INPUT -p udp --dport 5333 -j ACCEPT
ExecStopPost=/sbin/iptables -t nat -D PREROUTING -p udp --dport 53 -j REDIRECT --to-ports 5333
User=dns
Group=dns
Restart=always
RestartSec=5
WorkingDirectory=/home/dns
PrivateTmp=true
NoNewPrivileges=true
ReadOnlyDirectories=/etc

# Unfortunately, capabilities are basically worthless because they're designed to restrict root daemons. Instead, we use iptables to listen on privileged ports.
# Capabilities=cap_net_bind_service+pei
# SecureBits=keep-caps

[Install]
WantedBy=multi-user.target

Here we accomplish the following:

  • The daemon listens on 5333, but connections are successfully accepted on 53 thanks to iptables
  • We can include the commands in the unit file itself, and thus we save people headaches. systemd cleans up the firewall rules for us, making sure to remove them when the daemon isn't running.
  • We never run as root, and we make privilege escalation impossible (at least systemd claims to), supposedly even if the daemon is compromised and sets uid=0.

iptables is still, unfortunately, quite an ugly and difficult-to-use utility. If the daemon is listening on eth0:0 instead of eth0, for example, the commands are slightly different.

PostgreSQL: insert from another table

Very late answer, but I think my answer is more straight forward for specific use cases where users want to simply insert (copy) data from table A into table B:

INSERT INTO table_b (col1, col2, col3, col4, col5, col6)
SELECT col1, 'str_val', int_val, col4, col5, col6
FROM table_a

Integer division: How do you produce a double?

Best way to do this is

int i = 3;
Double d = i * 1.0;

d is 3.0 now.

Make ABC Ordered List Items Have Bold Style

a bit of a cheat, but it works:

HTML:

<ol type="A" style="font-weight: bold;">
  <li><span>Text</span></li>
  <li><span>More text</span></li>
</ol>

CSS:

li span { font-weight: normal; }

load external URL into modal jquery ui dialog

_x000D_
_x000D_
if you are using **Bootstrap** this is solution, _x000D_
_x000D_
$(document).ready(function(e) {_x000D_
    $('.bootpopup').click(function(){_x000D_
  var frametarget = $(this).attr('href');_x000D_
  targetmodal = '#myModal'; _x000D_
        $('#modeliframe').attr("src", frametarget );   _x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<!-- Latest compiled and minified CSS -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
_x000D_
<!-- Optional theme -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">_x000D_
_x000D_
<!-- Latest compiled and minified JavaScript -->_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>_x000D_
<!-- Button trigger modal -->_x000D_
<a  href="http://twitter.github.io/bootstrap/" title="Edit Transaction" class="btn btn-primary btn-lg bootpopup" data-toggle="modal" data-target="#myModal">_x000D_
  Launch demo modal_x000D_
</a>_x000D_
_x000D_
<!-- Modal -->_x000D_
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">_x000D_
  <div class="modal-dialog" role="document">_x000D_
    <div class="modal-content">_x000D_
      <div class="modal-header">_x000D_
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>_x000D_
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>_x000D_
      </div>_x000D_
      <div class="modal-body">_x000D_
         <iframe src="" id="modeliframe" style="zoom:0.60" frameborder="0" height="250" width="99.6%"></iframe>_x000D_
      </div>_x000D_
      <div class="modal-footer">_x000D_
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
        <button type="button" class="btn btn-primary">Save changes</button>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Network tools that simulate slow network connection

DummyNet

Try this FreeBSD based VMWare image. It also has an excellent how-to, purely free and stands up in 20 minutes.

Update: DummyNet also supports Linux, OSX and Windows by now

Comparing two collections for equality irrespective of the order of items in them

EDIT: I realized as soon as I posed that this really only works for sets -- it will not properly deal with collections that have duplicate items. For example { 1, 1, 2 } and { 2, 2, 1 } will be considered equal from this algorithm's perspective. If your collections are sets (or their equality can be measured that way), however, I hope you find the below useful.

The solution I use is:

return c1.Count == c2.Count && c1.Intersect(c2).Count() == c1.Count;

Linq does the dictionary thing under the covers, so this is also O(N). (Note, it's O(1) if the collections aren't the same size).

I did a sanity check using the "SetEqual" method suggested by Daniel, the OrderBy/SequenceEquals method suggested by Igor, and my suggestion. The results are below, showing O(N*LogN) for Igor and O(N) for mine and Daniel's.

I think the simplicity of the Linq intersect code makes it the preferable solution.

__Test Latency(ms)__
N, SetEquals, OrderBy, Intersect    
1024, 0, 0, 0    
2048, 0, 0, 0    
4096, 31.2468, 0, 0    
8192, 62.4936, 0, 0    
16384, 156.234, 15.6234, 0    
32768, 312.468, 15.6234, 46.8702    
65536, 640.5594, 46.8702, 31.2468    
131072, 1312.3656, 93.7404, 203.1042    
262144, 3765.2394, 187.4808, 187.4808    
524288, 5718.1644, 374.9616, 406.2084    
1048576, 11420.7054, 734.2998, 718.6764    
2097152, 35090.1564, 1515.4698, 1484.223

How can I generate a list or array of sequential integers in Java?

The following one-liner Java 8 version will generate [ 1, 2 ,3 ... 10 ]. The first arg of iterate is the first nr in the sequence, and the first arg of limit is the last number.

List<Integer> numbers = Stream.iterate(1, n -> n + 1)
                              .limit(10)
                              .collect(Collectors.toList());

Datetime current year and month in Python

The question asks to use datetime specifically.

This is a way that uses datetime only:

year = datetime.now().year
month = datetime.now().month

How to create a sub array from another array in Java?

Using Apache ArrayUtils downloadable at this link you can easy use the method

subarray(boolean[] array, int startIndexInclusive, int endIndexExclusive) 

"boolean" is only an example, there are methods for all primitives java types

What's the actual use of 'fail' in JUnit test case?

Let's say you are writing a test case for a negative flow where the code being tested should raise an exception.

try{
   bizMethod(badData);
   fail(); // FAIL when no exception is thrown
} catch (BizException e) {
   assert(e.errorCode == THE_ERROR_CODE_U_R_LOOKING_FOR)
}

Python Pandas merge only certain columns

You can use .loc to select the specific columns with all rows and then pull that. An example is below:

pandas.merge(dataframe1, dataframe2.iloc[:, [0:5]], how='left', on='key')

In this example, you are merging dataframe1 and dataframe2. You have chosen to do an outer left join on 'key'. However, for dataframe2 you have specified .iloc which allows you to specific the rows and columns you want in a numerical format. Using :, your selecting all rows, but [0:5] selects the first 5 columns. You could use .loc to specify by name, but if your dealing with long column names, then .iloc may be better.

ValueError when checking if variable is None or numpy.array

To stick to == without consideration of the other type, the following is also possible.
type(a) == type(None)

How to use protractor to check if an element is visible?

 element(by.className('your-class-name')).isDisplayed().then(function (isVisible) {
if (isVisible) {
    // element is visible
} else {
    // element is not visible
}
}).catch(function(err){
console.log("Element is not found");
})

C# guid and SQL uniqueidentifier

// Create Instance of Connection and Command Object
SqlConnection myConnection = new SqlConnection(GentEFONRFFConnection);
myConnection.Open();
SqlCommand myCommand = new SqlCommand("your Procedure Name", myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.Add("@orgid", SqlDbType.UniqueIdentifier).Value = orgid;
myCommand.Parameters.Add("@statid", SqlDbType.UniqueIdentifier).Value = statid;
myCommand.Parameters.Add("@read", SqlDbType.Bit).Value = read;
myCommand.Parameters.Add("@write", SqlDbType.Bit).Value = write;
// Mark the Command as a SPROC

myCommand.ExecuteNonQuery();

myCommand.Dispose();
myConnection.Close();

How do include paths work in Visual Studio?

You need to make sure and have the following:

#include <windows.h>

and not this:

#include "windows.h"

If that's not the problem, then check RichieHindle's response.

What are some great online database modeling tools?

The DB Designer Fork project claims that it can generate FireBird sql scripts.

git command to move a folder inside another

Command:

$ git mv oldFolderName newFolderName

It usually works fine.

Error "bad source ..." typically indicates that after last commit there were some renames in the source directory and hence git mv cannot find the expected file.

The solution is simple - just commit before applying git mv.

Spring boot Security Disable security

You can configure to toggle spring security in your project by following below 2 steps:

STEP 1: Add a @ConditionalOnProperty annotation on top of your SecurityConfig class. Refer below:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity (prePostEnabled = true)
@ConditionalOnProperty (name = "myproject.security.enabled", havingValue = "true", matchIfMissing = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
   // your security config
}

STEP 2: Add following config to your application.properties or application.yml file.

application.properties

security.ignored=/**
myproject.security.enabled=false

OR

application.yml

security:
  ignored: /**

myproject:
  security:
    enabled: false

Install mysql-python (Windows)

If you are trying to use mysqlclient on WINDOWS with this failure, try to install the lower version instead:

pip install mysqlclient==1.3.4

Using Axios GET with Authorization Header in React-Native App

Could not get this to work until I put Authorization in single quotes:

axios.get(URL, { headers: { 'Authorization': AuthStr } })

When do you use varargs in Java?

Varargs can be used when we are unsure about the number of arguments to be passed in a method. It creates an array of parameters of unspecified length in the background and such a parameter can be treated as an array in runtime.

If we have a method which is overloaded to accept different number of parameters, then instead of overloading the method different times, we can simply use varargs concept.

Also when the parameters' type is going to vary then using "Object...test" will simplify the code a lot.

For example:

public int calculate(int...list) {
    int sum = 0;
    for (int item : list) {
        sum += item;
    }
    return sum;
}

Here indirectly an array of int type (list) is passed as parameter and is treated as an array in the code.

For a better understanding follow this link(it helped me a lot in understanding this concept clearly): http://www.javadb.com/using-varargs-in-java

P.S: Even I was afraid of using varargs when I didn't knw abt it. But now I am used to it. As it is said: "We cling to the known, afraid of the unknown", so just use it as much as you can and you too will start liking it :)

How to check if the URL contains a given string?

Put in your js file

                var url = window.location.href;
                console.log(url);
                console.log(~url.indexOf("#product-consulation"));
                if (~url.indexOf("#product-consulation")) {
                    console.log('YES');
                    // $('html, body').animate({
                    //     scrollTop: $('#header').offset().top - 80
                    // }, 1000);
                } else {
                    console.log('NOPE');
                }

How to prevent 'query timeout expired'? (SQLNCLI11 error '80040e31')

Turns out that the post (or rather the whole table) was locked by the very same connection that I tried to update the post with.

I had a opened record set of the post that was created by:

Set RecSet = Conn.Execute()

This type of recordset is supposed to be read-only and when I was using MS Access as database it did not lock anything. But apparently this type of record set did lock something on MS SQL Server 2012 because when I added these lines of code before executing the UPDATE SQL statement...

RecSet.Close
Set RecSet = Nothing

...everything worked just fine.

So bottom line is to be careful with opened record sets - even if they are read-only they could lock your table from updates.

Deleting all files from a folder using PHP?

Another solution: This Class delete all files, subdirectories and files in the sub directories.

class Your_Class_Name {
    /**
     * @see http://php.net/manual/de/function.array-map.php
     * @see http://www.php.net/manual/en/function.rmdir.php 
     * @see http://www.php.net/manual/en/function.glob.php
     * @see http://php.net/manual/de/function.unlink.php
     * @param string $path
     */
    public function delete($path) {
        if (is_dir($path)) {
            array_map(function($value) {
                $this->delete($value);
                rmdir($value);
            },glob($path . '/*', GLOB_ONLYDIR));
            array_map('unlink', glob($path."/*"));
        }
    }
}

'pip install' fails for every package ("Could not find a version that satisfies the requirement")

Support for TLS 1.0 and 1.1 was dropped for PyPI. If your system does not use a more recent version, it could explain your error.

Could you try reinstalling pip system-wide, to update your system dependencies to a newer version of TLS?

This seems to be related to Unable to install Python libraries

See Dominique Barton's answer:

Apparently pip is trying to access PyPI via HTTPS (which is encrypted and fine), but with an old (insecure) SSL version. Your system seems to be out of date. It might help if you update your packages.

On Debian-based systems I'd try:

apt-get update && apt-get upgrade python-pip

On Red Hat Linux-based systems:

yum update python-pip # (or python2-pip, at least on Red Hat Linux 7)

On Mac:

sudo easy_install -U pip

You can also try to update openssl separately.

jQuery: How to capture the TAB keypress within a Textbox

$('#textbox').live('keypress', function(e) {
    if (e.keyCode === 9) {
        e.preventDefault();
        // do work
    }
});

Change <select>'s option and trigger events with JavaScript

You can fire the event manually after changing the selected option on the onclick event doing: document.getElementById("sel").onchange();

Why do abstract classes in Java have constructors?

Because abstract classes have state (fields) and somethimes they need to be initialized somehow.

How to horizontally align ul to center of div?

You can check this solved your problem...

    #headermenu ul{ 
        text-align: center;
    }
    #headermenu li { 
list-style-type: none;
        display: inline-block;
    }
    #headermenu ul li a{
        float: left;
    }

http://jsfiddle.net/thirtydot/VCZgW/

Multiple conditions in if statement shell script

if using /bin/sh you can use:

if [ <condition> ] && [ <condition> ]; then
    ...
fi

if using /bin/bash you can use:

if [[ <condition> && <condition> ]]; then
    ...
fi

Overflow-x:hidden doesn't prevent content from overflowing in mobile browsers

VictorS's comment on the accepted answer deserves to be it's own answer because it's a very elegant solution that does, indeed work. And I'll add a tad to it's usefulness.

Victor notes adding position:fixed works.

body.modal-open {
    overflow: hidden;
    position: fixed;
}

And indeed it does. However, it also has a slight side-affect of essentially scrolling to the top. position:absolute resolves this but, re-introduces the ability to scroll on mobile.

If you know your viewport (my plugin for adding viewport to the <body>) you can just add a css toggle for the position.

body.modal-open {
    // block scroll for mobile;
    // causes underlying page to jump to top;
    // prevents scrolling on all screens
    overflow: hidden;
    position: fixed;
}
body.viewport-lg {
    // block scroll for desktop;
    // will not jump to top;
    // will not prevent scroll on mobile
    position: absolute; 
}

I also add this to prevent the underlying page from jumping left/right when showing/hiding modals.

body {
    // STOP MOVING AROUND!
    overflow-x: hidden;
    overflow-y: scroll !important;
}

Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger

I had the same issue, for me this fixed the issue:
right click on the project ->maven -> update project

maven -> update project

Get current application physical path within Application_Start

You can also use

HttpRuntime.AppDomainAppVirtualPath

file_put_contents: Failed to open stream, no such file or directory

I was also stuck on the same kind of problem and I followed the simple steps below.

Just get the exact url of the file to which you want to copy, for example:

http://www.test.com/test.txt (file to copy)

Then pass the exact absolute folder path with filename where you do want to write that file.

  1. If you are on a Windows machine then d:/xampp/htdocs/upload/test.txt

  2. If you are on a Linux machine then /var/www/html/upload/test.txt

You can get the document root with the PHP function $_SERVER['DOCUMENT_ROOT'].

Filtering a spark dataframe based on date

df=df.filter(df["columnname"]>='2020-01-13')

Error in spring application context schema

I have recently had same issue with JPA-1.3

Nothing worked until I used explicit tools.xsd link

xsi:schemaLocation=" ...
    http://www.springframework.org/schema/tool
    http://www.springframework.org/schema/tool/spring-tool-3.2.xsd
    ... ">

like this:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
        http://www.springframework.org/schema/jdbc 
        http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
        http://www.springframework.org/schema/data/jpa
        http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
        http://www.springframework.org/schema/tool
        http://www.springframework.org/schema/tool/spring-tool-3.2.xsd
        ">

Static Final Variable in Java

In first statement you define variable, which common for all of the objects (class static field).

In the second statement you define variable, which belongs to each created object (a lot of copies).

In your case you should use the first one.

Php $_POST method to get textarea value

Always (always, always, I'm not kidding) use htmlspecialchars():

echo htmlspecialchars($_POST['contact_list']);

Maximum length of the textual representation of an IPv6 address?

Answered my own question:

IPv6 addresses are normally written as eight groups of four hexadecimal digits, where each group is separated by a colon (:).

So that's 39 characters max.

Best way to check if a character array is empty

Depends on whether or not your array is holding a null-terminated string. If so, then

if(text[0] == '\0') {}

should be sufficient.

Edit: Another method would be...

if (strcmp(text, "") == 0)

which is potentially less efficient but clearly expresses your intent.

What does ||= (or-equals) mean in Ruby?

Suppose a = 2 and b = 3

THEN, a ||= b will be resulted to a's value i.e. 2.

As when a evaluates to some value not resulted to false or nil.. That's why it ll not evaluate b's value.

Now Suppose a = nil and b = 3.

Then a ||= b will be resulted to 3 i.e. b's value.

As it first try to evaluates a's value which resulted to nil.. so it evaluated b's value.

The best example used in ror app is :

#To get currently logged in iser
def current_user
  @current_user ||= User.find_by_id(session[:user_id])
end

# Make current_user available in templates as a helper
helper_method :current_user

Where, User.find_by_id(session[:user_id]) is fired if and only if @current_user is not initialized before.

How to send POST request in JSON using HTTPClient in Android?

There are couple of ways to establish HHTP connection and fetch data from a RESTFULL web service. The most recent one is GSON. But before you proceed to GSON you must have some idea of the most traditional way of creating an HTTP Client and perform data communication with a remote server. I have mentioned both the methods to send POST & GET requests using HTTPClient.

/**
 * This method is used to process GET requests to the server.
 * 
 * @param url 
 * @return String
 * @throws IOException
 */
public static String connect(String url) throws IOException {

    HttpGet httpget = new HttpGet(url);
    HttpResponse response;
    HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used. 
    int timeoutConnection = 60*1000;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    // Set the default socket timeout (SO_TIMEOUT) 
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = 60*1000;

    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    HttpClient httpclient = new DefaultHttpClient(httpParameters);
    try {

        response = httpclient.execute(httpget);

        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream instream = entity.getContent();
            result = convertStreamToString(instream);
            //instream.close();
        }
    } 
    catch (ClientProtocolException e) {
        Utilities.showDLog("connect","ClientProtocolException:-"+e);
    } catch (IOException e) {
        Utilities.showDLog("connect","IOException:-"+e); 
    }
    return result;
}


 /**
 * This method is used to send POST requests to the server.
 * 
 * @param URL
 * @param paramenter
 * @return result of server response
 */
static public String postHTPPRequest(String URL, String paramenter) {       

    HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used. 
    int timeoutConnection = 60*1000;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    // Set the default socket timeout (SO_TIMEOUT) 
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = 60*1000;

    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    HttpClient httpclient = new DefaultHttpClient(httpParameters);
    HttpPost httppost = new HttpPost(URL);
    httppost.setHeader("Content-Type", "application/json");
    try {
        if (paramenter != null) {
            StringEntity tmp = null;
            tmp = new StringEntity(paramenter, "UTF-8");
            httppost.setEntity(tmp);
        }
        HttpResponse httpResponse = null;
        httpResponse = httpclient.execute(httppost);
        HttpEntity entity = httpResponse.getEntity();
        if (entity != null) {
            InputStream input = null;
            input = entity.getContent();
            String res = convertStreamToString(input);
            return res;
        }
    } 
     catch (Exception e) {
        System.out.print(e.toString());
    }
    return null;
}

How to check if a Java 8 Stream is empty?

Following Stuart's idea, this could be done with a Spliterator like this:

static <T> Stream<T> defaultIfEmpty(Stream<T> stream, Stream<T> defaultStream) {
    final Spliterator<T> spliterator = stream.spliterator();
    final AtomicReference<T> reference = new AtomicReference<>();
    if (spliterator.tryAdvance(reference::set)) {
        return Stream.concat(Stream.of(reference.get()), StreamSupport.stream(spliterator, stream.isParallel()));
    } else {
        return defaultStream;
    }
}

I think this works with parallel Streams as the stream.spliterator() operation will terminate the stream, and then rebuild it as required

In my use-case I needed a default Stream rather than a default value. that's quite easy to change if this is not what you need

curl.h no such file or directory

yes please download curl-devel as instructed above. also don't forget to link to lib curl:

-L/path/of/curl/lib/libcurl.a (g++)

cheers

css 'pointer-events' property alternative for IE

Best solution:

.disabled{filter: alpha(opacity=50);opacity: 0.5;z-index: 1;pointer-events: none;}

Runs perfectly on all browsers

How to run a single test with Mocha?

Looking into https://mochajs.org/#usage we see that simply use

mocha test/myfile

will work. You can omit the '.js' at the end.

Return Boolean Value on SQL Select Statement

For those of you who are interested in getting the value adding a custom column name, this worked for me:

CAST(
    CASE WHEN EXISTS ( 
           SELECT * 
           FROM mytable 
           WHERE mytable.id = 1
    ) 
    THEN TRUE 
    ELSE FALSE 
    END AS bool) 
AS "nameOfMyColumn"

You can skip the double quotes from the column name in case you're not interested in keeping the case sensitivity of the name (in some clients).

I slightly tweaked @Chad's answer for this.

Android Studio does not show layout preview

Changing the theme(near the android symbol for changing API version) from AppTheme to anything else like DeviceDefault or Holo fixed the problem easily.

What is the difference between Cloud Computing and Grid Computing?

Cloud Computing is For Service Oriented where as Grid Computing is for Application Oriented. Grid computing is used to build Virtual supercomputer using a middler ware to achieve a common task that can be shared among several resources. most probably this task will be kind of computing or data storage.

Cloud computing is providing services over the internet through several servers uses Virtualization.In cloud computing either you can provide service in three types Iaas , Paas, Saas . This will give you solution when you don't have any resources for a short time Business service over the Internet.

Where is JAVA_HOME on macOS Mojave (10.14) to Lion (10.7)?

For Fish terminal users on Mac (I believe it's available on Linux as well), this should work:

set -Ux JAVA_8 (/usr/libexec/java_home --version 1.8)
set -Ux JAVA_12 (/usr/libexec/java_home --version 12)
set -Ux JAVA_HOME $JAVA_8       //or whichever version you want as default

How do I encode a JavaScript object as JSON?

I think you can use JSON.stringify:

// after your each loop
JSON.stringify(values);

Pandas read_csv from url

UPDATE: From pandas 0.19.2 you can now just pass read_csv() the url directly, although that will fail if it requires authentication.


For older pandas versions, or if you need authentication, or for any other HTTP-fault-tolerant reason:

Use pandas.read_csv with a file-like object as the first argument.

  • If you want to read the csv from a string, you can use io.StringIO.

  • For the URL https://github.com/cs109/2014_data/blob/master/countries.csv, you get html response, not raw csv; you should use the url given by the Raw link in the github page for getting raw csv response , which is https://raw.githubusercontent.com/cs109/2014_data/master/countries.csv

Example:

import pandas as pd
import io
import requests
url="https://raw.githubusercontent.com/cs109/2014_data/master/countries.csv"
s=requests.get(url).content
c=pd.read_csv(io.StringIO(s.decode('utf-8')))

Notes:

in Python 2.x, the string-buffer object was StringIO.StringIO

UTC Date/Time String to Timezone

function _settimezone($time,$defaultzone,$newzone)
{
$date = new DateTime($time, new DateTimeZone($defaultzone));
$date->setTimezone(new DateTimeZone($newzone));
$result=$date->format('Y-m-d H:i:s');
return $result;
}

$defaultzone="UTC";
$newzone="America/New_York";
$time="2011-01-01 15:00:00";
$newtime=_settimezone($time,$defaultzone,$newzone);

Disable scrolling when touch moving certain element

document.addEventListener('touchstart', function(e) {e.preventDefault()}, false);
document.addEventListener('touchmove', function(e) {e.preventDefault()}, false);

This should prevent scrolling, but it will also break other touch events unless you define a custom way to handle them.

SELECT INTO USING UNION QUERY

INSERT INTO #Temp1
SELECT val1, val2 
FROM TABLE1
 UNION
SELECT val1, val2
FROM TABLE2

Why use Gradle instead of Ant or Maven?

This isn't my answer, but it definitely resonates with me. It's from ThoughtWorks' Technology Radar from October 2012:

Two things have caused fatigue with XML-based build tools like Ant and Maven: too many angry pointy braces and the coarseness of plug-in architectures. While syntax issues can be dealt with through generation, plug-in architectures severely limit the ability for build tools to grow gracefully as projects become more complex. We have come to feel that plug-ins are the wrong level of abstraction, and prefer language-based tools like Gradle and Rake instead, because they offer finer-grained abstractions and more flexibility long term.

List rows after specific date

Simply put:

SELECT * 
FROM TABLE_NAME
WHERE
dob > '1/21/2012'

Where 1/21/2012 is the date and you want all data, including that date.

SELECT * 
FROM TABLE_NAME
WHERE
dob BETWEEN '1/21/2012' AND '2/22/2012'

Use a between if you're selecting time between two dates

Relative path in HTML

The relative pathing is based on the document level of the client side i.e. the URL level of the document as seen in the browser.

If the URL of your website is: http://www.example.com/mywebsite/ then starting at the root level starts above the "mywebsite" folder path.

Anaconda export Environment file

  1. First activate your conda environment (the one u want to export/backup)
conda activate myEnv
  1. Export all packages to a file (myEnvBkp.txt)
conda list --explicit > myEnvBkp.txt
  1. Restore/import the environment:
conda create --name myEnvRestored --file myEnvBkp.txt

How to install MySQLdb (Python data access library to MySQL) on Mac OS X?

As stated on Installing MySQL-python on mac :

pip uninstall MySQL-python
brew install mysql
pip install MySQL-python

Then test it :

python -c "import MySQLdb"

Adding a color background and border radius to a Layout

background.xml in drawable folder.

<?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
    <solid android:color="#FFFFFF"/>    
    <stroke
        android:width="3dp"
        android:color="#0FECFF" />

    //specify gradient
    <gradient
        android:startColor="#ffffffff" 
        android:endColor="#110000FF" 
        android:angle="90"/> 

    <padding
        android:left="5dp"
        android:top="5dp"
        android:right="5dp"
        android:bottom="5dp"/> 
    <corners
        android:bottomRightRadius="7dp"
        android:bottomLeftRadius="7dp" 
        android:topLeftRadius="7dp"
        android:topRightRadius="7dp"/> 
</shape>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="210dp"
    android:orientation="vertical"
    android:layout_marginBottom="10dp"        
    android:background="@drawable/background">

In Python, how do I read the exif data for an image?

Here's the one that may be little easier to read. Hope this is helpful.

from PIL import Image
from PIL import ExifTags

exifData = {}
img = Image.open(picture.jpg)
exifDataRaw = img._getexif()
for tag, value in exifDataRaw.items():
    decodedTag = ExifTags.TAGS.get(tag, tag)
    exifData[decodedTag] = value

How to list all the files in android phone by using adb shell?

This command will show also if the file is hidden adb shell ls -laR | grep filename

Call Jquery function

Just add click event by jquery in $(document).ready() like :

$(document).ready(function(){

                  $('#YourControlID').click(function(){
                     if(Check your condtion)
                     {
                             $.messager.show({  
                                title:'My Title',  
                                msg:'The message content',  
                                showType:'fade',  
                                style:{  
                                    right:'',  
                                    bottom:''  
                                }  
                            });  
                     }
                 });
            });

How permission can be checked at runtime without throwing SecurityException?

Enable GPS location Android Studio

  1. Add permission entry in AndroidManifest.Xml

  1. MapsActivity.java

    public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
    
    private GoogleMap mMap;
    private Context context;
    private static final int PERMISSION_REQUEST_CODE = 1;
    Activity activity;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        context = getApplicationContext();
        activity = this;
        super.onCreate(savedInstanceState);
        requestPermission();
        checkPermission();
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    
    }
    
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        LatLng location = new LatLng(0, 0);
        mMap.addMarker(new MarkerOptions().position(location).title("Marker in Bangalore"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(location));
        mMap.setMyLocationEnabled(true);
    }
    
    private void requestPermission() {
        if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.ACCESS_FINE_LOCATION)) {
            Toast.makeText(context, "GPS permission allows us to access location data. Please allow in App Settings for additional functionality.", Toast.LENGTH_LONG).show();
        } else {
            ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST_CODE);
        }
    }
    
    private boolean checkPermission() {
        int result = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION);
        if (result == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            return false;
        }
    }
    

jQuery - replace all instances of a character in a string

You need to use a regular expression, so that you can specify the global (g) flag:

var s = 'some+multi+word+string'.replace(/\+/g, ' ');

(I removed the $() around the string, as replace is not a jQuery method, so that won't work at all.)

Can I use Twitter Bootstrap and jQuery UI at the same time?

The data-role="none" is the key to make them work together. You can apply to the elements you want bootstrap to touch but jquery mobile to ignore. like this input type="text" class="form-control" placeholder="Search" data-role="none"

Calculating moving average

  • Rolling Means/Maximums/Medians in the zoo package (rollmean)
  • MovingAverages in TTR
  • ma in forecast

Using sendmail from bash script for multiple recipients

to use sendmail from the shell script

subject="mail subject"
body="Hello World"
from="[email protected]"
to="[email protected],[email protected]"
echo -e "Subject:${subject}\n${body}" | sendmail -f "${from}" -t "${to}"

unix - count of columns in file

select any row in the file (in the example below, it's the 2nd row) and count the number of columns, where the delimiter is a space:

sed -n 2p text_file.dat | tr ' ' '\n' | wc -l

CSS '>' selector; what is it?

It means parent/child

example:

html>body

that's saying that body is a child of html

Check out: Selectors

Empty responseText from XMLHttpRequest

The browser is preventing you from cross-site scripting.

If the url is outside of your domain, then you need to do this on the server side or move it into your domain.

Collision resolution in Java HashMap

When you insert the pair (10, 17) and then (10, 20), there is technically no collision involved. You are just replacing the old value with the new value for a given key 10 (since in both cases, 10 is equal to 10 and also the hash code for 10 is always 10).

Collision happens when multiple keys hash to the same bucket. In that case, you need to make sure that you can distinguish between those keys. Chaining collision resolution is one of those techniques which is used for this.

As an example, let's suppose that two strings "abra ka dabra" and "wave my wand" yield hash codes 100 and 200 respectively. Assuming the total array size is 10, both of them end up in the same bucket (100 % 10 and 200 % 10). Chaining ensures that whenever you do map.get( "abra ka dabra" );, you end up with the correct value associated with the key. In the case of hash map in Java, this is done by using the equals method.

How to downgrade tensorflow, multiple versions possible?

Click to green checkbox on installed tensorflow and choose needed versionscreenshot Anaconda navigator

Serial Port (RS -232) Connection in C++

For the answer above, the default serial port is

        serialParams.BaudRate = 9600;
        serialParams.ByteSize = 8;
        serialParams.StopBits = TWOSTOPBITS;
        serialParams.Parity = NOPARITY;

Convert Float to Int in Swift

Converting is simple:

let float = Float(1.1) // 1.1
let int = Int(float) // 1

But it is not safe:

let float = Float(Int.max) + 1
let int = Int(float)

Will due to a nice crash:

fatal error: floating point value can not be converted to Int because it is greater than Int.max

So I've created an extension that handles overflow:

extension Double {
    // If you don't want your code crash on each overflow, use this function that operates on optionals
    // E.g.: Int(Double(Int.max) + 1) will crash:
    // fatal error: floating point value can not be converted to Int because it is greater than Int.max
    func toInt() -> Int? {
        if self > Double(Int.min) && self < Double(Int.max) {
            return Int(self)
        } else {
            return nil
        }
    }
}


extension Float {
    func toInt() -> Int? {
        if self > Float(Int.min) && self < Float(Int.max) {
            return Int(self)
        } else {
            return nil
        }
    }
}

I hope this can help someone

Do on-demand Mac OS X cloud services exist, comparable to Amazon's EC2 on-demand instances?

Here are some methods that may help others, though they aren't really services as much as they may be described as "methods that may, after some torture of effort or logic, lead to a claim of on-demand access to Mac OS X" (no doubt I should patent that phrase).

Fundamentally, I am inclined to believe that on-demand (per-hour) hosting does not exist, and @Erik has given information for the shortest feasible services, i.e. monthly hosting.


It seems that one may use EC2 itself, but install OS X on the instance through a lot of elbow grease.

  • This article on Lifehacker.com gives instructions for setting up OSX under Virtual Box and depends on hardware virtualization. It seems that the Cluster Compute instances (and Cluster GPU, but ignore these) are the only ones supporting hardware virtualization.
  • This article gives instructions for transferring a VirtualBox image to EC2.

Where this gets tricky is I'm not sure if this will work for a cluster compute instance. In fact, I think this is likely to be a royal pain. A similar approach may work for Rackspace or other cloud services.

I found only this site claiming on-demand Mac hosting, with a Mac Mini. It doesn't look particularly accurate: it offers free on-demand access to a Mini if one pays for a month of bandwidth. That's like free bandwidth if one rents a Mini for a month. That's not really how "on-demand" works.


Update 1: In the end, it seems that nobody offers a comparable service. An outfit called Media Temple claims they will offer the first virtual servers using Parallels, OS X Leopard, and some other stuff (in other words, I wonder if there is some caveat that makes them unique, but, without that caveat, someone else may have a usable offering).

After this search, I think that a counterpart to EC2 does not exist for the OS X operating system. It is extraordinarily unlikely that one would exist, offer a scalable solution, and yet be very difficult to find. One could set it up internally, but there's no reseller/vendor offering on-demand, hourly virtual servers. This may be disappointing, but not surprising - apparently iCloud is running on Amazon and Microsoft systems.

How to create a jQuery plugin with methods?

What about this approach:

jQuery.fn.messagePlugin = function(){
    var selectedObjects = this;
    return {
             saySomething : function(message){
                              $(selectedObjects).each(function(){
                                $(this).html(message);
                              });
                              return selectedObjects; // Preserve the jQuery chainability 
                            },
             anotherAction : function(){
                               //...
                               return selectedObjects;
                             }
           };
}
// Usage:
$('p').messagePlugin().saySomething('I am a Paragraph').css('color', 'red');

The selected objects are stored in the messagePlugin closure, and that function returns an object that contains the functions associated with the plugin, the in each function you can perform the desired actions to the currently selected objects.

You can test and play with the code here.

Edit: Updated code to preserve the power of the jQuery chainability.

How can I pad a String in Java?

Here is another way to pad to the right:

// put the number of spaces, or any character you like, in your paddedString

String paddedString = "--------------------";

String myStringToBePadded = "I like donuts";

myStringToBePadded = myStringToBePadded + paddedString.substring(myStringToBePadded.length());

//result:
myStringToBePadded = "I like donuts-------";

jQuery - multiple $(document).ready ...?

All will get executed and On first Called first run basis!!

<div id="target"></div>

<script>
  $(document).ready(function(){
    jQuery('#target').append('target edit 1<br>');
  });
  $(document).ready(function(){
    jQuery('#target').append('target edit 2<br>');
  });
  $(document).ready(function(){
    jQuery('#target').append('target edit 3<br>');
  });
</script>

Demo As you can see they do not replace each other

Also one thing i would like to mention

in place of this

$(document).ready(function(){});

you can use this shortcut

jQuery(function(){
   //dom ready codes
});

Unknown version of Tomcat was specified in Eclipse

It may be due to the access of the tomcat installation path(C:\Program Files\Apache Software Foundation\Tomcat 9.0) wasn't available with the current user.

How do I detect unsigned integer multiply overflow?

A clean way to do it would be to override all operators (+ and * in particular) and check for an overflow before performing the operations.

Getting "file not found" in Bridging Header when importing Objective-C frameworks into Swift project

I had the same problem. For me the reason was that I was using the same bridging-header for both my App and my Today Extension. My Today Extension does not include Parse, but because it was defined in the bridging-header it was trying to look for it. I created a new bridging-header for my Today Extension and the error dissapeared.

How to insert &nbsp; in XSLT

you can also use:

<xsl:value-of select="'&amp;nbsp'"/>

remember the amp after the & or you will get an error message

Background blur with CSS

There is a simple and very common technique by using 2 background images: a crisp and a blurry one. You set the crisp image as a background for the body and the blurry one as a background image for your container. The blurry image must be set to fixed positioning and the alignment is 100% perfect. I used it before and it works.

body {
    background: url(yourCrispImage.jpg) no-repeat;
}

#container {
    background: url(yourBlurryImage.jpg) no-repeat fixed;
}

You can see a working example at the following fiddle: http://jsfiddle.net/jTUjT/5/. Try to resize the browser and see that the alignment never fails.


If only CSS element() was supported by other browsers other than Mozilla's -moz-element() you could create great effects. See this demo with Mozilla.

AndroidStudio gradle proxy

For the new android studio 1.2 you find the gradle vm args under:

File
- Settings
  - Build, Execution, Deployment
    - Build Tools
      - Gradle

Javascript communication between browser tabs/windows

Found different way using HTML5 localstorage, I've create a library with events like API:

sysend.on('foo', function(message) {
    console.log(message);
});
var input = document.getElementsByTagName('input')[0];
document.getElementsByTagName('button')[0].onclick = function() {
    sysend.broadcast('foo', {message: input.value});
};

it will send messages to all other pages but not for current one.

How to right align widget in horizontal linear layout Android?

Try This..

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" 
    android:orientation="horizontal" 
    android:gravity="right" >



    <TextView android:text="TextView" android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </TextView>

</LinearLayout>

Escaping single quote in PHP when inserting into MySQL

You should be escaping each of these strings (in both snippets) with mysql_real_escape_string().

http://us3.php.net/mysql-real-escape-string

The reason your two queries are behaving differently is likely because you have magic_quotes_gpc turned on (which you should know is a bad idea). This means that strings gathered from $_GET, $_POST and $_COOKIES are escaped for you (i.e., "O'Brien" -> "O\'Brien").

Once you store the data, and subsequently retrieve it again, the string you get back from the database will not be automatically escaped for you. You'll get back "O'Brien". So, you will need to pass it through mysql_real_escape_string().

"Repository does not have a release file" error

I have been having this issue for a couple of weeks and finally decided to sit down and try and fix it. I have no interest in config file editing as I'm primarily a Windows user.

In a fit of "clickyness" I noticed that the ubuntu server location was set "for United kingdom". I switched this over to "Main Server" and hey presto... it all stared updating.

So, it seems like the regionalised server (for the UK at least) has a very limited support window so if you are an infrequent user it is likely it will not have a valid upgrade path from your current version to the latest.

Edit: I only just noticted the previous reply, after posting. 100% agree.

How do I see if Wi-Fi is connected on Android?

The NetworkInfo class is deprecated as of API level 29, along with the related access methods like ConnectivityManager#getNetworkInfo() and ConnectivityManager#getActiveNetworkInfo().

The documentation now suggests people to use the ConnectivityManager.NetworkCallback API for asynchronized callback monitoring, or use ConnectivityManager#getNetworkCapabilities or ConnectivityManager#getLinkProperties for synchronized access of network information

Callers should instead use the ConnectivityManager.NetworkCallback API to learn about connectivity changes, or switch to use ConnectivityManager#getNetworkCapabilities or ConnectivityManager#getLinkProperties to get information synchronously.


To check if WiFi is connected, here's the code that I use:

Kotlin:

val connMgr = applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
connMgr?: return false
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    val network: Network = connMgr.activeNetwork ?: return false
    val capabilities = connMgr.getNetworkCapabilities(network)
    return capabilities != null && capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
} else {
    val networkInfo = connMgr.activeNetworkInfo ?: return false
    return networkInfo.isConnected && networkInfo.type == ConnectivityManager.TYPE_WIFI
}

Java:

ConnectivityManager connMgr = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
if (connMgr == null) {
    return false;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    Network network = connMgr.getActiveNetwork();
    if (network == null) return false;
    NetworkCapabilities capabilities = connMgr.getNetworkCapabilities(network);
    return capabilities != null && capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI);
} else {
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    return networkInfo.isConnected() && networkInfo.getType() == ConnectivityManager.TYPE_WIFI;
}

Remember to also add permission ACCESS_NETWORK_STATE to your Manifest file.

Embedding Windows Media Player for all browsers

December 2020 :

  • We have now Firefox 83.0 and Chrome 87.0
  • Internet Explorer is dead, it has been replaced by the new Chromium-based Edge 87.0
  • Silverlight is dead
  • Windows XP is dead
  • WMV is not a standard : https://www.w3schools.com/html/html_media.asp

To answer the question :

  • You have to convert your WMV file to another format : MP4, WebM or Ogg video.
  • Then embed it in your page with the HTML 5 <video> element.

I think this question should be closed.

How do I make a batch file terminate upon encountering an error?

Add || goto :label to each line, and then define a :label.

For example, create this .cmd file:

@echo off

echo Starting very complicated batch file...
ping -invalid-arg || goto :error
echo OH noes, this shouldn't have succeeded.
goto :EOF

:error
echo Failed with error #%errorlevel%.
exit /b %errorlevel%

See also question about exiting batch file subroutine.

How to set character limit on the_content() and the_excerpt() in wordpress

<?php 
echo apply_filters( 'woocommerce_short_description', substr($post->post_excerpt, 0, 500) ) 
?>

How to convert an XML file to nice pandas dataframe?

You can easily use xml (from the Python standard library) to convert to a pandas.DataFrame. Here's what I would do (when reading from a file replace xml_data with the name of your file or file object):

import pandas as pd
import xml.etree.ElementTree as ET
import io

def iter_docs(author):
    author_attr = author.attrib
    for doc in author.iter('document'):
        doc_dict = author_attr.copy()
        doc_dict.update(doc.attrib)
        doc_dict['data'] = doc.text
        yield doc_dict

xml_data = io.StringIO(u'''\
<author type="XXX" language="EN" gender="xx" feature="xx" web="foobar.com">
    <documents count="N">
        <document KEY="e95a9a6c790ecb95e46cf15bee517651" web="www.foo_bar_exmaple.com"><![CDATA[A large text with lots of strings and punctuations symbols [...]
]]>
        </document>
        <document KEY="bc360cfbafc39970587547215162f0db" web="www.foo_bar_exmaple.com"><![CDATA[A large text with lots of strings and punctuations symbols [...]
]]>
        </document>
        <document KEY="19e71144c50a8b9160b3f0955e906fce" web="www.foo_bar_exmaple.com"><![CDATA[A large text with lots of strings and punctuations symbols [...]
]]>
        </document>
        <document KEY="21d4af9021a174f61b884606c74d9e42" web="www.foo_bar_exmaple.com"><![CDATA[A large text with lots of strings and punctuations symbols [...]
]]>
        </document>
        <document KEY="28a45eb2460899763d709ca00ddbb665" web="www.foo_bar_exmaple.com"><![CDATA[A large text with lots of strings and punctuations symbols [...]
]]>
        </document>
        <document KEY="a0c0712a6a351f85d9f5757e9fff8946" web="www.foo_bar_exmaple.com"><![CDATA[A large text with lots of strings and punctuations symbols [...]
]]>
        </document>
        <document KEY="626726ba8d34d15d02b6d043c55fe691" web="www.foo_bar_exmaple.com"><![CDATA[A large text with lots of strings and punctuations symbols [...]
]]>
        </document>
        <document KEY="2cb473e0f102e2e4a40aa3006e412ae4" web="www.foo_bar_exmaple.com"><![CDATA[A large text with lots of strings and punctuations symbols [...] [...]
]]>
        </document>
    </documents>
</author>
''')

etree = ET.parse(xml_data) #create an ElementTree object 
doc_df = pd.DataFrame(list(iter_docs(etree.getroot())))

If there are multiple authors in your original document or the root of your XML is not an author, then I would add the following generator:

def iter_author(etree):
    for author in etree.iter('author'):
        for row in iter_docs(author):
            yield row

and change doc_df = pd.DataFrame(list(iter_docs(etree.getroot()))) to doc_df = pd.DataFrame(list(iter_author(etree)))

Have a look at the ElementTree tutorial provided in the xml library documentation.

How to get the caret column (not pixels) position in a textarea, in characters, from the start?

Updated 5 September 2010

Seeing as everyone seems to get directed here for this issue, I'm adding my answer to a similar question, which contains the same code as this answer but with full background for those who are interested:

IE's document.selection.createRange doesn't include leading or trailing blank lines

To account for trailing line breaks is tricky in IE, and I haven't seen any solution that does this correctly, including any other answers to this question. It is possible, however, using the following function, which will return you the start and end of the selection (which are the same in the case of a caret) within a <textarea> or text <input>.

Note that the textarea must have focus for this function to work properly in IE. If in doubt, call the textarea's focus() method first.

function getInputSelection(el) {
    var start = 0, end = 0, normalizedValue, range,
        textInputRange, len, endRange;

    if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
        start = el.selectionStart;
        end = el.selectionEnd;
    } else {
        range = document.selection.createRange();

        if (range && range.parentElement() == el) {
            len = el.value.length;
            normalizedValue = el.value.replace(/\r\n/g, "\n");

            // Create a working TextRange that lives only in the input
            textInputRange = el.createTextRange();
            textInputRange.moveToBookmark(range.getBookmark());

            // Check if the start and end of the selection are at the very end
            // of the input, since moveStart/moveEnd doesn't return what we want
            // in those cases
            endRange = el.createTextRange();
            endRange.collapse(false);

            if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
                start = end = len;
            } else {
                start = -textInputRange.moveStart("character", -len);
                start += normalizedValue.slice(0, start).split("\n").length - 1;

                if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
                    end = len;
                } else {
                    end = -textInputRange.moveEnd("character", -len);
                    end += normalizedValue.slice(0, end).split("\n").length - 1;
                }
            }
        }
    }

    return {
        start: start,
        end: end
    };
}

Java - How to access an ArrayList of another class?

You can do the following:

  public class Numbers {
    private int number1 = 50;
    private int number2 = 100;
    private List<Integer> list;

    public Numbers() {
      list = new ArrayList<Integer>();
      list.add(number1);
      list.add(number2);
    }

    int getNumber(int pos)
    {
      return list.get(pos);
    }
  }

  public class Test {
    private Numbers numbers;

    public Test(){
      numbers = new Numbers();
      int number1 = numbers.getNumber(0);
      int number2 = numbers.getNumber(1);
    }
  }

How to clean node_modules folder of packages that are not in package.json?

You could remove your node_modules/ folder and then reinstall the dependencies from package.json.

rm -rf node_modules/
npm install

This would erase all installed packages in the current folder and only install the dependencies from package.json. If the dependencies have been previously installed npm will try to use the cached version, avoiding downloading the dependency a second time.

Git push error pre-receive hook declined

Might not be the case, but this was the solution to my "pre-receive hook declined" error:

There are some repositories that only allow modifications through Pull Request. This means that you have to

  1. Create a new branch taking as base the branch that you want to push your changes to.
  2. Commit and push your changes to the new branch.
  3. Open a Pull Request to merge your branch with the original one.

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

For anyone looking to style child elements of a :host here is an example of how to use ::ng-deep

:host::ng-deep <child element>

e.g :host::ng-deep span { color: red; }

As others said /deep/ is deprecated

How can I get sin, cos, and tan to use degrees instead of radians?

Multiply the input by Math.PI/180 to convert from degrees to radians before calling the system trig functions.

You could also define your own functions:

function sinDegrees(angleDegrees) {
    return Math.sin(angleDegrees*Math.PI/180);
};

and so on.

How to overcome "'aclocal-1.15' is missing on your system" warning?

A generic answer that may or not apply to this specific case:

As the error message hint at, aclocal-1.15 should only be required if you modified files that were used to generate aclocal.m4

If you don't modify any of those files (including configure.ac) then you should not need to have aclocal-1.15.

In my case, the problem was not that any of those files was modified but somehow the timestamp on configure.ac was 6 minutes later compared to aclocal.m4.

I haven't figured out why, but a clean clone of my git repo solved the issue for me. Maybe something linked to git and how it created files in the first place.

Rather than rerunning autoconf and friends, I would just try to get a clean clone and try again.

It's also possible that somebody committed a change to configure.ac but didn't regenerate the aclocal.m4, in which case you indeed have to rerun automake and friends.

How can I remove jenkins completely from linux

For sentOs, it's works for me At first stop service by sudo service jenkins stop

Than remove by sudo yum remove jenkins

How to Generate a random number of fixed length using JavaScript?

I was thinking about the same today and then go with the solution.

var generateOTP = function(otpLength=6) {
  let baseNumber = Math.pow(10, otpLength -1 );
  let number = Math.floor(Math.random()*baseNumber);
  /*
  Check if number have 0 as first digit
  */
  if (number < baseNumber) {
    number += baseNumber;
  }
  return number;
};

Let me know if it has any bug. Thanks.

How can one develop iPhone apps in Java?

I think we will have to wait a couple of years more to see more progress. However, there are now more frameworks and tools available:

Here a list of 5 options:

Excel Validation Drop Down list using VBA

You are defining your array as xlValidateList(), so when you try to assign the type, it gets confused as to what you are trying to assign to the type.

Instead, try this:

Dim MyList(5) As String
MyList(0) = 1
MyList(1) = 2
MyList(2) = 3
MyList(3) = 4
MyList(4) = 5
MyList(5) = 6

With Range("A1").Validation
    .Delete
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
         Operator:=xlBetween, Formula1:=Join(MyList, ",")
End With

Simplest Way to Test ODBC on WIndows

Make a file SOMEFILENAME.udl then double click on it and set it up as an ODBC connection object, username, pwd, target server

How to install Guest addition in Mac OS as guest and Windows machine as host

Guest Additions are available for MacOS starting with VirtualBox 6.0.

Installing:

  1. Boot & login into your guest macOS.
  2. In VirtualBox UI, use menu Devices | Insert Guest Additions CD image...
  3. CD will appear on your macOS desktop, open it.
  4. Run VBoxDarwinAdditions.pkg.
  5. Go through installer, it's mostly about clicking Next.
  6. At some step, macOS will be asking about permissions for Oracle. Click the button to go to System Preferences and allow it.
  7. If you forgot/misclicked in step 6, go to macOS System Preferences | Security & Privacy | General. In the bottom, there will be a question to allow permissions for Oracle. Allow it.

Troubleshooting

  1. macOS 10.15 introduced new code signing requirements; Guest additions installation will fail. However, if you reboot and apply step 7 from list above, shared clipboard will still work.
  2. VirtualBox < 6.0.12 has a bug where Guest Additions service doesn't start. Use newer VirtualBox.

How to update Xcode from command line

I got this error after deleting Xcode. I fixed it by resetting the command line tools path with sudo xcode-select -r.

Before:

navin@Radiant ~$ /usr/bin/clang
xcrun: error: active developer path ("/Applications/Xcode.app/Contents/Developer") does not exist
Use `sudo xcode-select --switch path/to/Xcode.app` to specify the Xcode that you wish to use for command line developer tools, or use `xcode-select --install` to install the standalone command line developer tools.
See `man xcode-select` for more details.

navin@Radiant ~$ xcode-select --install
xcode-select: error: command line tools are already installed, use "Software Update" to install updates

After:

navin@Radiant ~$ /usr/bin/clang
clang: error: no input files

How can you encode a string to Base64 in JavaScript?

Contributing with a minified polyfill for window.atob + window.btoa that I'm currently using.

(function(){function t(t){this.message=t}var e="undefined"!=typeof exports?exports:this,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";t.prototype=Error(),t.prototype.name="InvalidCharacterError",e.btoa||(e.btoa=function(e){for(var o,n,a=0,i=r,c="";e.charAt(0|a)||(i="=",a%1);c+=i.charAt(63&o>>8-8*(a%1))){if(n=e.charCodeAt(a+=.75),n>255)throw new t("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");o=o<<8|n}return c}),e.atob||(e.atob=function(e){if(e=e.replace(/=+$/,""),1==e.length%4)throw new t("'atob' failed: The string to be decoded is not correctly encoded.");for(var o,n,a=0,i=0,c="";n=e.charAt(i++);~n&&(o=a%4?64*o+n:n,a++%4)?c+=String.fromCharCode(255&o>>(6&-2*a)):0)n=r.indexOf(n);return c})})();

Creating a file name as a timestamp in a batch job

I know this thread is old but I just want to add this here because it helped me alot trying to figure this all out and its clean. The nice thing about this is you could put it in a loop for a batch file that's always running. Server up-time log or something. That's what I use it for anyways. I hope this helps someone someday.

@setlocal enableextensions enabledelayedexpansion
@echo off

call :timestamp freshtime freshdate
echo %freshdate% - %freshtime% - Some data >> "%freshdate - Somelog.log"

:timestamp
set hour=%time:~0,2%
if "%hour:~0,1%" == " " set hour=0%hour:~1,1%
set min=%time:~3,2%
if "%min:~0,1%" == " " set min=0%min:~1,1%
set secs=%time:~6,2%
if "%secs:~0,1%" == " " set secs=0%secs:~1,1%
set FreshTime=%hour%:%min%:%secs%

set year=%date:~-4%
set month=%date:~4,2%
if "%month:~0,1%" == " " set month=0%month:~1,1%
set day=%date:~7,2%
if "%day:~0,1%" == " " set day=0%day:~1,1%
set FreshDate=%month%.%day%.%year%

How to create threads in nodejs

NodeJS now includes threads (as an experimental feature at time of answering).

Android studio: emulator is running but not showing up in Run App "choose a running device"

in your device you want to run app on Go to settings About device >> Build number triple clicks or more and back to settings you will found "Developer options" appear go to and click on "USB debugging" Done

Angular2: Cannot read property 'name' of undefined

This worked for me:

export class Hero{
   id: number;
   name: string;

   public Hero(i: number, n: string){
     this.id = 0;
     this.name = '';
   }
 }

and make sure you initialize as well selectedHero

selectedHero: Hero = new Hero();

How to draw checkbox or tick mark in GitHub Markdown table?

There are very nice Emoji icons instructions available at

You can check them out. I hope you would find suitable icons for your writing.

Nice Emojis

Best,

init-param and context-param

Consider the below definition in web.xml

<servlet>
    <servlet-name>HelloWorld</servlet-name>
    <servlet-class>TestServlet</servlet-class>
    <init-param>
        <param-name>myprop</param-name>
        <param-value>value</param-value>
    </init-param>
</servlet>

You can see that init-param is defined inside a servlet element. This means it is only available to the servlet under declaration and not to other parts of the web application. If you want this parameter to be available to other parts of the application say a JSP this needs to be explicitly passed to the JSP. For instance passed as request.setAttribute(). This is highly inefficient and difficult to code.

So if you want to get access to global values from anywhere within the application without explicitly passing those values, you need to use Context Init parameters.

Consider the following definition in web.xml

 <web-app>
      <context-param>
           <param-name>myprop</param-name>
           <param-value>value</param-value>
      </context-param>
 </web-app>

This context param is available to all parts of the web application and it can be retrieved from the Context object. For instance, getServletContext().getInitParameter(“dbname”);

From a JSP you can access the context parameter using the application implicit object. For example, application.getAttribute(“dbname”);

What does "<html xmlns="http://www.w3.org/1999/xhtml">" do?

Its an XML namespace. It is required when you use XHTML 1.0 or 1.1 doctypes or application/xhtml+xml mimetypes.

You should be using HTML5 doctype, then you don't need it for text/html. Better start from template like this :

<!DOCTYPE html>
<html>
    <head>
        <meta charset=utf-8 />
        <title>domcument title</title>
        <link rel="stylesheet" href="/stylesheet.css" type="text/css" />
    </head>
    <body>
            <!-- your html content -->
            <script src="/script.js"></script>
    </body>
</html>



When you have put your Doctype straight - do and validate you html and your css .
That usually will sove you layout issues.

change html input type by JS?

This is not supported by some browsers (IE if I recall), but it works in the rest:

document.getElementById("password-field").attributes["type"] = "password";

or

document.getElementById("password-field").attributes["type"] = "text";

Connection Java-MySql : Public Key Retrieval is not allowed

First of all, please make sure your Database server is up and running. I was getting the same error, after trying all the answers listed here I found out that my Database server was not running.

You can check the same from MySQL Workbench, or Command line using

mysql -u USERNAME -p

This sounds obvious, but many times we assume that Database server is up and running all the time, especially when we are working on our local machine, when we restart/shutdown the machine, Database server will be shutdown automatically.

How can I test an AngularJS service from the console?

@JustGoscha's answer is spot on, but that's a lot to type when I want access, so I added this to the bottom of my app.js. Then all I have to type is x = getSrv('$http') to get the http service.

// @if DEBUG
function getSrv(name, element) {
    element = element || '*[ng-app]';
    return angular.element(element).injector().get(name);
}
// @endif

It adds it to the global scope but only in debug mode. I put it inside the @if DEBUG so that I don't end up with it in the production code. I use this method to remove debug code from prouduction builds.

How to go from one page to another page using javascript?

To simply redirect a browser using javascript:

window.location.href = "http://example.com/new_url";

To redirect AND submit a form (i.e. login details), requires no javascript:

<form action="/new_url" method="POST">
   <input name="username">
   <input type="password" name="password">
   <button type="submit">Submit</button>
</form>

How to escape regular expression special characters using javascript?

Use the backslash to escape a character. For example:

/\\d/

This will match \d instead of a numeric character

How to load local html file into UIWebView

When your project gets bigger, you might need some structure, so that your HTML page can reference files located in subfolders.

Assuming you drag your html_files folder to Xcode and select the Create folder references option, the following Swift code ensures that the WKWebView supports also the resulting folder structure:

import WebKit

@IBOutlet weak var webView: WKWebView!

if let path = Bundle.main.path(forResource: "sample", ofType: "html", inDirectory: "html_files") {
    webView.load( URLRequest(url: URL(fileURLWithPath: path)) )
}

This means that if your sample.html file contains an <img src="subfolder/myimage.jpg"> tag, then the image file myimage.jpg in subfolder will also be loaded and displayed.

Credits: https://stackoverflow.com/a/8436281/4769344

Creating a UITableView Programmatically

sample table

 #import "StartreserveViewController.h"
 #import "CollectionViewController.h"
 #import "TableViewCell1.h"
@interface StartreserveViewController ()


{
NSArray *name;
NSArray *images;
NSInteger selectindex;

}

@end

@implementation StartreserveViewController

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.

self.view.backgroundColor = [UIColor blueColor];
_startReservetable.backgroundColor = [UIColor blueColor];


name = [[NSArray alloc]initWithObjects:@"Mobiles",@"Costumes",@"Shoes", 
nil];
images = [[NSArray 
 alloc]initWithObjects:@"mobilestitle.jpg",@"costumetitle.jpeg", 
 @"shoestitle.png",nil];



  }

 - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

pragma mark - UiTableview Datasource

 -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
 {
return 1;
 }

 -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:
 (NSInteger)section
 {
return 3;
 }

 - (UITableViewCell *)tableView:(UITableView *)tableView 
  cellForRowAtIndexPath:(NSIndexPath *)indexPath
 {


static NSString *cellId = @"tableview";

TableViewCell1  *cell =[tableView dequeueReusableCellWithIdentifier:cellId];


cell.cellTxt .text = [name objectAtIndex:indexPath.row];

cell.cellImg.image = [UIImage imageNamed:[images 
objectAtIndex:indexPath.row]];

return cell;



 }


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:
(NSIndexPath *)indexPath
 {
selectindex = indexPath.row;
[self performSegueWithIdentifier:@"second" sender:self];
}



   #pragma mark - Navigation

 // In a storyboard-based application, you will often want to do a little     
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

if ([segue.identifier isEqualToString:@"second"])

  {
    CollectionViewController *obj = segue.destinationViewController;
           obj.receivename = [name objectAtIndex:selectindex];

  }



// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}

 @end

.h

#import <UIKit/UIKit.h>

@interface StartreserveViewController :      
UIViewController<UITableViewDelegate,UITableViewDataSource>    
@property (strong, nonatomic) IBOutlet UITableView *startReservetable;

 @end

How to force a script reload and re-execute?

I know that is to late, but I want to share my answer. What I did it's save de script's tags in a HTML file, locking up the scripts on my Index file in a div with an id, something like this.

<div id="ScriptsReload"><script src="js/script.js"></script></div>

and when I wanted to refresh I just used.

$("#ScriptsReload").load("html_with_scripts_tags.html", "", function(
    response,
    status,
    request
  ) {

  });

Getting path of captured image in Android using camera intent

There is a solution to create file (on external cache dir or anywhere else) and put this file's uri as output extra to camera intent - this will define path where taken picture will be stored.

Here is an example:

File file;
Uri fileUri;
final int RC_TAKE_PHOTO = 1;

    private void takePhoto() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        file = new File(getActivity().getExternalCacheDir(), 
                String.valueOf(System.currentTimeMillis()) + ".jpg");
        fileUri = Uri.fromFile(file);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        getActivity().startActivityForResult(intent, RC_TAKE_PHOTO);

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RC_TAKE_PHOTO && resultCode == RESULT_OK) {

                //do whatever you need with taken photo using file or fileUri

            }
        }
    }

Then if you don't need the file anymore, you can delete it using file.delete();

By the way, files from cache dir will be removed when user clears app's cache from apps settings.

PHP php_network_getaddresses: getaddrinfo failed: No such host is known

Your target domain might refuse to send you information. This can work as a filter based on browser agent or any other header information. This is a defense against bots, crawlers or any unwanted applications.

Is it possible to use vh minus pixels in a CSS calc()?

It does work indeed. Issue was with my less compiler. It was compiled in to:

.container {
  min-height: calc(-51vh);
}

Fixed with the following code in less file:

.container {
  min-height: calc(~"100vh - 150px");
}

Thanks to this link: Less Aggressive Compilation with CSS3 calc

Angular - Use pipes in services and components

As usual in Angular, you can rely on dependency injection:

import { DatePipe } from '@angular/common';

class MyService {

  constructor(private datePipe: DatePipe) {}

  transformDate(date) {
    return this.datePipe.transform(date, 'yyyy-MM-dd');
  }
}

Add DatePipe to your providers list in your module; if you forget to do this you'll get an error no provider for DatePipe:

providers: [DatePipe,...]

Update Angular 6: Angular 6 now offers pretty much every formatting functions used by the pipes publicly. For example, you can now use the formatDate function directly.

import { formatDate } from '@angular/common';

class MyService {

  constructor(@Inject(LOCALE_ID) private locale: string) {}

  transformDate(date) {
    return formatDate(date, 'yyyy-MM-dd', this.locale);
  }
}

Before Angular 5: Be warned though that the DatePipe was relying on the Intl API until version 5, which is not supported by all browsers (check the compatibility table).

If you're using older Angular versions, you should add the Intl polyfill to your project to avoid any problem. See this related question for a more detailed answer.

Use of Application.DoEvents()

Check out the MSDN Documentation for the Application.DoEvents method.

Python PDF library

The two that come to mind are:

Select entries between dates in doctrine 2

I believe the correct way of doing it would be to use query builder expressions:

$now = new DateTimeImmutable();
$thirtyDaysAgo = $now->sub(new \DateInterval("P30D"));
$qb->select('e')
   ->from('Entity','e')
   ->add('where', $qb->expr()->between(
            'e.datefield',
            ':from',
            ':to'
        )
    )
   ->setParameters(array('from' => $thirtyDaysAgo, 'to' => $now));

http://docs.doctrine-project.org/en/latest/reference/query-builder.html#the-expr-class

Edit: The advantage this method has over any of the other answers here is that it's database software independent - you should let Doctrine handle the date type as it has an abstraction layer for dealing with this sort of thing.

If you do something like adding a string variable in the form 'Y-m-d' it will break when it goes to a database platform other than MySQL, for example.

Declaring and using MySQL varchar variables

In Mysql, We can declare and use variables with set command like below

mysql> set @foo="manjeet";
mysql> select * from table where name = @foo;

SQL JOIN, GROUP BY on three tables to get totals

I have a tip for those, who want to get various aggregated values from the same table.

Lets say I have table with users and table with points the users acquire. So the connection between them is 1:N (one user, many points records).

Now in the table 'points' I also store the information about for what did the user get the points (login, clicking a banner etc.). And I want to list all users ordered by SUM(points) AND then by SUM(points WHERE type = x). That is to say ordered by all the points user has and then by points the user got for a specific action (eg. login).

The SQL would be:

SELECT SUM(points.points) AS points_all, SUM(points.points * (points.type = 7)) AS points_login
FROM user
LEFT JOIN points ON user.id = points.user_id
GROUP BY user.id

The beauty of this is in the SUM(points.points * (points.type = 7)) where the inner parenthesis evaluates to either 0 or 1 thus multiplying the given points value by 0 or 1, depending on wheteher it equals to the the type of points we want.

SQL update fields of one table from fields of another one

you can build and execute dynamic sql to do this, but its really not ideal

How do I clear a C++ array?

std::fill(a.begin(),a.end(),0);

is there a function in lodash to replace matched item

If you're just trying to replace one property, lodash _.find and _.set should be enough:

var arr = [{id: 1, name: "Person 1"}, {id: 2, name: "Person 2"}];

_.set(_.find(arr, {id: 1}), 'name', 'New Person');

Android: adbd cannot run as root in production builds

For those who rooted the Android device with Magisk, you can install adb_root from https://github.com/evdenis/adb_root. Then adb root can run smoothly.

How to get the URL of the current page in C#

the request.rawurl will gives the content of current page it gives the exact path that you required

use HttpContext.Current.Request.RawUrl

Doing a join across two databases with different collations on SQL Server and getting an error

A general purpose way is to coerce the collation to DATABASE_DEFAULT. This removes hardcoding the collation name which could change.

It's also useful for temp table and table variables, and where you may not know the server collation (eg you are a vendor placing your system on the customer's server)

select
    sone_field collate DATABASE_DEFAULT
from
    table_1
    inner join
    table_2 on table_1.field collate DATABASE_DEFAULT = table_2.field
where whatever

Extracting time from POSIXct

There have been previous answers that showed the trick. In essence:

  • you must retain POSIXct types to take advantage of all the existing plotting functions

  • if you want to 'overlay' several days worth on a single plot, highlighting the intra-daily variation, the best trick is too ...

  • impose the same day (and month and even year if need be, which is not the case here)

which you can do by overriding the day-of-month and month components when in POSIXlt representation, or just by offsetting the 'delta' relative to 0:00:00 between the different days.

So with times and val as helpfully provided by you:

## impose month and day based on first obs
ntimes <- as.POSIXlt(times)    # convert to 'POSIX list type'
ntimes$mday <- ntimes[1]$mday  # and $mon if it differs too
ntimes <- as.POSIXct(ntimes)   # convert back

par(mfrow=c(2,1))
plot(times,val)   # old times
plot(ntimes,val)  # new times

yields this contrasting the original and modified time scales:

enter image description here

Get JSON data from external URL and display it in a div as plain text

If you want to use plain javascript, but avoid promises, you can use Rami Sarieddine's solution, but substitute the promise with a callback function like this:

var getJSON = function(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open('get', url, true);
    xhr.responseType = 'json';
    xhr.onload = function() {
      var status = xhr.status;
      if (status == 200) {
        callback(null, xhr.response);
      } else {
        callback(status);
      }
    };
    xhr.send();
};

And you would call it like this:

getJSON('https://www.googleapis.com/freebase/v1/text/en/bob_dylan', function(err, data) {
  if (err != null) {
    alert('Something went wrong: ' + err);
  } else {
    alert('Your Json result is:  ' + data.result);
    result.innerText = data.result;
  }
});

Is there a way to get a list of all current temporary tables in SQL Server?

You can get list of temp tables by following query :

select left(name, charindex('_',name)-1) 
from tempdb..sysobjects
where charindex('_',name) > 0 and
xtype = 'u' and not object_id('tempdb..'+name) is null

How can I store JavaScript variable output into a PHP variable?

The ideal method would be to pass it with an AJAX call, but for a quick and dirty method, all you'd have to do is reload the page with this variable in a $_GET parameter -

<script>
  var a="Hello";
  window.location.href = window.location.href+'?a='+a;
</script>

Your page will reload and now in your PHP, you'll have access to the $_GET['a'] variable.

<?php 
  $variable = $_GET['a'];
?>

How can I make PHP display the error instead of giving me 500 Internal Server Error

Use "php -l <filename>" (that's an 'L') from the command line to output the syntax error that could be causing PHP to throw the status 500 error. It'll output something like:

PHP Parse error: syntax error, unexpected '}' in <filename> on line 18

How To Save Canvas As An Image With canvas.toDataURL()?

Similar to 1000Bugy's answer but simpler because you don't have to make an anchor on the fly and dispatch a click event manually (plus an IE fix).

If you make your download button an anchor you can highjack it right before the default anchor functionality is run. So onAnchorClick you can set the anchor href to the canvas base64 image and the anchor download attribute to whatever you want to name your image.

This does not work in (the current) IE because it doesn't implement the download attribute and prevents download of data uris. But this can be fixed by using window.navigator.msSaveBlob instead.

So your anchor click event handler would be as followed (where anchor, canvas and fileName are scope lookups):

function onClickAnchor(e) {
  if (window.navigator.msSaveBlob) {
    window.navigator.msSaveBlob(canvas.msToBlob(), fileName);
    e.preventDefault();
  } else {
    anchor.setAttribute('download', fileName);
    anchor.setAttribute('href', canvas.toDataURL());
  }
}

Here's a fiddle

jQuery validation plugin: accept only alphabetical characters?

 $('.AlphabetsOnly').keypress(function (e) {
        var regex = new RegExp(/^[a-zA-Z\s]+$/);
        var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
        if (regex.test(str)) {
            return true;
        }
        else {
            e.preventDefault();
            return false;
        }
    });

How can I create a war file of my project in NetBeans?

Right click your project, hit "Clean and Build". Netbeans does the rest.

under the dist directory of your app, you should find a pretty looking .war all ready for deployment.

this.getClass().getClassLoader().getResource("...") and NullPointerException

When you use

this.getClass().getResource("myFile.ext")

getResource will try to find the resource relative to the package. If you use:

this.getClass().getResource("/myFile.ext")

getResource will treat it as an absolute path and simply call the classloader like you would have if you'd done.

this.getClass().getClassLoader().getResource("myFile.ext")

The reason you can't use a leading / in the ClassLoader path is because all ClassLoader paths are absolute and so / is not a valid first character in the path.

Are these methods thread safe?

It follows the convention that static methods should be thread-safe, but actually in v2 that static api is a proxy to an instance method on a default instance: in the case protobuf-net, it internally minimises contention points, and synchronises the internal state when necessary. Basically the library goes out of its way to do things right so that you can have simple code.

android: data binding error: cannot find symbol class

I have got the same issue and I found that variable name and method were missing. Double check the layout file or look for build error that says DATABINDINGISSUE, or invalidate and restart android studio. It should work.