Programs & Examples On #R6rs

The 6th Revised Report on the Algorithmic Language Scheme.

Differences between strong and weak in Objective-C

Strong: Basically Used With Properties we used to get or send data from/into another classes. Weak: Usually all outlets, connections are of Weak type from Interface.

Nonatomic: Such type of properties are used in conditions when we don't want to share our outlet or object into different simultaneous Threads. In other words, Nonatomic instance make our properties to deal with one thread at a time. Hopefully it helpful for you.

Copy directory to another directory using ADD command

You can use COPY. You need to specify the directory explicitly. It won't be created by itself

COPY go /usr/local/go

Reference: Docker CP reference

Case Statement Equivalent in R

If you want to have sql-like syntax you can just make use of sqldf package. Tthe function to be used is also names sqldf and the syntax is as follows

sqldf(<your query in quotation marks>)

List of all special characters that need to be escaped in a regex

You can look at the javadoc of the Pattern class: http://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html

You need to escape any char listed there if you want the regular char and not the special meaning.

As a maybe simpler solution, you can put the template between \Q and \E - everything between them is considered as escaped.

How to pass a parameter to Vue @click event handler

I had the same issue and here is how I manage to pass through:

In your case you have addToCount() which is called. now to pass down a param when user clicks, you can say @click="addToCount(item.contactID)"

in your function implementation you can receive the params like:

addToCount(paramContactID){
 // the paramContactID contains the value you passed into the function when you called it
 // you can do what you want to do with the paramContactID in here!

}

Visual Studio Code Automatic Imports

I am using 'ImportJS' plugin by Devin Abbott for auto import and you can install this using below code

npm install --global import-js

Background position, margin-top?

If you mean you want the background image itself to be offset by 50 pixels from the top, like a background margin, then just switch out the top for 50px and you're set.

#thedivstatus {
    background-image: url("imagestatus.gif");
    background-position: right 50px;
    background-repeat: no-repeat;
}

JavaScript or jQuery browser back button click detector

suppose you have a button:

<button onclick="backBtn();">Back...</button>

Here the code of the backBtn method:

  function backBtn(){
                    parent.history.back();
                    return false;
                }

Javascript switch vs. if...else if...else

Sometimes it's better to use neither. For example, in a "dispatch" situation, Javascript lets you do things in a completely different way:

function dispatch(funCode) {
  var map = {
    'explode': function() {
      prepExplosive();
      if (flammable()) issueWarning();
      doExplode();
    },

    'hibernate': function() {
      if (status() == 'sleeping') return;
      // ... I can't keep making this stuff up
    },
    // ...
  };

  var thisFun = map[funCode];
  if (thisFun) thisFun();
}

Setting up multi-way branching by creating an object has a lot of advantages. You can add and remove functionality dynamically. You can create the dispatch table from data. You can examine it programmatically. You can build the handlers with other functions.

There's the added overhead of a function call to get to the equivalent of a "case", but the advantage (when there are lots of cases) of a hash lookup to find the function for a particular key.

JavaScript: Upload file

Pure JS

You can use fetch optionally with await-try-catch

let photo = document.getElementById("image-file").files[0];
let formData = new FormData();
     
formData.append("photo", photo);
fetch('/upload/image', {method: "POST", body: formData});

_x000D_
_x000D_
async function SavePhoto(inp) 
{
    let user = { name:'john', age:34 };
    let formData = new FormData();
    let photo = inp.files[0];      
         
    formData.append("photo", photo);
    formData.append("user", JSON.stringify(user)); 
    
    const ctrl = new AbortController()    // timeout
    setTimeout(() => ctrl.abort(), 5000);
    
    try {
       let r = await fetch('/upload/image', 
         {method: "POST", body: formData, signal: ctrl.signal}); 
       console.log('HTTP response code:',r.status); 
    } catch(e) {
       console.log('Huston we have problem...:', e);
    }
    
}
_x000D_
<input id="image-file" type="file" onchange="SavePhoto(this)" >
<br><br>
Before selecting the file open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>

<br><br>
(in stack overflow snippets there is problem with error handling, however in <a href="https://jsfiddle.net/Lamik/b8ed5x3y/5/">jsfiddle version</a> for 404 errors 4xx/5xx are <a href="https://stackoverflow.com/a/33355142/860099">not throwing</a> at all but we can read response status which contains code)
_x000D_
_x000D_
_x000D_

Old school approach - xhr

let photo = document.getElementById("image-file").files[0];  // file from input
let req = new XMLHttpRequest();
let formData = new FormData();

formData.append("photo", photo);                                
req.open("POST", '/upload/image');
req.send(formData);

_x000D_
_x000D_
function SavePhoto(e) 
{
    let user = { name:'john', age:34 };
    let xhr = new XMLHttpRequest();
    let formData = new FormData();
    let photo = e.files[0];      
    
    formData.append("user", JSON.stringify(user));   
    formData.append("photo", photo);
    
    xhr.onreadystatechange = state => { console.log(xhr.status); } // err handling
    xhr.timeout = 5000;
    xhr.open("POST", '/upload/image'); 
    xhr.send(formData);
}
_x000D_
<input id="image-file" type="file" onchange="SavePhoto(this)" >
<br><br>
Choose file and open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>

<br><br>
(the stack overflow snippets, has some problem with error handling - the xhr.status is zero (instead of 404) which is similar to situation when we run script from file on <a href="https://stackoverflow.com/a/10173639/860099">local disc</a> - so I provide also js fiddle version which shows proper http error code <a href="https://jsfiddle.net/Lamik/k6jtq3uh/2/">here</a>)
_x000D_
_x000D_
_x000D_

SUMMARY

  • In server side you can read original file name (and other info) which is automatically included to request by browser in filename formData parameter.
  • You do NOT need to set request header Content-Type to multipart/form-data - this will be set automatically by browser.
  • Instead of /upload/image you can use full address like http://.../upload/image.
  • If you want to send many files in single request use multiple attribute: <input multiple type=... />, and attach all chosen files to formData in similar way (e.g. photo2=...files[2];... formData.append("photo2", photo2);)
  • You can include additional data (json) to request e.g. let user = {name:'john', age:34} in this way: formData.append("user", JSON.stringify(user));
  • You can set timeout: for fetch using AbortController, for old approach by xhr.timeout= milisec
  • This solutions should work on all major browsers.

Converting String To Float in C#

You can use parsing with double instead of float to get more precision value.

Convert a video to MP4 (H.264/AAC) with ffmpeg

http://handbrake.fr is a nice high level tool with a lot of useful presets for mp4 for iPod, PS3, ... with both GUI and CLI interfaces for Linux, Windows and Mac OS X.

It comes with its own dependencies as a single statically linked fat binary so you have all the x264 / aac codecs included.

  $ HandBrakeCLI -Z Universal -i myinputfile.mov -o myoutputfile.mp4

To list all the available presets:

  $ HandBrakeCLI -z

How to get Last record from Sqlite?

Here's a simple example that simply returns the last line without need to sort anything from any column:

"SELECT * FROM TableName ORDER BY rowid DESC LIMIT 1;"       

Use virtualenv with Python with Visual Studio Code in Ubuntu

I got this from YouTube Setting up Python Visual Studio Code... Venv

OK, the video really didn't help me all that much, but... the first comment under (by the person who posted the video) makes a lot of sense and is pure gold.

Basically, open up Visual Studio Code' built-in Terminal. Then source <your path>/activate.sh, the usual way you choose a venv from the command line. I have a predefined Bash function to find & launch the right script file and that worked just fine.

Quoting that YouTube comment directly (all credit to aneuris ap):

(you really only need steps 5-7)

1. Open your command line/terminal and type `pip virtualenv`.
2. Create a folder in which the virtualenv will be placed in.
3. 'cd' to the script folder in the virtualenv and run activate.bat (CMD).
4. Deactivate to turn of the virtualenv (CMD).
5. Open the project in Visual Studio Code and use its built-in terminal to 'cd' to the script folder in you virtualenv.
6. Type source activates (in Visual Studio Code I use the Git terminal).
7. Deactivate to turn off the virtualenv.

As you may notice, he's talking about activate.bat. So, if it works for me on a Mac, and it works on Windows too, chances are it's pretty robust and portable.

Nginx - Customizing 404 page

You can setup a custom error page for every location block in your nginx.conf, or a global error page for the site as a whole.

To redirect to a simple 404 not found page for a specific location:

location /my_blog {
    error_page    404 /blog_article_not_found.html;
}

A site wide 404 page:

server {
    listen 80;
    error_page  404  /website_page_not_found.html;
    ...

You can append standard error codes together to have a single page for several types of errors:

location /my_blog {
    error_page 500 502 503 504 /server_error.html
}

To redirect to a totally different server, assuming you had an upstream server named server2 defined in your http section:

upstream server2 {
    server 10.0.0.1:80;
}
server {
    location /my_blog {
        error_page    404 @try_server2;
    }
    location @try_server2 {
        proxy_pass http://server2;
    }

The manual can give you more details, or you can search google for the terms nginx.conf and error_page for real life examples on the web.

Applying function with multiple arguments to create a new pandas column

You can go with @greenAfrican example, if it's possible for you to rewrite your function. But if you don't want to rewrite your function, you can wrap it into anonymous function inside apply, like this:

>>> def fxy(x, y):
...     return x * y

>>> df['newcolumn'] = df.apply(lambda x: fxy(x['A'], x['B']), axis=1)
>>> df
    A   B  newcolumn
0  10  20        200
1  20  30        600
2  30  10        300

How do you sort a dictionary by value?

Actually in C#, dictionaries don't have sort() methods. As you are more interested in sort by values, you can't get values until you provide them key. In short, you need to iterate through them using LINQ's OrderBy(),

var items = new Dictionary<string, int>();
items.Add("cat", 0);
items.Add("dog", 20);
items.Add("bear", 100);
items.Add("lion", 50);

// Call OrderBy() method here on each item and provide them the IDs.
foreach (var item in items.OrderBy(k => k.Key))
{
    Console.WriteLine(item);// items are in sorted order
}

You can do one trick:

var sortedDictByOrder = items.OrderBy(v => v.Value);

or:

var sortedKeys = from pair in dictName
            orderby pair.Value ascending
            select pair;

It also depends on what kind of values you are storing: single (like string, int) or multiple (like List, Array, user defined class). If it's single you can make list of it and then apply sort.
If it's user defined class, then that class must implement IComparable, ClassName: IComparable<ClassName> and override compareTo(ClassName c) as they are more faster and more object oriented than LINQ.

Selecting data from two different servers in SQL Server

try this:

SELECT * FROM OPENROWSET('SQLNCLI', 'Server=YOUR SERVER;Trusted_Connection=yes;','SELECT * FROM Table1') AS a
UNION
SELECT * FROM OPENROWSET('SQLNCLI', 'Server=ANOTHER SERVER;Trusted_Connection=yes;','SELECT * FROM Table1') AS a

Auto-indent in Notepad++

First download plugin manager this link then unzip the zip folder and copy this inside your program/ notepad++ folder . then restart your notepad++. then you see plugin manager inside plugin menu . then click plugin manager then click show plugin manager . It shows all your plugin list . from the list in bottom find XML tools , checked it and install it. then restart your notepad++. After open a document then plugins/xml tools/pretty plain(indent text) then enjoy.

How to check if a file contains a specific string using Bash

grep -q "something" file
[[ !? -eq 0 ]] && echo "yes" || echo "no"

What is the most efficient way to store a list in the Django models?

As this is an old question, and Django techniques must have changed significantly since, this answer reflects Django version 1.4, and is most likely applicable for v 1.5.

Django by default uses relational databases; you should make use of 'em. Map friendships to database relations (foreign key constraints) with the use of ManyToManyField. Doing so allows you to use RelatedManagers for friendlists, which use smart querysets. You can use all available methods such as filter or values_list.

Using ManyToManyField relations and properties:

class MyDjangoClass(models.Model):
    name = models.CharField(...)
    friends = models.ManyToManyField("self")

    @property
    def friendlist(self):
        # Watch for large querysets: it loads everything in memory
        return list(self.friends.all())

You can access a user's friend list this way:

joseph = MyDjangoClass.objects.get(name="Joseph")
friends_of_joseph = joseph.friendlist

Note however that these relations are symmetrical: if Joseph is a friend of Bob, then Bob is a friend of Joseph.

PostgreSQL IF statement

You could also use the the basic structure for the PL/pgSQL CASE with anonymous code block procedure block:

DO $$ BEGIN
    CASE
        WHEN boolean-expression THEN
          statements;
        WHEN boolean-expression THEN
          statements;
        ...
        ELSE
          statements;
    END CASE;
END $$;

References:

  1. http://www.postgresql.org/docs/current/static/sql-do.html
  2. https://www.postgresql.org/docs/current/static/plpgsql-control-structures.html

How do you get the length of a string?

It's not jquery you need, it's JS:

alert(str.length);

Does "\d" in regex mean a digit?

[0-9] is not always equivalent to \d. In python3, [0-9] matches only 0123456789 characters, while \d matches [0-9] and other digit characters, for example Eastern Arabic numerals ??????????.

INSERT and UPDATE a record using cursors in oracle

This is a highly inefficient way of doing it. You can use the merge statement and then there's no need for cursors, looping or (if you can do without) PL/SQL.

MERGE INTO studLoad l
USING ( SELECT studId, studName FROM student ) s
ON (l.studId = s.studId)
WHEN MATCHED THEN
  UPDATE SET l.studName = s.studName
   WHERE l.studName != s.studName
WHEN NOT MATCHED THEN 
INSERT (l.studID, l.studName)
VALUES (s.studId, s.studName)

Make sure you commit, once completed, in order to be able to see this in the database.


To actually answer your question I would do it something like as follows. This has the benefit of doing most of the work in SQL and only updating based on the rowid, a unique address in the table.

It declares a type, which you place the data within in bulk, 10,000 rows at a time. Then processes these rows individually.

However, as I say this will not be as efficient as merge.

declare

   cursor c_data is
    select b.rowid as rid, a.studId, a.studName
      from student a
      left outer join studLoad b
        on a.studId = b.studId
       and a.studName <> b.studName
           ;

   type t__data is table of c_data%rowtype index by binary_integer;
   t_data t__data;

begin

   open c_data;
   loop
      fetch c_data bulk collect into t_data limit 10000;

      exit when t_data.count = 0;

      for idx in t_data.first .. t_data.last loop
         if t_data(idx).rid is null then
            insert into studLoad (studId, studName)
            values (t_data(idx).studId, t_data(idx).studName);
         else
            update studLoad
               set studName = t_data(idx).studName
             where rowid = t_data(idx).rid
                   ;
         end if;
      end loop;

   end loop;
   close c_data;

end;
/

How to read an entire file to a string using C#?

if you want to pick file from Bin folder of the application then you can try following and don't forget to do exception handling.

string content = File.ReadAllText(Path.Combine(System.IO.Directory.GetCurrentDirectory(), @"FilesFolder\Sample.txt"));

Meaning of @classmethod and @staticmethod for beginner?

Rostyslav Dzinko's answer is very appropriate. I thought I could highlight one other reason you should choose @classmethod over @staticmethod when you are creating an additional constructor.

In the example above, Rostyslav used the @classmethod from_string as a Factory to create Date objects from otherwise unacceptable parameters. The same can be done with @staticmethod as is shown in the code below:

class Date:
  def __init__(self, month, day, year):
    self.month = month
    self.day   = day
    self.year  = year


  def display(self):
    return "{0}-{1}-{2}".format(self.month, self.day, self.year)


  @staticmethod
  def millenium(month, day):
    return Date(month, day, 2000)

new_year = Date(1, 1, 2013)               # Creates a new Date object
millenium_new_year = Date.millenium(1, 1) # also creates a Date object. 

# Proof:
new_year.display()           # "1-1-2013"
millenium_new_year.display() # "1-1-2000"

isinstance(new_year, Date) # True
isinstance(millenium_new_year, Date) # True

Thus both new_year and millenium_new_year are instances of the Date class.

But, if you observe closely, the Factory process is hard-coded to create Date objects no matter what. What this means is that even if the Date class is subclassed, the subclasses will still create plain Date objects (without any properties of the subclass). See that in the example below:

class DateTime(Date):
  def display(self):
      return "{0}-{1}-{2} - 00:00:00PM".format(self.month, self.day, self.year)


datetime1 = DateTime(10, 10, 1990)
datetime2 = DateTime.millenium(10, 10)

isinstance(datetime1, DateTime) # True
isinstance(datetime2, DateTime) # False

datetime1.display() # returns "10-10-1990 - 00:00:00PM"
datetime2.display() # returns "10-10-2000" because it's not a DateTime object but a Date object. Check the implementation of the millenium method on the Date class for more details.

datetime2 is not an instance of DateTime? WTF? Well, that's because of the @staticmethod decorator used.

In most cases, this is undesired. If what you want is a Factory method that is aware of the class that called it, then @classmethod is what you need.

Rewriting Date.millenium as (that's the only part of the above code that changes):

@classmethod
def millenium(cls, month, day):
    return cls(month, day, 2000)

ensures that the class is not hard-coded but rather learnt. cls can be any subclass. The resulting object will rightly be an instance of cls.
Let's test that out:

datetime1 = DateTime(10, 10, 1990)
datetime2 = DateTime.millenium(10, 10)

isinstance(datetime1, DateTime) # True
isinstance(datetime2, DateTime) # True


datetime1.display() # "10-10-1990 - 00:00:00PM"
datetime2.display() # "10-10-2000 - 00:00:00PM"

The reason is, as you know by now, that @classmethod was used instead of @staticmethod

How to pass parameters in $ajax POST?

I would recommend you to make use of the $.post or $.get syntax of jQuery for simple cases:

$.post('superman', { field1: "hello", field2 : "hello2"}, 
    function(returnedData){
         console.log(returnedData);
});

If you need to catch the fail cases, just do this:

$.post('superman', { field1: "hello", field2 : "hello2"}, 
    function(returnedData){
         console.log(returnedData);
}).fail(function(){
      console.log("error");
});

Additionally, if you always send a JSON string, you can use $.getJSON or $.post with one more parameter at the very end.

$.post('superman', { field1: "hello", field2 : "hello2"}, 
     function(returnedData){
        console.log(returnedData);
}, 'json');

How to make `setInterval` behave more in sync, or how to use `setTimeout` instead?

Given that neither time is going to be very accurate, one way to use setTimeout to be a little more accurate is to calculate how long the delay was since the last iteration, and then adjust the next iteration as appropriate. For example:

var myDelay = 1000;
var thisDelay = 1000;
var start = Date.now();

function startTimer() {    
    setTimeout(function() {
        // your code here...
        // calculate the actual number of ms since last time
        var actual = Date.now() - start;
        // subtract any extra ms from the delay for the next cycle
        thisDelay = myDelay - (actual - myDelay);
        start = Date.now();
        // start the timer again
        startTimer();
    }, thisDelay);
}

So the first time it'll wait (at least) 1000 ms, when your code gets executed, it might be a little late, say 1046 ms, so we subtract 46 ms from our delay for the next cycle and the next delay will be only 954 ms. This won't stop the timer from firing late (that's to be expected), but helps you to stop the delays from pilling up. (Note: you might want to check for thisDelay < 0 which means the delay was more than double your target delay and you missed a cycle - up to you how you want to handle that case).

Of course, this probably won't help you keep several timers in sync, in which case you might want to figure out how to control them all with the same timer.

So looking at your code, all your delays are a multiple of 500, so you could do something like this:

var myDelay = 500;
var thisDelay = 500;
var start = Date.now();
var beatCount = 0;

function startTimer() {    
    setTimeout(function() {
        beatCount++;
        // your code here...
        //code for the bass playing goes here  

        if (count%2 === 0) {
            //code for the chords playing goes here (every 1000 ms)
        }

        if (count%16) {
            //code for the drums playing goes here (every 8000 ms)
        }

        // calculate the actual number of ms since last time
        var actual = Date.now() - start;
        // subtract any extra ms from the delay for the next cycle
        thisDelay = myDelay - (actual - myDelay);
        start = Date.now();
        // start the timer again
        startTimer();
    }, thisDelay);
}

How to get the primary IP address of the local machine on Linux and OS X?

There's a node package for everything. It's cross-platform and easy to use.

$ npm install --global internal-ip-cli

$ internal-ip
fe80::1

$ internal-ip --ipv4
192.168.0.3

This is a controversial approach, but using npm for tooling is becoming more popular, like it or not.

Why shouldn't `&apos;` be used to escape single quotes?

If you really need single quotes, apostrophes, you can use

html    | numeric | hex
&lsquo; | &#145;  | &#x91; // for the left/beginning single-quote and
&rsquo; | &#146;  | &#x92; // for the right/ending single-quote

java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

Using the "Update project configuartion" messed up the build path of the project.

Fix: Open the "configure build path..." menu (right click on the project) and fix the Included/Excluded options for each source folder. That worked for me.

How to examine processes in OS X's Terminal?

Try ps -ef. man ps will give you all the options.

 -A      Display information about other users' processes, including those without controlling terminals.

 -e      Identical to -A.

 -f      Display the uid, pid, parent pid, recent CPU usage, process start time, controlling tty, elapsed CPU usage, and the associated command.  If the -u option is also used, display
         the user name rather then the numeric uid.  When -o or -O is used to add to the display following -f, the command field is not truncated as severely as it is in other formats.

Redirecting a page using Javascript, like PHP's Header->Location

You cannot mix JS and PHP that way, PHP is rendered before the page is sent to the browser (i.e. before the JS is run)

You can use window.location to change your current page.

$('.entry a:first').click(function() {
    window.location = "http://google.ca";
});

-XX:MaxPermSize with or without -XX:PermSize

If you're doing some performance tuning it's often recommended to set both -XX:PermSize and -XX:MaxPermSize to the same value to increase JVM efficiency.

Here is some information:

  1. Support for large page heap on x86 and amd64 platforms
  2. Java Support for Large Memory Pages
  3. Setting the Permanent Generation Size

You can also specify -XX:+CMSClassUnloadingEnabled to enable class unloading option if you are using CMS GC. It may help to decrease the probability of Java.lang.OutOfMemoryError: PermGen space

An unhandled exception was generated during the execution of the current web request

As far as I understand, you have more than one form tag in your web page that causes the problem. Make sure you have only one server-side form tag for each page.

HTTP URL Address Encoding in Java

Maybe can try UriUtils in org.springframework.web.util

UriUtils.encodeUri(input, "UTF-8")

Sending SOAP request using Python Requests

It is indeed possible.

Here is an example calling the Weather SOAP Service using plain requests lib:

import requests
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
#headers = {'content-type': 'application/soap+xml'}
headers = {'content-type': 'text/xml'}
body = """<?xml version="1.0" encoding="UTF-8"?>
         <SOAP-ENV:Envelope xmlns:ns0="http://ws.cdyne.com/WeatherWS/" xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/" 
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
            <SOAP-ENV:Header/>
              <ns1:Body><ns0:GetWeatherInformation/></ns1:Body>
         </SOAP-ENV:Envelope>"""

response = requests.post(url,data=body,headers=headers)
print response.content

Some notes:

  • The headers are important. Most SOAP requests will not work without the correct headers. application/soap+xml is probably the more correct header to use (but the weatherservice prefers text/xml
  • This will return the response as a string of xml - you would then need to parse that xml.
  • For simplicity I have included the request as plain text. But best practise would be to store this as a template, then you can load it using jinja2 (for example) - and also pass in variables.

For example:

from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('myapp', 'templates'))
template = env.get_template('soaprequests/WeatherSericeRequest.xml')
body = template.render()

Some people have mentioned the suds library. Suds is probably the more correct way to be interacting with SOAP, but I often find that it panics a little when you have WDSLs that are badly formed (which, TBH, is more likely than not when you're dealing with an institution that still uses SOAP ;) ).

You can do the above with suds like so:

from suds.client import Client
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
client = Client(url)
print client ## shows the details of this service

result = client.service.GetWeatherInformation() 
print result 

Note: when using suds, you will almost always end up needing to use the doctor!

Finally, a little bonus for debugging SOAP; TCPdump is your friend. On Mac, you can run TCPdump like so:

sudo tcpdump -As 0 

This can be helpful for inspecting the requests that actually go over the wire.

The above two code snippets are also available as gists:

How can I use MS Visual Studio for Android Development?

Much has changed since this question was asked. Visual Studio 2013 with update 4 and Visual Studio 2015 now have integrated tools for Apache Cordova and you can run them on a Visual Studio emulator for Android.

When to use a View instead of a Table?

Oh there are many differences you will need to consider

Views for selection:

  1. Views provide abstraction over tables. You can add/remove fields easily in a view without modifying your underlying schema
  2. Views can model complex joins easily.
  3. Views can hide database-specific stuff from you. E.g. if you need to do some checks using Oracles SYS_CONTEXT function or many other things
  4. You can easily manage your GRANTS directly on views, rather than the actual tables. It's easier to manage if you know a certain user may only access a view.
  5. Views can help you with backwards compatibility. You can change the underlying schema, but the views can hide those facts from a certain client.

Views for insertion/updates:

  1. You can handle security issues with views by using such functionality as Oracle's "WITH CHECK OPTION" clause directly in the view

Drawbacks

  1. You lose information about relations (primary keys, foreign keys)
  2. It's not obvious whether you will be able to insert/update a view, because the view hides its underlying joins from you

Converting java date to Sql timestamp

You can cut off the milliseconds using a Calendar:

java.util.Date utilDate = new java.util.Date();
Calendar cal = Calendar.getInstance();
cal.setTime(utilDate);
cal.set(Calendar.MILLISECOND, 0);
System.out.println(new java.sql.Timestamp(utilDate.getTime()));
System.out.println(new java.sql.Timestamp(cal.getTimeInMillis()));

Output:

2014-04-04 10:10:17.78
2014-04-04 10:10:17.0

SonarQube not picking up Unit Test Coverage

I had the similar issue, 0.0% coverage & no unit tests count on Sonar dashboard with SonarQube 6.7.2: Maven : 3.5.2, Java : 1.8, Jacoco : Worked with 7.0/7.9/8.0, OS : Windows

After a lot of struggle finding for correct solution on maven multi-module project,not like single module project here we need to say to pick jacoco reports from individual modules & merge to one report,So resolved issue with this configuration as my parent pom looks like:

 <properties>
            <!--Sonar -->
            <sonar.java.coveragePlugin>jacoco</sonar.java.coveragePlugin>
            <sonar.dynamicAnalysis>reuseReports</sonar.dynamicAnalysis>
        <sonar.jacoco.reportPath>${project.basedir}/../target/jacoco.exec</sonar.jacoco.reportPath>
            <sonar.language>java</sonar.language>

        </properties>

        <build>
            <pluginManagement>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-compiler-plugin</artifactId>
                        <configuration>
                            <source>1.5</source>
                            <target>1.5</target>
                        </configuration>
                    </plugin>

                    <plugin>
                        <groupId>org.sonarsource.scanner.maven</groupId>
                        <artifactId>sonar-maven-plugin</artifactId>
                        <version>3.4.0.905</version>
                    </plugin>

                    <plugin>
                        <groupId>org.jacoco</groupId>
                        <artifactId>jacoco-maven-plugin</artifactId>
                        <version>0.7.9</version>
                        <configuration>
                            <destFile>${sonar.jacoco.reportPath}</destFile>
                            <append>true</append>
                        </configuration>
                        <executions>
                            <execution>
                                <id>agent</id>
                                <goals>
                                    <goal>prepare-agent</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>

                </plugins>
            </pluginManagement>
        </build>

I've tried few other options like jacoco-aggregate & even creating a sub-module by including that in parent pom but nothing really worked & this is simple. I see in logs <sonar.jacoco.reportPath> is deprecated,but still works as is and seems like auto replaced on execution or can be manually updated to <sonar.jacoco.reportPaths> or latest. Once after doing setup in cmd start with mvn clean install then mvn org.jacoco:jacoco-maven-plugin:prepare-agent install (Check on project's target folder whether jacoco.exec is created) & then do mvn sonar:sonar , this is what I've tried please let me know if some other best possible solution available.Hope this helps!! If not please post your question..

Is there an online application that automatically draws tree structures for phrases/sentences?

There are lots of options out there. Many of which are available as downloadable software as well as public websites. I do not think many of them expect to be used as API's unless they explicitly state that.

The one that I found effective was Enju which did not have the character limit that the Marc's Carnagie Mellon link had. Marc also mentioned a VISL scanner in comments, but that requires java in the browser, which is a non-starter for me.

Note that recently, Google has offered a new NLP Machine Learning API that providers amoung other features, a automatic sentence parser. I will likely not update this answer again, especially since the question is closed, but I suspect that the other big ML cloud stacks will soon support the same.

Android/Java - Date Difference in days

Use the following functions:

   /**
     * Returns the number of days between two dates. The time part of the
     * days is ignored in this calculation, so 2007-01-01 13:00 and 2007-01-02 05:00
     * have one day inbetween.
     */
    public static long daysBetween(Date firstDate, Date secondDate) {
        // We only use the date part of the given dates
        long firstSeconds = truncateToDate(firstDate).getTime()/1000;
        long secondSeconds = truncateToDate(secondDate).getTime()/1000;
        // Just taking the difference of the millis.
        // These will not be exactly multiples of 24*60*60, since there
        // might be daylight saving time somewhere inbetween. However, we can
        // say that by adding a half day and rounding down afterwards, we always
        // get the full days.
        long difference = secondSeconds-firstSeconds;
        // Adding half a day
        if( difference >= 0 ) {
            difference += SECONDS_PER_DAY/2; // plus half a day in seconds
        } else {
            difference -= SECONDS_PER_DAY/2; // minus half a day in seconds
        }
        // Rounding down to days
        difference /= SECONDS_PER_DAY;

        return difference;
    }

    /**
     * Truncates a date to the date part alone.
     */
    @SuppressWarnings("deprecation")
    public static Date truncateToDate(Date d) {
        if( d instanceof java.sql.Date ) {
            return d; // java.sql.Date is already truncated to date. And raises an
                      // Exception if we try to set hours, minutes or seconds.
        }
        d = (Date)d.clone();
        d.setHours(0);
        d.setMinutes(0);
        d.setSeconds(0);
        d.setTime(((d.getTime()/1000)*1000));
        return d;
    }

Force browser to download image files on click

You don't need to write js to do that, simply use:

<a href="path_to/image.jpg" alt="something">Download image</a>

And the browser itself will automatically download the image.

If for some reason it doesn't work add the download attribute. With this attribute you can set a name for the downloadable file:

<a href="path_to/image.jpg" download="myImage">Download image</a>

Why are there two ways to unstage a file in Git?

git rm --cached is used to remove a file from the index. In the case where the file is already in the repo, git rm --cached will remove the file from the index, leaving it in the working directory and a commit will now remove it from the repo as well. Basically, after the commit, you would have unversioned the file and kept a local copy.

git reset HEAD file ( which by default is using the --mixed flag) is different in that in the case where the file is already in the repo, it replaces the index version of the file with the one from repo (HEAD), effectively unstaging the modifications to it.

In the case of unversioned file, it is going to unstage the entire file as the file was not there in the HEAD. In this aspect git reset HEAD file and git rm --cached are same, but they are not same ( as explained in the case of files already in the repo)

To the question of Why are there 2 ways to unstage a file in git? - there is never really only one way to do anything in git. that is the beauty of it :)

Why is HttpContext.Current null?

In IIS7 with integrated mode, Current is not available in Application_Start. There is a similar thread here.

Visual Studio 2010 shortcut to find classes and methods?

try: ctrl + P

type: @

followed by the name of the class,method or variable name you search for.

How do I make a splash screen?

     - Add in SplashActivity 

   public class SplashActivity extends Activity {

       private ProgressBar progressBar;
       int i=0;
       Context context;
       private GoogleApiClient googleApiClient;

       @Override
       protected void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.activity_splash);
           context = this;

           new Handler().postDelayed(new Runnable() {
               @Override
               public void run() {
                   startActivity(new Intent(Splash.this, LoginActivity.class));
                   finish();
               }
           }, 2000);

       }

   }

  - Add in activity_splash.xml

   <RelativeLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
       xmlns:tools="http://schemas.android.com/tools"
       xmlns:custom="http://schemas.android.com/apk/res-auto"
       android:background="@color/colorAccent"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       tools:context=".Splash">

       <ImageView
           android:id="@+id/ivLogo"
           android:layout_width="match_parent"
           android:layout_height="match_parent"
           android:src="@mipmap/icon_splash"
           android:layout_centerHorizontal="true"
           android:layout_centerVertical="true"/>


       <ProgressBar
           android:id="@+id/circle_progress"
           style="?android:attr/progressBarStyleHorizontal"
           android:layout_width="fill_parent"
           android:layout_height="wrap_content"
           android:layout_alignParentBottom="true"
           android:layout_marginBottom="5dp"
           android:max="100"
           android:progressTint="@color/green"
           android:visibility="visible" />

   </RelativeLayout>

  - Add in AndroidManifest.xml

    <activity android:name="ex.com.SplashActivity">
               <intent-filter>
                   <action android:name="android.intent.action.MAIN" />

                   <category android:name="android.intent.category.LAUNCHER" />
               </intent-filter>
           </activity>

Disable a Maven plugin defined in a parent POM

See if the plugin has a 'skip' configuration parameter. Nearly all do. if it does, just add it to a declaration in the child:

<plugin>
   <groupId>group</groupId>
   <artifactId>artifact</artifactId>
   <configuration>
     <skip>true</skip>
   </configuration>
</plugin>

If not, then use:

<plugin>    
<groupId>group</groupId>   
 <artifactId>artifact</artifactId>    
<executions>
     <execution>
       <id>TheNameOfTheRelevantExecution</id>
       <phase>none</phase>
     </execution>    
</executions>  
</plugin>

scp or sftp copy multiple files with single command

scp uses ssh for data transfer with the same authentication and provides the same security as ssh.

A best practise here is to implement "SSH KEYS AND PUBLIC KEY AUTHENTICATION". With this, you can write your scripts without worring about authentication. Simple as that.

See WHAT IS SSH-KEYGEN

how to add a jpg image in Latex

if you add a jpg,png,pdf picture, you should use pdflatex to compile it.

What is the difference between JOIN and JOIN FETCH when using JPA and Hibernate

If you have @oneToOne mapping set to FetchType.LAZY and you use second query (because you need Department objects to be loaded as part of Employee objects) what Hibernate will do is, it will issue queries to fetch Department objects for every individual Employee object it fetches from DB.

Later, in the code you might access Department objects via Employee to Department single-valued association and Hibernate will not issue any query to fetch Department object for the given Employee.

Remember, Hibernate still issues queries equal to the number of Employees it has fetched. Hibernate will issue same number of queries in both above queries, if you wish to access Department objects of all Employee objects

How to get Selected Text from select2 when using <input>

The code below also solves otherwise

.on("change", function(e) {

  var lastValue = e.currentTarget.value;
  var lastText = e.currentTarget.textContent;

 });

Python - Module Not Found

you need a file named __init__.py (two underscores on each side) in every folder in the hierarchy, so one in src/ and one in model/. This is what python looks for to know that it should access a particular folder. The files are meant to contain initialization instructions but even if you create them empty this will solve it.

PHP if not statements

I think this is the best and easiest way to do it:

if (!(isset($action) && ($action == "add" || $action == "delete")))

how to make a specific text on TextView BOLD

wtsang02 answer is the best way to go about it, since, Html.fromHtml("") is now deprecated. Here I'm just going to enhance it a little bit for whoever is having problem in dynamically making the first word bold, no matter whats the size of the sentence.

First lets create a method to get the first word:

 private String getFirstWord(String input){

    for(int i = 0; i < input.length(); i++){

        if(input.charAt(i) == ' '){

            return input.substring(0, i);
        }
    }

    return input;
}

Now let's say you have a long string like this:

String sentence = "[email protected] want's to be your friend!"

And you want your sentence to be like [email protected] want's to be your friend! All you have to do is- get the firstWord and get the lenght of it to make the firstWord bold, something like this:

String myFirstWord = getFirstWord(sentence);
int start = 0; // bold will start at index 0
int end = myFirstWord.length(); // and will finish at whatever the length of your first word

Now just follow wtsang02 's steps, like this:

SpannableStringBuilder fancySentence = new SpannableStringBuilder(sentence);
fancySentence.setSpan(new android.text.style.StyleSpan(Typeface.BOLD), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(fancySentence);

And that's it! Now you should be able to bold a word with any size from long/short sentence. Hope it will help someone, happy coding :)

Get resultset from oracle stored procedure

My solution was to create a pipelined function. The advantages are that the query can be a single line:

  • select * from table(yourfunction(param1, param2));
  • You can join your results to other tables or filter or sort them as you please..
  • the results appear as regular query results so you can easily manipulate them.

To define the function you would need to do something like the following:

  -- Declare the record columns
  TYPE your_record IS RECORD(
     my_col1 VARCHAR2(50), 
     my_col2 varchar2(4000)
  );
  TYPE your_results IS TABLE OF your_record;

  -- Declare the function
  function yourfunction(a_Param1 varchar2, a_Param2 varchar2)
  return your_results pipelined is
    rt          your_results;
  begin
    -- Your query to load the table type
    select s.col1,s.col2
    bulk collect into rt
    from your_table s
    where lower(s.col1) like lower('%'||a_Param1||'%');

    -- Stuff the results into the pipeline..
    if rt.count > 0 then 
      for i in rt.FIRST .. rt.LAST loop 
        pipe row (rt(i)); 
      end loop; 
    end if;

    -- Add more results as you please....
    return;
  end find;

And as mentioned above, all you would do to view your results is:

select * from table(yourfunction(param1, param2)) t order by t.my_col1;

Aborting a shell script if any command returns a non-zero value

I am just throwing in another one for reference since there was an additional question to Mark Edgars input and here is an additional example and touches on the topic overall:

[[ `cmd` ]] && echo success_else_silence

Which is the same as cmd || exit errcode as someone showed.

For example, I want to make sure a partition is unmounted if mounted:

[[ `mount | grep /dev/sda1` ]] && umount /dev/sda1

How to read an external local JSON file in JavaScript?

Depending on your browser, you may access to your local files. But this may not work for all the users of your app.

To do this, you can try the instructions from here: http://www.html5rocks.com/en/tutorials/file/dndfiles/

Once your file is loaded, you can retrieve the data using:

var jsonData = JSON.parse(theTextContentOfMyFile);

socket.emit() vs. socket.send()

Simple and precise (Source: Socket.IO google group):

socket.emit allows you to emit custom events on the server and client

socket.send sends messages which are received with the 'message' event

How to export SQL Server database to MySQL?

if you have a MSSQL compatible SQL dump you can convert it to MySQL queries one by one using this online tool

http://burrist.com/mstomy.php

Hope it saved your time

Is there any way to change input type="date" format?

As said, the <input type=date ... > is not fully implemented in most browsers, so let's talk about webkit like browsers (chrome).

Using linux, you can change it by changing the environment variable LANG, LC_TIME don't seems to work(for me at least).

You can type locale in a terminal to see your current values. I think the same concept can be applied to IOS.

eg: Using:

LANG=en_US.UTF-8 /opt/google/chrome/chrome

The date is showed as mm/dd/yyyy

Using:

LANG=pt_BR /opt/google/chrome/chrome

The date is showed as dd/mm/yyyy

You can use http://lh.2xlibre.net/locale/pt_BR/ (change pt_BR by your locale) to create you own custom locale and format your dates as you want.

A nice more advanced reference on how change default system date is: https://ccollins.wordpress.com/2009/01/06/how-to-change-date-formats-on-ubuntu/ and https://askubuntu.com/questions/21316/how-can-i-customize-a-system-locale

You can see you real current date format using date:

$ date +%x
01-06-2015

But as LC_TIME and d_fmt seems to be rejected by chrome ( and I think it's a bug in webkit or chrome ), sadly it don't work. :'(

So, unfortunately the response, is IF LANG environment variable do not solve your problem, there is no way yet.

IF a == true OR b == true statement

Comparison expressions should each be in their own brackets:

{% if (a == 'foo') or (b == 'bar') %}
    ...
{% endif %}

Alternative if you are inspecting a single variable and a number of possible values:

{% if a in ['foo', 'bar', 'qux'] %}
    ...
{% endif %}

How can I find non-ASCII characters in MySQL?

Based on the correct answer, but taking into account ASCII control characters as well, the solution that worked for me is this:

SELECT * FROM `table` WHERE NOT `field` REGEXP  "[\\x00-\\xFF]|^$";

It does the same thing: searches for violations of the ASCII range in a column, but lets you search for control characters too, since it uses hexadecimal notation for code points. Since there is no comparison or conversion (unlike @Ollie's answer), this should be significantly faster, too. (Especially if MySQL does early-termination on the regex query, which it definitely should.)

It also avoids returning fields that are zero-length. If you want a slightly-longer version that might perform better, you can use this instead:

SELECT * FROM `table` WHERE `field` <> "" AND NOT `field` REGEXP  "[\\x00-\\xFF]";

It does a separate check for length to avoid zero-length results, without considering them for a regex pass. Depending on the number of zero-length entries you have, this could be significantly faster.

Note that if your default character set is something bizarre where 0x00-0xFF don't map to the same values as ASCII (is there such a character set in existence anywhere?), this would return a false positive. Otherwise, enjoy!

Sort a Map<Key, Value> by values

The commons-collections library contains a solution called TreeBidiMap. Or, you could have a look at the Google Collections API. It has TreeMultimap which you could use.

And if you don't want to use these framework... they come with source code.

Sort Go map values by keys

All of the answers here now contain the old behavior of maps. In Go 1.12+, you can just print a map value and it will be sorted by key automatically. This has been added because it allows the testing of map values easily.

func main() {
    m := map[int]int{3: 5, 2: 4, 1: 3}
    fmt.Println(m)

    // In Go 1.12+
    // Output: map[1:3 2:4 3:5]

    // Before Go 1.12 (the order was undefined)
    // map[3:5 2:4 1:3]
}

Maps are now printed in key-sorted order to ease testing. The ordering rules are:

  • When applicable, nil compares low
  • ints, floats, and strings order by <
  • NaN compares less than non-NaN floats
  • bool compares false before true
  • Complex compares real, then imaginary
  • Pointers compare by machine address
  • Channel values compare by machine address
  • Structs compare each field in turn
  • Arrays compare each element in turn
  • Interface values compare first by reflect.Type describing the concrete type and then by concrete value as described in the previous rules.

When printing maps, non-reflexive key values like NaN were previously displayed as <nil>. As of this release, the correct values are printed.

Read more here.

how to get all child list from Firebase android

mDatabase.child("token").addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
              for (DataSnapshot snapshot:dataSnapshot.getChildren())
              {
                 String key= snapshot.getKey();
                 String value=snapshot.getValue().toString();
              }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Toast.makeText(ListUser.this,databaseError.toString(),Toast.LENGTH_SHORT).show();
            }
        });

Only work If child have no SubChild

enter image description here

Google Maps API throws "Uncaught ReferenceError: google is not defined" only when using AJAX

At a guess, you're initialising something before your initialize function: var directionsService = new google.maps.DirectionsService();

Move that into the function, so it won't try and execute it before the page is loaded.

var directionsDisplay, directionsService;
var map;
function initialize() {
  directionsService = new google.maps.DirectionsService();
  directionsDisplay = new google.maps.DirectionsRenderer();

How do I see active SQL Server connections?

You can use the sp_who stored procedure.

Provides information about current users, sessions, and processes in an instance of the Microsoft SQL Server Database Engine. The information can be filtered to return only those processes that are not idle, that belong to a specific user, or that belong to a specific session.

How to check if a radiobutton is checked in a radiogroup in Android?

try to use this

<RadioGroup
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"       
    android:orientation="horizontal"
>    
    <RadioButton
        android:id="@+id/standard_delivery"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/Standard_delivery"
        android:checked="true"
        android:layout_marginTop="4dp"
        android:layout_marginLeft="15dp"
        android:textSize="12dp"
        android:onClick="onRadioButtonClicked"   
    />

    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/Midnight_delivery"
        android:checked="false"
        android:layout_marginRight="15dp"
        android:layout_marginTop="4dp"
        android:textSize="12dp"
        android:onClick="onRadioButtonClicked"
        android:id="@+id/midnight_delivery"
    />    
</RadioGroup>

this is java class

public void onRadioButtonClicked(View view) {
        // Is the button now checked?
        boolean checked = ((RadioButton) view).isChecked();

        // Check which radio button was clicked
        switch(view.getId()) {
            case R.id.standard_delivery:
                if (checked)
                    Toast.makeText(DishActivity.this," standard delivery",Toast.LENGTH_LONG).show();
                    break;
            case R.id.midnight_delivery:
                if (checked)
                    Toast.makeText(DishActivity.this," midnight delivery",Toast.LENGTH_LONG).show();
                    break;
        }
    }

Calling a function of a module by using its name (a string)

The answer (I hope) no one ever wanted

Eval like behavior

getattr(locals().get("foo") or globals().get("foo"), "bar")()

Why not add auto-importing

getattr(
    locals().get("foo") or 
    globals().get("foo") or
    __import__("foo"), 
"bar")()

In case we have extra dictionaries we want to check

getattr(next((x for x in (f("foo") for f in 
                          [locals().get, globals().get, 
                           self.__dict__.get, __import__]) 
              if x)),
"bar")()

We need to go deeper

getattr(next((x for x in (f("foo") for f in 
              ([locals().get, globals().get, self.__dict__.get] +
               [d.get for d in (list(dd.values()) for dd in 
                                [locals(),globals(),self.__dict__]
                                if isinstance(dd,dict))
                if isinstance(d,dict)] + 
               [__import__])) 
        if x)),
"bar")()

Open File in Another Directory (Python)

If you know the full path to the file you can just do something similar to this. However if you question directly relates to relative paths, that I am unfamiliar with and would have to research and test.

path = 'C:\\Users\\Username\\Path\\To\\File'

with open(path, 'w') as f:
    f.write(data)

Edit:

Here is a way to do it relatively instead of absolute. Not sure if this works on windows, you will have to test it.

import os

cur_path = os.path.dirname(__file__)

new_path = os.path.relpath('..\\subfldr1\\testfile.txt', cur_path)
with open(new_path, 'w') as f:
    f.write(data)

Edit 2: One quick note about __file__, this will not work in the interactive interpreter due it being ran interactively and not from an actual file.

How to run 'sudo' command in windows

You normally wouldn't, since you wouldn't run it under *nix regardless. Do development in a user directory, and deploy afterwards to system directories.

What is the first character in the sort order used by Windows Explorer?

Only a few characters in the Windows code page 1252 (Latin-1) are not allowed as names. Note that the Windows Explorer will strip leading spaces from names and not allow you to call a files space dot something (like ?.txt), although this is allowed in the file system! Only a space and no file extension is invalid however.

If you create files through e.g. a Python script (this is what I did), then you can easily find out what is actually allowed and in what order the characters get sorted. The sort order varies based on your locale! Below are the results of my script, run with Python 2.7.15 on a German Windows 10 Pro 64bit:

Allowed:

       32  20  SPACE
!      33  21  EXCLAMATION MARK
#      35  23  NUMBER SIGN
$      36  24  DOLLAR SIGN
%      37  25  PERCENT SIGN
&      38  26  AMPERSAND
'      39  27  APOSTROPHE
(      40  28  LEFT PARENTHESIS
)      41  29  RIGHT PARENTHESIS
+      43  2B  PLUS SIGN
,      44  2C  COMMA
-      45  2D  HYPHEN-MINUS
.      46  2E  FULL STOP
/      47  2F  SOLIDUS
0      48  30  DIGIT ZERO
1      49  31  DIGIT ONE
2      50  32  DIGIT TWO
3      51  33  DIGIT THREE
4      52  34  DIGIT FOUR
5      53  35  DIGIT FIVE
6      54  36  DIGIT SIX
7      55  37  DIGIT SEVEN
8      56  38  DIGIT EIGHT
9      57  39  DIGIT NINE
;      59  3B  SEMICOLON
=      61  3D  EQUALS SIGN
@      64  40  COMMERCIAL AT
A      65  41  LATIN CAPITAL LETTER A
B      66  42  LATIN CAPITAL LETTER B
C      67  43  LATIN CAPITAL LETTER C
D      68  44  LATIN CAPITAL LETTER D
E      69  45  LATIN CAPITAL LETTER E
F      70  46  LATIN CAPITAL LETTER F
G      71  47  LATIN CAPITAL LETTER G
H      72  48  LATIN CAPITAL LETTER H
I      73  49  LATIN CAPITAL LETTER I
J      74  4A  LATIN CAPITAL LETTER J
K      75  4B  LATIN CAPITAL LETTER K
L      76  4C  LATIN CAPITAL LETTER L
M      77  4D  LATIN CAPITAL LETTER M
N      78  4E  LATIN CAPITAL LETTER N
O      79  4F  LATIN CAPITAL LETTER O
P      80  50  LATIN CAPITAL LETTER P
Q      81  51  LATIN CAPITAL LETTER Q
R      82  52  LATIN CAPITAL LETTER R
S      83  53  LATIN CAPITAL LETTER S
T      84  54  LATIN CAPITAL LETTER T
U      85  55  LATIN CAPITAL LETTER U
V      86  56  LATIN CAPITAL LETTER V
W      87  57  LATIN CAPITAL LETTER W
X      88  58  LATIN CAPITAL LETTER X
Y      89  59  LATIN CAPITAL LETTER Y
Z      90  5A  LATIN CAPITAL LETTER Z
[      91  5B  LEFT SQUARE BRACKET
\\     92  5C  REVERSE SOLIDUS
]      93  5D  RIGHT SQUARE BRACKET
^      94  5E  CIRCUMFLEX ACCENT
_      95  5F  LOW LINE
`      96  60  GRAVE ACCENT
a      97  61  LATIN SMALL LETTER A
b      98  62  LATIN SMALL LETTER B
c      99  63  LATIN SMALL LETTER C
d     100  64  LATIN SMALL LETTER D
e     101  65  LATIN SMALL LETTER E
f     102  66  LATIN SMALL LETTER F
g     103  67  LATIN SMALL LETTER G
h     104  68  LATIN SMALL LETTER H
i     105  69  LATIN SMALL LETTER I
j     106  6A  LATIN SMALL LETTER J
k     107  6B  LATIN SMALL LETTER K
l     108  6C  LATIN SMALL LETTER L
m     109  6D  LATIN SMALL LETTER M
n     110  6E  LATIN SMALL LETTER N
o     111  6F  LATIN SMALL LETTER O
p     112  70  LATIN SMALL LETTER P
q     113  71  LATIN SMALL LETTER Q
r     114  72  LATIN SMALL LETTER R
s     115  73  LATIN SMALL LETTER S
t     116  74  LATIN SMALL LETTER T
u     117  75  LATIN SMALL LETTER U
v     118  76  LATIN SMALL LETTER V
w     119  77  LATIN SMALL LETTER W
x     120  78  LATIN SMALL LETTER X
y     121  79  LATIN SMALL LETTER Y
z     122  7A  LATIN SMALL LETTER Z
{     123  7B  LEFT CURLY BRACKET
}     125  7D  RIGHT CURLY BRACKET
~     126  7E  TILDE
\x7f  127  7F  DELETE
\x80  128  80  EURO SIGN
\x81  129  81  
\x82  130  82  SINGLE LOW-9 QUOTATION MARK
\x83  131  83  LATIN SMALL LETTER F WITH HOOK
\x84  132  84  DOUBLE LOW-9 QUOTATION MARK
\x85  133  85  HORIZONTAL ELLIPSIS
\x86  134  86  DAGGER
\x87  135  87  DOUBLE DAGGER
\x88  136  88  MODIFIER LETTER CIRCUMFLEX ACCENT
\x89  137  89  PER MILLE SIGN
\x8a  138  8A  LATIN CAPITAL LETTER S WITH CARON
\x8b  139  8B  SINGLE LEFT-POINTING ANGLE QUOTATION
\x8c  140  8C  LATIN CAPITAL LIGATURE OE
\x8d  141  8D  
\x8e  142  8E  LATIN CAPITAL LETTER Z WITH CARON
\x8f  143  8F  
\x90  144  90  
\x91  145  91  LEFT SINGLE QUOTATION MARK
\x92  146  92  RIGHT SINGLE QUOTATION MARK
\x93  147  93  LEFT DOUBLE QUOTATION MARK
\x94  148  94  RIGHT DOUBLE QUOTATION MARK
\x95  149  95  BULLET
\x96  150  96  EN DASH
\x97  151  97  EM DASH
\x98  152  98  SMALL TILDE
\x99  153  99  TRADE MARK SIGN
\x9a  154  9A  LATIN SMALL LETTER S WITH CARON
\x9b  155  9B  SINGLE RIGHT-POINTING ANGLE QUOTATION MARK
\x9c  156  9C  LATIN SMALL LIGATURE OE
\x9d  157  9D  
\x9e  158  9E  LATIN SMALL LETTER Z WITH CARON
\x9f  159  9F  LATIN CAPITAL LETTER Y WITH DIAERESIS
\xa0  160  A0  NON-BREAKING SPACE
\xa1  161  A1  INVERTED EXCLAMATION MARK
\xa2  162  A2  CENT SIGN
\xa3  163  A3  POUND SIGN
\xa4  164  A4  CURRENCY SIGN
\xa5  165  A5  YEN SIGN
\xa6  166  A6  PIPE, BROKEN VERTICAL BAR
\xa7  167  A7  SECTION SIGN
\xa8  168  A8  SPACING DIAERESIS - UMLAUT
\xa9  169  A9  COPYRIGHT SIGN
\xaa  170  AA  FEMININE ORDINAL INDICATOR
\xab  171  AB  LEFT DOUBLE ANGLE QUOTES
\xac  172  AC  NOT SIGN
\xad  173  AD  SOFT HYPHEN
\xae  174  AE  REGISTERED TRADE MARK SIGN
\xaf  175  AF  SPACING MACRON - OVERLINE
\xb0  176  B0  DEGREE SIGN
\xb1  177  B1  PLUS-OR-MINUS SIGN
\xb2  178  B2  SUPERSCRIPT TWO - SQUARED
\xb3  179  B3  SUPERSCRIPT THREE - CUBED
\xb4  180  B4  ACUTE ACCENT - SPACING ACUTE
\xb5  181  B5  MICRO SIGN
\xb6  182  B6  PILCROW SIGN - PARAGRAPH SIGN
\xb7  183  B7  MIDDLE DOT - GEORGIAN COMMA
\xb8  184  B8  SPACING CEDILLA
\xb9  185  B9  SUPERSCRIPT ONE
\xba  186  BA  MASCULINE ORDINAL INDICATOR
\xbb  187  BB  RIGHT DOUBLE ANGLE QUOTES
\xbc  188  BC  FRACTION ONE QUARTER
\xbd  189  BD  FRACTION ONE HALF
\xbe  190  BE  FRACTION THREE QUARTERS
\xbf  191  BF  INVERTED QUESTION MARK
\xc0  192  C0  LATIN CAPITAL LETTER A WITH GRAVE
\xc1  193  C1  LATIN CAPITAL LETTER A WITH ACUTE
\xc2  194  C2  LATIN CAPITAL LETTER A WITH CIRCUMFLEX
\xc3  195  C3  LATIN CAPITAL LETTER A WITH TILDE
\xc4  196  C4  LATIN CAPITAL LETTER A WITH DIAERESIS
\xc5  197  C5  LATIN CAPITAL LETTER A WITH RING ABOVE
\xc6  198  C6  LATIN CAPITAL LETTER AE
\xc7  199  C7  LATIN CAPITAL LETTER C WITH CEDILLA
\xc8  200  C8  LATIN CAPITAL LETTER E WITH GRAVE
\xc9  201  C9  LATIN CAPITAL LETTER E WITH ACUTE
\xca  202  CA  LATIN CAPITAL LETTER E WITH CIRCUMFLEX
\xcb  203  CB  LATIN CAPITAL LETTER E WITH DIAERESIS
\xcc  204  CC  LATIN CAPITAL LETTER I WITH GRAVE
\xcd  205  CD  LATIN CAPITAL LETTER I WITH ACUTE
\xce  206  CE  LATIN CAPITAL LETTER I WITH CIRCUMFLEX
\xcf  207  CF  LATIN CAPITAL LETTER I WITH DIAERESIS
\xd0  208  D0  LATIN CAPITAL LETTER ETH
\xd1  209  D1  LATIN CAPITAL LETTER N WITH TILDE
\xd2  210  D2  LATIN CAPITAL LETTER O WITH GRAVE
\xd3  211  D3  LATIN CAPITAL LETTER O WITH ACUTE
\xd4  212  D4  LATIN CAPITAL LETTER O WITH CIRCUMFLEX
\xd5  213  D5  LATIN CAPITAL LETTER O WITH TILDE
\xd6  214  D6  LATIN CAPITAL LETTER O WITH DIAERESIS
\xd7  215  D7  MULTIPLICATION SIGN
\xd8  216  D8  LATIN CAPITAL LETTER O WITH SLASH
\xd9  217  D9  LATIN CAPITAL LETTER U WITH GRAVE
\xda  218  DA  LATIN CAPITAL LETTER U WITH ACUTE
\xdb  219  DB  LATIN CAPITAL LETTER U WITH CIRCUMFLEX
\xdc  220  DC  LATIN CAPITAL LETTER U WITH DIAERESIS
\xdd  221  DD  LATIN CAPITAL LETTER Y WITH ACUTE
\xde  222  DE  LATIN CAPITAL LETTER THORN
\xdf  223  DF  LATIN SMALL LETTER SHARP S
\xe0  224  E0  LATIN SMALL LETTER A WITH GRAVE
\xe1  225  E1  LATIN SMALL LETTER A WITH ACUTE
\xe2  226  E2  LATIN SMALL LETTER A WITH CIRCUMFLEX
\xe3  227  E3  LATIN SMALL LETTER A WITH TILDE
\xe4  228  E4  LATIN SMALL LETTER A WITH DIAERESIS
\xe5  229  E5  LATIN SMALL LETTER A WITH RING ABOVE
\xe6  230  E6  LATIN SMALL LETTER AE
\xe7  231  E7  LATIN SMALL LETTER C WITH CEDILLA
\xe8  232  E8  LATIN SMALL LETTER E WITH GRAVE
\xe9  233  E9  LATIN SMALL LETTER E WITH ACUTE
\xea  234  EA  LATIN SMALL LETTER E WITH CIRCUMFLEX
\xeb  235  EB  LATIN SMALL LETTER E WITH DIAERESIS
\xec  236  EC  LATIN SMALL LETTER I WITH GRAVE
\xed  237  ED  LATIN SMALL LETTER I WITH ACUTE
\xee  238  EE  LATIN SMALL LETTER I WITH CIRCUMFLEX
\xef  239  EF  LATIN SMALL LETTER I WITH DIAERESIS
\xf0  240  F0  LATIN SMALL LETTER ETH
\xf1  241  F1  LATIN SMALL LETTER N WITH TILDE
\xf2  242  F2  LATIN SMALL LETTER O WITH GRAVE
\xf3  243  F3  LATIN SMALL LETTER O WITH ACUTE
\xf4  244  F4  LATIN SMALL LETTER O WITH CIRCUMFLEX
\xf5  245  F5  LATIN SMALL LETTER O WITH TILDE
\xf6  246  F6  LATIN SMALL LETTER O WITH DIAERESIS
\xf7  247  F7  DIVISION SIGN
\xf8  248  F8  LATIN SMALL LETTER O WITH SLASH
\xf9  249  F9  LATIN SMALL LETTER U WITH GRAVE
\xfa  250  FA  LATIN SMALL LETTER U WITH ACUTE
\xfb  251  FB  LATIN SMALL LETTER U WITH CIRCUMFLEX
\xfc  252  FC  LATIN SMALL LETTER U WITH DIAERESIS
\xfd  253  FD  LATIN SMALL LETTER Y WITH ACUTE
\xfe  254  FE  LATIN SMALL LETTER THORN
\xff  255  FF  LATIN SMALL LETTER Y WITH DIAERESIS

Forbidden:

\x00    0  00  NULL CHAR
\x01    1  01  START OF HEADING
\x02    2  02  START OF TEXT
\x03    3  03  END OF TEXT
\x04    4  04  END OF TRANSMISSION
\x05    5  05  ENQUIRY
\x06    6  06  ACKNOWLEDGEMENT
\x07    7  07  BELL
\x08    8  08  BACK SPACE
\t      9  09  HORIZONTAL TAB
\n     10  0A  LINE FEED
\x0b   11  0B  VERTICAL TAB
\x0c   12  0C  FORM FEED
\r     13  0D  CARRIAGE RETURN
\x0e   14  0E  SHIFT OUT / X-ON
\x0f   15  0F  SHIFT IN / X-OFF
\x10   16  10  DATA LINE ESCAPE
\x11   17  11  DEVICE CONTROL 1 (OFT. XON)
\x12   18  12  DEVICE CONTROL 2
\x13   19  13  DEVICE CONTROL 3 (OFT. XOFF)
\x14   20  14  DEVICE CONTROL 4
\x15   21  15  NEGATIVE ACKNOWLEDGEMENT
\x16   22  16  SYNCHRONOUS IDLE
\x17   23  17  END OF TRANSMIT BLOCK
\x18   24  18  CANCEL
\x19   25  19  END OF MEDIUM
\x1a   26  1A  SUBSTITUTE
\x1b   27  1B  ESCAPE
\x1c   28  1C  FILE SEPARATOR
\x1d   29  1D  GROUP SEPARATOR
\x1e   30  1E  RECORD SEPARATOR
\x1f   31  1F  UNIT SEPARATOR
"      34  22  QUOTATION MARK
*      42  2A  ASTERISK
:      58  3A  COLON
<      60  3C  LESS-THAN SIGN
>      62  3E  GREATER-THAN SIGN
?      63  3F  QUESTION MARK
|     124  7C  VERTICAL LINE

Screenshot of how Explorer sorts the files for me:

German Windows Explorer

The highlighted file with the ? white smiley face was added manually by me (Alt+1) to show where this Unicode character (U+263A) ends up, see Jimbugs' answer.

The first file has a space as name (0x20), the second is the non-breaking space (0xa0). The files in the bottom half of the third row which look like they have no name use the characters with hex codes 0x81, 0x8D, 0x8F, 0x90, 0x9D (in this order from top to bottom).

Render basic HTML view?

In server.js, please include

var express = require("express");
var app     = express();
var path    = require("path");


app.get('/',function(req,res){
  res.sendFile(path.join(__dirname+'/index.html'));
  //__dirname : It will resolve to your project folder.
});

Maven Install on Mac OS X

macOS Sierra onwards

brew install maven

How do I drop a foreign key constraint only if it exists in sql server?

ALTER TABLE [dbo].[TableName]
    DROP CONSTRAINT FK_TableName_TableName2

Force IE8 Into IE7 Compatiblity Mode

its even simpler than that. Using HTML you can just add this metatag to your page (first thing on the page):

<meta http-equiv="X-UA-Compatible" content="IE=7" />

If you wanted to do it using.net, you just have to send your http request with that meta information in the header. This would require a page refresh to work though.

Also, you can look at a similar question here: Compatibility Mode in IE8 using VBScript

What is a correct MIME type for .docx, .pptx, etc.?

A working method in android to populates the mapping list mime types.

private static void fileMimeTypeMapping() {
     MIMETYPE_MAPPING.put("3gp", Collections.list("video/3gpp"));
     MIMETYPE_MAPPING.put("7z", Collections.list("application/x-7z-compressed"));
     MIMETYPE_MAPPING.put("accdb", Collections.list("application/msaccess"));
     MIMETYPE_MAPPING.put("ai", Collections.list("application/illustrator"));
     MIMETYPE_MAPPING.put("apk", Collections.list("application/vnd.android.package-archive"));
     MIMETYPE_MAPPING.put("arw", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("avi", Collections.list("video/x-msvideo"));
     MIMETYPE_MAPPING.put("bash", Collections.list("text/x-shellscript"));
     MIMETYPE_MAPPING.put("bat", Collections.list("application/x-msdos-program"));
     MIMETYPE_MAPPING.put("blend", Collections.list("application/x-blender"));
     MIMETYPE_MAPPING.put("bin", Collections.list("application/x-bin"));
     MIMETYPE_MAPPING.put("bmp", Collections.list("image/bmp"));
     MIMETYPE_MAPPING.put("bpg", Collections.list("image/bpg"));
     MIMETYPE_MAPPING.put("bz2", Collections.list("application/x-bzip2"));
     MIMETYPE_MAPPING.put("cb7", Collections.list("application/x-cbr"));
     MIMETYPE_MAPPING.put("cba", Collections.list("application/x-cbr"));
     MIMETYPE_MAPPING.put("cbr", Collections.list("application/x-cbr"));
     MIMETYPE_MAPPING.put("cbt", Collections.list("application/x-cbr"));
     MIMETYPE_MAPPING.put("cbtc", Collections.list("application/x-cbr"));
     MIMETYPE_MAPPING.put("cbz", Collections.list("application/x-cbr"));
     MIMETYPE_MAPPING.put("cc", Collections.list("text/x-c"));
     MIMETYPE_MAPPING.put("cdr", Collections.list("application/coreldraw"));
     MIMETYPE_MAPPING.put("class", Collections.list("application/java"));
     MIMETYPE_MAPPING.put("cnf", Collections.list("text/plain"));
     MIMETYPE_MAPPING.put("conf", Collections.list("text/plain"));
     MIMETYPE_MAPPING.put("cpp", Collections.list("text/x-c++src"));
     MIMETYPE_MAPPING.put("cr2", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("css", Collections.list("text/css"));
     MIMETYPE_MAPPING.put("csv", Collections.list("text/csv"));
     MIMETYPE_MAPPING.put("cvbdl", Collections.list("application/x-cbr"));
     MIMETYPE_MAPPING.put("c", Collections.list("text/x-c"));
     MIMETYPE_MAPPING.put("c++", Collections.list("text/x-c++src"));
     MIMETYPE_MAPPING.put("dcr", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("deb", Collections.list("application/x-deb"));
     MIMETYPE_MAPPING.put("dng", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("doc", Collections.list("application/msword"));
     MIMETYPE_MAPPING.put("docm", Collections.list("application/vnd.ms-word.document.macroEnabled.12"));
     MIMETYPE_MAPPING.put("docx", Collections.list("application/vnd.openxmlformats-officedocument.wordprocessingml.document"));
     MIMETYPE_MAPPING.put("dot", Collections.list("application/msword"));
     MIMETYPE_MAPPING.put("dotx", Collections.list("application/vnd.openxmlformats-officedocument.wordprocessingml.template"));
     MIMETYPE_MAPPING.put("dv", Collections.list("video/dv"));
     MIMETYPE_MAPPING.put("eot", Collections.list("application/vnd.ms-fontobject"));
     MIMETYPE_MAPPING.put("epub", Collections.list("application/epub+zip"));
     MIMETYPE_MAPPING.put("eps", Collections.list("application/postscript"));
     MIMETYPE_MAPPING.put("erf", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("exe", Collections.list("application/x-ms-dos-executable"));
     MIMETYPE_MAPPING.put("flac", Collections.list("audio/flac"));
     MIMETYPE_MAPPING.put("flv", Collections.list("video/x-flv"));
     MIMETYPE_MAPPING.put("gif", Collections.list("image/gif"));
     MIMETYPE_MAPPING.put("gpx", Collections.list("application/gpx+xml"));
     MIMETYPE_MAPPING.put("gz", Collections.list("application/gzip"));
     MIMETYPE_MAPPING.put("gzip", Collections.list("application/gzip"));
     MIMETYPE_MAPPING.put("h", Collections.list("text/x-h"));
     MIMETYPE_MAPPING.put("heic", Collections.list("image/heic"));
     MIMETYPE_MAPPING.put("heif", Collections.list("image/heif"));
     MIMETYPE_MAPPING.put("hh", Collections.list("text/x-h"));
     MIMETYPE_MAPPING.put("hpp", Collections.list("text/x-h"));
     MIMETYPE_MAPPING.put("htaccess", Collections.list("text/plain"));
     MIMETYPE_MAPPING.put("ical", Collections.list("text/calendar"));
     MIMETYPE_MAPPING.put("ics", Collections.list("text/calendar"));
     MIMETYPE_MAPPING.put("iiq", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("impress", Collections.list("text/impress"));
     MIMETYPE_MAPPING.put("java", Collections.list("text/x-java-source"));
     MIMETYPE_MAPPING.put("jp2", Collections.list("image/jp2"));
     MIMETYPE_MAPPING.put("jpeg", Collections.list("image/jpeg"));
     MIMETYPE_MAPPING.put("jpg", Collections.list("image/jpeg"));
     MIMETYPE_MAPPING.put("jps", Collections.list("image/jpeg"));
     MIMETYPE_MAPPING.put("k25", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("kdc", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("key", Collections.list("application/x-iwork-keynote-sffkey"));
     MIMETYPE_MAPPING.put("keynote", Collections.list("application/x-iwork-keynote-sffkey"));
     MIMETYPE_MAPPING.put("kml", Collections.list("application/vnd.google-earth.kml+xml"));
     MIMETYPE_MAPPING.put("kmz", Collections.list("application/vnd.google-earth.kmz"));
     MIMETYPE_MAPPING.put("kra", Collections.list("application/x-krita"));
     MIMETYPE_MAPPING.put("ldif", Collections.list("text/x-ldif"));
     MIMETYPE_MAPPING.put("love", Collections.list("application/x-love-game"));
     MIMETYPE_MAPPING.put("lwp", Collections.list("application/vnd.lotus-wordpro"));
     MIMETYPE_MAPPING.put("m2t", Collections.list("video/mp2t"));
     MIMETYPE_MAPPING.put("m3u", Collections.list("audio/mpegurl"));
     MIMETYPE_MAPPING.put("m3u8", Collections.list("audio/mpegurl"));
     MIMETYPE_MAPPING.put("m4a", Collections.list("audio/mp4"));
     MIMETYPE_MAPPING.put("m4b", Collections.list("audio/m4b"));
     MIMETYPE_MAPPING.put("m4v", Collections.list("video/mp4"));
     MIMETYPE_MAPPING.put("markdown", Collections.list(MIMETYPE_TEXT_MARKDOWN));
     MIMETYPE_MAPPING.put("mdown", Collections.list(MIMETYPE_TEXT_MARKDOWN));
     MIMETYPE_MAPPING.put("md", Collections.list(MIMETYPE_TEXT_MARKDOWN));
     MIMETYPE_MAPPING.put("mdb", Collections.list("application/msaccess"));
     MIMETYPE_MAPPING.put("mdwn", Collections.list(MIMETYPE_TEXT_MARKDOWN));
     MIMETYPE_MAPPING.put("mkd", Collections.list(MIMETYPE_TEXT_MARKDOWN));
     MIMETYPE_MAPPING.put("mef", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("mkv", Collections.list("video/x-matroska"));
     MIMETYPE_MAPPING.put("mobi", Collections.list("application/x-mobipocket-ebook"));
     MIMETYPE_MAPPING.put("mov", Collections.list("video/quicktime"));
     MIMETYPE_MAPPING.put("mp3", Collections.list("audio/mpeg"));
     MIMETYPE_MAPPING.put("mp4", Collections.list("video/mp4"));
     MIMETYPE_MAPPING.put("mpeg", Collections.list("video/mpeg"));
     MIMETYPE_MAPPING.put("mpg", Collections.list("video/mpeg"));
     MIMETYPE_MAPPING.put("mpo", Collections.list("image/jpeg"));
     MIMETYPE_MAPPING.put("msi", Collections.list("application/x-msi"));
     MIMETYPE_MAPPING.put("mts", Collections.list("video/MP2T"));
     MIMETYPE_MAPPING.put("mt2s", Collections.list("video/MP2T"));
     MIMETYPE_MAPPING.put("nef", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("numbers", Collections.list("application/x-iwork-numbers-sffnumbers"));
     MIMETYPE_MAPPING.put("odf", Collections.list("application/vnd.oasis.opendocument.formula"));
     MIMETYPE_MAPPING.put("odg", Collections.list("application/vnd.oasis.opendocument.graphics"));
     MIMETYPE_MAPPING.put("odp", Collections.list("application/vnd.oasis.opendocument.presentation"));
     MIMETYPE_MAPPING.put("ods", Collections.list("application/vnd.oasis.opendocument.spreadsheet"));
     MIMETYPE_MAPPING.put("odt", Collections.list("application/vnd.oasis.opendocument.text"));
     MIMETYPE_MAPPING.put("oga", Collections.list("audio/ogg"));
     MIMETYPE_MAPPING.put("ogg", Collections.list("audio/ogg"));
     MIMETYPE_MAPPING.put("ogv", Collections.list("video/ogg"));
     MIMETYPE_MAPPING.put("one", Collections.list("application/msonenote"));
     MIMETYPE_MAPPING.put("opus", Collections.list("audio/ogg"));
     MIMETYPE_MAPPING.put("orf", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("otf", Collections.list("application/font-sfnt"));
     MIMETYPE_MAPPING.put("pages", Collections.list("application/x-iwork-pages-sffpages"));
     MIMETYPE_MAPPING.put("pdf", Collections.list("application/pdf"));
     MIMETYPE_MAPPING.put("pfb", Collections.list("application/x-font"));
     MIMETYPE_MAPPING.put("pef", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("php", Collections.list("application/x-php"));
     MIMETYPE_MAPPING.put("pl", Collections.list("application/x-perl"));
     MIMETYPE_MAPPING.put("pls", Collections.list("audio/x-scpls"));
     MIMETYPE_MAPPING.put("png", Collections.list("image/png"));
     MIMETYPE_MAPPING.put("pot", Collections.list("application/vnd.ms-powerpoint"));
     MIMETYPE_MAPPING.put("potm", Collections.list("application/vnd.ms-powerpoint.template.macroEnabled.12"));
     MIMETYPE_MAPPING.put("potx", Collections.list("application/vnd.openxmlformats-officedocument.presentationml.template"));
     MIMETYPE_MAPPING.put("ppa", Collections.list("application/vnd.ms-powerpoint"));
     MIMETYPE_MAPPING.put("ppam", Collections.list("application/vnd.ms-powerpoint.addin.macroEnabled.12"));
     MIMETYPE_MAPPING.put("pps", Collections.list("application/vnd.ms-powerpoint"));
     MIMETYPE_MAPPING.put("ppsm", Collections.list("application/vnd.ms-powerpoint.slideshow.macroEnabled.12"));
     MIMETYPE_MAPPING.put("ppsx", Collections.list("application/vnd.openxmlformats-officedocument.presentationml.slideshow"));
     MIMETYPE_MAPPING.put("ppt", Collections.list("application/vnd.ms-powerpoint"));
     MIMETYPE_MAPPING.put("pptm", Collections.list("application/vnd.ms-powerpoint.presentation.macroEnabled.12"));
     MIMETYPE_MAPPING.put("pptx", Collections.list("application/vnd.openxmlformats-officedocument.presentationml.presentation"));
     MIMETYPE_MAPPING.put("ps", Collections.list("application/postscript"));
     MIMETYPE_MAPPING.put("psd", Collections.list("application/x-photoshop"));
     MIMETYPE_MAPPING.put("py", Collections.list("text/x-python"));
     MIMETYPE_MAPPING.put("raf", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("rar", Collections.list("application/x-rar-compressed"));
     MIMETYPE_MAPPING.put("reveal", Collections.list("text/reveal"));
     MIMETYPE_MAPPING.put("rss", Collections.list("application/rss+xml"));
     MIMETYPE_MAPPING.put("rtf", Collections.list("application/rtf"));
     MIMETYPE_MAPPING.put("rw2", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("schema", Collections.list("text/plain"));
     MIMETYPE_MAPPING.put("sgf", Collections.list("application/sgf"));
     MIMETYPE_MAPPING.put("sh-lib", Collections.list("text/x-shellscript"));
     MIMETYPE_MAPPING.put("sh", Collections.list("text/x-shellscript"));
     MIMETYPE_MAPPING.put("srf", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("sr2", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("tar", Collections.list("application/x-tar"));
     MIMETYPE_MAPPING.put("tar.bz2", Collections.list("application/x-bzip2"));
     MIMETYPE_MAPPING.put("tar.gz", Collections.list("application/x-compressed"));
     MIMETYPE_MAPPING.put("tbz2", Collections.list("application/x-bzip2"));
     MIMETYPE_MAPPING.put("tcx", Collections.list("application/vnd.garmin.tcx+xml"));
     MIMETYPE_MAPPING.put("tex", Collections.list("application/x-tex"));
     MIMETYPE_MAPPING.put("tgz", Collections.list("application/x-compressed"));
     MIMETYPE_MAPPING.put("tiff", Collections.list("image/tiff"));
     MIMETYPE_MAPPING.put("tif", Collections.list("image/tiff"));
     MIMETYPE_MAPPING.put("ttf", Collections.list("application/font-sfnt"));
     MIMETYPE_MAPPING.put("txt", Collections.list("text/plain"));
     MIMETYPE_MAPPING.put("vcard", Collections.list("text/vcard"));
     MIMETYPE_MAPPING.put("vcf", Collections.list("text/vcard"));
     MIMETYPE_MAPPING.put("vob", Collections.list("video/dvd"));
     MIMETYPE_MAPPING.put("vsd", Collections.list("application/vnd.visio"));
     MIMETYPE_MAPPING.put("vsdm", Collections.list("application/vnd.ms-visio.drawing.macroEnabled.12"));
     MIMETYPE_MAPPING.put("vsdx", Collections.list("application/vnd.ms-visio.drawing"));
     MIMETYPE_MAPPING.put("vssm", Collections.list("application/vnd.ms-visio.stencil.macroEnabled.12"));
     MIMETYPE_MAPPING.put("vssx", Collections.list("application/vnd.ms-visio.stencil"));
     MIMETYPE_MAPPING.put("vstm", Collections.list("application/vnd.ms-visio.template.macroEnabled.12"));
     MIMETYPE_MAPPING.put("vstx", Collections.list("application/vnd.ms-visio.template"));
     MIMETYPE_MAPPING.put("wav", Collections.list("audio/wav"));
     MIMETYPE_MAPPING.put("webm", Collections.list("video/webm"));
     MIMETYPE_MAPPING.put("woff", Collections.list("application/font-woff"));
     MIMETYPE_MAPPING.put("wpd", Collections.list("application/vnd.wordperfect"));
     MIMETYPE_MAPPING.put("wmv", Collections.list("video/x-ms-wmv"));
     MIMETYPE_MAPPING.put("xcf", Collections.list("application/x-gimp"));
     MIMETYPE_MAPPING.put("xla", Collections.list("application/vnd.ms-excel"));
     MIMETYPE_MAPPING.put("xlam", Collections.list("application/vnd.ms-excel.addin.macroEnabled.12"));
     MIMETYPE_MAPPING.put("xls", Collections.list("application/vnd.ms-excel"));
     MIMETYPE_MAPPING.put("xlsb", Collections.list("application/vnd.ms-excel.sheet.binary.macroEnabled.12"));
     MIMETYPE_MAPPING.put("xlsm", Collections.list("application/vnd.ms-excel.sheet.macroEnabled.12"));
     MIMETYPE_MAPPING.put("xlsx", Collections.list("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
     MIMETYPE_MAPPING.put("xlt", Collections.list("application/vnd.ms-excel"));
     MIMETYPE_MAPPING.put("xltm", Collections.list("application/vnd.ms-excel.template.macroEnabled.12"));
     MIMETYPE_MAPPING.put("xltx", Collections.list("application/vnd.openxmlformats-officedocument.spreadsheetml.template"));
     MIMETYPE_MAPPING.put("xrf", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("yaml", Arrays.asList("application/yaml", "text/plain"));
     MIMETYPE_MAPPING.put("yml", Arrays.asList("application/yaml", "text/plain"));
     MIMETYPE_MAPPING.put("zip", Collections.list("application/zip"));
     MIMETYPE_MAPPING.put("url", Collections.list("application/internet-shortcut"));
     MIMETYPE_MAPPING.put("webloc", Collections.list("application/internet-shortcut"));
     MIMETYPE_MAPPING.put("js", Arrays.asList("application/javascript", "text/plain"));
     MIMETYPE_MAPPING.put("json", Arrays.asList("application/json", "text/plain"));
     MIMETYPE_MAPPING.put("fb2", Arrays.asList("application/x-fictionbook+xml", "text/plain"));
     MIMETYPE_MAPPING.put("html", Arrays.asList("text/html", "text/plain"));
     MIMETYPE_MAPPING.put("htm", Arrays.asList("text/html", "text/plain"));
     MIMETYPE_MAPPING.put("m", Arrays.asList("text/x-matlab", "text/plain"));
     MIMETYPE_MAPPING.put("svg", Arrays.asList("image/svg+xml", "text/plain"));
     MIMETYPE_MAPPING.put("swf", Arrays.asList("application/x-shockwave-flash", "application/octet-stream"));
     MIMETYPE_MAPPING.put("xml", Arrays.asList("application/xml", "text/plain"));

}

Getting parts of a URL (Regex)

Try the following:

^((ht|f)tp(s?)\:\/\/|~/|/)?([\w]+:\w+@)?([a-zA-Z]{1}([\w\-]+\.)+([\w]{2,5}))(:[\d]{1,5})?((/?\w+/)+|/?)(\w+\.[\w]{3,4})?((\?\w+=\w+)?(&\w+=\w+)*)?

It supports HTTP / FTP, subdomains, folders, files etc.

I found it from a quick google search:

http://geekswithblogs.net/casualjim/archive/2005/12/01/61722.aspx

1067 error on attempt to start MySQL

In my case, in order to delete a heavy schema from mysql server, just went to C:\ProgramData\MySQL\MySQL Server 5.7\Data and deleted relevant folder. But it was not being deleted because mysqld.exe was preventing it. so I stopped mysqld.exe, deleted the folder and then all the schemas went disappeared from the list in mysql workbench. No matter how much I tried to restart mysql service, it didnt unless I restored that folder from junk. Hope it helps someone who tried the same shortcut as I did.

Merge two array of objects based on a key

You can do this in one line

_x000D_
_x000D_
let arr1 = [_x000D_
    { id: "abdc4051", date: "2017-01-24" },_x000D_
    { id: "abdc4052", date: "2017-01-22" }_x000D_
];_x000D_
_x000D_
let arr2 = [_x000D_
    { id: "abdc4051", name: "ab" },_x000D_
    { id: "abdc4052", name: "abc" }_x000D_
];_x000D_
_x000D_
const mergeById = (a1, a2) =>_x000D_
    a1.map(itm => ({_x000D_
        ...a2.find((item) => (item.id === itm.id) && item),_x000D_
        ...itm_x000D_
    }));_x000D_
_x000D_
console.log(mergeById(arr1, arr2));
_x000D_
_x000D_
_x000D_

  1. Map over array1
  2. Search through array2 for array1.id
  3. If you find it ...spread the result of array2 into array1

The final array will only contain id's that match from both arrays

C: How to free nodes in the linked list?

Simply by iterating over the list:

struct node *n = head;
while(n){
   struct node *n1 = n;
   n = n->next;
   free(n1);
}

C - reading command line parameters

When you write your main function, you typically see one of two definitions:

  • int main(void)
  • int main(int argc, char **argv)

The second form will allow you to access the command line arguments passed to the program, and the number of arguments specified (arguments are separated by spaces).

The arguments to main are:

  • int argc - the number of arguments passed into your program when it was run. It is at least 1.
  • char **argv - this is a pointer-to-char *. It can alternatively be this: char *argv[], which means 'array of char *'. This is an array of C-style-string pointers.

Basic Example

For example, you could do this to print out the arguments passed to your C program:

#include <stdio.h>

int main(int argc, char **argv)
{
    for (int i = 0; i < argc; ++i)
    {
        printf("argv[%d]: %s\n", i, argv[i]);
    }
}

I'm using GCC 4.5 to compile a file I called args.c. It'll compile and build a default a.out executable.

[birryree@lilun c_code]$ gcc -std=c99 args.c

Now run it...

[birryree@lilun c_code]$ ./a.out hello there
argv[0]: ./a.out
argv[1]: hello
argv[2]: there

So you can see that in argv, argv[0] is the name of the program you ran (this is not standards-defined behavior, but is common. Your arguments start at argv[1] and beyond.

So basically, if you wanted a single parameter, you could say...

./myprogram integral


A Simple Case for You

And you could check if argv[1] was integral, maybe like strcmp("integral", argv[1]) == 0.

So in your code...

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

int main(int argc, char **argv)
{
    if (argc < 2) // no arguments were passed
    {
        // do something
    }

    if (strcmp("integral", argv[1]) == 0)
    {
        runIntegral(...); //or something
    }
    else
    {
        // do something else.
    }
}

Better command line parsing

Of course, this was all very rudimentary, and as your program gets more complex, you'll likely want more advanced command line handling. For that, you could use a library like GNU getopt.

Display a jpg image on a JPanel

You could also use

ImageIcon background = new ImageIcon("Background/background.png");
JLabel label = new JLabel();
label.setBounds(0, 0, x, y);
label.setIcon(background);

JPanel panel = new JPanel();
panel.setLayout(null);
panel.add(label);

if your working with a absolut value as layout.

Getting the actual usedrange

I use the following vba code to determine the entire used rows range for the worksheet to then shorten the selected range of a column:

    Set rUsedRowRange = Selection.Worksheet.UsedRange.Columns( _
    Selection.Column - Selection.Worksheet.UsedRange.Column + 1)

Also works the other way around:

    Set rUsedColumnRange = Selection.Worksheet.UsedRange.Rows( _
    Selection.Row - Selection.Worksheet.UsedRange.Row + 1)

How to delete a specific file from folder using asp.net

In my project i am using ajax and i create a web method in my code behind like this

in front

 $("#attachedfiles a").live("click", function () {
            var row = $(this).closest("tr");
            var fileName = $("td", row).eq(0).html();
            $.ajax({
                type: "POST",
                url: "SendEmail.aspx/RemoveFile",
                data: '{fileName: "' + fileName + '" }',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function () { },
                failure: function (response) {
                    alert(response.d);
                }
            });
            row.remove();
        });  

in code behind

        [WebMethod]
        public static void RemoveFile(string fileName)
        {
            List<HttpPostedFile> files = (List<HttpPostedFile>)HttpContext.Current.Session["Files"];
            files.RemoveAll(f => f.FileName.ToLower().EndsWith(fileName.ToLower()));

            if (System.IO.File.Exists(HttpContext.Current.Server.MapPath("~/Employee/uploads/" + fileName)))
            {
                System.IO.File.Delete(HttpContext.Current.Server.MapPath("~/Employee/uploads/" + fileName));
            }
        }

i think this will help you.

Copying sets Java

Java 8+:

Set<String> copy = new HashSet<>(mySet); 

Is "&#160;" a replacement of "&nbsp;"?

Those do both mean non-breaking space, yes. &#xA0; is another synonym, in hex.

What port number does SOAP use?

SOAP (Simple Object Access Protocol) is the communication protocol in the web service scenario.

One benefit of SOAP is that it allowas RPC to execute through a firewall. But to pass through a firewall, you will probably want to use 80. it uses port no.8084 To the firewall, a SOAP conversation on 80 looks like a POST to a web page. However, there are extensions in SOAP which are specifically aimed at the firewall. In the future, it may be that firewalls will be configured to filter SOAP messages. But as of today, most firewalls are SOAP ignorant.

so exclusively open SOAP Port in Firewalls

How do I specify "not equals to" when comparing strings in an XSLT <xsl:if>?

As Filburt says; but also note that it's usually better to write

test="not(Count = 'N/A')"

If there's exactly one Count element they mean the same thing, but if there's no Count, or if there are several, then the meanings are different.

6 YEARS LATER

Since this answer seems to have become popular, but may be a little cryptic to some readers, let me expand it.

The "=" and "!=" operator in XPath can compare two sets of values. In general, if A and B are sets of values, then "=" returns true if there is any pair of values from A and B that are equal, while "!=" returns true if there is any pair that are unequal.

In the common case where A selects zero-or-one nodes, and B is a constant (say "NA"), this means that not(A = "NA") returns true if A is either absent, or has a value not equal to "NA". By contrast, A != "NA" returns true if A is present and not equal to "NA". Usually you want the "absent" case to be treated as "not equal", which means that not(A = "NA") is the appropriate formulation.

Calculate percentage Javascript

Heres another approach.

HTML:

<input type='text' id="pointspossible" class="clsInput" />
<input type='text' id="pointsgiven"  class="clsInput" />
<button id="btnCalculate">Calculate</button>
<input type='text' id="pointsperc" disabled/>

JS Code:

function isNumeric(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}


$('#btnCalculate').on('click', function() {
    var a = $('#pointspossible').val().replace(/ +/g, "");
    var b = $('#pointsgiven').val().replace(/ +/g, "");
    var perc = "0";
    if (a.length > 0 && b.length > 0) {
        if (isNumeric(a) && isNumeric(b)) {
            perc = a / b * 100;
        }
    }    
    $('#pointsperc').val(perc).toFixed(3);
});

Live Sample: Percentage Calculator

Magento - Retrieve products with a specific attribute value

create attribute name is "price_screen_tab_name". and access using this simple formula.

<?php $_product = $this->getProduct(); ?>
<?php echo $_product->getData('price_screen_tab_name');?>

find all unchecked checkbox in jquery

As the error message states, jQuery does not include a :unchecked selector.
Instead, you need to invert the :checked selector:

$("input:checkbox:not(:checked)")

How to add a TextView to a LinearLayout dynamically in Android?

If you are using Linearlayout. its params should be "wrap_content" to add dynamic data in your layout xml. if you use match or fill parent then you cannot see the output.

It Should be like this.

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content" android:layout_height="wrap_content">
        <ListView
            android:id="@+id/list"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >
        </ListView>
    </LinearLayout>

How to create a numpy array of all True or all False?

numpy.full((2,2), True, dtype=bool)

How can I list all commits that changed a specific file?

# Shows commit history with patch
git log -p -<no_of_commits> --follow <file_name>

# Shows brief details like "1 file changed, 6 insertions(+), 1 deletion(-)"
git log --stat --follow <file_name>

Reference

Create a root password for PHPMyAdmin

Open phpMyAdmin and select the SQL tab. Then type this command:

SET PASSWORD FOR 'root'@'localhost' = PASSWORD('your_root_password');

Also change to this line in config.inc.php:

$cfg['Servers'][$i]['auth_type'] = 'cookie';

To make phpMyAdmin prompts for your MySQL username and password.

Cannot redeclare function php

Remove the function and check the output of:

var_dump(function_exists('parseDate'));

In which case, change the name of the function.

If you get false, you're including the file with that function twice, replace :

include

by

include_once

And replace :

require

by

require_once

EDIT : I'm just a little too late, post before beat me to it !

Iframe transparent background

I've used this creating an IFrame through Javascript and it worked for me:

// IFrame points to the IFrame element, obviously
IFrame.src = 'about: blank';
IFrame.style.backgroundColor = "transparent";
IFrame.frameBorder = "0";
IFrame.allowTransparency="true";

Not sure if it makes any difference, but I set those properties before adding the IFrame to the DOM. After adding it to the DOM, I set its src to the real URL.

ORA-01653: unable to extend table by in tablespace ORA-06512

You could also turn on autoextend for the whole database using this command:

ALTER DATABASE DATAFILE 'C:\ORACLEXE\APP\ORACLE\ORADATA\XE\SYSTEM.DBF'
AUTOEXTEND ON NEXT 1M MAXSIZE 1024M;

Just change the filepath to point to your system.dbf file.

Credit Here

python: how to identify if a variable is an array or a scalar

Simply use size instead of len!

>>> from numpy import size
>>> N = [2, 3, 5]
>>> size(N)
3
>>> N = array([2, 3, 5])
>>> size(N)
3
>>> P = 5
>>> size(P)
1

Ruby max integer

Ruby automatically converts integers to a large integer class when they overflow, so there's (practically) no limit to how big they can be.

If you are looking for the machine's size, i.e. 64- or 32-bit, I found this trick at ruby-forum.com:

machine_bytes = ['foo'].pack('p').size
machine_bits = machine_bytes * 8
machine_max_signed = 2**(machine_bits-1) - 1
machine_max_unsigned = 2**machine_bits - 1

If you are looking for the size of Fixnum objects (integers small enough to store in a single machine word), you can call 0.size to get the number of bytes. I would guess it should be 4 on 32-bit builds, but I can't test that right now. Also, the largest Fixnum is apparently 2**30 - 1 (or 2**62 - 1), because one bit is used to mark it as an integer instead of an object reference.

There is already an object named in the database

Maybe you have changed the namespace in your project!
There is a table in your data base called dbo.__MigrationHistory. The table has a column called ContextKey.
The value of this column is based on your namespace. for example is "DataAccess.Migrations.Configuration".
When you change the namespace, it causes duplicate table names with different namespaces.
So, after you change namespace in code side, change the namespace in this table in database, too, (for all rows).
For example, if you change the namespace to EFDataAccess, then you should change the values of ContextKey column in dbo.__MigrationHistory to "EFDataAccess.Migrations.Configuration".
Then in code side, in Tools => Package Manager Console, use the update-database command.

Another option instead of changing the context value in the database is to hard code the context value in your code to the old namespace value. This is possible by inheriting DbMigrationsConfiguration<YourDbContext> and in the constructor just assign the old context value to ContextKey, than inherit from MigrateDatabaseToLatestVersion<YourDbContext, YourDbMigrationConfiguration> and leave that class empty. The last thing to do is call Database.SetInitializer(new YourDbInitializer()); in your DbContext in a static constructor.

I hope your problem will be fixed.

How to set the title of UIButton as left alignment?

Set the contentHorizontalAlignment:

emailBtn.contentHorizontalAlignment = .left;

You might also want to adjust the content left inset otherwise the text will touch the left border:

emailBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);

// Swift 3 and up:
emailBtn.contentEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0);

How to align td elements in center

What worked for me is the following (in view of the confusion in other answers):

<td style="text-align:center;">
    <input type="radio" name="ageneral" value="male">
</td>

The proposed solution (text-align) works but must be used in a style attribute.

MessageBox with YesNoCancel - No & Cancel triggers same event

Closing conformation alert:

Private Sub cmd_exit_click()

    ' By clicking on the button the MsgBox will appear
    If MsgBox("Are you sure want to exit now?", MsgBoxStyle.YesNo, "closing warning") = MsgBoxResult.Yes Then ' If you select yes in the MsgBox then it will close the window
               Me.Close() ' Close the window
    Else
        ' Will not close the application
    End If
End Sub

Shell script - remove first and last quote (") from a variable

If you're using jq and trying to remove the quotes from the result, the other answers will work, but there's a better way. By using the -r option, you can output the result with no quotes.

$ echo '{"foo": "bar"}' | jq '.foo'
"bar"

$ echo '{"foo": "bar"}' | jq -r '.foo'
bar

tSQL - Conversion from varchar to numeric works for all but integer

Converting a varchar value into an int fails when the value includes a decimal point to prevent loss of data.

If you convert to a decimal or float value first, then convert to int, the conversion works.

Either example below will return 7082:

SELECT CONVERT(int, CONVERT(decimal(12,7), '7082.7758172'));
SELECT CAST(CAST('7082.7758172' as float) as int);

Be aware that converting to a float value may result, in rare circumstances, in a loss of precision. I would tend towards using a decimal value, however you'll need to specify precision and scale values that make sense for the varchar data you're converting.

How to loop over directories in Linux?

cd /tmp
find . -maxdepth 1 -mindepth 1 -type d -printf '%f\n'

A short explanation:

  • find finds files (quite obviously)

  • . is the current directory, which after the cd is /tmp (IMHO this is more flexible than having /tmp directly in the find command. You have only one place, the cd, to change, if you want more actions to take place in this folder)

  • -maxdepth 1 and -mindepth 1 make sure that find only looks in the current directory and doesn't include . itself in the result

  • -type d looks only for directories

  • -printf '%f\n prints only the found folder's name (plus a newline) for each hit.

Et voilà!

Passing a variable to a powershell script via command line

Passed parameter like below,

Param([parameter(Mandatory=$true,
   HelpMessage="Enter name and key values")]
   $Name,
   $Key)

.\script_name.ps1 -Name name -Key key

How to completely uninstall Visual Studio 2010?

There is a solution here : Add

/full /netfx at the end of the path!

This should clear almost all. You should only be left with SQL Server.

Excel VBA - select a dynamic cell range

So it depends on how you want to pick the incrementer, but this should work:

Range("A1:" & Cells(1, i).Address).Select

Where i is the variable that represents the column you want to select (1=A, 2=B, etc.). Do you want to do this by column letter instead? We can adjust if so :)

If you want the beginning to be dynamic as well, you can try this:

Sub SelectCols()

    Dim Col1 As Integer
    Dim Col2 As Integer

    Col1 = 2
    Col2 = 4

    Range(Cells(1, Col1), Cells(1, Col2)).Select

End Sub

How to display with n decimal places in Matlab

i use like tim say sprintf('%0.6f', x), it's a string then i change it to number by using command str2double(x).

Tool to compare directories (Windows 7)

The tool that richardtz suggests is excellent.

Another one that is amazing and comes with a 30 day free trial is Araxis Merge. This one does a 3 way merge and is much more feature complete than winmerge, but it is a commercial product.

You might also like to check out Scott Hanselman's developer tool list, which mentions a couple more in addition to winmerge

<> And Not In VB.NET

If you need to know if the variable exists use Is/IsNot Nothing.

Using <> requires that the variable you're evaluating have the "<>" operator defined. Check out

 Dim b As HttpContext
 If b <> Nothing Then
    ...
 End If

and the resultant error

Error   1   Operator '<>' is not defined for types 'System.Web.HttpContext' and 'System.Web.HttpContext'.   

DataGridView - Focus a specific cell

            //For me it's the best way to look for the value of a spezific column
            int seekValue = 5;
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                var columnValue = Convert.ToInt32(row.Cells["ColumnName"].Value);
                if (columnValue == seekValue)
                {
                    dataGridView1.CurrentCell = row.Cells[0];
                }
            }

Bootstrap carousel multiple frames at once

You can add multiple li in ol tag that has attribute as class with value "carousel-indicators" and with data-slide-to has sequential values like 0 to 6 or 0 to 9.

than you just need to copy and paste the div which has attribute as class with value "item".

This works for me.

<div data-ride="carousel" class="carousel slide" id="myCarousel">
    <!-- Indicators -->
    <ol class="carousel-indicators">
        <li class="" data-slide-to="0" data-target="#myCarousel"></li>
        <li data-slide-to="1" data-target="#myCarousel" class=""></li>
        <li data-slide-to="2" data-target="#myCarousel" class="active"></li>
        <li data-slide-to="3" data-target="#myCarousel" class=""></li>
        <li data-slide-to="4" data-target="#myCarousel" class=""></li>
        <li data-slide-to="5" data-target="#myCarousel" class=""></li>
        <li data-slide-to="6" data-target="#myCarousel" class=""></li>
    </ol>
    <div role="listbox" class="carousel-inner">
        <div class="item active">
            <img alt="First slide" src="images/carousel/11.jpg"
                class="first-slide">
        </div>
        <div class="item">
            <img alt="Second slide" src="images/carousel/22.jpg"
                class="second-slide">
        </div>
        <div class="item">
            <img alt="Third slide" src="images/carousel/33.jpg"
                class="third-slide">
        </div>
        <div class="item">
            <img alt="Third slide" src="images/carousel/44.jpeg"
                class="fourth-slide">
        </div>
        <div class="item">
            <img alt="Third slide" src="images/carousel/55.jpg"
                class="third-slide">
        </div>
        <div class="item">
            <img alt="Third slide" src="images/carousel/66.jpg"
                class="third-slide">
        </div>
        <div class="item">
            <img alt="Third slide" src="images/carousel/77.jpg"
                class="third-slide">
        </div>
    </div>
    <a data-slide="prev" role="button" href="#myCarousel"
        class="left carousel-control"> <span aria-hidden="true"
        class="glyphicon glyphicon-chevron-left"></span> <span
        class="sr-only">Previous</span>
    </a> <a data-slide="next" role="button" href="#myCarousel"
        class="right carousel-control"> <span aria-hidden="true"
        class="glyphicon glyphicon-chevron-right"></span> <span
        class="sr-only">Next</span>
    </a>
</div>

How do you set your pythonpath in an already-created virtualenv?

  1. Initialize your virtualenv
cd venv

source bin/activate
  1. Just set or change your python path by entering command following:
export PYTHONPATH='/home/django/srmvenv/lib/python3.4'
  1. for checking python path enter in python:
   python

      \>\> import sys

      \>\> sys.path

Does C have a string type?

To note it in the languages you mentioned:

Java:

String str = new String("Hello");

Python:

str = "Hello"

Both Java and Python have the concept of a "string", C does not have the concept of a "string". C has character arrays which can come in "read only" or manipulatable.

C:

char * str = "Hello";  // the string "Hello\0" is pointed to by the character pointer
                       // str. This "string" can not be modified (read only)

or

char str[] = "Hello";  // the characters: 'H''e''l''l''o''\0' have been copied to the 
                       // array str. You can change them via: str[x] = 't'

A character array is a sequence of contiguous characters with a unique sentinel character at the end (normally a NULL terminator '\0'). Note that the sentinel character is auto-magically appended for you in the cases above.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException

First you should learn about loops, in this case most suitable is for loop. For instance let's initialize whole table with increasing values starting with 0:

final int SIZE = 10;
int[] array = new int[SIZE];
for (int i = 0; i < SIZE; i++) {
    array[i] = i;
}

Now you can modify it to initialize your table with values as per your assignment. But what happen if you replace condition i < SIZE with i < 11? Well, you will get IndexOutOfBoundException, as you try to access (at some point) an object under index 10, but the highest index in 10-element array is 9. So you are trying, in other words, to find friend's home with number 11, but there are only 10 houses in the street.

In case of the code you presented, well, there must be more of it, as you can not get this error (exception) from that code.

In what cases do I use malloc and/or new?

Rare case to consider using malloc/free instead of new/delete is when you're allocating and then reallocating (simple pod types, not objects) using realloc as there is no similar function to realloc in C++ (although this can be done using a more C++ approach).

latex tabular width the same as the textwidth

The tabularx package gives you

  1. the total width as a first parameter, and
  2. a new column type X, all X columns will grow to fill up the total width.

For your example:

\usepackage{tabularx}
% ...    
\begin{document}
% ...

\begin{tabularx}{\textwidth}{|X|X|X|}
\hline
Input & Output& Action return \\
\hline
\hline
DNF &  simulation & jsp\\
\hline
\end{tabularx}

How can I store and retrieve images from a MySQL database using PHP?

First you create a MySQL table to store images, like for example:

create table testblob (
    image_id        tinyint(3)  not null default '0',
    image_type      varchar(25) not null default '',
    image           blob        not null,
    image_size      varchar(25) not null default '',
    image_ctgy      varchar(25) not null default '',
    image_name      varchar(50) not null default ''
);

Then you can write an image to the database like:

/***
 * All of the below MySQL_ commands can be easily
 * translated to MySQLi_ with the additions as commented
 ***/ 
$imgData = file_get_contents($filename);
$size = getimagesize($filename);
mysql_connect("localhost", "$username", "$password");
mysql_select_db ("$dbname");
// mysqli 
// $link = mysqli_connect("localhost", $username, $password,$dbname); 
$sql = sprintf("INSERT INTO testblob
    (image_type, image, image_size, image_name)
    VALUES
    ('%s', '%s', '%d', '%s')",
    /***
     * For all mysqli_ functions below, the syntax is:
     * mysqli_whartever($link, $functionContents); 
     ***/
    mysql_real_escape_string($size['mime']),
    mysql_real_escape_string($imgData),
    $size[3],
    mysql_real_escape_string($_FILES['userfile']['name'])
    );
mysql_query($sql);

You can display an image from the database in a web page with:

$link = mysql_connect("localhost", "username", "password");
mysql_select_db("testblob");
$sql = "SELECT image FROM testblob WHERE image_id=0";
$result = mysql_query("$sql");
header("Content-type: image/jpeg");
echo mysql_result($result, 0);
mysql_close($link);

Android emulator doesn't take keyboard input - SDK tools rev 20

Here is some workaround that actually worked for me, it is the same solution as in the most popular answer - just add hw.keyboard=yes to config.ini but since this didn't work for me I additionally

  1. renamed config.ini (any name will do) to something like consssssfig.ini
  2. restarted emulator (obviously it didn't start)
  3. renamed config.ini back again
  4. (I am not sure if relevant) I added this new parameter (hw.keyboard=yes) at the beggining of config.ini file

Print very long string completely in pandas dataframe

Use pd.set_option('display.max_colwidth', None) for automatic linebreaks and multi-line cells.

This is a great resource on how to use jupyters display with pandas to the fullest.


Edited: Used to be pd.set_option('display.max_colwidth', -1).

Setting default checkbox value in Objective-C?

Documentation on UISwitch says:

[mySwitch setOn:NO]; 

In Interface Builder, select your switch and in the Attributes inspector you'll find State which can be set to on or off.

How to upgrade PostgreSQL from version 9.6 to version 10.1 without losing data?

My solution for upgrading from Postgresql 11 to Postgresql 12 on Windows 10 is the following.

As a first remark you will need to be able stop and start the Postgresql service. You can do this by the following commands in Powershell.

Start: pg_ctl start -D “d:\postgresql\11\data”

Stop: pg_ctl stop -D “d:\postgresql\11\data”

Status: pg_ctl status -D “d:\postgresql\11\data”

It would be wise to make a backup before doing the upgrade. The Postgresql 11 instance must be running. Then to copy the globals do

pg_dumpall -U postgres -g -f d:\bakup\postgresql\11\globals.sql

and then for each database

pg_dump -U postgres -Fc <database> > d:\backup\postgresql\11\<database>.fc

or

pg_dump -U postgres -Fc -d <database> -f d:\backup\postgresql\11\<database>.fc

If not already done install Postgresql 12 (as Postgresql 11 is also installed this will be on port 5433)

Then to do the upgrade as follows:

1) Stop Postgresql 11 service (see above)

2) Edit the postgresql.conf file in d:\postgresql\12\data and change port = 5433 to port = 5432

3) Edit the windows user environment path (windows start then type env) to point to Postgresql 12 instead of Postresql 11

4) Run upgrade by entering the following command.

pg_upgrade `
-b “c:\program files\postgresql\11\bin” `
-B “c:\program files\postgresql\12\bin” `
-d “d:\postgresql\11\data” `
-D “d:\postgresql\12\data” --username=postgres

(In powershell use backtick (or backquote) ` to continue the command on the next line)

5) and finally start the new Postgresql 12 service

pg_ctl start -D “d:\postgresql\12\data”

Convert number of minutes into hours & minutes using PHP

Sorry for bringing up an old topic, but I used some code from one of these answers a lot, and today I told myself I could do it without stealing someone's code. I was surprised how easy it was. What I wanted is 510 minutes to be return as 08:30, so this is what the code does.

function tm($nm, $lZ = true){ //tm = to military (time), lZ = leading zero (if true it returns 510 as 08:30, if false 8:30
  $mins = $nm % 60;
  if($mins == 0)    $mins = "0$mins"; //adds a zero, so it doesn't return 08:0, but 08:00

  $hour = floor($nm / 60);

  if($lZ){
    if($hour < 10) return "0$hour:$mins";
  }

  return "$hour:$mins";
}

I use short variable names because I'm going to use the function a lot, and I'm lazy.

Proper way to concatenate variable strings

As simple as joining lists in python itself.

ansible -m debug -a msg="{{ '-'.join(('list', 'joined', 'together')) }}" localhost

localhost | SUCCESS => {
  "msg": "list-joined-together" }

Works the same way using variables:

ansible -m debug -a msg="{{ '-'.join((var1, var2, var3)) }}" localhost

Setting Authorization Header of HttpClient

To set basic authentication with C# HttpClient. The following code is working for me.

   using (var client = new HttpClient())
        {
            var webUrl ="http://localhost/saleapi/api/";
            var uri = "api/sales";
            client.BaseAddress = new Uri(webUrl);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.ConnectionClose = true;

            //Set Basic Auth
            var user = "username";
            var password = "password";
            var base64String =Convert.ToBase64String( Encoding.ASCII.GetBytes($"{user}:{password}"));
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",base64String);

            var result = await client.PostAsJsonAsync(uri, model);
            return result;
        }

How can I get terminal output in python?

The easiest way is to use the library commands

import commands
print commands.getstatusoutput('echo "test" | wc')

How to start IDLE (Python editor) without using the shortcut on Windows Vista?

I got a shortcut for Idle (Python GUI).

  • Click on Window icon at the bottom left or use Window Key (only Python 2), you will see Idle (Python GUI) icon
  • Right click on the icon then more
  • Open File Location
  • A new window will appears, and you will see the shortcut of Idle (Python GUI)
  • Right click, hold down and pull out to desktop to create a shortcut of Python GUI on desktop.

Jquery If radio button is checked

$("input").bind('click', function(e){
   if ($(this).val() == 'Yes') {
        $("body").append('whatever');
   }
});

Difference between x86, x32, and x64 architectures?

x86 means Intel 80x86 compatible. This used to include the 8086, a 16-bit only processor. Nowadays it roughly means any CPU with a 32-bit Intel compatible instruction set (usually anything from Pentium onwards). Never read x32 being used.

x64 means a CPU that is x86 compatible but has a 64-bit mode as well (most often the 64-bit instruction set as introduced by AMD is meant; Intel's idea of a 64-bit mode was totally stupid and luckily Intel admitted that and is now using AMDs variant).

So most of the time you can simplify it this way: x86 is Intel compatible in 32-bit mode, x64 is Intel compatible in 64-bit mode.

Check if an image is loaded (no errors) with jQuery

After reading the interesting solutions on this page, I created an easy-to-use solution highly influenced by SLaks' and Noyo's post that seems to be working on pretty recent versions (as of writing) of Chrome, IE, Firefox, Safari, and Opera (all on Windows). Also, it worked on an iPhone/iPad emulator I used.

One major difference between this solution and SLaks and Noyo's post is that this solution mainly checks the naturalWidth and naturalHeight properties. I've found that in the current browser versions, those two properties seem to provide the most helpful and consistent results.

This code returns TRUE when an image has loaded fully AND successfully. It returns FALSE when an image either has not loaded fully yet OR has failed to load.

One thing you will need to be aware of is that this function will also return FALSE if the image is a 0x0 pixel image. But those images are quite uncommon, and I can't think of a very useful case where you would want to check to see if a 0x0 pixel image has loaded yet :)

First we attach a new function called "isLoaded" to the HTMLImageElement prototype, so that the function can be used on any image element.

HTMLImageElement.prototype.isLoaded = function() {

    // See if "naturalWidth" and "naturalHeight" properties are available.
    if (typeof this.naturalWidth == 'number' && typeof this.naturalHeight == 'number')
        return !(this.naturalWidth == 0 && this.naturalHeight == 0);

    // See if "complete" property is available.
    else if (typeof this.complete == 'boolean')
        return this.complete;

    // Fallback behavior: return TRUE.
    else
        return true;

};

Then, any time we need to check the loading status of the image, we just call the "isLoaded" function.

if (someImgElement.isLoaded()) {
    // YAY! The image loaded
}
else {
    // Image has not loaded yet
}

Per giorgian's comment on SLaks' and Noyo's post, this solution probably can only be used as a one-time check on Safari Mobile if you plan on changing the SRC attribute. But you can work around that by creating an image element with a new SRC attribute instead of changing the SRC attribute on an existing image element.

Converting a pointer into an integer

Use uintptr_t as your integer type.

How to serialize Joda DateTime with Jackson JSON processor?

In the object you're mapping:

@JsonSerialize(using = CustomDateSerializer.class)
public DateTime getDate() { ... }

In CustomDateSerializer:

public class CustomDateSerializer extends JsonSerializer<DateTime> {

    private static DateTimeFormatter formatter = 
        DateTimeFormat.forPattern("dd-MM-yyyy");

    @Override
    public void serialize(DateTime value, JsonGenerator gen, 
                          SerializerProvider arg2)
        throws IOException, JsonProcessingException {

        gen.writeString(formatter.print(value));
    }
}

How can I replace a regex substring match in Javascript?

using str.replace(regex, $1);:

var str   = 'asd-0.testing';
var regex = /(asd-)\d(\.\w+)/;

if (str.match(regex)) {
    str = str.replace(regex, "$1" + "1" + "$2");
}

Edit: adaptation regarding the comment

Operation Not Permitted when on root - El Capitan (rootless disabled)

If you want to take control of /usr/bin/

You will need to reboot your system:

Right after the boot sound, Hold down Command-R to boot into the Recovery System

Click the Utilities menu and select Terminal

Type csrutil disable and press return

Click the ? menu and select Restart

Once you have committed your changes, make sure to re-enable SIP! It does a lot to protect your system. (Same steps as above except type: csrutil enable)

nginx error connect to php5-fpm.sock failed (13: Permission denied)

To those who tried everything in this thread and still stuck: This solved my problem. I updated /usr/local/nginx/conf/nginx.conf

  1. Uncomment the line saying user

  2. make it www-data so it becomes: user www-data;

  3. Save it (root access required)

  4. Restart nginx

How do I get the object if it exists, or None if it does not exist?

From django docs

get() raises a DoesNotExist exception if an object is not found for the given parameters. This exception is also an attribute of the model class. The DoesNotExist exception inherits from django.core.exceptions.ObjectDoesNotExist

You can catch the exception and assign None to go.

from django.core.exceptions import ObjectDoesNotExist
try:
    go  = Content.objects.get(name="baby")
except ObjectDoesNotExist:
    go = None

Generate full SQL script from EF 5 Code First Migrations

The API appears to have changed (or at least, it doesn't work for me).

Running the following in the Package Manager Console works as expected:

Update-Database -Script -SourceMigration:0

How do I convert an existing callback API to promises?

The callback style function always like this(almost all function in node.js is this style):

//fs.readdir(path[, options], callback)
fs.readdir('mypath',(err,files)=>console.log(files))

This style has same feature:

  1. the callback function is passed by last argument.

  2. the callback function always accept the error object as it's first argument.

So, you could write a function for convert a function with this style like this:

const R =require('ramda')

/**
 * A convenient function for handle error in callback function.
 * Accept two function res(resolve) and rej(reject) ,
 * return a wrap function that accept a list arguments,
 * the first argument as error, if error is null,
 * the res function will call,else the rej function.
 * @param {function} res the function which will call when no error throw
 * @param {function} rej the function which will call when  error occur
 * @return {function} return a function that accept a list arguments,
 * the first argument as error, if error is null, the res function
 * will call,else the rej function
 **/
const checkErr = (res, rej) => (err, ...data) => R.ifElse(
    R.propEq('err', null),
    R.compose(
        res,
        R.prop('data')
    ),
    R.compose(
        rej,
        R.prop('err')
    )
)({err, data})

/**
 * wrap the callback style function to Promise style function,
 * the callback style function must restrict by convention:
 * 1. the function must put the callback function where the last of arguments,
 * such as (arg1,arg2,arg3,arg...,callback)
 * 2. the callback function must call as callback(err,arg1,arg2,arg...)
 * @param {function} fun the callback style function to transform
 * @return {function} return the new function that will return a Promise,
 * while the origin function throw a error, the Promise will be Promise.reject(error),
 * while the origin function work fine, the Promise will be Promise.resolve(args: array),
 * the args is which callback function accept
 * */
 const toPromise = (fun) => (...args) => new Promise(
    (res, rej) => R.apply(
        fun,
        R.append(
            checkErr(res, rej),
            args
        )
    )
)

For more concise, above example used ramda.js. Ramda.js is a excellent library for functional programming. In above code, we used it's apply(like javascript function.prototype.apply) and append(like javascript function.prototype.push ). So, we could convert the a callback style function to promise style function now:

const {readdir} = require('fs')
const readdirP = toPromise(readdir)
readdir(Path)
    .then(
        (files) => console.log(files),
        (err) => console.log(err)
    )

toPromise and checkErr function is own by berserk library, it's a functional programming library fork by ramda.js(create by me).

Hope this answer is useful for you.

Is there an XSL "contains" directive?

From Zvon.org XSLT Reference:

XPath function: boolean contains (string, string) 

Hope this helps.

Open window in JavaScript with HTML inserted

I would not recomend you to use document.write as others suggest, because if you will open such window twice your HTML will be duplicated 2 times (or more).

Use innerHTML instead

var win = window.open("", "Title", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=780,height=200,top="+(screen.height-400)+",left="+(screen.width-840));
win.document.body.innerHTML = "HTML";

How to know the version of pip itself

Start Python and type import pip pip.__version__ which works for all python packages.

nginx - client_max_body_size has no effect

I meet the same problem, but I found it nothing to do with nginx. I am using nodejs as backend server, use nginx as a reverse proxy, 413 code is triggered by node server. node use koa parse the body. koa limit the urlencoded length.

formLimit: limit of the urlencoded body. If the body ends up being larger than this limit, a 413 error code is returned. Default is 56kb.

set formLimit to bigger can solve this problem.

How do I convert a C# List<string[]> to a Javascript array?

Many of these answers do work, but I have found the easiest way by far is to send data through ViewData or ViewBag and let JSON.Net serialize it.

I use this technique when Javascript is needed for HTML generation before the page load or when AJAX overhead needs to be avoided:

In the controller:

public ActionResult MyController()
{
    var addresses = myAddressesGetter();
    ViewData["addresses"] = addresses ;
    return View();
}

In the view:

@section scripts {
<script type="text/javascript">
    var MyjavascriptAddresses: @Html.Raw(JsonConvert.SerializeObject(ViewData["addresses"])),
</script>
}

You can always rely on JSON.NET whereas some browsers have poor JSON deserialization support. Another benefit over some methods in that you can see the Javascript using your browser's View --> Source, since it is simply text generated server-side.

Note that In most situations, Web API a more elegant way to get JSON to the client.

How to overwrite styling in Twitter Bootstrap

Came across this late, but I think it could use another answer.

If you're using sass, you can actually change the variables before you import bootstrap. http://twitter.github.com/bootstrap/customize.html#variables

Change any of them, such as:

$bodyBackground: red;
@import "bootstrap";

Alternatively if there isn't a variable available for what you want to change, you can override the styles or add your own.

Sass:

@import "bootstrap";

/* override anything manually, like rounded buttons */
.btn {
  border-radius: 0;
}

Also see this: Proper SCSS Asset Structure in Rails

What is the difference between JavaScript and ECMAScript?

I doubt we'd ever use the word "ECMAScript" if not for the fact that the name "JavaScript" is owned by Sun. For all intents and purposes, the language is JavaScript. You don't go to the bookstore looking for ECMAScript books, do you?

It's a bit too simple to say that "JavaScript" is the implementation. JScript is Microsoft's implementation.

What does the 'L' in front a string mean in C++?

'L' means wchar_t, which, as opposed to a normal character, requires 16-bits of storage rather than 8-bits. Here's an example:

"A"    = 41
"ABC"  = 41 42 43
L"A"   = 00 41
L"ABC" = 00 41 00 42 00 43

A wchar_t is twice big as a simple char. In daily use you don't need to use wchar_t, but if you are using windows.h you are going to need it.

What is the difference between __str__ and __repr__?

On page 358 of the book Python scripting for computational science by Hans Petter Langtangen, it clearly states that

  • The __repr__ aims at a complete string representation of the object;
  • The __str__ is to return a nice string for printing.

So, I prefer to understand them as

  • repr = reproduce
  • str = string (representation)

from the user's point of view although this is a misunderstanding I made when learning python.

A small but good example is also given on the same page as follows:

Example

In [38]: str('s')
Out[38]: 's'

In [39]: repr('s')
Out[39]: "'s'"

In [40]: eval(str('s'))
Traceback (most recent call last):

  File "<ipython-input-40-abd46c0c43e7>", line 1, in <module>
    eval(str('s'))

  File "<string>", line 1, in <module>

NameError: name 's' is not defined


In [41]: eval(repr('s'))
Out[41]: 's'

How can I link a photo in a Facebook album to a URL

You can only do this to you own photos. Due to recent upgrades, Facebook has made this more difficult. To do this, go to the album page where the photo is that you want to link to. You should see thumbnail images of the photos in the album. Hold down the "Control" or "Command" key while clicking the photo that you wish to link to. A new browser tab will open with the picture you clicked. Under the picture there is a URL that you can send to others to share the photo. You might have to have the privacy settings for that album set so that anyone can see the photos in that album. If you don't the person who clicks the link may have to be signed in and also be your "friend."

Here is an example of one of my photos: http://www.facebook.com/photo.php?pid=43764341&l=0d8a526a64&id=25502298 -it's my cat.

Update:

The link below the photo no longer appears. Once you open the photo in a new tab you can right click the photo (Control+click for Mac users) and click "Copy Image URL" or similar and then share this link. Based on my tests the person who clicks the link doesn't need to use Facebook. The photo will load without the Facebook interface. Like this - http://a1.sphotos.ak.fbcdn.net/hphotos-ak-ash4/189088_867367406856_25502298_43764341_1304758_n.jpg

How to deal with certificates using Selenium?

WebDriverManager.chromedriver().setup();
ChromeOptions options = new ChromeOptions();
options.addArguments("--ignore-certificate-errors");
driver = new ChromeDriver(options);

I have used it for Java with Chrome browser it is working nice

How do I capture the output into a variable from an external process in PowerShell?

Or try this. It will capture output into variable $scriptOutput:

& "netdom.exe" $params | Tee-Object -Variable scriptOutput | Out-Null

$scriptOutput

Java8: sum values from specific field of the objects in a list

Try:

int sum = lst.stream().filter(o -> o.field > 10).mapToInt(o -> o.field).sum();

How to change default text color using custom theme?

When you create an App, a file called styles.xml will be created in your res/values folder. If you change the styles, you can change the background, text color, etc for all your layouts. That way you don’t have to go into each individual layout and change the it manually.

styles.xml:

<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="Theme.AppBaseTheme" parent="@android:style/Theme.Light">
    <item name="android:editTextColor">#295055</item> 
    <item name="android:textColorPrimary">#295055</item>
    <item name="android:textColorSecondary">#295055</item>
    <item name="android:textColorTertiary">#295055</item>
    <item name="android:textColorPrimaryInverse">#295055</item>
    <item name="android:textColorSecondaryInverse">#295055</item>
    <item name="android:textColorTertiaryInverse">#295055</item>

     <item name="android:windowBackground">@drawable/custom_background</item>        
</style>

<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
    <!-- All customizations that are NOT specific to a particular API-level can go here. -->
</style>

parent="@android:style/Theme.Light" is Google’s native colors. Here is a reference of what the native styles are: https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/res/res/values/themes.xml

The default Android style is also called “Theme”. So you calling it Theme probably confused the program.

name="Theme.AppBaseTheme" means that you are creating a style that inherits all the styles from parent="@android:style/Theme.Light". This part you can ignore unless you want to inherit from AppBaseTheme again. = <style name="AppTheme" parent="AppBaseTheme">

@drawable/custom_background is a custom image I put in the drawable’s folder. It is a 300x300 png image.

#295055 is a dark blue color.

My code changes the background and text color. For Button text, please look through Google’s native stlyes (the link I gave u above).

Then in Android Manifest, remember to include the code:

<application
android:theme="@style/Theme.AppBaseTheme">

Show hide div using codebehind

There are a few ways to handle rendering/showing controls on the page and you should take note to what happens with each method.

Rendering and Visibility

There are some instances where elements on your page don't need to be rendered for the user because of some type of logic or database value. In this case, you can prevent rendering (creating the control on the returned web page) altogether. You would want to do this if the control doesn't need to be shown later on the client side because no matter what, the user viewing the page never needs to see it.

Any controls or elements can have their visibility set from the server side. If it is a plain old html element, you just need to set the runat attribute value to server on the markup page.

<div id="myDiv" runat="server"></div>

The decision to render the div or not can now be done in the code behind class like so:

myDiv.Visible = someConditionalBool;

If set to true, it will be rendered on the page and if it's false it won't be rendered at all, not even hidden.

Client Side Hiding

Hiding an element is done on the client side only. Meaning, it's rendered but it has a display CSS style set on it which instructs your browser to not show it to the user. This is beneficial when you want to hide/show things based on user input. It's important to know that the element CAN be hidden on the server side too as long as the element/control has runat=server set just as I explained in the previous example.

Hiding in the Code Behind Class

To hide an element that you want rendered to the page but hidden is another simple single line of code:

myDiv.Style["display"] = "none";

If you have a need to remove the display style server side, it can be done by removing the display style, or setting it to a different value like inline or block (values described here).

myDiv.Style.Remove("display");
// -- or --
myDiv.Style["display"] = "inline";

Hiding on the Client Side with javascript

Using plain old javascript, you can easily hide the same element in this manner

var myDivElem = document.getElementById("myDiv");
myDivElem.style.display = "none";

// then to show again
myDivElem.style.display = "";

jQuery makes hiding elements a little simpler if you prefer to use jQuery:

var myDiv = $("#<%=myDiv.ClientID%>");
myDiv.hide();

// ... and to show 
myDiv.show();

Get connection string from App.config

Also check that you've included the System.Configuration dll under your references. Without it, you won't have access to the ConfigurationManager class in the System.Configuration namespace.

Hive Alter table change Column Name

alter table table_name change old_col_name new_col_name new_col_type;

Here is the example

hive> alter table test change userVisit userVisit2 STRING;      
    OK
    Time taken: 0.26 seconds
    hive> describe test;                                      
    OK
    uservisit2              string                                      
    category                string                                      
    uuid                    string                                      
    Time taken: 0.213 seconds, Fetched: 3 row(s)

Launch Bootstrap Modal on page load

In my case adding jQuery to display the modal didn't work:

$(document).ready(function() {
    $('#myModal').modal('show');
});

Which seemed to be because the modal had attribute aria-hidden="true":

<div class="modal fade" aria-hidden="true" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">

Removing that attribute was needed as well as the jQuery above:

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">

Note that I tried changing the modal classes from modal fade to modal fade in, and that didn't work. Also, changing the classes from modal fade to modal show stopped the modal from being able to be closed.

pip installing in global site-packages instead of virtualenv

It's also worth checking that you didn't modify somehow the path to your virtualenv.

In that case the first line in bin/pip (and the rest of the executables) would have an incorrect path.

You can either edit these files and fix the path or remove and install again the virtualenv.

I want to declare an empty array in java and then I want do update it but the code is not working

You can do some thing like this,

Initialize with empty array and assign the values later

String importRt = "23:43 43:34";
if(null != importRt) {
            importArray = Arrays.stream(importRt.split(" "))
                    .map(String::trim)
                    .toArray(String[]::new);
        }

System.out.println(Arrays.toString(exportImportArray));

Hope it helps..

How can I read a text file from the SD card in Android?

You should have READ_EXTERNAL_STORAGE permission for reading sdcard. Add permission in manifest.xml

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

From android 6.0 or higher, your app must ask user to grant the dangerous permissions at runtime. Please refer this link Permissions overview

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
    }
}

How to round up a number to nearest 10?

My first impulse was to google for "php math" and I discovered that there's a core math library function called "round()" that likely is what you want.

Excel VBA Run-time error '13' Type mismatch

Thank you guys for all your help! Finally I was able to make it work perfectly thanks to a friend and also you! Here is the final code so you can also see how we solve it.

Thanks again!

Option Explicit

Sub k()

Dim x As Integer, i As Integer, a As Integer
Dim name As String
'name = InputBox("Please insert the name of the sheet")
i = 1
name = "Reserva"
Sheets(name).Cells(4, 57) = Sheets(name).Cells(4, 56)

On Error GoTo fim
x = Sheets(name).Cells(4, 56).Value
Application.Calculation = xlCalculationManual
Do While Not IsEmpty(Sheets(name).Cells(i + 4, 56))
    a = 0
    If Sheets(name).Cells(4 + i, 56) <> x Then
        If Sheets(name).Cells(4 + i, 56) <> 0 Then
            If Sheets(name).Cells(4 + i, 56) = 3 Then
                a = x
                Sheets(name).Cells(4 + i, 57) = Sheets(name).Cells(4 + i, 56) - x
                x = Cells(4 + i, 56) - x
            End If
            Sheets(name).Cells(4 + i, 57) = Sheets(name).Cells(4 + i, 56) - a
            x = Sheets(name).Cells(4 + i, 56) - a
        Else
        Cells(4 + i, 57) = ""
        End If
    Else
    Cells(4 + i, 57) = ""
    End If

i = i + 1
Loop
Application.Calculation = xlCalculationAutomatic
Exit Sub
fim:
MsgBox Err.Description
Application.Calculation = xlCalculationAutomatic
End Sub

PostgreSQL "DESCRIBE TABLE"

I worked out the following script for get table schema.

'CREATE TABLE ' || 'yourschema.yourtable' || E'\n(\n' ||
array_to_string(
array_agg(
'    ' || column_expr
)
, E',\n'
) || E'\n);\n'
from
(
SELECT '    ' || column_name || ' ' || data_type || 
coalesce('(' || character_maximum_length || ')', '') || 
case when is_nullable = 'YES' then ' NULL' else ' NOT NULL' end as column_expr
FROM information_schema.columns
WHERE table_schema || '.' || table_name = 'yourschema.yourtable'
ORDER BY ordinal_position
) column_list;

How to set ssh timeout?

Use the -o ConnectTimeout and -o BatchMode=yes -o StrictHostKeyChecking=no .

ConnectTimeout keeps the script from hanging, BatchMode keeps it from hanging with Host unknown, YES to add to known_hosts, and StrictHostKeyChecking adds the fingerprint automatically.

**** NOTE **** The "StrictHostKeyChecking" was only intended for internal networks where you trust you hosts. Depending on the version of the SSH client, the "Are you sure you want to add your fingerprint" can cause the client to hang indefinitely (mainly old versions running on AIX). Most modern versions do not suffer from this issue. If you have to deal with fingerprints with multiple hosts, I recommend maintaining the known_hosts file with some sort of configuration management tool like puppet/ansible/chef/salt/etc.

How do I use disk caching in Picasso?

I had the same problem and used Glide library instead. Cache is out of the box there. https://github.com/bumptech/glide

Why write <script type="text/javascript"> when the mime type is set by the server?

It allows browsers to determine if they can handle the scripting/style language before making a request for the script or stylesheet (or, in the case of embedded script/style, identify which language is being used).

This would be much more important if there had been more competition among languages in browser space, but VBScript never made it beyond IE and PerlScript never made it beyond an IE specific plugin while JSSS was pretty rubbish to begin with.

The draft of HTML5 makes the attribute optional.

Difference between VARCHAR and TEXT in MySQL

There is an important detail that has been omitted in the answer above.

MySQL imposes a limit of 65,535 bytes for the max size of each row. The size of a VARCHAR column is counted towards the maximum row size, while TEXT columns are assumed to be storing their data by reference so they only need 9-12 bytes. That means even if the "theoretical" max size of your VARCHAR field is 65,535 characters you won't be able to achieve that if you have more than one column in your table.

Also note that the actual number of bytes required by a VARCHAR field is dependent on the encoding of the column (and the content). MySQL counts the maximum possible bytes used toward the max row size, so if you use a multibyte encoding like utf8mb4 (which you almost certainly should) it will use up even more of your maximum row size.

Correction: Regardless of how MySQL computes the max row size, whether or not the VARCHAR/TEXT field data is ACTUALLY stored in the row or stored by reference depends on your underlying storage engine. For InnoDB the row format affects this behavior. (Thanks Bill-Karwin)

Reasons to use TEXT:

  • If you want to store a paragraph or more of text
  • If you don't need to index the column
  • If you have reached the row size limit for your table

Reasons to use VARCHAR:

  • If you want to store a few words or a sentence
  • If you want to index the (entire) column
  • If you want to use the column with foreign-key constraints

null terminating a string

Be very careful: NULL is a macro used mainly for pointers. The standard way of terminating a string is:

char *buffer;
...
buffer[end_position] = '\0';

This (below) works also but it is not a big difference between assigning an integer value to a int/short/long array and assigning a character value. This is why the first version is preferred and personally I like it better.

buffer[end_position] = 0; 

Powershell Execute remote exe with command line arguments on remote computer

Are you trying to pass the command line arguments to the program AS you launch it? I am working on something right now that does exactly this, and it was a lot simpler than I thought. If I go into the command line, and type

C:\folder\app.exe/xC:\folder\file.txt

then my application launches, and creates a file in the specified directory with the specified name.

I wanted to do this through a Powershell script on a remote machine, and figured out that all I needed to do was put

$s = New-PSSession -computername NAME -credential LOGIN
    Invoke-Command -session $s -scriptblock {C:\folder\app.exe /xC:\folder\file.txt}
Remove-PSSession $s

(I have a bunch more similar commands inside the session, this is just the minimum it requires to run) notice the space between the executable, and the command line arguments. It works for me, but I am not sure exactly how your application works, or if that is even how you pass arguments to it.

*I can also have my application push the file back to my own local computer by changing the script-block to

C:\folder\app.exe /x"\\LocalPC\DATA (C)\localfolder\localfile.txt"

You need the quotes if your file-path has a space in it.

EDIT: actually, this brought up some silly problems with Powershell launching the application as a service or something, so I did some searching, and figured out that you can call CMD to execute commands for you on the remote computer. This way, the command is carried out EXACTLY as if you had just typed it into a CMD window on the remote machine. Put the command in the scriptblock into double quotes, and then put a cmd.exe /C before it. like this:

cmd.exe /C "C:\folder\app.exe/xC:\folder\file.txt"

this solved all of the problems that I have been having recently.

EDIT EDIT: Had more problems, and found a much better way to do it.

start-process -filepath C:\folder\app.exe -argumentlist "/xC:\folder\file.txt"

and this doesn't hang up your terminal window waiting for the remote process to end. Just make sure you have a way to terminate the process if it doesn't do that on it's own. (mine doesn't, required the coding of another argument)

How do I run a simple bit of code in a new thread?

// following declaration of delegate ,,,
public delegate long GetEnergyUsageDelegate(DateTime lastRunTime, 
                                            DateTime procDateTime);

// following inside of some client method
GetEnergyUsageDelegate nrgDel = GetEnergyUsage;
IAsyncResult aR = nrgDel.BeginInvoke(lastRunTime, procDT, null, null);
while (!aR.IsCompleted) Thread.Sleep(500);
int usageCnt = nrgDel.EndInvoke(aR);

Charles your code(above) is not correct. You do not need to spin wait for completion. EndInvoke will block until the WaitHandle is signaled.

If you want to block until completion you simply need to

nrgDel.EndInvoke(nrgDel.BeginInvoke(lastRuntime,procDT,null,null));

or alternatively

ar.AsyncWaitHandle.WaitOne();

But what is the point of issuing anyc calls if you block? You might as well just use a synchronous call. A better bet would be to not block and pass in a lambda for cleanup:

nrgDel.BeginInvoke(lastRuntime,procDT,(ar)=> {ar.EndInvoke(ar);},null);

One thing to keep in mind is that you must call EndInvoke. A lot of people forget this and end up leaking the WaitHandle as most async implementations release the waithandle in EndInvoke.

Could not load file or assembly 'Microsoft.Web.Infrastructure,

On my machine the Nuget dependency wasn't downloaded correctly, the lib folder inside the nuget package didn't exist, hence the error.

Before

enter image description here

I renamed the Nuget Package in the packages folder and Nuget redownloaded it correctly with the necessary lib folder.

After enter image description here

What's the use of session.flush() in Hibernate

Calling EntityManager#flush does have side-effects. It is conveniently used for entity types with generated ID values (sequence values): such an ID is available only upon synchronization with underlying persistence layer. If this ID is required before the current transaction ends (for logging purposes for instance), flushing the session is required.

Is there an easy way to reload css without reloading the page?

One more jQuery solution

For a single stylesheet with id "css" try this:

$('#css').replaceWith('<link id="css" rel="stylesheet" href="css/main.css?t=' + Date.now() + '"></link>');

Wrap it in a function that has global scrope and you can use it from the Developer Console in Chrome or Firebug in Firefox:

var reloadCSS = function() {
  $('#css').replaceWith('<link id="css" rel="stylesheet" href="css/main.css?t=' + Date.now() + '"></link>');
};

Remove characters from C# string

Comparing various suggestions (as well as comparing in the context of single-character replacements with various sizes and positions of the target).

In this particular case, splitting on the targets and joining on the replacements (in this case, empty string) is the fastest by at least a factor of 3. Ultimately, performance is different depending on the number of replacements, where the replacements are in the source, and the size of the source. #ymmv

Results

(full results here)

| Test                      | Compare | Elapsed                                                            |
|---------------------------|---------|--------------------------------------------------------------------|
| SplitJoin                 | 1.00x   | 29023 ticks elapsed (2.9023 ms) [in 10K reps, 0.00029023 ms per]   |
| Replace                   | 2.77x   | 80295 ticks elapsed (8.0295 ms) [in 10K reps, 0.00080295 ms per]   |
| RegexCompiled             | 5.27x   | 152869 ticks elapsed (15.2869 ms) [in 10K reps, 0.00152869 ms per] |
| LinqSplit                 | 5.43x   | 157580 ticks elapsed (15.758 ms) [in 10K reps, 0.0015758 ms per]   |
| Regex, Uncompiled         | 5.85x   | 169667 ticks elapsed (16.9667 ms) [in 10K reps, 0.00169667 ms per] |
| Regex                     | 6.81x   | 197551 ticks elapsed (19.7551 ms) [in 10K reps, 0.00197551 ms per] |
| RegexCompiled Insensitive | 7.33x   | 212789 ticks elapsed (21.2789 ms) [in 10K reps, 0.00212789 ms per] |
| Regex Insentive           | 7.52x   | 218164 ticks elapsed (21.8164 ms) [in 10K reps, 0.00218164 ms per] |

Test Harness (LinqPad)

(note: the Perf and Vs are timing extensions I wrote)

void test(string title, string sample, string target, string replacement) {
    var targets = target.ToCharArray();

    var tox = "[" + target + "]";
    var x = new Regex(tox);
    var xc = new Regex(tox, RegexOptions.Compiled);
    var xci = new Regex(tox, RegexOptions.Compiled | RegexOptions.IgnoreCase);

    // no, don't dump the results
    var p = new Perf/*<string>*/();
        p.Add(string.Join(" ", title, "Replace"), n => targets.Aggregate(sample, (res, curr) => res.Replace(new string(curr, 1), replacement)));
        p.Add(string.Join(" ", title, "SplitJoin"), n => String.Join(replacement, sample.Split(targets)));
        p.Add(string.Join(" ", title, "LinqSplit"), n => String.Concat(sample.Select(c => targets.Contains(c) ? replacement : new string(c, 1))));
        p.Add(string.Join(" ", title, "Regex"), n => Regex.Replace(sample, tox, replacement));
        p.Add(string.Join(" ", title, "Regex Insentive"), n => Regex.Replace(sample, tox, replacement, RegexOptions.IgnoreCase));
        p.Add(string.Join(" ", title, "Regex, Uncompiled"), n => x.Replace(sample, replacement));
        p.Add(string.Join(" ", title, "RegexCompiled"), n => xc.Replace(sample, replacement));
        p.Add(string.Join(" ", title, "RegexCompiled Insensitive"), n => xci.Replace(sample, replacement));

    var trunc = 40;
    var header = sample.Length > trunc ? sample.Substring(0, trunc) + "..." : sample;

    p.Vs(header);
}

void Main()
{
    // also see https://stackoverflow.com/questions/7411438/remove-characters-from-c-sharp-string

    "Control".Perf(n => { var s = "*"; });


    var text = "My name @is ,Wan.;'; Wan";
    var clean = new[] { '@', ',', '.', ';', '\'' };

    test("stackoverflow", text, string.Concat(clean), string.Empty);


    var target = "o";
    var f = "x";
    var replacement = "1";

    var fillers = new Dictionary<string, string> {
        { "short", new String(f[0], 10) },
        { "med", new String(f[0], 300) },
        { "long", new String(f[0], 1000) },
        { "huge", new String(f[0], 10000) }
    };

    var formats = new Dictionary<string, string> {
        { "start", "{0}{1}{1}" },
        { "middle", "{1}{0}{1}" },
        { "end", "{1}{1}{0}" }
    };

    foreach(var filler in fillers)
    foreach(var format in formats) {
        var title = string.Join("-", filler.Key, format.Key);
        var sample = string.Format(format.Value, target, filler.Value);

        test(title, sample, target, replacement);
    }
}

Getting Database connection in pure JPA setup

I'm using a old version of Hibernate (3.3.0) with a newest version of OpenEJB (4.6.0). My solution was:

EntityManagerImpl entityManager = (EntityManagerImpl)em.getDelegate();
Session session = entityManager.getSession();
Connection connection = session.connection();
Statement statement = null;
try {
    statement = connection.createStatement();
    statement.execute(sql);
    connection.commit();
} catch (SQLException e) {
    throw new RuntimeException(e);
}

I had an error after that:

Commit can not be set while enrolled in a transaction

Because this code above was inside a EJB Controller (you can't commit inside a transaction). I annotated the method with @TransactionAttribute(value = TransactionAttributeType.NOT_SUPPORTED) and the problem was gone.

How to manually trigger click event in ReactJS?

Riffing on Aaron Hakala's answer with useRef inspired by this answer https://stackoverflow.com/a/54316368/3893510

const myRef = useRef(null);

  const clickElement = (ref) => {
    ref.current.dispatchEvent(
      new MouseEvent('click', {
        view: window,
        bubbles: true,
        cancelable: true,
        buttons: 1,
      }),
    );
  };

And your JSX:

<button onClick={() => clickElement(myRef)}>Click<button/>
<input ref={myRef}>

How to force two figures to stay on the same page in LaTeX?

I had this problem while trying to mix figures and text. What worked for me was the 'H' option without the '!' option. \begin{figure}[H]
'H' tries to forces the figure to be exactly where you put it in the code. This requires you include \usepackage{float}

The options are explained here

Google Maps setCenter()

in your code, at line

map.setCenter(new GLatLng(lat, lon), 5);

the setCenter method takes just one parameter, for the lat:long location. Why are you passing two parameters there ?

I suggest you should change it to,

map.setCenter(new GLatLng(lat, lon));

Swift days between two NSDates

Here is my answer for Swift 3:

func daysBetweenDates(startDate: NSDate, endDate: NSDate, inTimeZone timeZone: TimeZone? = nil) -> Int {
    var calendar = Calendar.current
    if let timeZone = timeZone {
        calendar.timeZone = timeZone
    }
    let dateComponents = calendar.dateComponents([.day], from: startDate.startOfDay, to: endDate.startOfDay)
    return dateComponents.day!
}

Convert LocalDateTime to LocalDateTime in UTC

Here's a simple little utility class that you can use to convert local date times from zone to zone, including a utility method directly to convert a local date time from the current zone to UTC (with main method so you can run it and see the results of a simple test):

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;

public final class DateTimeUtil {
    private DateTimeUtil() {
        super();
    }

    public static void main(final String... args) {
        final LocalDateTime now = LocalDateTime.now();
        final LocalDateTime utc = DateTimeUtil.toUtc(now);

        System.out.println("Now: " + now);
        System.out.println("UTC: " + utc);
    }

    public static LocalDateTime toZone(final LocalDateTime time, final ZoneId fromZone, final ZoneId toZone) {
        final ZonedDateTime zonedtime = time.atZone(fromZone);
        final ZonedDateTime converted = zonedtime.withZoneSameInstant(toZone);
        return converted.toLocalDateTime();
    }

    public static LocalDateTime toZone(final LocalDateTime time, final ZoneId toZone) {
        return DateTimeUtil.toZone(time, ZoneId.systemDefault(), toZone);
    }

    public static LocalDateTime toUtc(final LocalDateTime time, final ZoneId fromZone) {
        return DateTimeUtil.toZone(time, fromZone, ZoneOffset.UTC);
    }

    public static LocalDateTime toUtc(final LocalDateTime time) {
        return DateTimeUtil.toUtc(time, ZoneId.systemDefault());
    }
}

Context.startForegroundService() did not then call Service.startForeground()

I have a work around for this problem. I have verified this fix in my own app(300K+ DAU), which can reduce at least 95% of this kind of crash, but still cannot 100% avoid this problem.

This problem happens even when you ensure to call startForeground() just after service started as Google documented. It may be because the service creation and initialization process already cost more than 5 seconds in many scenarios, then no matter when and where you call startForeground() method, this crash is unavoidable.

My solution is to ensure that startForeground() will be executed within 5 seconds after startForegroundService() method, no matter how long your service need to be created and initialized. Here is the detailed solution.

  1. Do not use startForegroundService at the first place, use bindService() with auto_create flag. It will wait for the service initialization. Here is the code, my sample service is MusicService:

    final Context applicationContext = context.getApplicationContext();
    Intent intent = new Intent(context, MusicService.class);
    applicationContext.bindService(intent, new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder binder) {
            if (binder instanceof MusicBinder) {
                MusicBinder musicBinder = (MusicBinder) binder;
                MusicService service = musicBinder.getService();
                if (service != null) {
                    // start a command such as music play or pause.
                    service.startCommand(command);
                    // force the service to run in foreground here.
                    // the service is already initialized when bind and auto_create.
                    service.forceForeground();
                }
            }
            applicationContext.unbindService(this);
        }
    
        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    }, Context.BIND_AUTO_CREATE);
    
  2. Then here is MusicBinder implementation:

    /**
     * Use weak reference to avoid binder service leak.
     */
     public class MusicBinder extends Binder {
    
         private WeakReference<MusicService> weakService;
    
         /**
          * Inject service instance to weak reference.
          */
         public void onBind(MusicService service) {
             this.weakService = new WeakReference<>(service);
         }
    
         public MusicService getService() {
             return weakService == null ? null : weakService.get();
         }
     }
    
  3. The most important part, MusicService implementation, forceForeground() method will ensure that startForeground() method is called just after startForegroundService():

    public class MusicService extends MediaBrowserServiceCompat {
    ...
        private final MusicBinder musicBind = new MusicBinder();
    ...
        @Override
        public IBinder onBind(Intent intent) {
            musicBind.onBind(this);
            return musicBind;
        }
    ...
        public void forceForeground() {
            // API lower than 26 do not need this work around.
            if (Build.VERSION.SDK_INT >= 26) {
                Intent intent = new Intent(this, MusicService.class);
                // service has already been initialized.
                // startForeground method should be called within 5 seconds.
                ContextCompat.startForegroundService(this, intent);
                Notification notification = mNotificationHandler.createNotification(this);
                // call startForeground just after startForegroundService.
                startForeground(Constants.NOTIFICATION_ID, notification);
            }
        }
    }
    
  4. If you want to run the step 1 code snippet in a pending intent, such as if you want to start a foreground service in a widget (a click on widget button) without opening your app, you can wrap the code snippet in a broadcast receiver, and fire a broadcast event instead of start service command.

That is all. Hope it helps. Good luck.

git pull error "The requested URL returned error: 503 while accessing"

A 50X error is an internal server error. There's nothing wrong on your end, but something's up on the server's end.

http://www.checkupdown.com/status/E503.html

The Web server (running the Web site) is currently unable to handle the HTTP request due to a temporary overloading or maintenance of the server. The implication is that this is a temporary condition which will be alleviated after some delay.

Just be patient and wait. :-)

How to extract file name from path?

Here's a simple VBA solution I wrote that works with Windows, Unix, Mac, and URL paths.

sFileName = Mid(Mid(sPath, InStrRev(sPath, "/") + 1), InStrRev(sPath, "\") + 1)

sFolderName = Left(sPath, Len(sPath) - Len(sFileName))

You can test the output using this code:

'Visual Basic for Applications 
http = "https://www.server.com/docs/Letter.txt"
unix = "/home/user/docs/Letter.txt"
dos = "C:\user\docs\Letter.txt"
win = "\\Server01\user\docs\Letter.txt"
blank = ""

sPath = unix 
sFileName = Mid(Mid(sPath, InStrRev(sPath, "/") + 1), InStrRev(sPath, "\") + 1)
sFolderName = Left(sPath, Len(sPath) - Len(sFileName))

Debug.print "Folder: " & sFolderName & " File: " & sFileName

Also see: Wikipedia - Path (computing)

In reactJS, how to copy text to clipboard?

For those people who are trying to select from the DIV instead of the text field, here is the code. The code is self-explanatory but comment here if you want more information:

     import React from 'react';
     ....

    //set ref to your div
          setRef = (ref) => {
            // debugger; //eslint-disable-line
            this.dialogRef = ref;
          };

          createMarkeup = content => ({
            __html: content,
          });

    //following function select and copy data to the clipboard from the selected Div. 
   //Please note that it is only tested in chrome but compatibility for other browsers can be easily done

          copyDataToClipboard = () => {
            try {
              const range = document.createRange();
              const selection = window.getSelection();
              range.selectNodeContents(this.dialogRef);
              selection.removeAllRanges();
              selection.addRange(range);
              document.execCommand('copy');
              this.showNotification('Macro copied successfully.', 'info');
              this.props.closeMacroWindow();
            } catch (err) {
              // console.log(err); //eslint-disable-line
              //alert('Macro copy failed.');
            }
          };

              render() {
                    return (
                        <div
                          id="macroDiv"
                          ref={(el) => {
                            this.dialogRef = el;
                          }}
                          // className={classes.paper}
                          dangerouslySetInnerHTML={this.createMarkeup(this.props.content)}
                        />
                    );
            }

How to make custom error pages work in ASP.NET MVC 4

It seems i came late to the party, but you should better check this out too.

So in system.web for caching up exceptions within the application such as return HttpNotFound()

  <system.web>
    <customErrors mode="RemoteOnly">
      <error statusCode="404" redirect="/page-not-found" />
      <error statusCode="500" redirect="/internal-server-error" />
    </customErrors>
  </system.web>

and in system.webServer for catching up errors that were caught by IIS and did not made their way to the asp.net framework

 <system.webServer>
    <httpErrors errorMode="DetailedLocalOnly">
      <remove statusCode="404"/>
      <error statusCode="404" path="/page-not-found" responseMode="Redirect"/>
      <remove statusCode="500"/>
      <error statusCode="500" path="/internal-server-error" responseMode="Redirect"/>
  </system.webServer>

In the last one if you worry about the client response then change the responseMode="Redirect" to responseMode="File" and serve a static html file, since this one will display a friendly page with an 200 response code.

Could not install packages due to an EnvironmentError: [Errno 13]

For MacOs & Unix

Just by adding sudo to command will work, as it would run it as a superuser.

sudo pip install --upgrade pip

It is advised that you should not directly do it though - please see this post

Counting number of words in a file

I would change your approach a bit. First, I would use a BufferedReader to read the file file in line-by-line using readLine(). Then split each line on whitespace using String.split("\\s") and use the size of the resulting array to see how many words are on that line. To get the number of characters you could either look at the size of each line or of each split word (depending of if you want to count whitespace as characters).

Best practice to look up Java Enum

We do all our enums like this when it comes to Rest/Json etc. It has the advantage that the error is human readable and also gives you the accepted value list. We are using a custom method MyEnum.fromString instead of MyEnum.valueOf, hope it helps.

public enum MyEnum {

    A, B, C, D;

    private static final Map<String, MyEnum> NAME_MAP = Stream.of(values())
            .collect(Collectors.toMap(MyEnum::toString, Function.identity()));

    public static MyEnum fromString(final String name) {
        MyEnum myEnum = NAME_MAP.get(name);
        if (null == myEnum) {
            throw new IllegalArgumentException(String.format("'%s' has no corresponding value. Accepted values: %s", name, Arrays.asList(values())));
        }
        return myEnum;
    }
}

so for example if you call

MyEnum value = MyEnum.fromString("X");

you'll get an IllegalArgumentException with the following message:

'X' has no corresponding value. Accepted values: [A, B, C, D]

you can change the IllegalArgumentException to a custom one.