Programs & Examples On #Openpgp

The OpenPGP standard was originally derived from PGP (Pretty Good Privacy)

How to display gpg key details without importing it?

I seem to be able to get along with simply:

$gpg <path_to_file>

Which outputs like this:

$ gpg /tmp/keys/something.asc 
  pub  1024D/560C6C26 2014-11-26 Something <[email protected]>
  sub  2048g/0C1ACCA6 2014-11-26

The op didn't specify in particular what key info is relevant. This output is all I care about.

Creating an Arraylist of Objects

How to Creating an Arraylist of Objects.

Create an array to store the objects:

ArrayList<MyObject> list = new ArrayList<MyObject>();

In a single step:

list.add(new MyObject (1, 2, 3)); //Create a new object and adding it to list. 

or

MyObject myObject = new MyObject (1, 2, 3); //Create a new object.
list.add(myObject); // Adding it to the list.

convert HTML ( having Javascript ) to PDF using JavaScript

Copy and paste this in your site to provide a link which will convert the page to a PDF page.

<a href="javascript:void(window.open('http://www.htmltopdfconverter.net/?convert='+window.location))">Convert To PDF</a>

When is each sorting algorithm used?

First, a definition, since it's pretty important: A stable sort is one that's guaranteed not to reorder elements with identical keys.

Recommendations:

Quick sort: When you don't need a stable sort and average case performance matters more than worst case performance. A quick sort is O(N log N) on average, O(N^2) in the worst case. A good implementation uses O(log N) auxiliary storage in the form of stack space for recursion.

Merge sort: When you need a stable, O(N log N) sort, this is about your only option. The only downsides to it are that it uses O(N) auxiliary space and has a slightly larger constant than a quick sort. There are some in-place merge sorts, but AFAIK they are all either not stable or worse than O(N log N). Even the O(N log N) in place sorts have so much larger a constant than the plain old merge sort that they're more theoretical curiosities than useful algorithms.

Heap sort: When you don't need a stable sort and you care more about worst case performance than average case performance. It's guaranteed to be O(N log N), and uses O(1) auxiliary space, meaning that you won't unexpectedly run out of heap or stack space on very large inputs.

Introsort: This is a quick sort that switches to a heap sort after a certain recursion depth to get around quick sort's O(N^2) worst case. It's almost always better than a plain old quick sort, since you get the average case of a quick sort, with guaranteed O(N log N) performance. Probably the only reason to use a heap sort instead of this is in severely memory constrained systems where O(log N) stack space is practically significant.

Insertion sort: When N is guaranteed to be small, including as the base case of a quick sort or merge sort. While this is O(N^2), it has a very small constant and is a stable sort.

Bubble sort, selection sort: When you're doing something quick and dirty and for some reason you can't just use the standard library's sorting algorithm. The only advantage these have over insertion sort is being slightly easier to implement.


Non-comparison sorts: Under some fairly limited conditions it's possible to break the O(N log N) barrier and sort in O(N). Here are some cases where that's worth a try:

Counting sort: When you are sorting integers with a limited range.

Radix sort: When log(N) is significantly larger than K, where K is the number of radix digits.

Bucket sort: When you can guarantee that your input is approximately uniformly distributed.

Use of 'const' for function parameters

There is a good discussion on this topic in the old "Guru of the Week" articles on comp.lang.c++.moderated here.

The corresponding GOTW article is available on Herb Sutter's web site here.

Getting new Twitter API consumer and secret keys

From the Twitter FAQ:

Most integrations with the API will require you to identify your application to Twitter by way of an API key. On the Twitter platform, the term "API key" usually refers to what's called an OAuth consumer key. This string identifies your application when making requests to the API. In OAuth 1.0a, your "API keys" probably refer to the combination of this consumer key and the "consumer secret," a string that is used to securely "sign" your requests to Twitter.

passing object by reference in C++

Passing by reference in the above case is just an alias for the actual object.

You'll be referring to the actual object just with a different name.

There are many advantages which references offer compared to pointer references.

How can I remove a trailing newline?

"line 1\nline 2\r\n...".replace('\n', '').replace('\r', '')
>>> 'line 1line 2...'

or you could always get geekier with regexps :)

have fun!

How to keep console window open

To be able to give it input without it closing as well you could enclose the code in a while loop

while (true) 
{
     <INSERT CODE HERE>
}

It will continue to halt at Console.ReadLine();, then do another loop when you input something.

Remove the last line from a file in Bash

awk "NR != `wc -l < text.file`" text.file |> text.file

This snippet does the trick.

Where are static methods and static variables stored in Java?

When we create a static variable or method it is stored in the special area on heap: PermGen(Permanent Generation), where it lays down with all the data applying to classes(non-instance data). Starting from Java 8 the PermGen became - Metaspace. The difference is that Metaspace is auto-growing space, while PermGen has a fixed Max size, and this space is shared among all of the instances. Plus the Metaspace is a part of a Native Memory and not JVM Memory.

You can look into this for more details.

How to select an element by classname using jqLite?

If elem.find() is not working for you, check that you are including JQuery script before angular script....

Load a WPF BitmapImage from a System.Drawing.Bitmap

It took me some time to get the conversion working both ways, so here are the two extension methods I came up with:

using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows.Media.Imaging;

public static class BitmapConversion {

    public static Bitmap ToWinFormsBitmap(this BitmapSource bitmapsource) {
        using (MemoryStream stream = new MemoryStream()) {
            BitmapEncoder enc = new BmpBitmapEncoder();
            enc.Frames.Add(BitmapFrame.Create(bitmapsource));
            enc.Save(stream);

            using (var tempBitmap = new Bitmap(stream)) {
                // According to MSDN, one "must keep the stream open for the lifetime of the Bitmap."
                // So we return a copy of the new bitmap, allowing us to dispose both the bitmap and the stream.
                return new Bitmap(tempBitmap);
            }
        }
    }

    public static BitmapSource ToWpfBitmap(this Bitmap bitmap) {
        using (MemoryStream stream = new MemoryStream()) {
            bitmap.Save(stream, ImageFormat.Bmp);

            stream.Position = 0;
            BitmapImage result = new BitmapImage();
            result.BeginInit();
            // According to MSDN, "The default OnDemand cache option retains access to the stream until the image is needed."
            // Force the bitmap to load right now so we can dispose the stream.
            result.CacheOption = BitmapCacheOption.OnLoad;
            result.StreamSource = stream;
            result.EndInit();
            result.Freeze();
            return result;
        }
    }
}

Using the HTML5 "required" attribute for a group of checkboxes?

I had the same problem and I my solution was this:

HTML:

<form id="processForm.php" action="post">
  <div class="input check_boxes required wish_payment_type">
    <div class="wish_payment_type">
    <span class="checkbox payment-radio">
      <label for="wish_payment_type_1">
        <input class="check_boxes required" id="wish_payment_type_1" name="wish[payment_type][]" type="checkbox" value="1">Foo
      </label>
    </span>
    <span class="checkbox payment-radio">
      <label for="wish_payment_type_2">
        <input class="check_boxes required" id="wish_payment_type_2" name="wish[payment_type][]" type="checkbox" value="2">Bar
      </label>
    </span>
    <span class="checkbox payment-radio">
      <label for="wish_payment_type_3">
        <input class="check_boxes required" id="wish_payment_type_3" name="wish[payment_type][]" type="checkbox" value="3">Buzz
      </label>

      <input id='submit' type="submit" value="Submit">
  </div>
</form>

JS:

var verifyPaymentType = function () {
  var checkboxes = $('.wish_payment_type .checkbox');
  var inputs = checkboxes.find('input');
  var first = inputs.first()[0];

  inputs.on('change', function () {
    this.setCustomValidity('');
  });

  first.setCustomValidity(checkboxes.find('input:checked').length === 0 ? 'Choose one' : '');
}

$('#submit').click(verifyPaymentType);

https://jsfiddle.net/oywLo5z4/

ObservableCollection not noticing when Item in it changes (even with INotifyPropertyChanged)

ObservableCollection will not propagate individual item changes as CollectionChanged events. You will either need to subscribe to each event and forward it manually, or you can check out the BindingList[T] class, which will do this for you.

Unable to compile class for JSP

Try adding this to your web.xml:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/your-servlet-name.xml
    </param-value>

HTML tag <a> want to add both href and onclick working

To achieve this use following html:

<a href="www.mysite.com" onclick="make(event)">Item</a>

<script>
    function make(e) {
        // ...  your function code
        // e.preventDefault();   // use this to NOT go to href site
    }
</script>

Here is working example.

How to add minutes to current time in swift

You can use in swift 4 or 5

    let date = Date()
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd H:mm:ss"
    let current_date_time = dateFormatter.string(from: date)
    print("before add time-->",current_date_time)

    //adding 5 miniuts
    let addminutes = date.addingTimeInterval(5*60)
    dateFormatter.dateFormat = "yyyy-MM-dd H:mm:ss"
    let after_add_time = dateFormatter.string(from: addminutes)
    print("after add time-->",after_add_time)

output:

before add time--> 2020-02-18 10:38:15
after add time--> 2020-02-18 10:43:15

An implementation of the fast Fourier transform (FFT) in C#

Here's another; a C# port of the Ooura FFT. It's reasonably fast. The package also includes overlap/add convolution and some other DSP stuff, under the MIT license.

https://github.com/hughpyle/inguz-DSPUtil/blob/master/Fourier.cs

Get the last 4 characters of a string

Like this:

>>>mystr = "abcdefghijkl"
>>>mystr[-4:]
'ijkl'

This slices the string's last 4 characters. The -4 starts the range from the string's end. A modified expression with [:-4] removes the same 4 characters from the end of the string:

>>>mystr[:-4]
'abcdefgh'

For more information on slicing see this Stack Overflow answer.

How do you synchronise projects to GitHub with Android Studio?

Android Studio 3.0

I love how easy this is in Android Studio.

1. Enter your GitHub login info

In Android Studio go to File > Settings > Version Control > GitHub. Then enter your GitHub username and password. (You only have to do this step once. For future projects you can skip it.)

enter image description here

2. Share your project

With your Android Studio project open, go to VCS > Import into Version Control > Share Project on GitHub.

Then click Share and OK.

enter image description here

That's all!

Trigger event on body load complete js/jquery

You may also use the defer attribute in the script tag. As long as you do not specify async which would of course not be useful for your aim.

Example:

<script src="//other-domain.com/script.js" defer></script>
<script src="myscript.js" defer></script>

As described here:

In the above example, the browser will download both scripts in parallel and execute them just before DOMContentLoaded fires, maintaining their order.

[...] deferred scripts should run after the document had parsed, in the order they were added [...]

Related Stackoverflow discussions: How exactly does <script defer=“defer”> work?

Date to milliseconds and back to date in Swift

//Date to milliseconds
func currentTimeInMiliseconds() -> Int {
    let currentDate = Date()
    let since1970 = currentDate.timeIntervalSince1970
    return Int(since1970 * 1000)
}

//Milliseconds to date
extension Int {
    func dateFromMilliseconds() -> Date {
        return Date(timeIntervalSince1970: TimeInterval(self)/1000)
    }
}

I removed seemingly useless conversion via string and all those random !.

How do I replace part of a string in PHP?

You can try

$string = "this is the test for string." ;
$string = str_replace(' ', '_', $string);
$string = substr($string,0,10);

var_dump($string);

Output

this_is_th

Best C/C++ Network Library

Aggregated List of Libraries

How to run multiple SQL commands in a single SQL connection?

using (var connection = new SqlConnection("Enter Your Connection String"))
    {
        connection.Open();
    
        using (var command = connection.CreateCommand())
        {
            command.CommandText = "Enter the First Command Here";
            command.ExecuteNonQuery();
    
            command.CommandText = "Enter Second Comand Here";
            command.ExecuteNonQuery();

    //Similarly You can Add Multiple
        }
    }

Swift - iOS - Dates and times in different format

Here is a solution that works with Xcode 10.1 (FEB 23 2019) :

func getCurrentDateTime() {

    let now = Date()
    let formatter = DateFormatter()
    formatter.locale = Locale(identifier: "fr_FR")
    formatter.dateFormat = "EEEE dd MMMM YYYY"
    labelDate.text = formatter.string(from: now)
    labelDate.font = UIFont(name: "HelveticaNeue-Bold", size: 12)
    labelDate.textColor = UIColor.lightGray

    let text = formatter.string(from: now)
    labelDate.text = text.uppercased()
}

The "Accueil" Label is not connected to the code.

Change variable name in for loop using R

Another option is using eval and parse, as in

d = 5
for (i in 1:10){
     eval(parse(text = paste('a', 1:10, ' = d + rnorm(3)', sep='')[i]))
}

Is it possible to get all arguments of a function as single object inside that function?

Yes if you have no idea that how many arguments are possible at the time of function declaration then you can declare the function with no parameters and can access all variables by arguments array which are passed at the time of function calling.

How do I raise the same Exception with a custom message in Python?

Either raise the new exception with your error message using

raise Exception('your error message')

or

raise ValueError('your error message')

within the place where you want to raise it OR attach (replace) error message into current exception using 'from' (Python 3.x supported only):

except ValueError as e:
  raise ValueError('your message') from e

How to capitalize the first letter of text in a TextView in an Android Application

For future visitors, you can also (best IMHO) import WordUtil from Apache and add a lot of useful methods to you app, like capitalize as shown here:

How to capitalize the first character of each word in a string

Get only specific attributes with from Laravel Collection

this is a follow up on the patricus [answer][1] above but for nested arrays:

$topLevelFields =  ['id','status'];
$userFields = ['first_name','last_name','email','phone_number','op_city_id'];

return $onlineShoppers->map(function ($user) { 
    return collect($user)->only($topLevelFields)
                             ->merge(collect($user['user'])->only($userFields))->all();  
    })->all();

Solution to "subquery returns more than 1 row" error

You can use in():

select * 
from table
where id in (multiple row query)

or use a join:

select distinct t.* 
from source_of_id_table s
join table t on t.id = s.t_id
where <conditions for source_of_id_table>

The join is never a worse choice for performance, and depending on the exact situation and the database you're using, can give much better performance.

Delete files older than 15 days using PowerShell

just simply (PowerShell V5)

Get-ChildItem "C:\temp" -Recurse -File | Where CreationTime -lt  (Get-Date).AddDays(-15)  | Remove-Item -Force

Java count occurrence of each item in an array

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

public class MultiString {

    public HashMap<String, Integer> countIntem( String[] array ) {

        Arrays.sort(array);
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        Integer count = 0;
        String first = array[0];
        for( int counter = 0; counter < array.length; counter++ ) {
            if(first.hashCode() == array[counter].hashCode()) {
                count = count + 1;
            } else {
                map.put(first, count);
                count = 1;
            }
            first = array[counter];
            map.put(first, count);
        }

        return map;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String[] array = { "name1", "name1", "name2", "name2", "name2",
                "name3", "name1", "name1", "name2", "name2", "name2", "name3" };

        HashMap<String, Integer> countMap = new MultiString().countIntem(array);
        System.out.println(countMap);
    }
}



Gives you O(n) complexity.

Enabling WiFi on Android Emulator

When using an AVD with API level 25 or higher, the emulator provides a simulated Wi-Fi access point ("AndroidWifi"), and Android automatically connects to it.

Source : https://developer.android.com/studio/run/emulator.html#wi-fi

NULL or BLANK fields (ORACLE)

So I just wondered about the same, but had at the same time had a solution to this. I wanted a query that included all rows in the table and counting both blanks and non blanks. So I came up with this.

SELECT COUNT(col_name)                                 VALUE_COUNT
       COUNT(NVL(col_name, 'X') - COUNT(col_name)      NULL_VALUE_COUNT
FROM   table
[CONDITIONS]

Instead of the NVL function you can count the primary key column to obtain the total count of rows

It works like a charm

How to recover corrupted Eclipse workspace?

None of the above worked for me. But what actually worked was deleting all *.snap files from my workspace. This also preserves almost all settings including imported projects. Make sure to back up the workspace before trying it though!!!

What is the most efficient string concatenation method in python?

For a small set of short strings (i.e. 2 or 3 strings of no more than a few characters), plus is still way faster. Using mkoistinen's wonderful script in Python 2 and 3:

plus 2.679107467004 (100.00% as fast)
join 3.653773699996 (73.32% as fast)
form 6.594011374000 (40.63% as fast)
intp 4.568015249999 (58.65% as fast)

So when your code is doing a huge number of separate small concatenations, plus is the preferred way if speed is crucial.

How to write and read java serialized objects into a file

I think you have to write each object to an own File or you have to split the one when reading it. You may also try to serialize your list and retrieve that when deserializing.

How to get the id of the element clicked using jQuery

I wanted to share how you can use this to change a attribute of the button, because it took me some time to figure it out...

For example in order to change it's background to yellow:

$("#"+String(this.id)).css("background-color","yellow");

How do I link to a library with Code::Blocks?

At a guess, you used Code::Blocks to create a Console Application project. Such a project does not link in the GDI stuff, because console applications are generally not intended to do graphics, and TextOut is a graphics function. If you want to use the features of the GDI, you should create a Win32 Gui Project, which will be set up to link in the GDI for you.

Simple way to find if two different lists contain exactly the same elements?

It depends on what concrete List class you are using. The abstract class AbstractCollection has a method called containsAll(Collection) that takes another collection ( a List is a collection) and:

Returns true if this collection contains all of the elements in the specified collection.

So if an ArrayList is being passed in you can call this method to see if they are exactly the same.

       List foo = new ArrayList();
    List bar = new ArrayList();
    String str = "foobar";

    foo.add(str);
    bar.add(str);

    foo.containsAll(bar);

The reason for containsAll() is because it iterates through the first list looking for the match in the second list. So if they are out of order equals() will not pick it up.

EDIT: I just want to make a comment here about the amortized running time of performing the various options being offered. Is running time important? Sure. Is it the only thing you should consider? No.

The cost of copying EVERY single element from your lists into other lists takes time, and it also takes up a good chunk of memory (effectively doubling the memory you are using).

So if memory in your JVM isn't a concern (which it should generally be) then you still need to consider the time it takes to copy every element from two lists into two TreeSets. Remember it is sorting every element as it enters them.

My final advice? You need to consider your data set and how many elements you have in your data set, and also how large each object in your data set is before you can make a good decision here. Play around with them, create one each way and see which one runs faster. It's a good exercise.

How to find and restore a deleted file in a Git repository

I had the same question. Without knowing it, I had created a dangling commit.

List dangling commits

git fsck --lost-found

Inspect each dangling commit

git reset --hard <commit id>

My files reappeared when I moved to the dangling commit.

git status for the reason:

“HEAD detached from <commit id where it detached>”

What is the difference between a string and a byte string?

Note: I will elaborate more my answer for Python 3 since the end of life of Python 2 is very close.

In Python 3

bytes consists of sequences of 8-bit unsigned values, while str consists of sequences of Unicode code points that represent textual characters from human languages.

>>> # bytes
>>> b = b'h\x65llo'
>>> type(b)
<class 'bytes'>
>>> list(b)
[104, 101, 108, 108, 111]
>>> print(b)
b'hello'
>>>
>>> # str
>>> s = 'nai\u0308ve'
>>> type(s)
<class 'str'>
>>> list(s)
['n', 'a', 'i', '¨', 'v', 'e']
>>> print(s)
nai¨ve

Even though bytes and str seem to work the same way, their instances are not compatible with each other, i.e, bytes and str instances can't be used together with operators like > and +. In addition, keep in mind that comparing bytes and str instances for equality, i.e. using ==, will always evaluate to False even when they contain exactly the same characters.

>>> # concatenation
>>> b'hi' + b'bye' # this is possible
b'hibye'
>>> 'hi' + 'bye' # this is also possible
'hibye'
>>> b'hi' + 'bye' # this will fail
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't concat str to bytes
>>> 'hi' + b'bye' # this will also fail
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "bytes") to str
>>>
>>> # comparison
>>> b'red' > b'blue' # this is possible
True
>>> 'red'> 'blue' # this is also possible
True
>>> b'red' > 'blue' # you can't compare bytes with str
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '>' not supported between instances of 'bytes' and 'str'
>>> 'red' > b'blue' # you can't compare str with bytes
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '>' not supported between instances of 'str' and 'bytes'
>>> b'blue' == 'red' # equality between str and bytes always evaluates to False
False
>>> b'blue' == 'blue' # equality between str and bytes always evaluates to False
False

Another issue when dealing with bytes and str is present when working with files that are returned using the open built-in function. On one hand, if you want ot read or write binary data to/from a file, always open the file using a binary mode like 'rb' or 'wb'. On the other hand, if you want to read or write Unicode data to/from a file, be aware of the default encoding of your computer, so if necessary pass the encoding parameter to avoid surprises.

In Python 2

str consists of sequences of 8-bit values, while unicode consists of sequences of Unicode characters. One thing to keep in mind is that str and unicode can be used together with operators if str only consists of 7-bit ASCI characters.

It might be useful to use helper functions to convert between str and unicode in Python 2, and between bytes and str in Python 3.

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

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

Declaring a boolean in JavaScript using just var

How about something like this:

var MyNamespace = {
    convertToBoolean: function (value) {
        //VALIDATE INPUT
        if (typeof value === 'undefined' || value === null) return false;

        //DETERMINE BOOLEAN VALUE FROM STRING
        if (typeof value === 'string') {
            switch (value.toLowerCase()) {
                case 'true':
                case 'yes':
                case '1':
                    return true;
                case 'false':
                case 'no':
                case '0':
                    return false;
            }
        }

        //RETURN DEFAULT HANDLER
        return Boolean(value);
    }
};

Then you can use it like this:

MyNamespace.convertToBoolean('true') //true
MyNamespace.convertToBoolean('no') //false
MyNamespace.convertToBoolean('1') //true
MyNamespace.convertToBoolean(0) //false

I have not tested it for performance, but converting from type to type should not happen too often otherwise you open your app up to instability big time!

Difference between partition key, composite key and clustering key in Cassandra?

Worth to note, you will probably use those lots more than in similar concepts in relational world (composite keys).

Example - suppose you have to find last N users who recently joined user group X. How would you do this efficiently given reads are predominant in this case? Like that (from offical Cassandra guide):

CREATE TABLE group_join_dates (
    groupname text,
    joined timeuuid,
    join_date text,
    username text,
    email text,
    age int,
    PRIMARY KEY ((groupname, join_date), joined)
) WITH CLUSTERING ORDER BY (joined DESC)

Here, partitioning key is compound itself and the clustering key is a joined date. The reason why a clustering key is a join date is that results are already sorted (and stored, which makes lookups fast). But why do we use a compound key for partitioning key? Because we always want to read as few partitions as possible. How putting join_date in there helps? Now users from the same group and the same join date will reside in a single partition! This means we will always read as few partitions as possible (first start with the newest, then move to older and so on, rather than jumping between them).

In fact, in extreme cases you would also need to use the hash of a join_date rather than a join_date alone - so that if you query for last 3 days often those share the same hash and therefore are available from same partition!

How to create virtual column using MySQL SELECT?

You can add virtual columns as

SELECT '1' as temp

But if you tries to put where condition to additionally generated column, it wont work and will show an error message as the column doesn't exist.

We can solve this issue by returning sql result as a table.ie,

SELECT tb.* from (SELECT 1 as temp) as tb WHERE tb.temp = 1

How to export a Hive table into a CSV file?

If you're using Hive 11 or better you can use the INSERT statement with the LOCAL keyword.

Example:

insert overwrite local directory '/home/carter/staging' row format delimited fields terminated by ',' select * from hugetable;

Note that this may create multiple files and you may want to concatenate them on the client side after it's done exporting.

Using this approach means you don't need to worry about the format of the source tables, can export based on arbitrary SQL query, and can select your own delimiters and output formats.

How to insert a new key value pair in array in php?

Try this:

foreach($array as $k => $obj) { 
    $obj->{'newKey'} = "value"; 
}

Loop through childNodes

If you do a lot of this sort of thing then it might be worth defining the function for yourself.

if (typeof NodeList.prototype.forEach == "undefined"){
    NodeList.prototype.forEach = function (cb){
        for (var i=0; i < this.length; i++) {
            var node = this[i];
            cb( node, i );
        }
    };
}

Chrome Fullscreen API

The API only works during user interaction, so it cannot be used maliciously. Try the following code:

addEventListener("click", function() {
    var el = document.documentElement,
      rfs = el.requestFullscreen
        || el.webkitRequestFullScreen
        || el.mozRequestFullScreen
        || el.msRequestFullscreen 
    ;

    rfs.call(el);
});

How to detect orientation change?

With iOS 13.1.2, orientation always return 0 until device is rotated. I need to call UIDevice.current.beginGeneratingDeviceOrientationNotifications() before any rotation event occurs to get actual rotation.

How to reset sequence in postgres and fill id column with new data?

Reset the sequence:

SELECT setval('sequence_name', 0);

Updating current records:

UPDATE foo SET id = DEFAULT;

How do you test that a Python function throws an exception?

For await/async aiounittest there is a slightly different pattern:

https://aiounittest.readthedocs.io/en/latest/asynctestcase.html#aiounittest.AsyncTestCase

async def test_await_async_fail(self):
    with self.assertRaises(Exception) as e:
        await async_one()

multi line comment vb.net in Visual studio 2010

Create a new toolbar and add the commands

  • Edit.SelectionComment
  • Edit.SelectionUncomment

Select your custom tookbar to show it.

You will then see the icons as mention by moriartyn

How can I beautify JSON programmatically?

Programmatic formatting solution:

The JSON.stringify method supported by many modern browsers (including IE8) can output a beautified JSON string:

JSON.stringify(jsObj, null, "\t"); // stringify with tabs inserted at each level
JSON.stringify(jsObj, null, 4);    // stringify with 4 spaces at each level
Demo: http://jsfiddle.net/AndyE/HZPVL/

This method is also included with json2.js, for supporting older browsers.

Manual formatting solution

If you don't need to do it programmatically, Try JSON Lint. Not only will it prettify your JSON, it will validate it at the same time.

Boolean vs boolean in Java

You can use Boolean / boolean. Simplicity is the way to go. If you do not need specific api (Collections, Streams, etc.) and you are not foreseeing that you will need them - use primitive version of it (boolean).

  1. With primitives you guarantee that you will not pass null values.
    You will not fall in traps like this. The code below throws NullPointerException (from: Booleans, conditional operators and autoboxing):

    public static void main(String[] args) throws Exception { Boolean b = true ? returnsNull() : false; // NPE on this line. System.out.println(b); } public static Boolean returnsNull() { return null; }

  2. Use Boolean when you need an object, eg:

    • Stream of Booleans,
    • Optional
    • Collections of Booleans

Send form data using ajax

The code you've posted has two problems:

First: <input type="buttom" should be <input type="button".... This probably is just a typo but without button your input will be treated as type="text" as the default input type is text.

Second: In your function f() definition, you are using the form parameter thinking it's already a jQuery object by using form.attr("action"). Then similarly in the $.post method call, you're passing fname and lname which are HTMLInputElements. I believe what you want is form's action url and input element's values.

Try with the following changes:

HTML

<form action="/echo/json/" method="post">
    <input type="text" name="lname" />
    <input type="text" name="fname" />

    <!-- change "buttom" to "button" -->
    <input type="button" name="send" onclick="return f(this.form ,this.form.fname ,this.form.lname) " />
</form>

JavaScript

function f(form, fname, lname) {
    att = form.action; // Use form.action
    $.post(att, {
        fname: fname.value, // Use fname.value
        lname: lname.value // Use lname.value
    }).done(function (data) {
        alert(data);
    });
    return true;
}

Here is the fiddle.

How to send data to COM PORT using JAVA?

An alternative to javax.comm is the rxtx library which supports more platforms than javax.comm.

Class Not Found Exception when running JUnit test

NoClassDefFoundError really means it can't initilize the class. It has nothing to do with finding the class. I got this error when calling trim() on a null String.

JUnit won't show NullPointerException. The string isn't null when running normally because I'm fetching the string from a properties file which is not availible for tests.

My advice is to remove pieces from the class until your tests start passing. Then you can determine which line is giving the error.

How can I run dos2unix on an entire directory?

A common use case appears to be to standardize line endings for all files committed to a Git repository:

git ls-files | xargs dos2unix

Keep in mind that certain files (e.g. *.sln, *.bat) etc are only used on Windows operating systems and should keep the CRLF ending:

git ls-files '*.sln' '*.bat' | xargs unix2dos

If necessary, use .gitattributes

How to pass props to {this.props.children}

Render props is most accurate approach to this problem. Instead of passing the child component to parent component as children props, let parent render child component manually. Render is built-in props in react, which takes function parameter. In this function you can let parent component render whatever you want with custom parameters. Basically it does the same thing as child props but it is more customizable.

class Child extends React.Component {
  render() {
    return <div className="Child">
      Child
      <p onClick={this.props.doSomething}>Click me</p>
           {this.props.a}
    </div>;
  }
}

class Parent extends React.Component {
  doSomething(){
   alert("Parent talks"); 
  }

  render() {
    return <div className="Parent">
      Parent
      {this.props.render({
        anythingToPassChildren:1, 
        doSomething: this.doSomething})}
    </div>;
  }
}

class Application extends React.Component {
  render() {
    return <div>
      <Parent render={
          props => <Child {...props} />
        }/>
    </div>;
  }
}

Example at codepen

Conflict with dependency 'com.android.support:support-annotations'. Resolved versions for app (23.1.0) and test app (23.0.1) differ

I was getting the same error today:

Error:Execution failed for task ':app:preDebugAndroidTestBuild'.> Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ.

What I did:

  • I simply updated all my dependencies to 27.1.1 instead of 26.1.0
  • Also, updated my compileSdkVersion 27 and targetSdkVersion 27 which were 26 earlier

And com.android.support:support-annotations error was gone!

For Ref:

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.0'
    implementation 'com.android.support:design:27.1.1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

How to change current working directory using a batch file

A simpler syntax might be

pushd %root%

How to minify php page html output?

All of the preg_replace() solutions above have issues of single line comments, conditional comments and other pitfalls. I'd recommend taking advantage of the well-tested Minify project rather than creating your own regex from scratch.

In my case I place the following code at the top of a PHP page to minify it:

function sanitize_output($buffer) {
    require_once('min/lib/Minify/HTML.php');
    require_once('min/lib/Minify/CSS.php');
    require_once('min/lib/JSMin.php');
    $buffer = Minify_HTML::minify($buffer, array(
        'cssMinifier' => array('Minify_CSS', 'minify'),
        'jsMinifier' => array('JSMin', 'minify')
    ));
    return $buffer;
}
ob_start('sanitize_output');

MVC Redirect to View from jQuery with parameters

This would also work I believe:

$('#results').on('click', '.item', function () {
            var NestId = $(this).data('id');
            var url = '@Html.Raw(Url.Action("Artists", new { NestId = @NestId }))';
            window.location.href = url; 
        })

Errors in pom.xml with dependencies (Missing artifact...)

It seemed that a lot of dependencies were incorrect.

enter image description here

Download the whole POM here

A good place to look for the correct dependencies is the Maven Repository website.

Tower of Hanoi: Recursive Algorithm

I am trying to get recursion too.

I found a way i think,

i think of it like a chain of steps(the step isnt constant it may change depending on the previous node)

I have to figure out 2 things:

  1. previous node
  2. step kind
  3. after the step what else before call(this is the argument for the next call

example

factorial

1,2,6,24,120 ......... or

1,2*(1),3*(2*1),4*(3*2*1,5*(4*3*2*1)

step=multiple by last node

after the step what i need to get to the next node,abstract 1

ok

function =

n*f(n-1) 

its 2 steps process
from a-->to step--->b

i hoped this help,just think about 2 thniks,not how to get from node to node,but node-->step-->node

node-->step is the body of the function step-->node is the arguments of the other function

bye:) hope i helped

COLLATION 'utf8_general_ci' is not valid for CHARACTER SET 'latin1'

Firstly run this query

SHOW VARIABLES LIKE '%char%';

You have character_set_server='latin1'

If so,go into your config file,my.cnf and add or uncomment these lines:

character-set-server = utf8
collation-server = utf8_unicode_ci

Restart the server. Yes late to the party,just encountered the same issue.

Can scripts be inserted with innerHTML?

For anyone still trying to do this, no, you can't inject a script using innerHTML, but it is possible to load a string into a script tag using a Blob and URL.createObjectURL.

I've created an example that lets you run a string as a script and get the 'exports' of the script returned through a promise:

function loadScript(scriptContent, moduleId) {
    // create the script tag
    var scriptElement = document.createElement('SCRIPT');

    // create a promise which will resolve to the script's 'exports'
    // (i.e., the value returned by the script)
    var promise = new Promise(function(resolve) {
        scriptElement.onload = function() {
            var exports = window["__loadScript_exports_" + moduleId];
            delete window["__loadScript_exports_" + moduleId];
            resolve(exports);
        }
    });

    // wrap the script contents to expose exports through a special property
    // the promise will access the exports this way
    var wrappedScriptContent =
        "(function() { window['__loadScript_exports_" + moduleId + "'] = " + 
        scriptContent + "})()";

    // create a blob from the wrapped script content
    var scriptBlob = new Blob([wrappedScriptContent], {type: 'text/javascript'});

    // set the id attribute
    scriptElement.id = "__loadScript_module_" + moduleId;

    // set the src attribute to the blob's object url 
    // (this is the part that makes it work)
    scriptElement.src = URL.createObjectURL(scriptBlob);

    // append the script element
    document.body.appendChild(scriptElement);

    // return the promise, which will resolve to the script's exports
    return promise;
}

...

function doTheThing() {
    // no evals
    loadScript('5 + 5').then(function(exports) {
         // should log 10
        console.log(exports)
    });
}

I've simplified this from my actual implementation, so no promises that there aren't any bugs in it. But the principle works.

If you don't care about getting any value back after the script runs, it's even easier; just leave out the Promise and onload bits. You don't even need to wrap the script or create the global window.__load_script_exports_ property.

Array.push() and unique items

Yep, it's a small mistake.

if(this.items.indexOf(item) === -1) {
    this.items.push(item);
    console.log(this.items);
}

How to save and load numpy.array() data properly?

np.fromfile() has a sep= keyword argument:

Separator between items if file is a text file. Empty (“”) separator means the file should be treated as binary. Spaces (” ”) in the separator match zero or more whitespace characters. A separator consisting only of spaces must match at least one whitespace.

The default value of sep="" means that np.fromfile() tries to read it as a binary file rather than a space-separated text file, so you get nonsense values back. If you use np.fromfile('markers.txt', sep=" ") you will get the result you are looking for.

However, as others have pointed out, np.loadtxt() is the preferred way to convert text files to numpy arrays, and unless the file needs to be human-readable it is usually better to use binary formats instead (e.g. np.load()/np.save()).

How to get the first five character of a String

The problem with .Substring(,) is, that you need to be sure that the given string has at least the length of the asked number of characters, otherwise an ArgumentOutOfRangeException will be thrown.

Solution 1 (using 'Substring'):

var firstFive = stringValue != null ? 
                   stringValue.Substring(0, stringValue.Length >= 5 ? 5 : stringValue.Length) :
                   null;

The drawback of using .Substring( is that you'll need to check the length of the given string.

Solution 2 (using 'Take'):

var firstFive = stringValue != null ? 
                    string.Join("", stringValue.Take(5)) : 
                    null;

Using 'Take' will prevent that you need to check the length of the given string.

Change input value onclick button - pure javascript or jQuery

And here is the non jQuery answer.

Fiddle: http://jsfiddle.net/J7m7m/7/

function changeText(value) {
     document.getElementById('count').value = 500 * value;   
}

HTML slight modification:

Product price: $500
<br>
Total price: $500
<br>
<input type="button" onclick="changeText(2)" value="2&#x00A;Qty">
<input type="button" class="mnozstvi_sleva" value="4&#x00A;Qty" onClick="changeText(4)">
<br>
Total <input type="text" id="count" value="1"/>

EDIT: It is very clear that this is a non-desired way as pointed out below (I had it coming). So in essence, this is how you would do it in plain old javascript. Most people would suggest you to use jQuery (other answer has the jQuery version) for good reason.

How to put individual tags for a scatter plot

Perhaps use plt.annotate:

import numpy as np
import matplotlib.pyplot as plt

N = 10
data = np.random.random((N, 4))
labels = ['point{0}'.format(i) for i in range(N)]

plt.subplots_adjust(bottom = 0.1)
plt.scatter(
    data[:, 0], data[:, 1], marker='o', c=data[:, 2], s=data[:, 3] * 1500,
    cmap=plt.get_cmap('Spectral'))

for label, x, y in zip(labels, data[:, 0], data[:, 1]):
    plt.annotate(
        label,
        xy=(x, y), xytext=(-20, 20),
        textcoords='offset points', ha='right', va='bottom',
        bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
        arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))

plt.show()

enter image description here

How to find the extension of a file in C#?

private string GetExtension(string attachment_name)
{
    var index_point = attachment_name.IndexOf(".") + 1;
    return attachment_name.Substring(index_point);
}

How to get text from EditText?

Place the following after the setContentView() method.

final EditText edit =  (EditText) findViewById(R.id.Your_Edit_ID);
String emailString = (String) edit.getText().toString();
Log.d("email",emailString);

Rounding numbers to 2 digits after comma

This worked for me:

var new_number = float.toFixed(2);

Example:

var my_float = 0.6666

my_float.toFixed(3) # => 0.667

Save ArrayList to SharedPreferences

You can use serialization or Gson library to convert list to string and vice versa and then save string in preferences.

Using google's Gson library:

//Converting list to string
new Gson().toJson(list);

//Converting string to list
new Gson().fromJson(listString, CustomObjectsList.class);

Using Java serialization:

//Converting list to string
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(list);
oos.flush();
String string = Base64.encodeToString(bos.toByteArray(), Base64.DEFAULT);
oos.close();
bos.close();
return string;

//Converting string to list
byte[] bytesArray = Base64.decode(familiarVisitsString, Base64.DEFAULT);
ByteArrayInputStream bis = new ByteArrayInputStream(bytesArray);
ObjectInputStream ois = new ObjectInputStream(bis);
Object clone = ois.readObject();
ois.close();
bis.close();
return (CustomObjectsList) clone;

JsonMappingException: No suitable constructor found for type [simple type, class ]: can not instantiate from JSON object

You must realize what options Jackson has available for deserialization. In Java, method argument names are not present in the compiled code. That's why Jackson can't generally use constructors to create a well-defined object with everything already set.

So, if there is an empty constructor and there are also setters, it uses the empty constructor and setters. If there are no setters, some dark magic (reflections) is used to do it.

If you want to use a constructor with Jackson, you must use the annotations as mentioned by @PiersyP in his answer. You can also use a builder pattern. If you encounter some exceptions, good luck. Error handling in Jackson sucks big time, it's hard to understand that gibberish in error messages.

Disable pasting text into HTML form

How about sending a confirmation email to the email address that the user has just entered twice in which there is a link to a confirmation URL on your site, then you know that they have got the message?

Anyone that doesn't click to confirm the receipt of the email may have entered their email address incorrectly.

Not a perfect solution, but just some ideas.

how to automatically scroll down a html page?

You can use two different techniques to achieve this.

The first one is with javascript: set the scrollTop property of the scrollable element (e.g. document.body.scrollTop = 1000;).

The second is setting the link to point to a specific id in the page e.g.

<a href="mypage.html#sectionOne">section one</a>

Then if in your target page you'll have that ID the page will be scrolled automatically.

Angular4 - No value accessor for form control

You should use formControlName="surveyType" on an input and not on a div

What is unexpected T_VARIABLE in PHP?

It could be some other line as well. PHP is not always that exact.

Probably you are just missing a semicolon on previous line.

How to reproduce this error, put this in a file called a.php:

<?php
  $a = 5
  $b = 7;        // Error happens here.
  print $b;
?>

Run it:

eric@dev ~ $ php a.php

PHP Parse error:  syntax error, unexpected T_VARIABLE in
/home/el/code/a.php on line 3

Explanation:

The PHP parser converts your program to a series of tokens. A T_VARIABLE is a Token of type VARIABLE. When the parser processes tokens, it tries to make sense of them, and throws errors if it receives a variable where none is allowed.

In the simple case above with variable $b, the parser tried to process this:

$a = 5 $b = 7;

The PHP parser looks at the $b after the 5 and says "that is unexpected".

How to get input text value on click in ReactJS

First of all, you can't pass to alert second argument, use concatenation instead

alert("Input is " + inputValue);

Example

However in order to get values from input better to use states like this

_x000D_
_x000D_
var MyComponent = React.createClass({_x000D_
  getInitialState: function () {_x000D_
    return { input: '' };_x000D_
  },_x000D_
_x000D_
  handleChange: function(e) {_x000D_
    this.setState({ input: e.target.value });_x000D_
  },_x000D_
_x000D_
  handleClick: function() {_x000D_
    console.log(this.state.input);_x000D_
  },_x000D_
_x000D_
  render: function() {_x000D_
    return (_x000D_
      <div>_x000D_
        <input type="text" onChange={ this.handleChange } />_x000D_
        <input_x000D_
          type="button"_x000D_
          value="Alert the text input"_x000D_
          onClick={this.handleClick}_x000D_
        />_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
});_x000D_
_x000D_
ReactDOM.render(_x000D_
  <MyComponent />,_x000D_
  document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"></div>
_x000D_
_x000D_
_x000D_

Add a new item to recyclerview programmatically?

First add your item to mItems and then use:

mAdapter.notifyItemInserted(mItems.size() - 1);

this method is better than using:

mAdapter.notifyDataSetChanged();

in performance.

Why does the 260 character path length limit exist in Windows?

Quoting this article https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#maximum-path-length-limitation

Maximum Path Length Limitation

In the Windows API (with some exceptions discussed in the following paragraphs), the maximum length for a path is MAX_PATH, which is defined as 260 characters. A local path is structured in the following order: drive letter, colon, backslash, name components separated by backslashes, and a terminating null character. For example, the maximum path on drive D is "D:\some 256-character path string<NUL>" where "<NUL>" represents the invisible terminating null character for the current system codepage. (The characters < > are used here for visual clarity and cannot be part of a valid path string.)

Now we see that it is 1+2+256+1 or [drive][:\][path][null] = 260. One could assume that 256 is a reasonable fixed string length from the DOS days. And going back to the DOS APIs we realize that the system tracked the current path per drive, and we have 26 (32 with symbols) maximum drives (and current directories).

The INT 0x21 AH=0x47 says “This function returns the path description without the drive letter and the initial backslash.” So we see that the system stores the CWD as a pair (drive, path) and you ask for the path by specifying the drive (1=A, 2=B, …), if you specify a 0 then it assumes the path for the drive returned by INT 0x21 AH=0x15 AL=0x19. So now we know why it is 260 and not 256, because those 4 bytes are not stored in the path string.

Why a 256 byte path string, because 640K is enough RAM.

PowerShell: Comparing dates

As Get-Date returns a DateTime object you are able to compare them directly. An example:

(get-date 2010-01-02) -lt (get-date 2010-01-01)

will return false.

How do I convert a Python 3 byte-string variable into a regular string?

Call decode() on a bytes instance to get the text which it encodes.

str = bytes.decode()

How to solve COM Exception Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))?

My solution was to change the "Enable 32-Bit Applications" to True in the advanced settings of the relative app pool in IIS.

App Pool

Enable 32 bits applications

Is it possible to use global variables in Rust?

I am new to Rust, but this solution seems to work:

#[macro_use]
extern crate lazy_static;

use std::sync::{Arc, Mutex};

lazy_static! {
    static ref GLOBAL: Arc<Mutex<GlobalType> =
        Arc::new(Mutex::new(GlobalType::new()));
}

Another solution is to declare a crossbeam channel tx/rx pair as an immutable global variable. The channel should be bounded and can only hold 1 element. When you initialize the global variable, push the global instance into the channel. When using the global variable, pop the channel to acquire it and push it back when done using it.

Both solutions should provide a safe approach to using global variables.

org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException:

You are trying to read xls with explicit implementation poi classes for xlsx.

G:\Selenium Jar Files\TestData\Data.xls

Either use HSSFWorkbook and HSSFSheet classes or make your implementation more generic by using shared interfaces, like;

Change:

XSSFWorkbook workbook = new XSSFWorkbook(file);

To:

 org.apache.poi.ss.usermodel.Workbook workbook = WorkbookFactory.create(file);

And Change:

XSSFSheet sheet = workbook.getSheetAt(0);

To:

org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0);

JQuery Parsing JSON array

var dataArray = [];
var obj = jQuery.parseJSON(response);
  for( key in obj ) 
  dataArray.push([key.toString(), obj [key]]);
};

jQuery, get html of a whole element

You can clone it to get the entire contents, like this:

var html = $("<div />").append($("#div1").clone()).html();

Or make it a plugin, most tend to call this "outerHTML", like this:

jQuery.fn.outerHTML = function() {
  return jQuery('<div />').append(this.eq(0).clone()).html();
};

Then you can just call:

var html = $("#div1").outerHTML();

Running Selenium WebDriver python bindings in chrome

You need to make sure the standalone ChromeDriver binary (which is different than the Chrome browser binary) is either in your path or available in the webdriver.chrome.driver environment variable.

see http://code.google.com/p/selenium/wiki/ChromeDriver for full information on how wire things up.

Edit:

Right, seems to be a bug in the Python bindings wrt reading the chromedriver binary from the path or the environment variable. Seems if chromedriver is not in your path you have to pass it in as an argument to the constructor.

import os
from selenium import webdriver

chromedriver = "/Users/adam/Downloads/chromedriver"
os.environ["webdriver.chrome.driver"] = chromedriver
driver = webdriver.Chrome(chromedriver)
driver.get("http://stackoverflow.com")
driver.quit()

Find files in created between a date range

If you use GNU find, since version 4.3.3 you can do:

find -newerct "1 Aug 2013" ! -newerct "1 Sep 2013" -ls

It will accept any date string accepted by GNU date -d.

You can change the c in -newerct to any of a, B, c, or m for looking at atime/birth/ctime/mtime.

Another example - list files modified between 17:30 and 22:00 on Nov 6 2017:

find -newermt "2017-11-06 17:30:00" ! -newermt "2017-11-06 22:00:00" -ls

Full details from man find:

   -newerXY reference
          Compares the timestamp of the current file with reference.  The reference argument is normally the name of a file (and one of its timestamps  is  used
          for  the  comparison)  but  it may also be a string describing an absolute time.  X and Y are placeholders for other letters, and these letters select
          which time belonging to how reference is used for the comparison.

          a   The access time of the file reference
          B   The birth time of the file reference
          c   The inode status change time of reference
          m   The modification time of the file reference
          t   reference is interpreted directly as a time

          Some combinations are invalid; for example, it is invalid for X to be t.  Some combinations are not implemented on all systems; for example B  is  not
          supported on all systems.  If an invalid or unsupported combination of XY is specified, a fatal error results.  Time specifications are interpreted as
          for the argument to the -d option of GNU date.  If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal
          error  message  results.   If  you  specify a test which refers to the birth time of files being examined, this test will fail for any files where the
          birth time is unknown.

AngularJS event on window innerWidth size change

I found a jfiddle that might help here: http://jsfiddle.net/jaredwilli/SfJ8c/

Ive refactored the code to make it simpler for this.

// In your controller
var w = angular.element($window);
$scope.$watch(
  function () {
    return $window.innerWidth;
  },
  function (value) {
    $scope.windowWidth = value;
  },
  true
);

w.bind('resize', function(){
  $scope.$apply();
});

You can then reference to windowWidth from the html

<span ng-bind="windowWidth"></span>

Explanation of <script type = "text/template"> ... </script>

jQuery Templates is an example of something that uses this method to store HTML that will not be rendered directly (that’s the whole point) inside other HTML: http://api.jquery.com/jQuery.template/

What is the usefulness of PUT and DELETE HTTP request methods?

Safe Methods : Get Resource/No modification in resource
Idempotent : No change in resource status if requested many times
Unsafe Methods : Create or Update Resource/Modification in resource
Non-Idempotent : Change in resource status if requested many times

According to your requirement :

1) For safe and idempotent operation (Fetch Resource) use --------- GET METHOD
2) For unsafe and non-idempotent operation (Insert Resource) use--------- POST METHOD
3) For unsafe and idempotent operation (Update Resource) use--------- PUT METHOD
3) For unsafe and idempotent operation (Delete Resource) use--------- DELETE METHOD

How do I register a DLL file on Windows 7 64-bit?

There is a difference in Windows 7. Logging on as Administrator does not give the same rights as when running a program as Administrator.

Go to Start - All Programs - Accesories. Right click on the Command window and select "Run as administrator" Now register the dll normally via : regsrvr32 xxx.dll

Select every Nth element in CSS

Try this

div:nth-child(4n+4)

What are the differences between C, C# and C++ in terms of real-world applications?

Both C and C++ give you a lower level of abstraction that, with increased complexity, provides a breadth of access to underlying machine functionality that are not necessarily exposed with other languages. Compared to C, C++ adds the convenience of a fully object oriented language(reduced development time) which can, potentially, add an additional performance cost. In terms of real world applications, I see these languages applied in the following domains:

C

  • Kernel level software.
  • Hardware device drivers
  • Applications where access to old, stable code is required.

C,C++

  • Application or Server development where memory management needs to be fine tuned (and can't be left to generic garbage collection solutions).
  • Development environments that require access to libraries that do not interface well with more modern managed languages.
  • Although managed C++ can be used to access the .NET framework, it is not a seamless transition.

C# provides a managed memory model that adds a higher level of abstraction again. This level of abstraction adds convenience and improves development times, but complicates access to lower level APIs and makes specialized performance requirements problematic.

It is certainly possible to implement extremely high performance software in a managed memory environment, but awareness of the implications is essential.

The syntax of C# is certainly less demanding (and error prone) than C/C++ and has, for the initiated programmer, a shallower learning curve.

C#

  • Rapid client application development.
  • High performance Server development (StackOverflow for example) that benefits from the .NET framework.
  • Applications that require the benefits of the .NET framework in the language it was designed for.

Johannes Rössel makes the valid point that the use C# Pointers, Unsafe and Unchecked keywords break through the layer of abstraction upon which C# is built. I would emphasize that type of programming is the exception to most C# development scenarios and not a fundamental part of the language (as is the case with C/C++).

Intermediate language used in scalac?

maybe this will help you out:

http://lampwww.epfl.ch/~paltherr/phd/altherr-phd.pdf

or this page:

www.scala-lang.org/node/6372‎

How to call function on child component on parent events

Calling child component in parent

<component :is="my_component" ref="my_comp"></component>
<v-btn @click="$refs.my_comp.alertme"></v-btn>

in Child component

mycomp.vue

    methods:{     
    alertme(){
            alert("alert")
            }
    }

How to duplicate a git repository? (without forking)

I have noticed some of the other answers here use a bare clone and then mirror push to the new repository, however this does not work for me and when I open the new repository after that, the files look mixed up and not as I expect.

Here is a solution that definitely works for copying the files, although it does not preserve the original repository's revision history.

  1. git clone the repository onto your local machine.
  2. cd into the project directory and then run rm -rf .git to remove all the old git metadata including commit history, etc.
  3. Initialize a fresh git repository by running git init.
  4. Run git add . ; git commit -am "Initial commit" - Of course you can call this commit what you want.
  5. Set the origin to your new repository git remote add origin https://github.com/user/repo-name (replace the url with the url to your new repository)
  6. Push it to your new repository with git push origin master.

The pipe ' ' could not be found angular2 custom pipe

You need to include your pipe in module declaration:

declarations: [ UsersPipe ],
providers: [UsersPipe]

How to change default Anaconda python environment

Change permanent

conda install python={version}

Change Temporarily

View your environments

run conda info --envs on your terminal window or an Anconda Prompt

If It doesn't show environment that you want to install

run conda create -n py36 python=3.6 anaconda for python 3.6 change version as your prefer

Activating an environment (use Anaconda prompt)

run activate envnme envnme you can find by this commandconda info --envs as a example when you run conda info --envs it show

base * C:\Users\DulangaHeshan\Anaconda3 py36 C:\Users\DulangaHeshan\Anaconda3\envs\py36

then run activate py36

to check run python --version

In Windows, it is good practice to deactivate one environment before activating another. https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html?highlight=deactivate%20environment

Set markers for individual points on a line in Matplotlib

For future reference - the Line2D artist returned by plot() also has a set_markevery() method which allows you to only set markers on certain points - see https://matplotlib.org/api/_as_gen/matplotlib.lines.Line2D.html#matplotlib.lines.Line2D.set_markevery

Access cell value of datatable

foreach(DataRow row in dt.Rows)
{
    string value = row[3].ToString();
}

Convert byte[] to char[]

You must know the source encoding.

string someText = "The quick brown fox jumps over the lazy dog.";
byte[] bytes = Encoding.Unicode.GetBytes(someText);
char[] chars = Encoding.Unicode.GetChars(bytes);

How to avoid the "divide by zero" error in SQL?

Use NULLIF(exp,0) but in this way - NULLIF(ISNULL(exp,0),0)

NULLIF(exp,0) breaks if exp is null but NULLIF(ISNULL(exp,0),0) will not break

How to put a tooltip on a user-defined function

I just create a "help" version of the function. Shows up right below the function in autocomplete - the user can select it instead in an adjacent cell for instructions.

Public Function Foo(param1 as range, param2 as string) As String

    Foo = "Hello world"

End Function

Public Function Foo_Help() as String

Foo_Help = "The Foo function was designed to return the Foo value for a specified range a cells given a specified constant." & CHR(10) & "Parameters:" & CHR(10)
& "  param1 as Range   :   Specifies the range of cells the Foo function should operate on." & CHR(10)
&"  param2 as String  :   Specifies the constant the function should use to calculate Foo"
&" contact the Foo master at [email protected] for more information."

END FUNCTION

The carriage returns improve readability with wordwrap on. 2 birds with one stone, now the function has some documentation.

Why does jQuery or a DOM method such as getElementById not find the element?

the problem is that the dom element 'speclist' is not created at the time the javascript code is getting executed. So I put the javascript code inside a function and called that function on body onload event.

function do_this_first(){
   //appending code
}

<body onload="do_this_first()">
</body>

Phone number validation Android

You shouldn't be using Regular Expressions when validating phone numbers. Check out this JSON API - numverify.com - it's free for a nunver if calls a month and capable of checking any phone number. Plus, each request comes with location, line type and carrier information.

The ternary (conditional) operator in C

Compactness and the ability to inline an if-then-else construct into an expression.

How to enable NSZombie in Xcode?

in ur XCODE (4.3) next the play button :) (run)

select : edit scheme

the scheme management window will open

click on the Arguments tab

you should see : 1- Arguments passed on launch 2- environment variables

inside the the (2- environment variables) place Name: NSZombieEnabled
Value: YES

And its done....

How to iterate over arguments in a Bash script

Amplifying on baz's answer, if you need to enumerate the argument list with an index (such as to search for a specific word), you can do this without copying the list or mutating it.

Say you want to split an argument list at a double-dash ("--") and pass the arguments before the dashes to one command, and the arguments after the dashes to another:

 toolwrapper() {
   for i in $(seq 1 $#); do
     [[ "${!i}" == "--" ]] && break
   done || return $? # returns error status if we don't "break"

   echo "dashes at $i"
   echo "Before dashes: ${@:1:i-1}"
   echo "After dashes: ${@:i+1:$#}"
 }

Results should look like this:

 $ toolwrapper args for first tool -- and these are for the second
 dashes at 5
 Before dashes: args for first tool
 After dashes: and these are for the second

Add space between HTML elements only using CSS

span.middle {
    margin: 0 10px 0 10px; /*top right bottom left */
}

<span>text</span> <span class="middle">text</span> <span>text</span>

How to delete last character from a string using jQuery?

@skajfes and @GolezTrol provided the best methods to use. Personally, I prefer using "slice()". It's less code, and you don't have to know how long a string is. Just use:

//-----------------------------------------
// @param begin  Required. The index where 
//               to begin the extraction. 
//               1st character is at index 0
//
// @param end    Optional. Where to end the
//               extraction. If omitted, 
//               slice() selects all 
//               characters from the begin 
//               position to the end of 
//               the string.
var str = '123-4';
alert(str.slice(0, -1));

npm install errors with Error: ENOENT, chmod

This problem somehow arose for me on Mac when I was trying to run npm install -g bower. It was giving me a number of errors for not being able to find things like graceful-fs. I'm not sure how I installed npm originally, but it looks like perhaps it came down with node using homebrew. I first ran

brew uninstall node

This removed both node and npm from my path. From there I just reinstalled it

brew install node

When it completed I had node and npm on my path and I was able to run

rm -rf ~/.npm
npm install -g bower

This then installed bower successfully.

Updating the brew formulas and upgrading the installs didn't seem to work for me, I'm not sure why. The removal of the .npm folder was something that had worked for other people, and I had tried it without success. I did it this time just in case. Note also that neither of the following solved the problem for me, although it did for others:

npm cache clean
sudo npm cache clean

How do I stretch an image to fit the whole background (100% height x 100% width) in Flutter?

For me, to develop for web, works fine the following:

Image(
  image: AssetImage('lib/images/portadaSchamann5.png'),
  alignment: Alignment.center,
  height: double.infinity,
  width: double.infinity,
  fit: BoxFit.fill,
),

How to run a Runnable thread in Android at defined intervals?

If I understand correctly the documentation of Handler.post() method:

Causes the Runnable r to be added to the message queue. The runnable will be run on the thread to which this handler is attached.

So examples provided by @alex2k8, even though are working correctly, are not the same. In case, where Handler.post() is used, no new threads are created. You just post Runnable to the thread with Handler to be executed by EDT. After that, EDT only executes Runnable.run(), nothing else.

Remember: Runnable != Thread.

Counting how many times a certain char appears in a string before any other char appears

You could do this, it doesn't require LINQ, but it's not the best way to do it(since you make split the whole string and put it in an array and just pick the length of it, you could better just do a while loop and check every character), but it works.

int count = test.Split('$').Length - 1;

How to correctly write async method?

You are calling DoDownloadAsync() but you don't wait it. So your program going to the next line. But there is another problem, Async methods should return Task or Task<T>, if you return nothing and you want your method will be run asyncronously you should define your method like this:

private static async Task DoDownloadAsync()     {         WebClient w = new WebClient();          string txt = await w.DownloadStringTaskAsync("http://www.google.com/");         Debug.WriteLine(txt);     } 

And in Main method you can't await for DoDownloadAsync, because you can't use await keyword in non-async function, and you can't make Main async. So consider this:

var result = DoDownloadAsync();  Debug.WriteLine("DoDownload done"); result.Wait(); 

Where is Python language used?

With a few exceptions, Python is used pretty much wherever a programmer who knows Python wants to focus on solving a problem instead of struggling with implementation details. You'll find it in games, web applications, network servers, scientific computing, media tools, application scripting, etc. (There's a somewhat old list of some organizations that use it here.) People who know it well tend to love it because it strikes a very rare balance of conciseness and clarity, and (perhaps to a lesser extent) because it has a rich set of useful libraries.

Some places where Python isn't used as much:

  • Web browser scripts (because browsers implement JavaScript, not Python, though there are ways around that)
  • Large GUI applications (perhaps because good GUI bindings are relatively new)
  • Graphics engines (for performance reasons, but note that Python is sometimes used for the controlling logic that makes use of a graphics engine)
  • Small embedded devices (although some folks have had success with compact, stripped-down and special-purpose implementations of Python, and we're starting to see python tools for building applications on smart phones and tablets.)

How to make a JFrame button open another JFrame class in Netbeans?

JFrame.setVisible(true);

You can either use setVisible(false) or dispose() method to disappear current form.

Database Diagram Support Objects cannot be Installed ... no valid owner

In SQL Server Management Studio do the following:

  1. Right Click on your database, choose properties
  2. Go to the Options Page
  3. In the Drop down at right labeled "Compatibility Level" choose "SQL Server 2005(90)" 3-1. choose "SQL Server 2008" if you receive a comparability error.
  4. Go to the Files Page
  5. Enter "sa" in the owner textbox. 5-1 or click on the ellipses(...) and choose a rightful owner.
  6. Hit OK

after doing this, You will now be able to access the Database Diagrams.

enter image description here

Entity Framework Timeouts

In .Net Core (NetCore) use the following syntax to change the timeout from the default 30 seconds to 90 seconds:

public class DataContext : DbContext
{
    public DataContext(DbContextOptions<DataContext> options) : base(options)
    {
        this.Database.SetCommandTimeout(90); // <-- 90 seconds
    }
}

Convert NaN to 0 in javascript

You can do this:

a = a || 0

...which will convert a from any "falsey" value to 0.

The "falsey" values are:

  • false
  • null
  • undefined
  • 0
  • "" ( empty string )
  • NaN ( Not a Number )

Or this if you prefer:

a = a ? a : 0;

...which will have the same effect as above.


If the intent was to test for more than just NaN, then you can do the same, but do a toNumber conversion first.

a = +a || 0

This uses the unary + operator to try to convert a to a number. This has the added benefit of converting things like numeric strings '123' to a number.

The only unexpected thing may be if someone passes an Array that can successfully be converted to a number:

+['123']  // 123

Here we have an Array that has a single member that is a numeric string. It will be successfully converted to a number.

excel formula to subtract number of days from a date

Assuming the original date is in cell A1:

=A1-180

Works in at least Excel 2003 and 2010.

Converting HTML to Excel?

So long as Excel can open the file, the functionality to change the format of the opened file is built in.

To convert an .html file, open it using Excel (File - Open) and then save it as a .xlsx file from Excel (File - Save as).

To do it using VBA, the code would look like this:

Sub Open_HTML_Save_XLSX()

    Workbooks.Open Filename:="C:\Temp\Example.html"
    ActiveWorkbook.SaveAs Filename:= _
        "C:\Temp\Example.xlsx", FileFormat:= _
        xlOpenXMLWorkbook

End Sub

SOAP request in PHP with CURL

Tested and working!

  • with https, user & password

     <?php 
     //Data, connection, auth
     $dataFromTheForm = $_POST['fieldName']; // request data from the form
     $soapUrl = "https://connecting.website.com/soap.asmx?op=DoSomething"; // asmx URL of WSDL
     $soapUser = "username";  //  username
     $soapPassword = "password"; // password
    
     // xml post structure
    
     $xml_post_string = '<?xml version="1.0" encoding="utf-8"?>
                         <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
                           <soap:Body>
                             <GetItemPrice xmlns="http://connecting.website.com/WSDL_Service"> // xmlns value to be set to your WSDL URL
                               <PRICE>'.$dataFromTheForm.'</PRICE> 
                             </GetItemPrice >
                           </soap:Body>
                         </soap:Envelope>';   // data from the form, e.g. some ID number
    
        $headers = array(
                     "Content-type: text/xml;charset=\"utf-8\"",
                     "Accept: text/xml",
                     "Cache-Control: no-cache",
                     "Pragma: no-cache",
                     "SOAPAction: http://connecting.website.com/WSDL_Service/GetPrice", 
                     "Content-length: ".strlen($xml_post_string),
                 ); //SOAPAction: your op URL
    
         $url = $soapUrl;
    
         // PHP cURL  for https connection with auth
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
         curl_setopt($ch, CURLOPT_URL, $url);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($ch, CURLOPT_USERPWD, $soapUser.":".$soapPassword); // username and password - declared at the top of the doc
         curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
         curl_setopt($ch, CURLOPT_TIMEOUT, 10);
         curl_setopt($ch, CURLOPT_POST, true);
         curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request
         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    
         // converting
         $response = curl_exec($ch); 
         curl_close($ch);
    
         // converting
         $response1 = str_replace("<soap:Body>","",$response);
         $response2 = str_replace("</soap:Body>","",$response1);
    
         // convertingc to XML
         $parser = simplexml_load_string($response2);
         // user $parser to get your data out of XML response and to display it. 
     ?>
    

How do I use arrays in cURL POST requests

    $ch = curl_init();

    $data = array(
        'client_id' => 'xx',
        'client_secret' => 'xx',
        'redirect_uri' => $x,
        'grant_type' => 'xxx',
        'code' => $xx,
    );

    $data = http_build_query($data);

    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_URL, "https://example.com");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);

    $output = curl_exec($ch);

How to redirect Valgrind's output to a file?

valgrind --log-file="filename"

Does it matter what extension is used for SQLite database files?

In distributable software, I dont want my customers mucking about in the database by themselves. The program reads and writes it all by itself. The only reason for a user to touch the DB file is to take a backup copy. Therefore I have named it whatever_records.db

The simple .db extension tells the user that it is a binary data file and that's all they have to know. Calling it .sqlite invites the interested user to open it up and mess something up!

Totally depends on your usage scenario I suppose.

Auto height of div

As stated earlier by Jamie Dixon, a floated <div> is taken out of normal flow. All content that is still within normal flow will ignore it completely and not make space for it.

Try putting a different colored border border:solid 1px orange; around each of your <div> elements to see what they're doing. You might start by removing the floats and putting some dummy text inside the div. Then style them one at a time to get the desired layout.

How to change colour of blue highlight on select box dropdown

I believe you are looking for the outline CSS property (in conjunction with active and hover psuedo attributes):

/* turn it off completely */
select:active, select:hover {
  outline: none
}

/* make it red instead (with with same width and style) */
select:active, select:hover {
  outline-color: red
}

Full details of outline, outline-color, outline-style, and outline-width https://developer.mozilla.org/en-US/docs/Web/CSS/outline

Difference Between Select and SelectMany

Select many is like cross join operation in SQL where it takes the cross product.
For example if we have

Set A={a,b,c}
Set B={x,y}

Select many can be used to get the following set

{ (x,a) , (x,b) , (x,c) , (y,a) , (y,b) , (y,c) }

Note that here we take the all the possible combinations that can be made from the elements of set A and set B.

Here is a LINQ example you can try

List<string> animals = new List<string>() { "cat", "dog", "donkey" };
List<int> number = new List<int>() { 10, 20 };

var mix = number.SelectMany(num => animals, (n, a) => new { n, a });

the mix will have following elements in flat structure like

{(10,cat), (10,dog), (10,donkey), (20,cat), (20,dog), (20,donkey)}

Get everything after the dash in a string in JavaScript

var the_string = "sometext-20202";
var parts = the_string.split('-', 2);

// After calling split(), 'parts' is an array with two elements:
// parts[0] is 'sometext'
// parts[1] is '20202'

var the_text = parts[0];
var the_num  = parts[1];

Uncaught TypeError: Cannot read property 'value' of null

Add a check

if (document.getElementById('cal_preview') != null) {
    str = document.getElementById("cal_preview").value;
}

Ruby: Can I write multi-line string with no concatenation?

Other options:

#multi line string
multiline_string = <<EOM
This is a very long string
that contains interpolation
like #{4 + 5} \n\n
EOM

puts multiline_string

#another option for multiline string
message = <<-EOF
asdfasdfsador #{2+2} this month.
asdfadsfasdfadsfad.
EOF

puts message

Jquery Setting Value of Input Field

$('.formData').attr('value','YOUR_VALUE')

Ansible: Store command's stdout in new variable?

You have to store the content as a fact:

- set_fact:
    string_to_echo: "{{ command_output.stdout }}"

Qt 5.1.1: Application failed to start because platform plugin "windows" is missing

For a MinGW platform and if you are compiling a Debug target by a hand made CMakeLists.txt written ad hoc you need to add the qwindows.dll to the platform dir as well. The windeployqt executable does its work well but it seems that for some strange reason the CMake build needs the release variant as well. In summary it will be better to have both the qwindows.dll and qwindowsd.dll in your platform directory. I did not notice the same strange result when importing the CMake project in QtCreator and then running the build procedure. Compiling on the command line the CMake project seems to trigger the qwindows.dll dependency either if the correct one for the Debug target is set in place (qwindowsd.dll)

How can I use jQuery in Greasemonkey?

Perhaps you don't have a recent enough version of Greasemonkey. It was version 0.8 that added @require.

// @require https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js 

If you don't have 0.8, then use the technique Joan Piedra describes for manually adding a script element to the page.

Between version 0.8 and 0.9, @require is only processed when the script is first installed. If you change the list of required scripts, you need to uninstall your script and reinstall it; Greasemonkey downloads the required script once at installation and uses a cached copy thereafter.

As of 0.9, Greasemonkey behavior has changed (to address a tangentially related issue) so that it now loads the required scripts after every edit; reinstalling the script is no longer necessary.

How does DHT in torrents work?

With trackerless/DHT torrents, peer IP addresses are stored in the DHT using the BitTorrent infohash as the key. Since all a tracker does, basically, is respond to put/get requests, this functionality corresponds exactly to the interface that a DHT (distributed hash table) provides: it allows you to look up and store IP addresses in the DHT by infohash.

So a "get" request would look up a BT infohash and return a set of IP addresses. A "put" stores an IP address for a given infohash. This corresponds to the "announce" request you would otherwise make to the tracker to receive a dictionary of peer IP addresses.

In a DHT, peers are randomly assigned to store values belonging to a small fraction of the key space; the hashing ensures that keys are distributed randomly across participating peers. The DHT protocol (Kademlia for BitTorrent) ensures that put/get requests are routed efficiently to the peers responsible for maintaining a given key's IP address lists.

Passing an array using an HTML form hidden element

There are mainly two possible ways to achieve this:

  1. Serialize the data in some way:

    $postvalue = serialize($array); // Client side
    
    $array = unserialize($_POST['result']; // Server side
    

And then you can unserialize the posted values with unserialize($postvalue). Further information on this is here in the PHP manuals.

Alternativeley you can use the json_encode() and json_decode() functions to get a JSON formatted serialized string. You could even shrink the transmitted data with gzcompress() (note that this is performance intensive) and secure the transmitted data with base64_encode() (to make your data survive in non-8 bit clean transport layers) This could look like this:

    $postvalue = base64_encode(json_encode($array)); // Client side

    $array = json_decode(base64_decode($_POST['result'])); // Server side

A not recommended way to serialize your data (but very cheap in performance) is to simply use implode() on your array to get a string with all values separated by some specified character. On the server side you can retrieve the array with explode() then. But note that you shouldn't use a character for separation that occurs in the array values (or then escape it) and that you cannot transmit the array keys with this method.

  1. Use the properties of special named input elements:

    $postvalue = "";
    foreach ($array as $v) {
      $postvalue .= '<input type="hidden" name="result[]" value="' .$v. '" />';
    }
    

    Like this you get your entire array in the $_POST['result'] variable if the form is sent. Note that this doesn't transmit array keys. However you can achieve this by using result[$key] as name of each field.

Everyone of these methods got their own advantages and disadvantages. What you use is mainly depending on how large your array will be, since you should try to send a minimal amount of data with all of this methods.

Another way to achieve the same is to store the array in a server side session instead of transmitting it client side. Like this you can access the array over the $_SESSION variable and don't have to transmit anything over the form. For this have a look at a basic usage example of sessions on php.net.

How to convert an NSString into an NSNumber

I think NSDecimalNumber will do it:

Example:

NSNumber *theNumber = [NSDecimalNumber decimalNumberWithString:[stringVariable text]]];

NSDecimalNumber is a subclass of NSNumber, so implicit casting allowed.

Read data from a text file using Java

If you want to read line-by-line, use a BufferedReader. It has a readLine() method which returns the line as a String, or null if the end of the file has been reached. So you can do something like:

BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
String line;
while ((line = reader.readLine()) != null) {
 // Do something with line
}

(Note that this code doesn't handle exceptions or close the stream, etc)

How to do INSERT into a table records extracted from another table

Well I think the best way would be (will be?) to define 2 recordsets and use them as an intermediate between the 2 tables.

  1. Open both recordsets
  2. Extract the data from the first table (SELECT blablabla)
  3. Update 2nd recordset with data available in the first recordset (either by adding new records or updating existing records
  4. Close both recordsets

This method is particularly interesting if you plan to update tables from different databases (ie each recordset can have its own connection ...)

RichTextBox (WPF) does not have string property "Text"

The WPF RichTextBox has a Document property for setting the content a la MSDN:

// Create a FlowDocument to contain content for the RichTextBox.
        FlowDocument myFlowDoc = new FlowDocument();

        // Add paragraphs to the FlowDocument.
        myFlowDoc.Blocks.Add(new Paragraph(new Run("Paragraph 1")));
        myFlowDoc.Blocks.Add(new Paragraph(new Run("Paragraph 2")));
        myFlowDoc.Blocks.Add(new Paragraph(new Run("Paragraph 3")));
        RichTextBox myRichTextBox = new RichTextBox();

        // Add initial content to the RichTextBox.
        myRichTextBox.Document = myFlowDoc;

You can just use the AppendText method though if that's all you're after.

Hope that helps.

How to fetch all Git branches

For Visual Studio Users, On Package Manager console:

git branch | %{ git fetch upstream; git merge upstream/master}

Passing struct to function

When passing a struct to another function, it would usually be better to do as Donnell suggested above and pass it by reference instead.

A very good reason for this is that it makes things easier if you want to make changes that will be reflected when you return to the function that created the instance of it.

Here is an example of the simplest way to do this:

#include <stdio.h>

typedef struct student {
    int age;
} student;

void addStudent(student *s) {
    /* Here we can use the arrow operator (->) to dereference 
       the pointer and access any of it's members: */
    s->age = 10;
}

int main(void) {

    student aStudent = {0};     /* create an instance of the student struct */
    addStudent(&aStudent);      /* pass a pointer to the instance */

    printf("%d", aStudent.age);

    return 0;
}

In this example, the argument for the addStudent() function is a pointer to an instance of a student struct - student *s. In main(), we create an instance of the student struct and then pass a reference to it to our addStudent() function using the reference operator (&).

In the addStudent() function we can make use of the arrow operator (->) to dereference the pointer, and access any of it's members (functionally equivalent to: (*s).age).

Any changes that we make in the addStudent() function will be reflected when we return to main(), because the pointer gave us a reference to where in the memory the instance of the student struct is being stored. This is illustrated by the printf(), which will output "10" in this example.

Had you not passed a reference, you would actually be working with a copy of the struct you passed in to the function, meaning that any changes would not be reflected when you return to main - unless you implemented a way of passing the new version of the struct back to main or something along those lines!

Although pointers may seem off-putting at first, once you get your head around how they work and why they are so handy they become second nature, and you wonder how you ever coped without them!

Error handling with try and catch in Laravel

You are inside a namespace so you should use \Exception to specify the global namespace:

try {

  $this->buildXMLHeader();

} catch (\Exception $e) {

    return $e->getMessage();
}

In your code you've used catch (Exception $e) so Exception is being searched in/as:

App\Services\PayUService\Exception

Since there is no Exception class inside App\Services\PayUService so it's not being triggered. Alternatively, you can use a use statement at the top of your class like use Exception; and then you can use catch (Exception $e).

SQLAlchemy IN clause

How about

session.query(MyUserClass).filter(MyUserClass.id.in_((123,456))).all()

edit: Without the ORM, it would be

session.execute(
    select(
        [MyUserTable.c.id, MyUserTable.c.name], 
        MyUserTable.c.id.in_((123, 456))
    )
).fetchall()

select() takes two parameters, the first one is a list of fields to retrieve, the second one is the where condition. You can access all fields on a table object via the c (or columns) property.

Create an Array of Arraylists

  1. Creation and initialization

    Object[] yourArray = new Object[ARRAY_LENGTH];
    
  2. Write access

    yourArray[i]= someArrayList;
    

    to access elements of internal ArrayList:

    ((ArrayList<YourType>) yourArray[i]).add(elementOfYourType); //or other method
    
  3. Read access

    to read array element i as an ArrayList use type casting:

    someElement= (ArrayList<YourType>) yourArray[i];
    

    for array element i: to read ArrayList element at index j

    arrayListElement= ((ArrayList<YourType>) yourArray[i]).get(j);
    

What is the difference between <p> and <div>?

<p> is semantically used for text, paragraphs usually.

<div> is used for a block or area in a webpage. For example it could be used to make the area of a header.

They could probably be used interchangeably, but you shouldn't.

jQuery same click event for multiple elements

I have a link to an object containig many input fields, which requires to be handled by the same event. So I simply use find() to get all the inside objects, that need to have the event

var form = $('<form></form>');
// ... apending several input fields

form.find('input').on('change', onInputChange);

In case your objects are one level down the link children() instead find() method can be used.

LaTeX table positioning

What happens if the text plus tables plus text doesn't fit onto a single page? By trying to force the typesetting in this way, you are very likely to end up with pages that run too short; i.e., because a table cannot by default break over a page it will be pushed to the next, and leave a gap on the page before. You'll notice that you never see this in a published book.

The floating behaviour is a Good Thing! I recommend using [htbp] as the default setting for all tables and figures until your document is complete; only then should think about fine-tuning their precise placement.

P.S. Read the FAQ; most other answers here are partial combinations of advice given there.

How to store directory files listing into an array?

You may be tempted to use (*) but what if a directory contains the * character? It's very difficult to handle special characters in filenames correctly.

You can use ls -ls. However, it fails to handle newline characters.

# Store la -ls as an array
readarray -t files <<< $(ls -ls)
for (( i=1; i<${#files[@]}; i++ ))
{
    # Convert current line to an array
    line=(${files[$i]})
    # Get the filename, joining it together any spaces
    fileName=${line[@]:9}
    echo $fileName
}

If all you want is the file name, then just use ls:

for fileName in $(ls); do
    echo $fileName
done

See this article or this this post for more information about some of the difficulties of dealing with special characters in file names.

iPhone SDK on Windows (alternative solutions)

No one has brought up the hackintosh. If you have supported hardware it might be the best option.

MySQL stored procedure return value

Add:

  • DELIMITER at the beginning and end of the SP.
  • DROP PROCEDURE IF EXISTS validar_egreso; at the beginning
  • When calling the SP, use @variableName.

This works for me. (I modified some part of your script so ANYONE can run it with out having your tables).

DROP PROCEDURE IF EXISTS `validar_egreso`;

DELIMITER $$

CREATE DEFINER='root'@'localhost' PROCEDURE `validar_egreso` (
    IN codigo_producto VARCHAR(100),
    IN cantidad INT,
    OUT valido INT(11)
)
BEGIN

    DECLARE resta INT;
    SET resta = 0;

    SELECT (codigo_producto - cantidad) INTO resta;

    IF(resta > 1) THEN
       SET valido = 1;
    ELSE
       SET valido = -1;
    END IF;

    SELECT valido;
END $$

DELIMITER ;

-- execute the stored procedure
CALL validar_egreso(4, 1, @val);

-- display the result
select @val;

How to show Error & Warning Message Box in .NET/ How to Customize MessageBox

Try this:

MessageBox.Show("Some text", "Some title", 
    MessageBoxButtons.OK, MessageBoxIcon.Error);

Oracle - how to remove white spaces?

REPLACE(REPLACE(a.CUST_ADDRESS1,CHR(10),' '),CHR(13),' ') as ADDRESS

Replace X-axis with own values

Not sure if it's what you mean, but you can do this:

plot(1:10, xaxt = "n", xlab='Some Letters')
axis(1, at=1:10, labels=letters[1:10])

which then gives you the graph:

enter image description here

How to include quotes in a string

Escape them with backslashes.

"I want to learn \"C#\""

Simple PHP calculator

<!DOCTYPE html>
<html lang="en" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title>Calculator</title> 
    </head>
<body>

    <form method="GET">
    <h1>Calculator</h1>
    <p>This is a calculator made by Hau Teen Yee Fabrice and is free to use.</p>
        <ul>
     <ol> Multiplication: * </ol>
     <ol> Substraction: - </ol>
     <ol> Division: / </ol>
     <ol> Addition: + </ol>
        </ul>
     <p>Enter first number:</p>
        <input type="text" name="cal1">
        <p>Enter second number:</p>
        <input type="text" name="cal2">
        <p>Enter the calculator symbol</p>
        <input type="text" name="symbol">
        <button>Calculate</button>
    </form>
    <?php
    $cal1= $_GET['cal1'];
    $cal2= $_GET['cal2'];
    $symbol =$_GET['symbol'];

    if($symbol == '+')
    {
        $add = $cal1 + $cal2;
        echo "Addition is:".$add;
    }
    else if($symbol == '-')
    {
        $subs = $cal1 - $cal2;
        echo "Substraction is:".$subs;
    }
     else if($symbol == '*')
    {
        $mul = $cal1 * $cal2;
        echo "Multiply is:".$mul;
    }
    else if($symbol == '/')
    {
        $div = $cal1 / $cal2;
        echo "Division is:".$div;
    }
      else
    { 
        echo "Oops ,something wrong in your code son";
    }
    ?>
    </body> 
</html>

How to find the number of days between two dates

DECLARE @Firstdate DATE='2016-04-01',
 @LastDate DATE=GETDATE(),/*get today date*/
 @resultDay int=null

SET @resultDay=(SELECT DATEDIFF(d, @Firstdate, @LastDate))
PRINT @resultDay

C# 30 Days From Todays Date

One I can answer confidently!

DateTime expiryDate = DateTime.Now.AddDays(30);

Or possibly - if you just want the date without a time attached which might be more appropriate:

DateTime expiryDate = DateTime.Today.AddDays(30);

Xcode 6 Bug: Unknown class in Interface Builder file

I had the same problem.

In my case, Xcode wasn't adding my custom class to: Target > Build Phase > Compile Sources.

So I recommend you to verify if your CustomClass.m is there.

enter image description here

I hope this helps you.

Parse XML using JavaScript

I'm guessing from your last question, asked 20 minutes before this one, that you are trying to parse (read and convert) the XML found through using GeoNames' FindNearestAddress.

If your XML is in a string variable called txt and looks like this:

<address>
  <street>Roble Ave</street>
  <mtfcc>S1400</mtfcc>
  <streetNumber>649</streetNumber>
  <lat>37.45127</lat>
  <lng>-122.18032</lng>
  <distance>0.04</distance>
  <postalcode>94025</postalcode>
  <placename>Menlo Park</placename>
  <adminCode2>081</adminCode2>
  <adminName2>San Mateo</adminName2>
  <adminCode1>CA</adminCode1>
  <adminName1>California</adminName1>
  <countryCode>US</countryCode>
</address>

Then you can parse the XML with Javascript DOM like this:

if (window.DOMParser)
{
    parser = new DOMParser();
    xmlDoc = parser.parseFromString(txt, "text/xml");
}
else // Internet Explorer
{
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async = false;
    xmlDoc.loadXML(txt);
}

And get specific values from the nodes like this:

//Gets house address number
xmlDoc.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue;

//Gets Street name
xmlDoc.getElementsByTagName("street")[0].childNodes[0].nodeValue;

//Gets Postal Code
xmlDoc.getElementsByTagName("postalcode")[0].childNodes[0].nodeValue;

JSFiddle


Feb. 2019 edit:

In response to @gaugeinvariante's concerns about xml with Namespace prefixes. Should you have a need to parse xml with Namespace prefixes, everything should work almost identically:

NOTE: this will only work in browsers that support xml namespace prefixes such as Microsoft Edge

_x000D_
_x000D_
// XML with namespace prefixes 's', 'sn', and 'p' in a variable called txt_x000D_
txt = `_x000D_
<address xmlns:p='example.com/postal' xmlns:s='example.com/street' xmlns:sn='example.com/streetNum'>_x000D_
  <s:street>Roble Ave</s:street>_x000D_
  <sn:streetNumber>649</sn:streetNumber>_x000D_
  <p:postalcode>94025</p:postalcode>_x000D_
</address>`;_x000D_
_x000D_
//Everything else the same_x000D_
if (window.DOMParser)_x000D_
{_x000D_
    parser = new DOMParser();_x000D_
    xmlDoc = parser.parseFromString(txt, "text/xml");_x000D_
}_x000D_
else // Internet Explorer_x000D_
{_x000D_
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");_x000D_
    xmlDoc.async = false;_x000D_
    xmlDoc.loadXML(txt);_x000D_
}_x000D_
_x000D_
//The prefix should not be included when you request the xml namespace_x000D_
//Gets "streetNumber" (note there is no prefix of "sn"_x000D_
console.log(xmlDoc.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue);_x000D_
_x000D_
//Gets Street name_x000D_
console.log(xmlDoc.getElementsByTagName("street")[0].childNodes[0].nodeValue);_x000D_
_x000D_
//Gets Postal Code_x000D_
console.log(xmlDoc.getElementsByTagName("postalcode")[0].childNodes[0].nodeValue);
_x000D_
_x000D_
_x000D_

Detect user scroll down or scroll up in jQuery

To differentiate between scroll up/down in jQuery, you could use:

var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
$('#yourDiv').bind(mousewheelevt, function(e){

    var evt = window.event || e //equalize event object     
    evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible               
    var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF

    if(delta > 0) {
        //scroll up
    }
    else{
        //scroll down
    }   
});

This method also works in divs that have overflow:hidden.

I successfully tested it in FireFox, IE and Chrome.

Python calling method in class

Let's say you have a shiny Foo class. Well you have 3 options:

1) You want to use the method (or attribute) of a class inside the definition of that class:

class Foo(object):
    attribute1 = 1                   # class attribute (those don't use 'self' in declaration)
    def __init__(self):
        self.attribute2 = 2          # instance attribute (those are accessible via first
                                     # parameter of the method, usually called 'self'
                                     # which will contain nothing but the instance itself)
    def set_attribute3(self, value): 
        self.attribute3 = value

    def sum_1and2(self):
        return self.attribute1 + self.attribute2

2) You want to use the method (or attribute) of a class outside the definition of that class

def get_legendary_attribute1():
    return Foo.attribute1

def get_legendary_attribute2():
    return Foo.attribute2

def get_legendary_attribute1_from(cls):
    return cls.attribute1

get_legendary_attribute1()           # >>> 1
get_legendary_attribute2()           # >>> AttributeError: type object 'Foo' has no attribute 'attribute2'
get_legendary_attribute1_from(Foo)   # >>> 1

3) You want to use the method (or attribute) of an instantiated class:

f = Foo()
f.attribute1                         # >>> 1
f.attribute2                         # >>> 2
f.attribute3                         # >>> AttributeError: 'Foo' object has no attribute 'attribute3'
f.set_attribute3(3)
f.attribute3                         # >>> 3

How to delete columns in pyspark dataframe

Adding to @Patrick's answer, you can use the following to drop multiple columns

columns_to_drop = ['id', 'id_copy']
df = df.drop(*columns_to_drop)

What is the meaning of polyfills in HTML5?

A polyfill is a browser fallback, made in JavaScript, that allows functionality you expect to work in modern browsers to work in older browsers, e.g., to support canvas (an HTML5 feature) in older browsers.

It's sort of an HTML5 technique, since it is used in conjunction with HTML5, but it's not part of HTML5, and you can have polyfills without having HTML5 (for example, to support CSS3 techniques you want).

Here's a good post:

http://remysharp.com/2010/10/08/what-is-a-polyfill/

Here's a comprehensive list of Polyfills and Shims:

https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-browser-Polyfills

Scikit-learn: How to obtain True Positive, True Negative, False Positive and False Negative

You can obtain all of the parameters from the confusion matrix. The structure of the confusion matrix(which is 2X2 matrix) is as follows (assuming the first index is related to the positive label, and the rows are related to the true labels):

TP|FN
FP|TN

So

TP = cm[0][0]
FN = cm[0][1]
FP = cm[1][0]
TN = cm[1][1]

More details at https://en.wikipedia.org/wiki/Confusion_matrix

Android: How to change the ActionBar "Home" Icon to be something other than the app icon?

Might wanna check this, got everything you need for your app icons

http://developer.android.com/guide/practices/ui_guidelines/icon_design.html

update

I think by default it uses your launcher icon... Your best bet is to create a separate image... Designed for the action bar and using that. For that check: http://developer.android.com/guide/topics/ui/actionbar.html#ActionItems

How to diff one file to an arbitrary version in Git?

If you are fine using a graphical tool (or even prefer it) you can:

gitk pom.xml

In gitk you can then click any commit (to "select" it) and right click any other commit to select "Diff this -> selected" or "Diff selected -> this" in the popup menu, depending on what order you prefer.

Using C# regular expressions to remove HTML tags

try regular expression method at this URL: http://www.dotnetperls.com/remove-html-tags

/// <summary>
/// Remove HTML from string with Regex.
/// </summary>
public static string StripTagsRegex(string source)
{
return Regex.Replace(source, "<.*?>", string.Empty);
}

/// <summary>
/// Compiled regular expression for performance.
/// </summary>
static Regex _htmlRegex = new Regex("<.*?>", RegexOptions.Compiled);

/// <summary>
/// Remove HTML from string with compiled Regex.
/// </summary>
public static string StripTagsRegexCompiled(string source)
{
return _htmlRegex.Replace(source, string.Empty);
}

Generating an array of letters in the alphabet

Unfortunately there is no ready-to-use way.

You can use; char[] characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();

Can I convert a C# string value to an escaped string literal

I submit my own implementation, which handles null values and should be more performant on account of using array lookup tables, manual hex conversion, and avoiding switch statements.

using System;
using System.Text;
using System.Linq;

public static class StringLiteralEncoding {
  private static readonly char[] HEX_DIGIT_LOWER = "0123456789abcdef".ToCharArray();
  private static readonly char[] LITERALENCODE_ESCAPE_CHARS;

  static StringLiteralEncoding() {
    // Per http://msdn.microsoft.com/en-us/library/h21280bw.aspx
    var escapes = new string[] { "\aa", "\bb", "\ff", "\nn", "\rr", "\tt", "\vv", "\"\"", "\\\\", "??", "\00" };
    LITERALENCODE_ESCAPE_CHARS = new char[escapes.Max(e => e[0]) + 1];
    foreach(var escape in escapes)
      LITERALENCODE_ESCAPE_CHARS[escape[0]] = escape[1];
  }

  /// <summary>
  /// Convert the string to the equivalent C# string literal, enclosing the string in double quotes and inserting
  /// escape sequences as necessary.
  /// </summary>
  /// <param name="s">The string to be converted to a C# string literal.</param>
  /// <returns><paramref name="s"/> represented as a C# string literal.</returns>
  public static string Encode(string s) {
    if(null == s) return "null";

    var sb = new StringBuilder(s.Length + 2).Append('"');
    for(var rp = 0; rp < s.Length; rp++) {
      var c = s[rp];
      if(c < LITERALENCODE_ESCAPE_CHARS.Length && '\0' != LITERALENCODE_ESCAPE_CHARS[c])
        sb.Append('\\').Append(LITERALENCODE_ESCAPE_CHARS[c]);
      else if('~' >= c && c >= ' ')
        sb.Append(c);
      else
        sb.Append(@"\x")
          .Append(HEX_DIGIT_LOWER[c >> 12 & 0x0F])
          .Append(HEX_DIGIT_LOWER[c >>  8 & 0x0F])
          .Append(HEX_DIGIT_LOWER[c >>  4 & 0x0F])
          .Append(HEX_DIGIT_LOWER[c       & 0x0F]);
    }

    return sb.Append('"').ToString();
  }
}

Label python data points on plot

I had a similar issue and ended up with this:

enter image description here

For me this has the advantage that data and annotation are not overlapping.

from matplotlib import pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)

A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54

plt.plot(A,B)

# annotations at the side (ordered by B values)
x0,x1=ax.get_xlim()
y0,y1=ax.get_ylim()
for ii, ind in enumerate(np.argsort(B)):
    x = A[ind]
    y = B[ind]
    xPos = x1 + .02 * (x1 - x0)
    yPos = y0 + ii * (y1 - y0)/(len(B) - 1)
    ax.annotate('',#label,
          xy=(x, y), xycoords='data',
          xytext=(xPos, yPos), textcoords='data',
          arrowprops=dict(
                          connectionstyle="arc3,rad=0.",
                          shrinkA=0, shrinkB=10,
                          arrowstyle= '-|>', ls= '-', linewidth=2
                          ),
          va='bottom', ha='left', zorder=19
          )
    ax.text(xPos + .01 * (x1 - x0), yPos,
            '({:.2f}, {:.2f})'.format(x,y),
            transform=ax.transData, va='center')

plt.grid()
plt.show()

Using the text argument in .annotate ended up with unfavorable text positions. Drawing lines between a legend and the data points is a mess, as the location of the legend is hard to address.

Actual meaning of 'shell=True' in subprocess

An example where things could go wrong with Shell=True is shown here

>>> from subprocess import call
>>> filename = input("What file would you like to display?\n")
What file would you like to display?
non_existent; rm -rf / # THIS WILL DELETE EVERYTHING IN ROOT PARTITION!!!
>>> call("cat " + filename, shell=True) # Uh-oh. This will end badly...

Check the doc here: subprocess.call()

What does %~d0 mean in a Windows batch file?

%~d0 gives you the drive letter of argument 0 (the script name), %~p0 the path.

Play/pause HTML 5 video using JQuery

use this.. $('#video1').attr({'autoplay':'true'});

ImportError: No module named 'MySQL'

Use pip3 install mysql-connector to install the python packaged (if you are using Python 3. For Python 2 you can use pip).

Auto-click button element on page load using jQuery

JavaScript Pure:

<script type="text/javascript">
document.getElementById("modal").click();
</script>

JQuery:

<script type="text/javascript">
$(document).ready(function(){
    $("#modal").trigger('click'); 
});
</script>

or

<script type="text/javascript">
$(document).ready(function(){
    $("#modal").click(); 
});
</script>

How to do an INNER JOIN on multiple columns

If you want to search on both FROM and TO airports, you'll want to join on the Airports table twice - then you can use both from and to tables in your results set:

SELECT
   Flights.*,fromAirports.*,toAirports.*
FROM
   Flights
INNER JOIN 
   Airports fromAirports on Flights.fairport = fromAirports.code
INNER JOIN 
   Airports toAirports on Flights.tairport = toAirports.code
WHERE
 ...

How to finish current activity in Android

You can also use: finishAffinity()

Finish this activity as well as all activities immediately below it in the current task that have the same affinity.

How do I remove the space between inline/inline-block elements?

With PHP brackets:

_x000D_
_x000D_
ul li {_x000D_
  display: inline-block;_x000D_
}
_x000D_
    <ul>_x000D_
        <li>_x000D_
            <div>first</div>_x000D_
        </li><?_x000D_
        ?><li>_x000D_
            <div>first</div>_x000D_
        </li><?_x000D_
        ?><li>_x000D_
            <div>first</div>_x000D_
        </li>_x000D_
    </ul>
_x000D_
_x000D_
_x000D_

How to publish a Web Service from Visual Studio into IIS?

If using Visual Studio 2010 you can right-click on the project for the service, and select properties. Then select the Web tab. Under the Servers section you can configure the URL. There is also a button to create the virtual directory.

Get data from fs.readFile

var fs = require('fs');
var path = (process.cwd()+"\\text.txt");

fs.readFile(path , function(err,data)
{
    if(err)
        console.log(err)
    else
        console.log(data.toString());
});

How to remove underline from a name on hover

try this:

legend.green-color a:hover{
    text-decoration: none;
}

SELECT CONVERT(VARCHAR(10), GETDATE(), 110) what is the meaning of 110 here?

That number indicates Date and Time Styles

You need to look at CAST and CONVERT (Transact-SQL). Here you can find the meaning of all these Date and Time Styles.

Styles with century (e.g. 100, 101 etc) means year will come in yyyy format. While styles without century (e.g. 1,7,10) means year will come in yy format.

You can also refer to SQL Server Date Formats. Here you can find all date formats with examples.

Convert UTF-8 with BOM to UTF-8 with no BOM in Python

In Python 3 it's quite easy: read the file and rewrite it with utf-8 encoding:

s = open(bom_file, mode='r', encoding='utf-8-sig').read()
open(bom_file, mode='w', encoding='utf-8').write(s)

How to get current date in jquery?

Using pure Javascript your can prototype your own YYYYMMDD format;

Date.prototype.yyyymmdd = function() {
  var yyyy = this.getFullYear().toString();
  var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
  var dd  = this.getDate().toString();
  return yyyy + "/" + (mm[1]?mm:"0"+mm[0]) + "/" + (dd[1]?dd:"0"+dd[0]); // padding
};

var date = new Date();
console.log( date.yyyymmdd() ); // Assuming you have an open console