Programs & Examples On #Guava

Google's Core Java Library for Java and Android development.

Predicate in Java

A predicate is a function that returns a true/false (i.e. boolean) value, as opposed to a proposition which is a true/false (i.e. boolean) value. In Java, one cannot have standalone functions, and so one creates a predicate by creating an interface for an object that represents a predicate and then one provides a class that implements that interface. An example of an interface for a predicate might be:

public interface Predicate<ARGTYPE>
{
    public boolean evaluate(ARGTYPE arg);
}

And then you might have an implementation such as:

public class Tautology<E> implements Predicate<E>
{
     public boolean evaluate(E arg){
         return true;
     }
}

To get a better conceptual understanding, you might want to read about first-order logic.

Edit
There is a standard Predicate interface (java.util.function.Predicate) defined in the Java API as of Java 8. Prior to Java 8, you may find it convenient to reuse the com.google.common.base.Predicate interface from Guava.

Also, note that as of Java 8, it is much simpler to write predicates by using lambdas. For example, in Java 8 and higher, one can pass p -> true to a function instead of defining a named Tautology subclass like the above.

How to JUnit test that two List<E> contain the same elements in the same order?

For excellent code-readability, Fest Assertions has nice support for asserting lists

So in this case, something like:

Assertions.assertThat(returnedComponents).containsExactly("One", "Two", "Three");

Or make the expected list to an array, but I prefer the above approach because it's more clear.

Assertions.assertThat(returnedComponents).containsExactly(argumentComponents.toArray());

Combine multiple Collections into a single logical Collection?

If you're using at least Java 8, see my other answer.

If you're already using Google Guava, see Sean Patrick Floyd's answer.

If you're stuck at Java 7 and don't want to include Google Guava, you can write your own (read-only) Iterables.concat() using no more than Iterable and Iterator:

Constant number

public static <E> Iterable<E> concat(final Iterable<? extends E> iterable1,
                                     final Iterable<? extends E> iterable2) {
    return new Iterable<E>() {
        @Override
        public Iterator<E> iterator() {
            return new Iterator<E>() {
                final Iterator<? extends E> iterator1 = iterable1.iterator();
                final Iterator<? extends E> iterator2 = iterable2.iterator();

                @Override
                public boolean hasNext() {
                    return iterator1.hasNext() || iterator2.hasNext();
                }

                @Override
                public E next() {
                    return iterator1.hasNext() ? iterator1.next() : iterator2.next();
                }
            };
        }
    };
}

Variable number

@SafeVarargs
public static <E> Iterable<E> concat(final Iterable<? extends E>... iterables) {
    return concat(Arrays.asList(iterables));
}

public static <E> Iterable<E> concat(final Iterable<Iterable<? extends E>> iterables) {
    return new Iterable<E>() {
        final Iterator<Iterable<? extends E>> iterablesIterator = iterables.iterator();

        @Override
        public Iterator<E> iterator() {
            return !iterablesIterator.hasNext() ? Collections.emptyIterator()
                                                : new Iterator<E>() {
                Iterator<? extends E> iterableIterator = nextIterator();

                @Override
                public boolean hasNext() {
                    return iterableIterator.hasNext();
                }

                @Override
                public E next() {
                    final E next = iterableIterator.next();
                    findNext();
                    return next;
                }

                Iterator<? extends E> nextIterator() {
                    return iterablesIterator.next().iterator();
                }

                Iterator<E> findNext() {
                    while (!iterableIterator.hasNext()) {
                        if (!iterablesIterator.hasNext()) {
                            break;
                        }
                        iterableIterator = nextIterator();
                    }
                    return this;
                }
            }.findNext();
        }
    };
}

builder for HashMap

There's ImmutableMap.builder() in Guava.

Interface/enum listing standard mime-type constants

There's also a MediaType class in androidannotations in case you want to use with android! See here.

initializing a Guava ImmutableMap

"put" has been deprecated, refrain from using it, use .of instead

ImmutableMap<String, String> myMap = ImmutableMap.of(
    "city1", "Seattle",
    "city2", "Delhi"
);

Bi-directional Map in Java?

There is no bidirectional map in the Java Standard API. Either you can maintain two maps yourself or use the BidiMap from Apache Collections.

UnmodifiableMap (Java Collections) vs ImmutableMap (Google)

Guava Documentation

The JDK provides Collections.unmodifiableXXX methods, but in our opinion, these can be unwieldy and verbose; unpleasant to use everywhere you want to make defensive copies unsafe: the returned collections are only truly immutable if nobody holds a reference to the original collection inefficient: the data structures still have all the overhead of mutable collections, including concurrent modification checks, extra space in hash tables, etc.

Map implementation with duplicate keys

We don't need to depend on the Google Collections external library. You can simply implement the following Map:

Map<String, ArrayList<String>> hashMap = new HashMap<String, ArrayList>();

public static void main(String... arg) {
   // Add data with duplicate keys
   addValues("A", "a1");
   addValues("A", "a2");
   addValues("B", "b");
   // View data.
   Iterator it = hashMap.keySet().iterator();
   ArrayList tempList = null;

   while (it.hasNext()) {
      String key = it.next().toString();             
      tempList = hashMap.get(key);
      if (tempList != null) {
         for (String value: tempList) {
            System.out.println("Key : "+key+ " , Value : "+value);
         }
      }
   }
}

private void addValues(String key, String value) {
   ArrayList tempList = null;
   if (hashMap.containsKey(key)) {
      tempList = hashMap.get(key);
      if(tempList == null)
         tempList = new ArrayList();
      tempList.add(value);  
   } else {
      tempList = new ArrayList();
      tempList.add(value);               
   }
   hashMap.put(key,tempList);
}

Please make sure to fine tune the code.

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

With Java 8 it is so simple so it doesn't even need separate method anymore:

List<Integer> range = IntStream.rangeClosed(start, end)
    .boxed().collect(Collectors.toList());

Trim to remove white space

Why not try this?

html:

<p>
  a b c
</p>

js:

$("p").text().trim();

String comparison in bash. [[: not found

[[ is a bash-builtin. Your /bin/bash doesn't seem to be an actual bash.

From a comment:

Add #!/bin/bash at the top of file

Ignore python multiple return value

If this is a function that you use all the time but always discard the second argument, I would argue that it is less messy to create an alias for the function without the second return value using lambda.

def func():
    return 1, 2

func_ = lambda: func()[0] 

func_()  # Prints 1 

What is a Y-combinator?

The y-combinator implements anonymous recursion. So instead of

function fib( n ){ if( n<=1 ) return n; else return fib(n-1)+fib(n-2) }

you can do

function ( fib, n ){ if( n<=1 ) return n; else return fib(n-1)+fib(n-2) }

of course, the y-combinator only works in call-by-name languages. If you want to use this in any normal call-by-value language, then you will need the related z-combinator (y-combinator will diverge/infinite-loop).

Objective-C: Reading a file line by line

Just like @porneL said, the C api is very handy.

NSString* fileRoot = [[NSBundle mainBundle] pathForResource:@"record" ofType:@"txt"];
FILE *file = fopen([fileRoot UTF8String], "r");
char buffer[256];
while (fgets(buffer, 256, file) != NULL){
    NSString* result = [NSString stringWithUTF8String:buffer];
    NSLog(@"%@",result);
}

How to get string objects instead of Unicode from JSON?

That's because json has no difference between string objects and unicode objects. They're all strings in javascript.

I think JSON is right to return unicode objects. In fact, I wouldn't accept anything less, since javascript strings are in fact unicode objects (i.e. JSON (javascript) strings can store any kind of unicode character) so it makes sense to create unicode objects when translating strings from JSON. Plain strings just wouldn't fit since the library would have to guess the encoding you want.

It's better to use unicode string objects everywhere. So your best option is to update your libraries so they can deal with unicode objects.

But if you really want bytestrings, just encode the results to the encoding of your choice:

>>> nl = json.loads(js)
>>> nl
[u'a', u'b']
>>> nl = [s.encode('utf-8') for s in nl]
>>> nl
['a', 'b']

jQuery vs. javascript?

It's all about performance and development speed. Of course, if you are a good programmer and design something that is really tailored to your needs, you might achieve better performance than if you had used a Javascript framework. But do you have the time to do it all by yourself?

My personal opinion is that Javascript is incredibly useful and overused, but that if you really need it, a framework is the way to go.

Now comes the choice of the framework. For what benchmarks are worth, you can find one at http://ejohn.org/files/142/ . It also depends on which plugins are available and what you intend to do with them. I started using jQuery because it seemed to be maintained and well featured, even though it wasn't the fastest at that moment. I do not regret it but I didn't test anything else since then.

How to access the php.ini file in godaddy shared hosting linux

For some hosting accounts, I'm on Ultimate Classic Linux, the file name you need to use is .user.ini.

React PropTypes : Allow different types of PropTypes for one prop

For documentation purpose, it's better to list the string values that are legal:

size: PropTypes.oneOfType([
    PropTypes.number,
    PropTypes.oneOf([ 'SMALL', 'LARGE' ]),
]),

Catch Ctrl-C in C

#include<stdio.h>
#include<signal.h>
#include<unistd.h>

void sig_handler(int signo)
{
  if (signo == SIGINT)
    printf("received SIGINT\n");
}

int main(void)
{
  if (signal(SIGINT, sig_handler) == SIG_ERR)
  printf("\ncan't catch SIGINT\n");
  // A long long wait so that we can easily issue a signal to this process
  while(1) 
    sleep(1);
  return 0;
}

The function sig_handler checks if the value of the argument passed is equal to the SIGINT, then the printf is executed.

How does a hash table work?

Here's another way to look at it.

I assume you understand the concept of an array A. That's something that supports the operation of indexing, where you can get to the Ith element, A[I], in one step, no matter how large A is.

So, for example, if you want to store information about a group of people who all happen to have different ages, a simple way would be to have an array that is large enough, and use each person's age as an index into the array. Thay way, you could have one-step access to any person's information.

But of course there could be more than one person with the same age, so what you put in the array at each entry is a list of all the people who have that age. So you can get to an individual person's information in one step plus a little bit of search in that list (called a "bucket"). It only slows down if there are so many people that the buckets get big. Then you need a larger array, and some other way to get more identifying information about the person, like the first few letters of their surname, instead of using age.

That's the basic idea. Instead of using age, any function of the person that produces a good spread of values can be used. That's the hash function. Like you could take every third bit of the ASCII representation of the person's name, scrambled in some order. All that matters is that you don't want too many people to hash to the same bucket, because the speed depends on the buckets remaining small.

one line if statement in php

use the ternary operator ?:

change this

<?php if ($requestVars->_name == '') echo $redText; ?>

with

<?php echo ($requestVars->_name == '') ? $redText : ''; ?>

In short

// (Condition)?(thing's to do if condition true):(thing's to do if condition false);

How to send string from one activity to another?

Say there is EditText et1 in ur MainActivity and u wanna pass this to SecondActivity

String s=et1.getText().toString();
Bundle basket= new Bundle();
basket.putString("abc", s);
Intent a=new Intent(MainActivity.this,SecondActivity.class);
a.putExtras(basket);
startActivity(a);

now in Second Activity, say u wanna put the string passed from EditText et1 to TextView txt1 of SecondActivity

Bundle gt=getIntent().getExtras();
str=gt.getString("abc");
txt1.setText(str);

How can I remove the first line of a text file using bash/sed script?

Would using tail on N-1 lines and directing that into a file, followed by removing the old file, and renaming the new file to the old name do the job?

If i were doing this programatically, i would read through the file, and remember the file offset, after reading each line, so i could seek back to that position to read the file with one less line in it.

Should I use Vagrant or Docker for creating an isolated environment?

They are very much complementary.

I have been using a combination of VirtualBox, Vagrant and Docker for all my projects for several months and have strongly felt the following benefits.

In Vagrant you can completely do away with any Chef solo provisioning and all you need your vagrant file to do is prepare a machine that runs a single small shell script that installs docker. This means that my Vagrantfiles for every project are almost identical and very simple.

Here is a typical Vagrantfile

# -*- mode: ruby -*-
# vi: set ft=ruby :
VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  config.vm.box = "mark2"
  config.vm.box_url = "http://cloud-images.ubuntu.com/vagrant/trusty/current/trusty-server-cloudimg-amd64-vagrant-disk1.box"
  [3000, 5000, 2345, 15672, 5672, 15674, 27017, 28017, 9200, 9300, 11211, 55674, 61614, 55672, 5671, 61613].each do |p|
    config.vm.network :forwarded_port, guest: p, host: p
  end
  config.vm.network :private_network, ip: "192.168.56.20"
  config.vm.synced_folder ".", "/vagrant", :type => "nfs"
  config.vm.provider :virtualbox do |vb|
    vb.customize ["modifyvm", :id, "--memory", "2048"]
    vb.customize ["modifyvm", :id, "--cpus", "2"]
  end
  # Bootstrap to Docker
  config.vm.provision :shell, path: "script/vagrant/bootstrap", :privileged => true
  # Build docker containers
  config.vm.provision :shell, path: "script/vagrant/docker_build", :privileged => true
  # Start containers
  # config.vm.provision :shell, path: "script/vagrant/docker_start", :privileged => true
end

The Bootstrap file that installs docker looks like this

#!/usr/bin/env bash
echo 'vagrant  ALL= (ALL:ALL) NOPASSWD: ALL' >> /etc/sudoers
apt-get update -y
apt-get install htop -y
apt-get install linux-image-extra-`uname -r` -y
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 36A1D7869245C8950F966E92D8576A8BA88D21E9
echo deb http://get.docker.io/ubuntu docker main > /etc/apt/sources.list.d/docker.list
apt-get update -y
apt-get install lxc-docker -y
apt-get install curl -y

Now to get all the services I need running I have a docker_start script that looks somthing like this

#!/bin/bash
cd /vagrant
echo Starting required service containers
export HOST_NAME=192.168.56.20
# Start MongoDB
docker run --name=mongodb --detach=true --publish=27017:27017 --publish=28017:28017 dockerfile/mongodb
read -t5 -n1 -r -p "Waiting for mongodb to start..." key
# Start rabbitmq
docker run --name=rabbitmq --detach=true --publish=5671:5671 --publish=5672:5672 --publish=55672:55672 --publish=15672:15672 --publish=15674:15674 --publish=61613:61613 --env RABBITMQ_USER=guest --env RABBITMQ_PASS=guest rabbitmq
read -t5 -n1 -r -p "Waiting for rabbitmq to start..." key
# Start cache
docker run --name=memcached --detach=true --publish=11211:11211  ehazlett/memcached
read -t5 -n1 -r -p "Waiting for cache to start..." key
# Start elasticsearch
docker run --name=elasticsearch --detach=true --publish=9200:9200 --publish=9300:9300 dockerfile/elasticsearch
read -t5 -n1 -r -p "Waiting for elasticsearch to start..." key
echo "All services started"

In this example I am running MongoDB, Elastisearch, RabbitMQ and Memcached

A non-docker Chef solo configuration would be considerably more complicated.

A final big plus is gained when you are moving into production, translating the development environment over to an infrastructure of hosts that are all the same in that they just have enough config to run docker means very little work indeed.

If you interested I have a more detailed article on the development environment on my own web site at

Implementing A Vagrant / Docker Development Environment

Share link on Google+

<meta property="og:title" content="Ali Umair"/>
<meta property="og:description" content="Ali UMair is a web developer"/><meta property="og:image" content="../image" />

<a target="_blank" href="https://plus.google.com/share?url=<? echo urlencode('http://www..'); ?>"><img src="../gplus-black_icon.png" alt="" /></a>

this code will work with image text and description please put meta into head tag

"unary operator expected" error in Bash if condition

You can also set a default value for the variable, so you don't need to use two "[", which amounts to two processes ("[" is actually a program) instead of one.

It goes by this syntax: ${VARIABLE:-default}.

The whole thing has to be thought in such a way that this "default" value is something distinct from a "valid" value/content.

If that's not possible for some reason you probably need to add a step like checking if there's a value at all, along the lines of "if [ -z $VARIABLE ] ; then echo "the variable needs to be filled"", or "if [ ! -z $VARIABLE ] ; then #everything is fine, proceed with the rest of the script".

How to run DOS/CMD/Command Prompt commands from VB.NET?

I was inspired by Steve's answer but thought I'd add a bit of flare to it. I like to do the work up front of writing extension methods so later I have less work to do calling the method.

For example with the modified version of Steve's answer below, instead of making this call...

MyUtilities.RunCommandCom("DIR", "/W", true)

I can actually just type out the command and call it from my strings like this...

Directly in code.

Call "CD %APPDATA% & TREE".RunCMD()

OR

From a variable.

Dim MyCommand = "CD %APPDATA% & TREE"
MyCommand.RunCMD()

OR

From a textbox.

textbox.text.RunCMD(WaitForProcessComplete:=True)


Extension methods will need to be placed in a Public Module and carry the <Extension> attribute over the sub. You will also want to add Imports System.Runtime.CompilerServices to the top of your code file.

There's plenty of info on SO about Extension Methods if you need further help.


Extension Method

Public Module Extensions
''' <summary>
''' Extension method to run string as CMD command.
''' </summary>
''' <param name="command">[String] Command to run.</param>
''' <param name="ShowWindow">[Boolean](Default:False) Option to show CMD window.</param>
''' <param name="WaitForProcessComplete">[Boolean](Default:False) Option to wait for CMD process to complete before exiting sub.</param>
''' <param name="permanent">[Boolean](Default:False) Option to keep window visible after command has finished. Ignored if ShowWindow is False.</param>
<Extension>
Public Sub RunCMD(command As String, Optional ShowWindow As Boolean = False, Optional WaitForProcessComplete As Boolean = False, Optional permanent As Boolean = False)
    Dim p As Process = New Process()
    Dim pi As ProcessStartInfo = New ProcessStartInfo()
    pi.Arguments = " " + If(ShowWindow AndAlso permanent, "/K", "/C") + " " + command
    pi.FileName = "cmd.exe"
    pi.CreateNoWindow = Not ShowWindow
    If ShowWindow Then
        pi.WindowStyle = ProcessWindowStyle.Normal
    Else
        pi.WindowStyle = ProcessWindowStyle.Hidden
    End If
    p.StartInfo = pi
    p.Start()
    If WaitForProcessComplete Then Do Until p.HasExited : Loop
End Sub
End Module

JavaScript: Upload file

Unless you're trying to upload the file using ajax, just submit the form to /upload/image.

<form enctype="multipart/form-data" action="/upload/image" method="post">
    <input id="image-file" type="file" />
</form>

If you do want to upload the image in the background (e.g. without submitting the whole form), you can use ajax:

If conditions in a Makefile, inside a target

You can simply use shell commands. If you want to suppress echoing the output, use the "@" sign. For example:

clean:
    @if [ "test" = "test" ]; then\
        echo "Hello world";\
    fi

Note that the closing ";" and "\" are necessary.

How to use GNU Make on Windows?

user1594322 gave a correct answer but when I tried it I ran into admin/permission problems. I was able to copy 'mingw32-make.exe' and paste it, over-ruling/by-passing admin issues and then editing the copy to 'make.exe'. On VirtualBox in a Win7 guest.

Getting raw SQL query string from PDO prepared statements

PDOStatement has a public property $queryString. It should be what you want.

I've just notice that PDOStatement has an undocumented method debugDumpParams() which you may also want to look at.

Regular expression for a string that does not start with a sequence

You could use a negative look-ahead assertion:

^(?!tbd_).+

Or a negative look-behind assertion:

(^.{1,3}$|^.{4}(?<!tbd_).*)

Or just plain old character sets and alternations:

^([^t]|t($|[^b]|b($|[^d]|d($|[^_])))).*

How to detect a USB drive has been plugged in?

Microsoft API Code Pack. ShellObjectWatcher class.

How can I use Async with ForEach?

Add this extension method

public static class ForEachAsyncExtension
{
    public static Task ForEachAsync<T>(this IEnumerable<T> source, int dop, Func<T, Task> body)
    {
        return Task.WhenAll(from partition in Partitioner.Create(source).GetPartitions(dop) 
            select Task.Run(async delegate
            {
                using (partition)
                    while (partition.MoveNext())
                        await body(partition.Current).ConfigureAwait(false);
            }));
    }
}

And then use like so:

Task.Run(async () =>
{
    var s3 = new AmazonS3Client(Config.Instance.Aws.Credentials, Config.Instance.Aws.RegionEndpoint);
    var buckets = await s3.ListBucketsAsync();

    foreach (var s3Bucket in buckets.Buckets)
    {
        if (s3Bucket.BucketName.StartsWith("mybucket-"))
        {
            log.Information("Bucket => {BucketName}", s3Bucket.BucketName);

            ListObjectsResponse objects;
            try
            {
                objects = await s3.ListObjectsAsync(s3Bucket.BucketName);
            }
            catch
            {
                log.Error("Error getting objects. Bucket => {BucketName}", s3Bucket.BucketName);
                continue;
            }

            // ForEachAsync (4 is how many tasks you want to run in parallel)
            await objects.S3Objects.ForEachAsync(4, async s3Object =>
            {
                try
                {
                    log.Information("Bucket => {BucketName} => {Key}", s3Bucket.BucketName, s3Object.Key);
                    await s3.DeleteObjectAsync(s3Bucket.BucketName, s3Object.Key);
                }
                catch
                {
                    log.Error("Error deleting bucket {BucketName} object {Key}", s3Bucket.BucketName, s3Object.Key);
                }
            });

            try
            {
                await s3.DeleteBucketAsync(s3Bucket.BucketName);
            }
            catch
            {
                log.Error("Error deleting bucket {BucketName}", s3Bucket.BucketName);
            }
        }
    }
}).Wait();

Execute PHP function with onclick

It can be done and with rather simple php if this is your button

<input type="submit" name="submit>

and this is your php code

if(isset($_POST["submit"])) { php code here }

the code get's called when submit get's posted which happens when the button is clicked.

Hash table runtime complexity (insert, search and delete)

Perhaps you were looking at the space complexity? That is O(n). The other complexities are as expected on the hash table entry. The search complexity approaches O(1) as the number of buckets increases. If at the worst case you have only one bucket in the hash table, then the search complexity is O(n).

Edit in response to comment I don't think it is correct to say O(1) is the average case. It really is (as the wikipedia page says) O(1+n/k) where K is the hash table size. If K is large enough, then the result is effectively O(1). But suppose K is 10 and N is 100. In that case each bucket will have on average 10 entries, so the search time is definitely not O(1); it is a linear search through up to 10 entries.

SELECT from nothing?

For ClickHouse, the nothing is system.one

SELECT 1 FROM system.one

lodash multi-column sortBy descending

As of lodash 3.5.0 you can use sortByOrder (renamed orderBy in v4.3.0):

var data = _.sortByOrder(array_of_objects, ['type','name'], [true, false]);

Since version 3.10.0 you can even use standard semantics for ordering (asc, desc):

var data = _.sortByOrder(array_of_objects, ['type','name'], ['asc', 'desc']);

In version 4 of lodash this method has been renamed orderBy:

var data = _.orderBy(array_of_objects, ['type','name'], ['asc', 'desc']);

how to get text from textview

Try Like this.

tv1.setText("  " + Integer.toString(X[i]) + "\n" + "+" + " " + Integer.toString(Y[i]));

Customize the Authorization HTTP header

I would recommend not to use HTTP authentication with custom scheme names. If you feel that you have something of generic use, you can define a new scheme, though. See http://greenbytes.de/tech/webdav/draft-ietf-httpbis-p7-auth-latest.html#rfc.section.2.3 for details.

How to get Current Timestamp from Carbon in Laravel 5

With a \ before a Class declaration you are calling the root namespace:

$now = \Carbon\Carbon::now()->timestamp;

otherwise it looks for it at the current namespace declared at the beginning of the class. other solution is to use it:

use Carbon\Carbon
$now = Carbon::now()->timestamp;

you can even assign it an alias:

use Carbon\Carbon as Time;
$now = Time::now()->timestamp;

hope it helps.

Referencing a string in a string array resource with xml

Unfortunately:

  • It seems you can not reference a single item from an array in values/arrays.xml with XML. Of course you can in Java, but not XML. There's no information on doing so in the Android developer reference, and I could not find any anywhere else.

  • It seems you can't use an array as a key in the preferences layout. Each key has to be a single value with it's own key name.

What I want to accomplish: I want to be able to loop through the 17 preferences, check if the item is checked, and if it is, load the string from the string array for that preference name.

Here's the code I was hoping would complete this task:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());  
ArrayAdapter<String> itemsArrayList = new ArrayAdapter<String>(getBaseContext(),   android.R.layout.simple_list_item_1);  
String[] itemNames = getResources().getStringArray(R.array.itemNames_array);  


for (int i = 0; i < 16; i++) {  
    if (prefs.getBoolean("itemKey[i]", true)) {  
        itemsArrayList.add(itemNames[i]);  
    }  
} 

What I did:

  • I set a single string for each of the items, and referenced the single strings in the . I use the single string reference for the preferences layout checkbox titles, and the array for my loop.

  • To loop through the preferences, I just named the keys like key1, key2, key3, etc. Since you reference a key with a string, you have the option to "build" the key name at runtime.

Here's the new code:

for (int i = 0; i < 16; i++) {  
        if (prefs.getBoolean("itemKey" + String.valueOf(i), true)) {  
        itemsArrayList.add(itemNames[i]);  
    }  
}

Getting the class name of an instance?

Alternatively you can use the classmethod decorator:

class A:
    @classmethod
    def get_classname(cls):
        return cls.__name__

    def use_classname(self):
        return self.get_classname()

Usage:

>>> A.get_classname()
'A'
>>> a = A()
>>> a.get_classname()
'A'
>>> a.use_classname()
'A'

jQuery trigger event when click outside the element

I do not think document fires the click event. Try using the body element to capture the click event. Might need to check on that...

Appending to 2D lists in Python

[[]]*3 is not the same as [[], [], []].

It's as if you'd said

a = []
listy = [a, a, a]

In other words, all three list references refer to the same list instance.

How to select id with max date group by category in PostgreSQL?

This is a perfect use-case for DISTINCT ON - a Postgres specific extension of the standard DISTINCT:

SELECT DISTINCT ON (category)
       id  -- , category, date  -- any other column (expression) from the same row
FROM   tbl
ORDER  BY category, date DESC;

Careful with descending sort order. If the column can be NULL, you may want to add NULLS LAST:

DISTINCT ON is simple and fast. Detailed explanation in this related answer:

For big tables with many rows per category consider an alternative approach:

How to convert JSON to string?

You can use the JSON stringify method.

JSON.stringify({x: 5, y: 6}); // '{"x":5,"y":6}' or '{"y":6,"x":5}'

There is pretty good support for this across the board when it comes to browsers, as shown on http://caniuse.com/#search=JSON. You will note, however, that versions of IE earlier than 8 do not support this functionality natively.

If you wish to cater to those users as well you will need a shim. Douglas Crockford has provided his own JSON Parser on github.

C# Telnet Library

Another one, it is an older project but shares the complete source code: http://telnetcsharp.codeplex.com/

Setting the default Java character encoding

mvn clean install -Dfile.encoding=UTF-8 -Dmaven.repo.local=/path-to-m2

command worked with exec-maven-plugin to resolve following error while configuring a jenkins task.

Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=512m; support was removed in 8.0
Error occurred during initialization of VM
java.nio.charset.IllegalCharsetNameException: "UTF-8"
    at java.nio.charset.Charset.checkName(Charset.java:315)
    at java.nio.charset.Charset.lookup2(Charset.java:484)
    at java.nio.charset.Charset.lookup(Charset.java:464)
    at java.nio.charset.Charset.defaultCharset(Charset.java:609)
    at sun.nio.cs.StreamEncoder.forOutputStreamWriter(StreamEncoder.java:56)
    at java.io.OutputStreamWriter.<init>(OutputStreamWriter.java:111)
    at java.io.PrintStream.<init>(PrintStream.java:104)
    at java.io.PrintStream.<init>(PrintStream.java:151)
    at java.lang.System.newPrintStream(System.java:1148)
    at java.lang.System.initializeSystemClass(System.java:1192)

Add a column to existing table and uniquely number them on MS SQL Server

If you don't want your new column to be of type IDENTITY (auto-increment), or you want to be specific about the order in which your rows are numbered, you can add a column of type INT NULL and then populate it like this. In my example, the new column is called MyNewColumn and the existing primary key column for the table is called MyPrimaryKey.

UPDATE MyTable
SET MyTable.MyNewColumn = AutoTable.AutoNum
FROM
(
    SELECT MyPrimaryKey, 
    ROW_NUMBER() OVER (ORDER BY SomeColumn, SomeOtherColumn) AS AutoNum
    FROM MyTable 
) AutoTable
WHERE MyTable.MyPrimaryKey = AutoTable.MyPrimaryKey  

This works in SQL Sever 2005 and later, i.e. versions that support ROW_NUMBER()

How to empty a file using Python

Opening a file creates it and (unless append ('a') is set) overwrites it with emptyness, such as this:

open(filename, 'w').close()

what is difference between success and .done() method of $.ajax

success is the callback that is invoked when the request is successful and is part of the $.ajax call. done is actually part of the jqXHR object returned by $.ajax(), and replaces success in jQuery 1.8.

Python write line by line to a text file

Well, the problem you have is wrong line ending/encoding for notepad. Notepad uses Windows' line endings - \r\n and you use \n.

Is this very likely to create a memory leak in Tomcat?

The message is actually pretty clear: something creates a ThreadLocal with value of type org.apache.axis.MessageContext - this is a great hint. It most likely means that Apache Axis framework forgot/failed to cleanup after itself. The same problem occurred for instance in Logback. You shouldn't bother much, but reporting a bug to Axis team might be a good idea.

Tomcat reports this error because the ThreadLocals are created per HTTP worker threads. Your application is undeployed but HTTP threads remain - and these ThreadLocals as well. This may lead to memory leaks (org.apache.axis.MessageContext can't be unloaded) and some issues when these threads are reused in the future.

For details see: http://wiki.apache.org/tomcat/MemoryLeakProtection

How to center align the ActionBar title in Android?

A Kotlin-only solution that does not require to have changes in the XML Layouts:

//Function to call in onResume() of your activity
private fun centerToolbarText() {
    val mTitleTextView = AppCompatTextView(this)
    mTitleTextView.text = title
    mTitleTextView.setSingleLine()//Remove it if you want to allow multiple lines in the toolbar
    mTitleTextView.textSize = 25f
    val layoutParams = android.support.v7.app.ActionBar.LayoutParams(
        ActionBar.LayoutParams.WRAP_CONTENT,
        ActionBar.LayoutParams.WRAP_CONTENT
    )
    layoutParams.gravity = Gravity.CENTER
    supportActionBar?.setCustomView(mTitleTextView,layoutParams)
    supportActionBar?.displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM
}

Difference between subprocess.Popen and os.system

If you check out the subprocess section of the Python docs, you'll notice there is an example of how to replace os.system() with subprocess.Popen():

sts = os.system("mycmd" + " myarg")

...does the same thing as...

sts = Popen("mycmd" + " myarg", shell=True).wait()

The "improved" code looks more complicated, but it's better because once you know subprocess.Popen(), you don't need anything else. subprocess.Popen() replaces several other tools (os.system() is just one of those) that were scattered throughout three other Python modules.

If it helps, think of subprocess.Popen() as a very flexible os.system().

How to check if character is a letter in Javascript?

With respect to those special characters not being taken into account by simpler checks such as /[a-zA-Z]/.test(c), it can be beneficial to leverage ECMAScript case transformation (toUpperCase). It will take into account non-ASCII Unicode character classes of some foreign alphabets.

function isLetter(c) {
  return c.toLowerCase() != c.toUpperCase();
}

NOTE: this solution will work only for most Latin, Greek, Armenian and Cyrillic scripts. It will NOT work for Chinese, Japanese, Arabic, Hebrew and most other scripts.

Create a root password for PHPMyAdmin

I just faced the mysql user password problem - ERROR 1045: Access denied for user: 'root@localhost' (Using password: NO) - when I tried to do a do-release-upgrade on my operational system. So I corrected it in 2 steps.

Firstly, as I did not had access on phpmyadmin, so I followed the "Recover MySQL root password" step on the tutorial mensioned by ThoKra: https://www.howtoforge.com/setting-changing-resetting-mysql-root-passwords

Secondly, with one of the users that I know the password, I made some password changes to the others users through phpmyadmin itself according to SonDang's information.

Install sbt on ubuntu

As an alternative approach, you can save the SBT Extras script to a file called sbt.sh and set the permission to executable. Then add this file to your path, or just put it under your ~/bin directory.

The bonus here, is that it will download and use the correct version of SBT depending on your project properties. This is a nice convenience if you tend to compile open source projects that you pull from GitHub and other.

%matplotlib line magic causes SyntaxError in Python script

There are several reasons as to why this wouldn't work.

It is possible that matplotlib is not properly installed. have you tried running:

conda install matplotlib

If that doesn't work, look at your %PATH% environment variable, does it contain your libraries and python paths?

Similar problem on github anaconda

commons httpclient - Adding query string parameters to GET/POST request

I am using httpclient 4.4.

For solr query I used the following way and it worked.

NameValuePair nv2 = new BasicNameValuePair("fq","(active:true) AND (category:Fruit OR category1:Vegetable)");
nvPairList.add(nv2);
NameValuePair nv3 = new BasicNameValuePair("wt","json");
nvPairList.add(nv3);
NameValuePair nv4 = new BasicNameValuePair("start","0");
nvPairList.add(nv4);
NameValuePair nv5 = new BasicNameValuePair("rows","10");
nvPairList.add(nv5);

HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
URI uri = new URIBuilder(request.getURI()).addParameters(nvPairList).build();
            request.setURI(uri);

HttpResponse response = client.execute(request);    
if (response.getStatusLine().getStatusCode() != 200) {

}

BufferedReader br = new BufferedReader(
                             new InputStreamReader((response.getEntity().getContent())));

String output;
System.out.println("Output  .... ");
String respStr = "";
while ((output = br.readLine()) != null) {
    respStr = respStr + output;
    System.out.println(output);
}

MySQL: is a SELECT statement case sensitive?

Marc B's answer is mostly correct.

If you are using a nonbinary string (CHAR, VARCHAR, TEXT), comparisons are case-insensitive, per the default collation.

If you are using a binary string (BINARY, VARBINARY, BLOB), comparisons are case-sensitive, so you'll need to use LOWER as described in other answers.

If you are not using the default collation and you are using a nonbinary string, case sensitivity is decided by the chosen collation.

Source: https://dev.mysql.com/doc/refman/8.0/en/case-sensitivity.html. Read closely. Some others have mistaken it to say that comparisons are necessarily case-sensitive or insensitive. This is not the case.

Sleep function in Windows, using C

MSDN: Header: Winbase.h (include Windows.h)

XmlSerializer giving FileNotFoundException at constructor

This exception can also be trapped by a managed debugging assistant (MDA) called BindingFailure.

This MDA is useful if your application is designed to ship with pre-build serialization assemblies. We do this to increase performance for our application. It allows us to make sure that the pre-built serialization assemblies are being properly built by our build process, and loaded by the application without being re-built on the fly.

It's really not useful except in this scenario, because as other posters have said, when a binding error is trapped by the Serializer constructor, the serialization assembly is re-built at runtime. So you can usually turn it off.

Find all special characters in a column in SQL Server 2008

The following transact SQL script works for all languages (international). The solution is not to check for alphanumeric but to check for not containing special characters.

DECLARE @teststring nvarchar(max)
SET @teststring = 'Test''Me'
SELECT 'IS ALPHANUMERIC: ' + @teststring
WHERE @teststring NOT LIKE '%[-!#%&+,./:;<=>@`{|}~"()*\\\_\^\?\[\]\'']%' {ESCAPE '\'}

ImportError: No module named enum

Or run a pip install --upgrade pip enum34

Access elements of parent window from iframe

I think you can just use window.parent from the iframe. window.parent returns the window object of the parent page, so you could do something like:

window.parent.document.getElementById('yourdiv');

Then do whatever you want with that div.

Flutter: RenderBox was not laid out

i

I used this code to fix the issue of displaying items in the horizontal list.

new Container(
      height: 20,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget>[
          ListView.builder(
            scrollDirection: Axis.horizontal,
            shrinkWrap: true,
            itemCount: array.length,
            itemBuilder: (context, index){
              return array[index];
            },
          ),
        ],
      ),
    );

show more/Less text with just HTML and JavaScript

Try to toggle height.

function toggleTextArea()
{
  var limitedHeight = '40px';
  var targetEle = document.getElementById("textarea");
  targetEle.style.height = (targetEle.style.height === '') ? limitedHeight : '';
}

How do I find the value of $CATALINA_HOME?

Just as a addition. You can find the Catalina Paths in

->RUN->RUN CONFIGURATIONS->APACHE TOMCAT->ARGUMENTS

In the VM Arguments the Paths are listed and changeable

How to change the value of ${user} variable used in Eclipse templates

EGit Solution

One would expect creating or changing template variables on a project-, workspace-, or environment-basis is a standard Eclipse feature. Sadly, it is not. More so, given that Eclipse plugins can define new variables and templates, there should be plugins out there providing a solution. If they are, they must be hard to find. mmm-TemplateVariable, which is available in the Eclipse Marketplace, is a step in the right direction for Maven users, giving the ability to include version, artifactId, etc. in templates.

Fortunately, EGit, which is an Eclipse tool for Git, provides very flexible means for including many different variables in code templates. The only requirement is that your project uses Git. If you don’t use Git, but are serious about software development, now is the time to learn (Pro Git book). If you are forced to use a legacy version control system, try changing some minds.

Thanks to the efforts of harmsk, EGit 4.0 and above includes the ability to use Git configuration key values in templates. This allows setting template values based on repository settings (project), user settings (account), and/or global settings (workstation).

The following example shows how to set up Eclipse and Git for a multi-user development workstation and use a custom Git configuration key in lieu of ${user} to provide more flexibility. Although the example is based on a Windows 10 installation of Eclipse Mars and Git for Windows, the example is applicable to Linux and OSX running Eclipse and Git using their respective command line tools.

To avoid possible confusion between Git’s user.name configuration key and Java’s user.name system property, a custom Git configuration key – user.author – will be used to provide an author’s name and/or credentials.

Configuring Templates

The format of a Git template variable is as follows

${<name>:git_config(<key>)}

where <name> is any arbitrary variable name and <key> is the Git configuration key whose value should be used. Given that, changing the Comments?Types template to

/**
 * @author ${author:git_config(user.author)}
 *
 * ${tags}
 */

will now attempt to resolve the author’s name from Git’s user.author configuration key. Without any further configuration, any newly created comments will not include a name after @author, since none has been defined yet.

Configuring Git

From the command line

Git System Configuration - This configuration step makes changes to Git’s system-wide configuration applicable to all accounts on the workstation unless overridden by user or repository settings. Because system-wide configurations are part the underlying Git application (e.g. Git for Windows), changes will require Administrator privileges. Run Git Bash, cmd, or PowerShell as Administrator. The following command will set the system-wide author.

git config --system user.author “SET ME IN GLOBAL(USER) or REPOSITORY(LOCAL) SETTINGS”

The purpose of this “author” is to serve as a reminder that it should be set elsewhere. This is particularly useful when new user accounts are being used on the workstation.

To verify this setting, create an empty Java project that uses Git or open an existing Git-based project. Create a class and use Source?Generate Element Comment from the context menu, ALT-SHIFT-J, or start a JavaDoc comment. The resulting @author tag should be followed by the warning.

The remaining configuration changes can be performed without Administrator privileges.

Git Global(User) Configuration - Global, or user, configurations are those associated with a specific user and will override system-wide configurations. These settings apply to all Git-based projects unless overridden by repository settings. If the author name is different due to various project types such as for work, open source contributions, or personal, set the most frequently used here.

git config --global user.author “Mr. John Smith”

Having configured the global value, return to the test project used early and apply a class comment. The@author tag should now show the global setting.

Git Repository(Local) Configuration - Lastly, a repository or local configuration can be used to configure an author for a specific project. Unlike the previous configurations, a repository configuration must be done from within the repository. Using Git Bash, PowerShell, etc. navigate into the test project’s repository.

git config --local user.author “smithy”

Given this, new comments in the test project will use the locally defined author name. Other Git-based projects, will still use the global author name.

From Within Eclipse

The configuration changes above can also be set from within Eclipse through its Preferences: Team?Git-Configuration. Eclipse must be run as Administrator to change system-wide Git configurations.

In Sum

Although this example dealt specifically with the most common issue, that of changing ${user}, this approach can be used for more. However, caution should be exercised not to use Git-defined configuration keys, unless it is specifically intended.

How to verify element present or visible in selenium 2 (Selenium WebDriver)

To check if element is visible we need to use element.isDisplayed(); But if we need to check for presence of element anywhere in Dom we can use following method

public boolean isElementPresentCheckUsingJavaScriptExecutor(WebElement element) {
        JavascriptExecutor jse=(JavascriptExecutor) driver;
        try {
            Object obj = jse.execute("return typeof(arguments[0]) != 'undefined' && arguments[0] != null;",
                    element);
            if (obj.toString().contains("true")) {
                System.out.println("isElementPresentCheckUsingJavaScriptExecutor: SUCCESS");
                return true;
            } else {
                System.out.println("isElementPresentCheckUsingJavaScriptExecutor: FAIL");
            }

        } catch (NoSuchElementException e) {
            System.out.println("isElementPresentCheckUsingJavaScriptExecutor: FAIL");
        }
        return false;
    }

How do you add an in-app purchase to an iOS application?

Swift Answer

This is meant to supplement my Objective-C answer for Swift users, to keep the Objective-C answer from getting too big.

Setup

First, set up the in-app purchase on appstoreconnect.apple.com. Follow the beginning part of my Objective-C answer (steps 1-13, under the App Store Connect header) for instructions on doing that.

It could take a few hours for your product ID to register in App Store Connect, so be patient.

Now that you've set up your in-app purchase information on App Store Connect, we need to add Apple's framework for in-app-purchases, StoreKit, to the app.

Go into your Xcode project, and go to the application manager (blue page-like icon at the top of the left bar where your app's files are). Click on your app under targets on the left (it should be the first option), then go to "Capabilities" at the top. On the list, you should see an option "In-App Purchase". Turn this capability ON, and Xcode will add StoreKit to your project.

Coding

Now, we're going to start coding!

First, make a new swift file that will manage all of your in-app-purchases. I'm going to call it IAPManager.swift.

In this file, we're going to create a new class, called IAPManager that is a SKProductsRequestDelegate and SKPaymentTransactionObserver. At the top, make sure you import Foundation and StoreKit

import Foundation
import StoreKit

public class IAPManager: NSObject, SKProductsRequestDelegate,
                         SKPaymentTransactionObserver {
}

Next, we're going to add a variable to define the identifier for our in-app purchase (you could also use an enum, which would be easier to maintain if you have multiple IAPs).

// This should the ID of the in-app-purchase you made on AppStore Connect.
// if you have multiple IAPs, you'll need to store their identifiers in
// other variables, too (or, preferably in an enum).
let removeAdsID = "com.skiplit.removeAds"

Let's add an initializer for our class next:

// This is the initializer for your IAPManager class
//
// A better, and more scaleable way of doing this
// is to also accept a callback in the initializer, and call
// that callback in places like the paymentQueue function, and
// in all functions in this class, in place of calls to functions
// in RemoveAdsManager (you'll see those calls in the code below).

let productID: String
init(productID: String){
    self.productID = productID
}

Now, we're going to add the required functions for SKProductsRequestDelegate and SKPaymentTransactionObserver to work:

We'll add the RemoveAdsManager class later

// This is called when a SKProductsRequest receives a response
public func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse){
    // Let's try to get the first product from the response
    // to the request
    if let product = response.products.first{
        // We were able to get the product! Make a new payment
        // using this product
        let payment = SKPayment(product: product)

        // add the new payment to the queue
        SKPaymentQueue.default().add(self)
        SKPaymentQueue.default().add(payment)
    }
    else{
        // Something went wrong! It is likely that either
        // the user doesn't have internet connection, or
        // your product ID is wrong!
        //
        // Tell the user in requestFailed() by sending an alert,
        // or something of the sort

        RemoveAdsManager.removeAdsFailure()
    }
}

// This is called when the user restores their IAP sucessfully
private func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue){
    // For every transaction in the transaction queue...
    for transaction in queue.transactions{
        // If that transaction was restored
        if transaction.transactionState == .restored{
            // get the producted ID from the transaction
            let productID = transaction.payment.productIdentifier

            // In this case, we have only one IAP, so we don't need to check
            // what IAP it is. However, this is useful if you have multiple IAPs!
            // You'll need to figure out which one was restored
            if(productID.lowercased() == IAPManager.removeAdsID.lowercased()){
                // Restore the user's purchases
                RemoveAdsManager.restoreRemoveAdsSuccess()
            }

            // finish the payment
            SKPaymentQueue.default().finishTransaction(transaction)
        }
    }
}

// This is called when the state of the IAP changes -- from purchasing to purchased, for example.
// This is where the magic happens :)
public func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]){
    for transaction in transactions{
        // get the producted ID from the transaction
        let productID = transaction.payment.productIdentifier

        // In this case, we have only one IAP, so we don't need to check
        // what IAP it is.
        // However, if you have multiple IAPs, you'll need to use productID
        // to check what functions you should run here!

        switch transaction.transactionState{
        case .purchasing:
            // if the user is currently purchasing the IAP,
            // we don't need to do anything.
            //
            // You could use this to show the user
            // an activity indicator, or something like that
            break
        case .purchased:
            // the user successfully purchased the IAP!
            RemoveAdsManager.removeAdsSuccess()
            SKPaymentQueue.default().finishTransaction(transaction)
        case .restored:
                // the user restored their IAP!
                IAPTestingHandler.restoreRemoveAdsSuccess()
                SKPaymentQueue.default().finishTransaction(transaction)
        case .failed:
                // The transaction failed!
                RemoveAdsManager.removeAdsFailure()
                // finish the transaction
                SKPaymentQueue.default().finishTransaction(transaction)
        case .deferred:
                // This happens when the IAP needs an external action
                // in order to proceeded, like Ask to Buy
                RemoveAdsManager.removeAdsDeferred()
                break
        }
    }
}

Now let's add some functions that can be used to start a purchase or a restore purchases:

// Call this when you want to begin a purchase
// for the productID you gave to the initializer
public func beginPurchase(){
    // If the user can make payments
    if SKPaymentQueue.canMakePayments(){
        // Create a new request
        let request = SKProductsRequest(productIdentifiers: [productID])
        // Set the request delegate to self, so we receive a response
        request.delegate = self
        // start the request
        request.start()
    }
    else{
        // Otherwise, tell the user that
        // they are not authorized to make payments,
        // due to parental controls, etc
    }
}

// Call this when you want to restore all purchases
// regardless of the productID you gave to the initializer
public func beginRestorePurchases(){
    // restore purchases, and give responses to self
    SKPaymentQueue.default().add(self)
    SKPaymentQueue.default().restoreCompletedTransactions()
}

Next, let's add a new utilities class to manage our IAPs. All of this code could be in one class, but having it multiple makes it a little cleaner. I'm going to make a new class called RemoveAdsManager, and in it, put a few functions

public class RemoveAdsManager{

    class func removeAds()
    class func restoreRemoveAds()

    class func areAdsRemoved() -> Bool

    class func removeAdsSuccess()
    class func restoreRemoveAdsSuccess()
    class func removeAdsDeferred()
    class func removeAdsFailure()
}

The first three functions, removeAds, restoreRemoveAds, and areAdsRemoved, are functions that you'll call to do certain actions. The last four are one that will be called by IAPManager.

Let's add some code to the first two functions, removeAds and restoreRemoveAds:

// Call this when the user wants
// to remove ads, like when they
// press a "remove ads" button
class func removeAds(){
    // Before starting the purchase, you could tell the
    // user that their purchase is happening, maybe with
    // an activity indicator

    let iap = IAPManager(productID: IAPManager.removeAdsID)
    iap.beginPurchase()
}

// Call this when the user wants
// to restore their IAP purchases,
// like when they press a "restore
// purchases" button.
class func restoreRemoveAds(){
    // Before starting the purchase, you could tell the
    // user that the restore action is happening, maybe with
    // an activity indicator

    let iap = IAPManager(productID: IAPManager.removeAdsID)
    iap.beginRestorePurchases()
}

And lastly, let's add some code to the last five functions.

// Call this to check whether or not
// ads are removed. You can use the
// result of this to hide or show
// ads
class func areAdsRemoved() -> Bool{
    // This is the code that is run to check
    // if the user has the IAP.

    return UserDefaults.standard.bool(forKey: "RemoveAdsPurchased")
}

// This will be called by IAPManager
// when the user sucessfully purchases
// the IAP
class func removeAdsSuccess(){
    // This is the code that is run to actually
    // give the IAP to the user!
    //
    // I'm using UserDefaults in this example,
    // but you may want to use Keychain,
    // or some other method, as UserDefaults
    // can be modified by users using their
    // computer, if they know how to, more
    // easily than Keychain

    UserDefaults.standard.set(true, forKey: "RemoveAdsPurchased")
    UserDefaults.standard.synchronize()
}

// This will be called by IAPManager
// when the user sucessfully restores
//  their purchases
class func restoreRemoveAdsSuccess(){
    // Give the user their IAP back! Likely all you'll need to
    // do is call the same function you call when a user
    // sucessfully completes their purchase. In this case, removeAdsSuccess()

    removeAdsSuccess()
}

// This will be called by IAPManager
// when the IAP failed
class func removeAdsFailure(){
    // Send the user a message explaining that the IAP
    // failed for some reason, and to try again later
}

// This will be called by IAPManager
// when the IAP gets deferred.
class func removeAdsDeferred(){
    // Send the user a message explaining that the IAP
    // was deferred, and pending an external action, like
    // Ask to Buy.
}

Putting it all together, we get something like this:

import Foundation
import StoreKit

public class RemoveAdsManager{

    // Call this when the user wants
    // to remove ads, like when they
    // press a "remove ads" button
    class func removeAds(){
        // Before starting the purchase, you could tell the
        // user that their purchase is happening, maybe with
        // an activity indicator

        let iap = IAPManager(productID: IAPManager.removeAdsID)
        iap.beginPurchase()
    }

    // Call this when the user wants
    // to restore their IAP purchases,
    // like when they press a "restore
    // purchases" button.
    class func restoreRemoveAds(){
        // Before starting the purchase, you could tell the
        // user that the restore action is happening, maybe with
        // an activity indicator

        let iap = IAPManager(productID: IAPManager.removeAdsID)
        iap.beginRestorePurchases()
    }

    // Call this to check whether or not
    // ads are removed. You can use the
    // result of this to hide or show
    // ads
    class func areAdsRemoved() -> Bool{
        // This is the code that is run to check
        // if the user has the IAP.

        return UserDefaults.standard.bool(forKey: "RemoveAdsPurchased")
    }

    // This will be called by IAPManager
    // when the user sucessfully purchases
    // the IAP
    class func removeAdsSuccess(){
        // This is the code that is run to actually
        // give the IAP to the user!
        //
        // I'm using UserDefaults in this example,
        // but you may want to use Keychain,
        // or some other method, as UserDefaults
        // can be modified by users using their
        // computer, if they know how to, more
        // easily than Keychain

        UserDefaults.standard.set(true, forKey: "RemoveAdsPurchased")
        UserDefaults.standard.synchronize()
    }

    // This will be called by IAPManager
    // when the user sucessfully restores
    //  their purchases
    class func restoreRemoveAdsSuccess(){
        // Give the user their IAP back! Likely all you'll need to
        // do is call the same function you call when a user
        // sucessfully completes their purchase. In this case, removeAdsSuccess()
        removeAdsSuccess()
    }

    // This will be called by IAPManager
    // when the IAP failed
    class func removeAdsFailure(){
        // Send the user a message explaining that the IAP
        // failed for some reason, and to try again later
    }

    // This will be called by IAPManager
    // when the IAP gets deferred.
    class func removeAdsDeferred(){
        // Send the user a message explaining that the IAP
        // was deferred, and pending an external action, like
        // Ask to Buy.
    }

}

public class IAPManager: NSObject, SKProductsRequestDelegate, SKPaymentTransactionObserver{

    // This should the ID of the in-app-purchase you made on AppStore Connect.
    // if you have multiple IAPs, you'll need to store their identifiers in
    // other variables, too (or, preferably in an enum).
    static let removeAdsID = "com.skiplit.removeAds"

    // This is the initializer for your IAPManager class
    //
    // An alternative, and more scaleable way of doing this
    // is to also accept a callback in the initializer, and call
    // that callback in places like the paymentQueue function, and
    // in all functions in this class, in place of calls to functions
    // in RemoveAdsManager.
    let productID: String
    init(productID: String){
        self.productID = productID
    }

    // Call this when you want to begin a purchase
    // for the productID you gave to the initializer
    public func beginPurchase(){
        // If the user can make payments
        if SKPaymentQueue.canMakePayments(){
            // Create a new request
            let request = SKProductsRequest(productIdentifiers: [productID])
            request.delegate = self
            request.start()
        }
        else{
            // Otherwise, tell the user that
            // they are not authorized to make payments,
            // due to parental controls, etc
        }
    }

    // Call this when you want to restore all purchases
    // regardless of the productID you gave to the initializer
    public func beginRestorePurchases(){
        SKPaymentQueue.default().add(self)
        SKPaymentQueue.default().restoreCompletedTransactions()
    }

    // This is called when a SKProductsRequest receives a response
    public func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse){
        // Let's try to get the first product from the response
        // to the request
        if let product = response.products.first{
            // We were able to get the product! Make a new payment
            // using this product
            let payment = SKPayment(product: product)

            // add the new payment to the queue
            SKPaymentQueue.default().add(self)
            SKPaymentQueue.default().add(payment)
        }
        else{
            // Something went wrong! It is likely that either
            // the user doesn't have internet connection, or
            // your product ID is wrong!
            //
            // Tell the user in requestFailed() by sending an alert,
            // or something of the sort

            RemoveAdsManager.removeAdsFailure()
        }
    }

    // This is called when the user restores their IAP sucessfully
    private func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue){
        // For every transaction in the transaction queue...
        for transaction in queue.transactions{
            // If that transaction was restored
            if transaction.transactionState == .restored{
                // get the producted ID from the transaction
                let productID = transaction.payment.productIdentifier

                // In this case, we have only one IAP, so we don't need to check
                // what IAP it is. However, this is useful if you have multiple IAPs!
                // You'll need to figure out which one was restored
                if(productID.lowercased() == IAPManager.removeAdsID.lowercased()){
                    // Restore the user's purchases
                    RemoveAdsManager.restoreRemoveAdsSuccess()
                }

                // finish the payment
                SKPaymentQueue.default().finishTransaction(transaction)
            }
        }
    }

    // This is called when the state of the IAP changes -- from purchasing to purchased, for example.
    // This is where the magic happens :)
    public func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]){
        for transaction in transactions{
            // get the producted ID from the transaction
            let productID = transaction.payment.productIdentifier

            // In this case, we have only one IAP, so we don't need to check
            // what IAP it is.
            // However, if you have multiple IAPs, you'll need to use productID
            // to check what functions you should run here!

            switch transaction.transactionState{
            case .purchasing:
                // if the user is currently purchasing the IAP,
                // we don't need to do anything.
                //
                // You could use this to show the user
                // an activity indicator, or something like that
                break
            case .purchased:
                // the user sucessfully purchased the IAP!
                RemoveAdsManager.removeAdsSuccess()
                SKPaymentQueue.default().finishTransaction(transaction)
            case .restored:
                // the user restored their IAP!
                RemoveAdsManager.restoreRemoveAdsSuccess()
                SKPaymentQueue.default().finishTransaction(transaction)
            case .failed:
                // The transaction failed!
                RemoveAdsManager.removeAdsFailure()
                // finish the transaction
                SKPaymentQueue.default().finishTransaction(transaction)
            case .deferred:
                // This happens when the IAP needs an external action
                // in order to proceeded, like Ask to Buy
                RemoveAdsManager.removeAdsDeferred()
                break
            }
        }
    }

}

Lastly, you need to add some way for the user to start the purchase and call RemoveAdsManager.removeAds() and start a restore and call RemoveAdsManager.restoreRemoveAds(), like a button somewhere! Keep in mind that, per the App Store guidelines, you do need to provide a button to restore purchases somewhere.

Submitting for review

The last thing to do is submit your IAP for review on App Store Connect! For detailed instructions on doing that, you can follow the last part of my Objective-C answer, under the Submitting for review header.

PHP How to fix Notice: Undefined variable:

I would guess your query isn't running as expected and you are getting to the return line with undefined variables.

Also, the way you are doing the variable assignment, you would be overwriting the same variable with each loop iteration, so you wouldn't return the entire result set.

Finally, it seems odd to return a numerically-keyed result set instead of an associatively-keyed one. Consider naming only the fields needed in the SELECT and keeping the key assignments. So something like this:

Function ShowDataPatient($idURL){
       $query =" select * from cmu_list_insurance,cmu_home,cmu_patient where cmu_home.home_id = (select home_id from cmu_patient where patient_hn like '%$idURL%')
                 AND cmu_patient.patient_hn like '%$idURL%'
                 AND cmu_list_insurance.patient_id like (select patient_id from cmu_patient where patient_hn like '%$idURL%') ";

   $result = pg_query($query) or die('Query failed: ' . pg_last_error());

   $return = array();
   while ($row = pg_fetch_array($result)){
       $return[] = $row;
   }          

   return $return;
}

You might also consider opening a question about how to improve your query, is it is pretty heinous as it stands now.

How can query string parameters be forwarded through a proxy_pass with nginx?

github gist https://gist.github.com/anjia0532/da4a17f848468de5a374c860b17607e7

#set $token "?"; # deprecated

set $token ""; # declar token is ""(empty str) for original request without args,because $is_args concat any var will be `?`

if ($is_args) { # if the request has args update token to "&"
    set $token "&";
}

location /test {
    set $args "${args}${token}k1=v1&k2=v2"; # update original append custom params with $token
    # if no args $is_args is empty str,else it's "?"
    # http is scheme
    # service is upstream server
    #proxy_pass http://service/$uri$is_args$args; # deprecated remove `/`
    proxy_pass http://service$uri$is_args$args; # proxy pass
}

#http://localhost/test?foo=bar ==> http://service/test?foo=bar&k1=v1&k2=v2

#http://localhost/test/ ==> http://service/test?k1=v1&k2=v2

Wait for page load in Selenium

In python, you can simply use:

driver.implicitly_wait(30)

How to get two or more commands together into a batch file

Try this: edited

@echo off
set "comd=dir /b /s *.zip"
set "pathName="
set /p "pathName=Enter The Value: "
cd /d "%pathName%"
%comd%
pause

What is a magic number, and why is it bad?

A magic number can also be a number with special, hardcoded semantics. For example, I once saw a system where record IDs > 0 were treated normally, 0 itself was "new record", -1 was "this is the root" and -99 was "this was created in the root". 0 and -99 would cause the WebService to supply a new ID.

What's bad about this is that you're reusing a space (that of signed integers for record IDs) for special abilities. Maybe you'll never want to create a record with ID 0, or with a negative ID, but even if not, every person who looks either at the code or at the database might stumble on this and be confused at first. It goes without saying those special values weren't well-documented.

Arguably, 22, 7, -12 and 620 count as magic numbers, too. ;-)

How to run a .jar in mac?

Make Executable your jar and after that double click on it on Mac OS then it works successfully.

sudo chmod +x filename.jar

Try this, I hope this works.

How to delete an app from iTunesConnect / App Store Connect

As per 2018 in App Store Connect. We can delete/remove application with following stats.

enter image description here

App Store Connect details for Remove an app

So, from now onwards we can delete our test applications too from app store connect.

enter image description here

Why is semicolon allowed in this python snippet?

Semicolon (";") is only needed for separation of statements within a same block, such as if we have the following C code:

if(a>b)
{
largest=a;  //here largest and count are integer variables
count+=1;
}

It can be written in Python in either of the two forms:

if a>b:   
    largest=a
    count=count+1

Or

if a>b:    largest=a;count=count+1

In the above example you could have any number of statements within an if block and can be separated by ";" instead.

Hope that nothing is as simple as above explanation.

Trigger Change event when the Input value changed programmatically?

You are using jQuery, right? Separate JavaScript from HTML.

You can use trigger or triggerHandler.

var $myInput = $('#changeProgramatic').on('change', ChangeValue);

var anotherFunction = function() {
  $myInput.val('Another value');
  $myInput.trigger('change');
};

COPYing a file in a Dockerfile, no such file or directory?

Previous calls on COPY may be changing the directory.

COPY ./server/package.json ./server      # this passes, but the dest ./server is considered a file

COPY ./server/dist ./server/dist         # error, ./server/dist is not a directory

Add a trailing slash to the first call

COPY ./server/package.json ./server/

Is there a way to specify a max height or width for an image?

editied to add support for ie6:

Try

<img style="height:725px;max-width:500px;width: expression(this.width > 500 ? 500: true);" id="img_DocPreview" src="Images/empty.jpg" />

This should set the height to 725px but prevent the width from exceeding 500px. The width expression works around ie6 and is ignored by other browsers.

How to find a min/max with Ruby

All those results generate garbage in a zealous attempt to handle more than two arguments. I'd be curious to see how they perform compared to good 'ol:

def max (a,b)
  a>b ? a : b
end

which is, by-the-way, my official answer to your question.

How to skip "are you sure Y/N" when deleting files in batch files

Use del /F /Q to force deletion of read-only files (/F) and directories and not ask to confirm (/Q) when deleting via wildcard.

Multiple aggregations of the same column using pandas GroupBy.agg()

Would something like this work:

In [7]: df.groupby('dummy').returns.agg({'func1' : lambda x: x.sum(), 'func2' : lambda x: x.prod()})
Out[7]: 
              func2     func1
dummy                        
1     -4.263768e-16 -0.188565

Javascript reduce() on Object

Try this one. It will sort numbers from other variables.

const obj = {
   a: 1,
   b: 2,
   c: 3
};
const result = Object.keys(obj)
.reduce((acc, rec) => typeof obj[rec] === "number" ? acc.concat([obj[rec]]) : acc, [])
.reduce((acc, rec) => acc + rec)

How to write a shell script that runs some commands as superuser and some commands not as superuser, without having to babysit it?

File sutest

#!/bin/bash
echo "uid is ${UID}"
echo "user is ${USER}"
echo "username is ${USERNAME}"

run it: `./sutest' gives me

uid is 500
user is stephenp
username is stephenp

but using sudo: sudo ./sutest gives

uid is 0
user is root
username is stephenp

So you retain the original user name in $USERNAME when running as sudo. This leads to a solution similar to what others posted:

#!/bin/bash
sudo -u ${USERNAME} normal_command_1
root_command_1
root_command_2
sudo -u ${USERNAME} normal_command_2
# etc.

Just sudo to invoke your script in the first place, it will prompt for the password once.


I originally wrote this answer on Linux, which does have some differences with OS X

OS X (I'm testing this on Mountain Lion 10.8.3) has an environment variable SUDO_USER when you're running sudo, which can be used in place of USERNAME above, or to be more cross-platform the script could check to see if SUDO_USER is set and use it if so, or use USERNAME if that's set.

Changing the original script for OS X, it becomes...

#!/bin/bash
sudo -u ${SUDO_USER} normal_command_1
root_command_1
root_command_2
sudo -u ${SUDO_USER} normal_command_2
# etc.

A first stab at making it cross-platform could be...

#!/bin/bash
#
# set "THE_USER" to SUDO_USER if that's set,
#  else set it to USERNAME if THAT is set,
#   else set it to the string "unknown"
# should probably then test to see if it's "unknown"
#
THE_USER=${SUDO_USER:-${USERNAME:-unknown}}

sudo -u ${THE_USER} normal_command_1
root_command_1
root_command_2
sudo -u ${THE_USER} normal_command_2
# etc.

import error: 'No module named' *does* exist

I met the same problem, and I try the pdb.set_trace() before the error line.

My problem is the package name duplicate with the module name, like:

test
+-- __init__.py
+-- a
¦   +-- __init__.py
¦   +-- test.py
+-- b
    +-- __init__.py

and at file a/__init__.py, using from test.b import xxx will cause ImportError: No module named b.

Efficiently replace all accented characters in a string?

Not a single answer mentions String.localeCompare, which happens to do exactly what you originally wanted, but not what you're asking for.

var list = ['a', 'b', 'c', 'o', 'u', 'z', 'ä', 'ö', 'ü'];

list.sort((a, b) => a.localeCompare(b));

console.log(list);

//Outputs ['a', 'ä', 'b', 'c', 'o', 'ö', 'u', 'ü', 'z']

The second and third parameter are not supported by older browsers though. It's an option worth considering nonetheless.

C# equivalent to Java's charAt()?

Simply use String.ElementAt(). It's quite similar to java's String.charAt(). Have fun coding!

WebAPI Multiple Put/Post parameters

Request parameters like

enter image description here

Web api Code be like

public class OrderItemDetailsViewModel
{
    public Order order { get; set; }
    public ItemDetails[] itemDetails { get; set; }
}

public IHttpActionResult Post(OrderItemDetailsViewModel orderInfo)
{
    Order ord = orderInfo.order;
    var ordDetails = orderInfo.itemDetails;
    return Ok();
}

move column in pandas dataframe

You can rearrange columns directly by specifying their order:

df = df[['a', 'y', 'b', 'x']]

In the case of larger dataframes where the column titles are dynamic, you can use a list comprehension to select every column not in your target set and then append the target set to the end.

>>> df[[c for c in df if c not in ['b', 'x']] 
       + ['b', 'x']]
   a  y  b   x
0  1 -1  2   3
1  2 -2  4   6
2  3 -3  6   9
3  4 -4  8  12

To make it more bullet proof, you can ensure that your target columns are indeed in the dataframe:

cols_at_end = ['b', 'x']
df = df[[c for c in df if c not in cols_at_end] 
        + [c for c in cols_at_end if c in df]]

Nested Git repositories?

I would use one repository per project. That way, the history becomes easier to browse through.

I would also check the version of the third party library I'm using, into the repository of the project using it.

Should I declare Jackson's ObjectMapper as a static field?

Yes, that is safe and recommended.

The only caveat from the page you referred is that you can't be modifying configuration of the mapper once it is shared; but you are not changing configuration so that is fine. If you did need to change configuration, you would do that from the static block and it would be fine as well.

EDIT: (2013/10)

With 2.0 and above, above can be augmented by noting that there is an even better way: use ObjectWriter and ObjectReader objects, which can be constructed by ObjectMapper. They are fully immutable, thread-safe, meaning that it is not even theoretically possible to cause thread-safety issues (which can occur with ObjectMapper if code tries to re-configure instance).

Is it possible to force row level locking in SQL Server?

Use the ALLOW_PAGE_LOCKS clause of ALTER/CREATE INDEX:

ALTER INDEX indexname ON tablename SET (ALLOW_PAGE_LOCKS = OFF);

Regex to remove all special characters from string?

tmp = Regex.Replace(n, @"\W+", "");

\w matches letters, digits, and underscores, \W is the negated version.

unique() for more than one variable

This is an addition to Josh's answer.

You can also keep the values of other variables while filtering out duplicated rows in data.table

Example:

library(data.table)

#create data table
dt <- data.table(
  V1=LETTERS[c(1,1,1,1,2,3,3,5,7,1)],
  V2=LETTERS[c(2,3,4,2,1,4,4,6,7,2)],
  V3=c(1),
  V4=c(2) )

> dt
# V1 V2 V3 V4
# A  B  1  2
# A  C  1  2
# A  D  1  2
# A  B  1  2
# B  A  1  2
# C  D  1  2
# C  D  1  2
# E  F  1  2
# G  G  1  2
# A  B  1  2

# set the key to all columns
setkey(dt)

# Get Unique lines in the data table
unique( dt[list(V1, V2), nomatch = 0] ) 

# V1 V2 V3 V4
# A  B  1  2
# A  C  1  2
# A  D  1  2
# B  A  1  2
# C  D  1  2
# E  F  1  2
# G  G  1  2

Alert: If there are different combinations of values in the other variables, then your result will be

unique combination of V1 and V2

Utilizing multi core for tar+gzip/bzip compression/decompression

Common approach

There is option for tar program:

-I, --use-compress-program PROG
      filter through PROG (must accept -d)

You can use multithread version of archiver or compressor utility.

Most popular multithread archivers are pigz (instead of gzip) and pbzip2 (instead of bzip2). For instance:

$ tar -I pbzip2 -cf OUTPUT_FILE.tar.bz2 paths_to_archive
$ tar --use-compress-program=pigz -cf OUTPUT_FILE.tar.gz paths_to_archive

Archiver must accept -d. If your replacement utility hasn't this parameter and/or you need specify additional parameters, then use pipes (add parameters if necessary):

$ tar cf - paths_to_archive | pbzip2 > OUTPUT_FILE.tar.gz
$ tar cf - paths_to_archive | pigz > OUTPUT_FILE.tar.gz

Input and output of singlethread and multithread are compatible. You can compress using multithread version and decompress using singlethread version and vice versa.

p7zip

For p7zip for compression you need a small shell script like the following:

#!/bin/sh
case $1 in
  -d) 7za -txz -si -so e;;
   *) 7za -txz -si -so a .;;
esac 2>/dev/null

Save it as 7zhelper.sh. Here the example of usage:

$ tar -I 7zhelper.sh -cf OUTPUT_FILE.tar.7z paths_to_archive
$ tar -I 7zhelper.sh -xf OUTPUT_FILE.tar.7z

xz

Regarding multithreaded XZ support. If you are running version 5.2.0 or above of XZ Utils, you can utilize multiple cores for compression by setting -T or --threads to an appropriate value via the environmental variable XZ_DEFAULTS (e.g. XZ_DEFAULTS="-T 0").

This is a fragment of man for 5.1.0alpha version:

Multithreaded compression and decompression are not implemented yet, so this option has no effect for now.

However this will not work for decompression of files that haven't also been compressed with threading enabled. From man for version 5.2.2:

Threaded decompression hasn't been implemented yet. It will only work on files that contain multiple blocks with size information in block headers. All files compressed in multi-threaded mode meet this condition, but files compressed in single-threaded mode don't even if --block-size=size is used.

Recompiling with replacement

If you build tar from sources, then you can recompile with parameters

--with-gzip=pigz
--with-bzip2=lbzip2
--with-lzip=plzip

After recompiling tar with these options you can check the output of tar's help:

$ tar --help | grep "lbzip2\|plzip\|pigz"
  -j, --bzip2                filter the archive through lbzip2
      --lzip                 filter the archive through plzip
  -z, --gzip, --gunzip, --ungzip   filter the archive through pigz

jquery: $(window).scrollTop() but no $(window).scrollBottom()

This is a quick hack: just assign the scroll value to a very large number. This will ensure that the page is scrolled to the bottom. Using plain javascript:

document.body.scrollTop = 100000;

Change Default branch in gitlab

In the latest GitLab Community Edition version 9.2.2.:

  1. You have to click on 'Settings' tab located at right most on tabs panel after opening the project.
  2. Under 'Settings' you will get section 'Default Branch' dropdown which will give you all branches for the repository. Select the desired branch.
  3. Scroll down to hit green colored 'Save changes' button located just after 'Project Avatar'.

Please refer image below:

enter image description here

Is there a standard function to check for null, undefined, or blank variables in JavaScript?

For my case I tried with if null,'', !variable, But it did not work.

See my code below to get the text from an html field

var status=$(this).text(); //for example (for my case)

if there was no value(no text) in the status variable ,I was trying to set the value 'novalue' to status variable.

the following code worked.

if(status == false)
{
   status='novalue';
} 

when there was no text found for satus variable the above code assigned 'novalue' to the status variable

What is the maximum number of edges in a directed graph with n nodes?

Putting it another way:

A complete graph is an undirected graph where each distinct pair of vertices has an unique edge connecting them. This is intuitive in the sense that, you are basically choosing 2 vertices from a collection of n vertices.

nC2 = n!/(n-2)!*2! = n(n-1)/2

This is the maximum number of edges an undirected graph can have. Now, for directed graph, each edge converts into two directed edges. So just multiply the previous result with two. That gives you the result: n(n-1)

What is :: (double colon) in Python when subscripting sequences?

Python uses the :: to separate the End, the Start, and the Step value.

How do I check out an SVN project into Eclipse as a Java project?

If it wasn't checked in as a Java Project, you can add the java nature as shown here.

Single quotes vs. double quotes in C or C++

Single quotes are denoting a char, double denote a string.

In Java, it is also the same.

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays

You can declare the books (on line 2) as an array:

title: any = 'List of books are represted in the bookstore';
books: any = []; 
constructor(private service:  AppService){
}

ngOnInit(){
  this.getBookDetails();
}

getBookDetails() {
    this.service.getBooks().subscribe(books => {
        this.books = books.json();
        console.log(this.books);
    });
}

Execute Python script via crontab

Just use crontab -e and follow the tutorial here.

Look at point 3 for a guide on how to specify the frequency.

Based on your requirement, it should effectively be:

*/10 * * * * /usr/bin/python script.py

How can I determine the URL that a local Git repository was originally cloned from?

I can never remember all the parameters to Git commands, so I just put an alias in the ~/.gitconfig file that makes more sense to me, so I can remember it, and it results in less typing:

[alias]
url = ls-remote --get-url

After reloading the terminal, you can then just type:

> git url

Here are a few more of my frequently used ones:

[alias]
cd = checkout
ls = branch
lsr = branch --remote
lst = describe --tags

I also highly recommend git-extras which has a git info command which provides much more detailed information on the remote and local branches.

Preview an image before it is uploaded

Please take a look at the sample code below:

_x000D_
_x000D_
function readURL(input) {_x000D_
  if (input.files && input.files[0]) {_x000D_
    var reader = new FileReader();_x000D_
    _x000D_
    reader.onload = function(e) {_x000D_
      $('#blah').attr('src', e.target.result);_x000D_
    }_x000D_
    _x000D_
    reader.readAsDataURL(input.files[0]); // convert to base64 string_x000D_
  }_x000D_
}_x000D_
_x000D_
$("#imgInp").change(function() {_x000D_
  readURL(this);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form runat="server">_x000D_
  <input type='file' id="imgInp" />_x000D_
  <img id="blah" src="#" alt="your image" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

Also, you can try this sample here.

How to create a simple http proxy in node.js?

Here's a proxy server using request that handles redirects. Use it by hitting your proxy URL http://domain.com:3000/?url=[your_url]

var http = require('http');
var url = require('url');
var request = require('request');

http.createServer(onRequest).listen(3000);

function onRequest(req, res) {

    var queryData = url.parse(req.url, true).query;
    if (queryData.url) {
        request({
            url: queryData.url
        }).on('error', function(e) {
            res.end(e);
        }).pipe(res);
    }
    else {
        res.end("no url found");
    }
}

Turn on torch/flash on iPhone

//import fremework in .h file 

#import <AVFoundation/AVFoundation.h>
{
 AVCaptureSession *torchSession;
}

@property(nonatomic,retain)AVCaptureSession *torchSession;


-(IBAction)onoff:(id)sender;

//implement in .m file

@synthesize torchSession;

-(IBAction)onoff:(id)sender
{
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if ([device hasTorch] && [device hasFlash])
    {
        if (device.torchMode == AVCaptureTorchModeOff) 
        {
            [button setTitle:@"OFF" forState:UIControlStateNormal];

            AVCaptureDeviceInput *flashInput = [AVCaptureDeviceInput deviceInputWithDevice:device error: nil];

            AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init];
            AVCaptureSession *session = [[AVCaptureSession alloc] init];

            [session beginConfiguration];
            [device lockForConfiguration:nil];
            [device setTorchMode:AVCaptureTorchModeOn];
            [device setFlashMode:AVCaptureFlashModeOn];
            [session addInput:flashInput];
            [session addOutput:output];
            [device unlockForConfiguration];
            [output release];
            [session commitConfiguration];
            [session startRunning];
            [self setTorchSession:session];
            [session release];
        }
        else 
        {
            [button setTitle:@"ON" forState:UIControlStateNormal];
            [torchSession stopRunning];
        }
    }
}

- (void)dealloc
{
    [torchSession release];
    [super dealloc];
}

C#: Assign same value to multiple variables in single statement

Your example would be:

int num1 = 1;
int num2 = 1;

num1 = num2 = 5;

How to remove the first character of string in PHP?

Use substr:

$str = substr($str, 1); // this is a applepie :)

How do I change the UUID of a virtual disk?

If you've copied a disk (vmdk file) from one machine to another and need to change a disk's UUID in the copy, you don't need to change the Machine UUID as has been suggested by another answer.

All you need to do is to assign a new UUID to the disk image:

VBoxManage internalcommands sethduuid your-box-disk2.vmdk
UUID changed to: 5d34479f-5597-4b78-a1fa-94e200d16bbb

and then replace the old UUID with the newly generated one in two places in your *.vbox file

<MediaRegistry>
  <HardDisks>
    <HardDisk uuid="{5d34479f-5597-4b78-a1fa-94e200d16bbb}" location="box-disk2.vmdk" format="VMDK" type="Normal"/>
  </HardDisks>

and in

    <AttachedDevice type="HardDisk" hotpluggable="false" port="0" device="0">
      <Image uuid="{5d34479f-5597-4b78-a1fa-94e200d16bbb}"/>
    </AttachedDevice>

It worked for me for VirtualBox ver. 5.1.8 running on Mac OS X El Capitan.

jQuery if div contains this text, replace that part of the text

If it's possible, you could wrap the word(s) you want to replace in a span tag, like so:

<div class="text_div">
    This div <span>contains</span> some text.
</div>

You can then easily change its contents with jQuery:

$('.text_div > span').text('hello everyone');

If you can't wrap it in a span tag, you could use regular expressions.

github: server certificate verification failed

Another possible cause is that the clock of your machine is not synced (e.g. on Raspberry Pi). Check the current date/time using:

$ date

If the date and/or time is incorrect, try to update using:

$ sudo ntpdate -u time.nist.gov

Dynamically Changing log4j log level

I have used this method with success to reduce the verbosity of the "org.apache.http" logs:

ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("org.apache.http");
logger.setLevel(Level.TRACE);
logger.setAdditive(false);

Change drive in git bash for windows

How I do it in Windows 10

Go to your folder directory you want to open in git bash like so

enter image description here

After you have reached the folder simply type git bash in the top navigation area like so and hit enter.

enter image description here

A git bash for the destined folder will open for you.

enter image description here

Hope that helps.

Calculate execution time of a SQL query?

Please use

-- turn on statistics IO for IO related 
SET STATISTICS IO ON 
GO

and for time calculation use

SET STATISTICS TIME ON
GO

then It will give result for every query . In messages window near query input window.

Why is this HTTP request not working on AWS Lambda?

I've found lots of posts across the web on the various ways to do the request, but none that actually show how to process the response synchronously on AWS Lambda.

Here's a Node 6.10.3 lambda function that uses an https request, collects and returns the full body of the response, and passes control to an unlisted function processBody with the results. I believe http and https are interchangable in this code.

I'm using the async utility module, which is easier to understand for newbies. You'll need to push that to your AWS Stack to use it (I recommend the serverless framework).

Note that the data comes back in chunks, which are gathered in a global variable, and finally the callback is called when the data has ended.

'use strict';

const async = require('async');
const https = require('https');

module.exports.handler = function (event, context, callback) {

    let body = "";
    let countChunks = 0;

    async.waterfall([
        requestDataFromFeed,
        // processBody,
    ], (err, result) => {
        if (err) {
            console.log(err);
            callback(err);
        }
        else {
            const message = "Success";
            console.log(result.body);
            callback(null, message);
        }
    });

    function requestDataFromFeed(callback) {
        const url = 'https://put-your-feed-here.com';
        console.log(`Sending GET request to ${url}`);
        https.get(url, (response) => {
            console.log('statusCode:', response.statusCode);
            response.on('data', (chunk) => {
                countChunks++;
                body += chunk;
            });
            response.on('end', () => {
                const result = {
                    countChunks: countChunks,
                    body: body
                };
                callback(null, result);
            });
        }).on('error', (err) => {
            console.log(err);
            callback(err);
        });
    }
};

"column not allowed here" error in INSERT statement

This error creeps in if we make some spelling mistake in entering the variable name. Like in stored proc, I have the variable name x and in my insert statement I am using

insert into tablename values(y);

It will throw an error column not allowed here.

Remove spaces from a string in VB.NET

2015: Newer LINQ & lambda.

  1. As this is an old Q (and Answer), just thought to update it with newer 2015 methods.
  2. The original "space" can refer to non-space whitespace (ie, tab, newline, paragraph separator, line feed, carriage return, etc, etc).
  3. Also, Trim() only remove the spaces from the front/back of the string, it does not remove spaces inside the string; eg: " Leading and Trailing Spaces " will become "Leading and Trailing Spaces", but the spaces inside are still present.

Function RemoveWhitespace(fullString As String) As String
    Return New String(fullString.Where(Function(x) Not Char.IsWhiteSpace(x)).ToArray())
End Function

This will remove ALL (white)-space, leading, trailing and within the string.

Get the key corresponding to the minimum value within a dictionary

Here's an answer that actually gives the solution the OP asked for:

>>> d = {320:1, 321:0, 322:3}
>>> d.items()
[(320, 1), (321, 0), (322, 3)]
>>> # find the minimum by comparing the second element of each tuple
>>> min(d.items(), key=lambda x: x[1]) 
(321, 0)

Using d.iteritems() will be more efficient for larger dictionaries, however.

height style property doesn't work in div elements

You try to set the height property of an inline element, which is not possible. You can try to make it a block element, or perhaps you meant to alter the line-height property?

ggplot geom_text font size control

Here are a few options for changing text / label sizes

library(ggplot2)

# Example data using mtcars

a <- aggregate(mpg ~ vs + am , mtcars, function(i) round(mean(i)))

p <- ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) + 
            geom_bar(stat="identity",position="dodge") + 
            geom_text(data = a, aes(label = mpg), 
                            position = position_dodge(width=0.9),  size=20)

The size in the geom_text changes the size of the geom_text labels.

p <- p + theme(axis.text = element_text(size = 15)) # changes axis labels

p <- p + theme(axis.title = element_text(size = 25)) # change axis titles

p <- p + theme(text = element_text(size = 10)) # this will change all text size 
                                                             # (except geom_text)


For this And why size of 10 in geom_text() is different from that in theme(text=element_text()) ?

Yes, they are different. I did a quick manual check and they appear to be in the ratio of ~ (14/5) for geom_text sizes to theme sizes.

So a horrible fix for uniform sizes is to scale by this ratio

geom.text.size = 7
theme.size = (14/5) * geom.text.size

ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) + 
  geom_bar(stat="identity",position="dodge") + 
  geom_text(data = a, aes(label = mpg), 
            position = position_dodge(width=0.9),  size=geom.text.size) + 
  theme(axis.text = element_text(size = theme.size, colour="black")) 

This of course doesn't explain why? and is a pita (and i assume there is a more sensible way to do this)

Adding a new line/break tag in XML

Had same issue when I had to develop a fixed length field format.

Usually we do not use line separator for binary files but For some reason our customer wished to add a line break as separator between records. They set

< record_delimiter value="\n"/ >

but this didn't work as records got two additional characters:
< record1 > \n < record2 > \n.... and so on.

Did following change and it just worked.

< record_delimiter value="\n"/> => < record_delimiter value="&#xA;"/ >

After unmarshaling Java interprets as new line character.

How to retrieve form values from HTTPPOST, dictionary or?

Simply, you can use FormCollection like:

[HttpPost] 
public ActionResult SubmitAction(FormCollection collection)
{
     // Get Post Params Here
 string var1 = collection["var1"];
}

You can also use a class, that is mapped with Form values, and asp.net mvc engine automagically fills it:

//Defined in another file
class MyForm
{
  public string var1 { get; set; }
}

[HttpPost]
public ActionResult SubmitAction(MyForm form)
{      
  string var1 = form1.Var1;
}

mysql alphabetical order

If you want to restrict the rows that are returned by a query, you need to use a WHERE clause, rather than an ORDER BY clause. Try

select name from user where name like 'b%'

How to handle authentication popup with Selenium WebDriver using Java

The Alert Method, authenticateUsing() lets you skip the Http Basic Authentication box.

WebDriverWait wait = new WebDriverWait(driver, 10);      
Alert alert = wait.until(ExpectedConditions.alertIsPresent());     
alert.authenticateUsing(new UserAndPassword(username, password));

As of Selenium 3.4 it is still in beta

Right now implementation is only done for InternetExplorerDriver

SQLSTATE[HY000] [1045] Access denied for user 'username'@'localhost' using CakePHP

That error message usually means that either the password we are using doesn't match what MySQL thinks the password should be for the user we're connecting as, or a matching MySQL user doesn't exist (hasn't been created).

In MySQL, a user is identified by both a username ("test2") and a host ("localhost").

The error message identifies the user ("test2") and the host ("localhost") values...

  'test2'@'localhost'

We can check to see if the user exists, using this query from a client we can connect from:

 SELECT user, host FROM mysql.user

We're looking for a row that has "test2" for user, and "localhost" for host.

 user     host       
 -------  -----------
 test2     127.0.0.1  cleanup
 test2     ::1        
 test2     localhost  

If that row doesn't exist, then the host may be set to wildcard value of %, to match any other host that isn't a match.

If the row exists, then the password may not match. We can change the password (if we're connected as a user with sufficient privileges, e.g. root

 SET PASSWORD FOR 'test2'@'localhost' = PASSWORD('mysecretcleartextpassword')

We can also verify that the user has privileges on objects in the database.

 GRANT SELECT ON jobs.* TO 'test2'@'localhost' 

EDIT

If we make changes to mysql privilege tables with DML operations (INSERT,UPDATE,DELETE), those changes will not take effect until MySQL re-reads the tables. We can make changes effective by forcing a re-read with a FLUSH PRIVILEGES statement, executed by a privileged user.

disabling spring security in spring boot app

Use security.ignored property:

security.ignored=/**

security.basic.enable: false will just disable some part of the security auto-configurations but your WebSecurityConfig still will be registered.

There is a default security password generated at startup

Try to Autowired the AuthenticationManagerBuilder:

@Override
@Autowired
protected void configure(AuthenticationManagerBuilder auth) throws Exception { ... }

How do I select elements of an array given condition?

For 2D arrays, you can do this. Create a 2D mask using the condition. Typecast the condition mask to int or float, depending on the array, and multiply it with the original array.

In [8]: arr
Out[8]: 
array([[ 1.,  2.,  3.,  4.,  5.],
       [ 6.,  7.,  8.,  9., 10.]])

In [9]: arr*(arr % 2 == 0).astype(np.int) 
Out[9]: 
array([[ 0.,  2.,  0.,  4.,  0.],
       [ 6.,  0.,  8.,  0., 10.]])

How to let an ASMX file output JSON

From WebService returns XML even when ResponseFormat set to JSON:

Make sure that the request is a POST request, not a GET. Scott Guthrie has a post explaining why.

Though it's written specifically for jQuery, this may also be useful to you:
Using jQuery to Consume ASP.NET JSON Web Services

Table and Index size in SQL Server

The exec sp_spaceused without parameter shows the summary for the whole database. The foreachtable solution generates one result set per table - which SSMS might not be able to handle if you have too many tables.

I created a script which collects the table infos via sp_spaceused and displays a summary in a single record set, sorted by size.

create table #t
(
  name nvarchar(128),
  rows varchar(50),
  reserved varchar(50),
  data varchar(50),
  index_size varchar(50),
  unused varchar(50)
)

declare @id nvarchar(128)
declare c cursor for
select '[' + sc.name + '].[' + s.name + ']' FROM sysobjects s INNER JOIN sys.schemas sc ON s.uid = sc.schema_id where s.xtype='U'

open c
fetch c into @id

while @@fetch_status = 0 begin

  insert into #t
  exec sp_spaceused @id

  fetch c into @id
end

close c
deallocate c

select * from #t
order by convert(int, substring(data, 1, len(data)-3)) desc

drop table #t

Using client certificate in Curl command

This is how I did it:

curl -v \
  --key ./admin-key.pem \
  --cert ./admin.pem \
  https://xxxx/api/v1/

Java 11 package javax.xml.bind does not exist

According to the release-notes, Java 11 removed the Java EE modules:

java.xml.bind (JAXB) - REMOVED
  • Java 8 - OK
  • Java 9 - DEPRECATED
  • Java 10 - DEPRECATED
  • Java 11 - REMOVED

See JEP 320 for more info.

You can fix the issue by using alternate versions of the Java EE technologies. Simply add Maven dependencies that contain the classes you need:

<dependency>
  <groupId>javax.xml.bind</groupId>
  <artifactId>jaxb-api</artifactId>
  <version>2.3.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-core</artifactId>
  <version>2.3.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>2.3.0</version>
</dependency>

Jakarta EE 8 update (Mar 2020)

Instead of using old JAXB modules you can fix the issue by using Jakarta XML Binding from Jakarta EE 8:

<dependency>
  <groupId>jakarta.xml.bind</groupId>
  <artifactId>jakarta.xml.bind-api</artifactId>
  <version>2.3.3</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>2.3.3</version>
  <scope>runtime</scope>
</dependency>

Jakarta EE 9 update (Nov 2020)

Use latest release of Eclipse Implementation of JAXB 3.0.0:

<dependency>
  <groupId>jakarta.xml.bind</groupId>
  <artifactId>jakarta.xml.bind-api</artifactId>
  <version>3.0.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>3.0.0</version>
  <scope>runtime</scope>
</dependency>

Note: Jakarta EE 9 adopts new API package namespace jakarta.xml.bind.*, so update import statements:

javax.xml.bind -> jakarta.xml.bind

How do I check (at runtime) if one class is a subclass of another?

You can use isinstance if you have an instance, or issubclass if you have a class. Normally thought its a bad idea. Normally in Python you work out if an object is capable of something by attempting to do that thing to it.

plot is not defined

Change that import to

from matplotlib.pyplot import *

Note that this style of imports (from X import *) is generally discouraged. I would recommend using the following instead:

import matplotlib.pyplot as plt
plt.plot([1,2,3,4])

Compare two files line by line and generate the difference in another file

If you need to solve this with coreutils the accepted answer is good:

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

You can also use sd (stream diff), which doesn't require sorting nor process substitution and supports infinite streams, like so:

cat file1 | sd 'cat file2' > file3

Probably not that much of a benefit on this example, but still consider it; in some cases you won't be able to use comm nor grep -F nor diff.

Here's a blogpost I wrote about diffing streams on the terminal, which introduces sd.

How to get the current time in milliseconds from C in Linux?

You have to do something like this:

struct timeval  tv;
gettimeofday(&tv, NULL);

double time_in_mill = 
         (tv.tv_sec) * 1000 + (tv.tv_usec) / 1000 ; // convert tv_sec & tv_usec to millisecond

Change the default editor for files opened in the terminal? (e.g. set it to TextEdit/Coda/Textmate)

Most programs will check the $EDITOR environment variable, so you can set that to the path of TextEdit in your bashrc. Git will use this as well.

How to do this:

  • Add the following to your ~/.bashrc file:
    export EDITOR="/Applications/TextEdit.app/Contents/MacOS/TextEdit"
  • or just type the following command into your Terminal:
    echo "export EDITOR=\"/Applications/TextEdit.app/Contents/MacOS/TextEdit\"" >> ~/.bashrc

If you are using zsh, use ~/.zshrc instead of ~/.bashrc.

Can't push to GitHub because of large file which I already deleted

I got the same problem and none of the answers work for me. I solved by the following steps:

1. Find which commit(s) contains the large file

git log --all -- 'large_file`

The bottom commit is the oldest commit in the result list.

2. Find the one just before the oldest.

git log

Suppose you got:

commit 3f7dd04a6e6dbdf1fff92df1f6344a06119d5d32

3. Git rebase

git rebase -i 3f7dd04a6e6dbdf1fff92df1f6344a06119d5d32

Tips:

  1. List item
  2. I just choose drop for the commits contains the large file.
  3. You may meet conflicts during rebase fix them and use git rebase --continue to continue until you finish it.
  4. If anything went wrong during rebase use git rebase --abort to cancel it.

How to assign pointer address manually in C programming language?

int *p=(int *)0x1234 = 10; //0x1234 is the memory address and value 10 is assigned in that address


unsigned int *ptr=(unsigned int *)0x903jf = 20;//0x903j is memory address and value 20 is assigned 

Basically in Embedded platform we are using directly addresses instead of names

Firebase onMessageReceived not called when app in background

I had this issue(app doesn't want to open on notification click if app is in background or closed), and the problem was an invalid click_action in notification body, try removing or changing it to something valid.

Update query PHP MySQL

<?php
require 'db_config.php';


  $id  = $_POST["id"];
  $post = $_POST;

  $sql = "UPDATE items SET title = '".$post['title']."'

    ,description = '".$post['description']."' 

    WHERE id = '".$id."'";

  $result = $mysqli->query($sql);


  $sql = "SELECT * FROM items WHERE id = '".$id."'"; 

  $result = $mysqli->query($sql);

  $data = $result->fetch_assoc();


echo json_encode($data);
?>

Is it possible in Java to catch two exceptions in the same catch block?

If you aren't on java 7, you can extract your exception handling to a method - that way you can at least minimize duplication

try {
   // try something
}
catch(ExtendsRuntimeException e) { handleError(e); }
catch(Exception e) { handleError(e); }

Using BeautifulSoup to extract text without tags

I think you could solve this with .strip() in gazpacho:

Input:

html = """\
<p>
  <strong class="offender">YOB:</strong> 1987<br />
  <strong class="offender">RACE:</strong> WHITE<br />
  <strong class="offender">GENDER:</strong> FEMALE<br />
  <strong class="offender">HEIGHT:</strong> 5'05''<br />
  <strong class="offender">WEIGHT:</strong> 118<br />
  <strong class="offender">EYE COLOR:</strong> GREEN<br />
  <strong class="offender">HAIR COLOR:</strong> BROWN<br />
</p>
"""

Code:

soup = Soup(html)
text = soup.find("p").strip(whitespace=False) # to keep \n characters intact
lines = [
    line.strip()
    for line in text.split("\n")
    if line != ""
]
data = dict([line.split(": ") for line in lines])

Output:

print(data)
# {'YOB': '1987',
#  'RACE': 'WHITE',
#  'GENDER': 'FEMALE',
#  'HEIGHT': "5'05''",
#  'WEIGHT': '118',
#  'EYE COLOR': 'GREEN',
#  'HAIR COLOR': 'BROWN'}

Seeking useful Eclipse Java code templates

Code Section

//--------------------------------------------------------------
//                       ${title}
//--------------------------------------------------------------
${cursor}

Use this template to make commenting sections of code easier. it's not very complex, but has saved me lots of time :)

How can I repeat a character in Bash?

You can use:

printf '=%.0s' {1..100}

How this works:

Bash expands {1..100} so the command becomes:

printf '=%.0s' 1 2 3 4 ... 100

I've set printf's format to =%.0s which means that it will always print a single = no matter what argument it is given. Therefore it prints 100 =s.

How to stop the task scheduled in java.util.Timer class

timer.cancel();  //Terminates this timer,discarding any currently scheduled tasks.

timer.purge();   // Removes all cancelled tasks from this timer's task queue.

List only stopped Docker containers

Only stopped containers can be listed using:

docker ps --filter "status=exited"

or

docker ps -f "status=exited"

Are multi-line strings allowed in JSON?

While not standard, I found that some of the JSON libraries have options to support multiline Strings. I am saying this with the caveat, that this will hurt your interoperability.

However in the specific scenario I ran into, I needed to make a config file that was only ever used by one system readable and manageable by humans. And opted for this solution in the end.

Here is how this works out on Java with Jackson:

JsonMapper mapper = JsonMapper.builder()
   .enable(JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS)
   .build()

Get current date in DD-Mon-YYY format in JavaScript/Jquery

const date = new Date();

date.toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' }))

How to enable file sharing for my app?

If you find by alphabet in plist, it should be "Application supports iTunes file sharing".

Why can't decimal numbers be represented exactly in binary?

you know integer numbers right? each bit represent 2^n


2^4=16
2^3=8
2^2=4
2^1=2
2^0=1

well its the same for floating point(with some distinctions) but the bits represent 2^-n 2^-1=1/2=0.5
2^-2=1/(2*2)=0.25
2^-3=0.125
2^-4=0.0625

Floating point binary representation:

sign  Exponent    Fraction(i think invisible 1 is appended to the fraction )
B11  B10 B9 B8   B7 B6 B5 B4 B3 B2 B1 B0

How to check if a Java 8 Stream is empty?

I think should be enough to map a boolean

In code this is:

boolean isEmpty = anyCollection.stream()
    .filter(p -> someFilter(p)) // Add my filter
    .map(p -> Boolean.TRUE) // For each element after filter, map to a TRUE
    .findAny() // Get any TRUE
    .orElse(Boolean.FALSE); // If there is no match return false

Convert YYYYMMDD string date to a datetime value

You should have to use DateTime.TryParseExact.

var newDate = DateTime.ParseExact("20111120", 
                                  "yyyyMMdd", 
                                   CultureInfo.InvariantCulture);

OR

string str = "20111021";
string[] format = {"yyyyMMdd"};
DateTime date;

if (DateTime.TryParseExact(str, 
                           format, 
                           System.Globalization.CultureInfo.InvariantCulture,
                           System.Globalization.DateTimeStyles.None, 
                           out date))
{
     //valid
}

Non greedy (reluctant) regex matching in sed?

sed certainly has its place but this not not one of them !

As Dee has pointed out: Just use cut. It is far simpler and much more safe in this case. Here's an example where we extract various components from the URL using Bash syntax:

url="http://www.suepearson.co.uk/product/174/71/3816/"

protocol=$(echo "$url" | cut -d':' -f1)
host=$(echo "$url" | cut -d'/' -f3)
urlhost=$(echo "$url" | cut -d'/' -f1-3)
urlpath=$(echo "$url" | cut -d'/' -f4-)

gives you:

protocol = "http"
host = "www.suepearson.co.uk"
urlhost = "http://www.suepearson.co.uk"
urlpath = "product/174/71/3816/"

As you can see this is a lot more flexible approach.

(all credit to Dee)

Unused arguments in R

I had the same problem as you. I had a long list of arguments, most of which were irrelevant. I didn't want to hard code them in. This is what I came up with

library(magrittr)
do_func_ignore_things <- function(data, what){
    acceptable_args <- data[names(data) %in% (formals(what) %>% names)]
    do.call(what, acceptable_args %>% as.list)
}

do_func_ignore_things(c(n = 3, hello = 12, mean = -10), "rnorm")
# -9.230675 -10.503509 -10.927077

Reorder bars in geom_bar ggplot2 by value

Your code works fine, except that the barplot is ordered from low to high. When you want to order the bars from high to low, you will have to add a -sign before value:

ggplot(corr.m, aes(x = reorder(miRNA, -value), y = value, fill = variable)) + 
  geom_bar(stat = "identity")

which gives:

enter image description here


Used data:

corr.m <- structure(list(miRNA = structure(c(5L, 2L, 3L, 6L, 1L, 4L), .Label = c("mmu-miR-139-5p", "mmu-miR-1983", "mmu-miR-301a-3p", "mmu-miR-5097", "mmu-miR-532-3p", "mmu-miR-96-5p"), class = "factor"),
                         variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "pos", class = "factor"),
                         value = c(7L, 75L, 70L, 5L, 10L, 47L)),
                    class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6"))

How to prevent page from reloading after form submit - JQuery

The <button> element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:

  1. Use <button type="button"> to override default submission behavior
  2. Use event.preventDefault() in the onSubmit event to prevent form submission

Solution 1:

  • Advantage: simple change to markup
  • Disadvantage: subverts default form behavior, especially when JS is disabled. What if the user wants to hit "enter" to submit?

Insert extra type attribute to your button markup:

<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>

Solution 2:

  • Advantage: form will work even when JS is disabled, and respects standard form UI/UX such that at least one button is used for submission

Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:

$(document).ready(function () {
  // Listen to click event on the submit button
  $('#button').click(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Better variant:

In this improvement, we listen to the submit event emitted from the <form> element:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Even better variant: use .serialize() to serialize your form, but remember to add name attributes to your input:

The name attribute is required for .serialize() to work, as per jQuery's documentation:

For a form element's value to be included in the serialized string, the element must have a name attribute.

<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]">

And then in your JS:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    // Prevent form submission which refreshes page
    e.preventDefault();

    // Serialize data
    var formData = $(this).serialize();

    // Make AJAX request
    $.post("process.php", formData).complete(function() {
      console.log("Success");
    });
  });
});

Validating email addresses using jQuery and regex

I would recommend that you use the jQuery plugin for Verimail.js.

Why?

  • IANA TLD validation
  • Syntax validation (according to RFC 822)
  • Spelling suggestion for the most common TLDs and email domains
  • Deny temporary email account domains such as mailinator.com

How?

Include verimail.jquery.js on your site and use the function:

$("input#email-address").verimail({
    messageElement: "p#status-message"
});

If you have a form and want to validate the email on submit, you can use the getVerimailStatus-function:

if($("input#email-address").getVerimailStatus() < 0){
    // Invalid email
}else{
    // Valid email
}

Razor View Without Layout

I think it's better work with individual "views", Im trying to move from PHP to MVC4, its really hard but im on the right way...

Answering your question, if you'll work individual pages, just edit the _ViewStart.cshtml

@{
  Layout = null;
}

Another tip if you're getting some issues with CSS path...

Put "../" before of the url

This are the 2 problems that i get today, and I resolve in that way!

Regards;

Windows equivalent of OS X Keychain?

If you are on windows got to control pannel -> windows Credentials

What is the 'dynamic' type in C# 4.0 used for?

COM interop. Especially IUnknown. It was designed specially for it.

How to convert image file data in a byte array to a Bitmap?

Just try this:

Bitmap bitmap = BitmapFactory.decodeFile("/path/images/image.jpg");
ByteArrayOutputStream blob = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /* Ignored for PNGs */, blob);
byte[] bitmapdata = blob.toByteArray();

If bitmapdata is the byte array then getting Bitmap is done like this:

Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata, 0, bitmapdata.length);

Returns the decoded Bitmap, or null if the image could not be decoded.

CURRENT_TIMESTAMP in milliseconds

Use:

Select curtime(4);

This will give you milliseconds.

jQuery remove special characters from string and more

Remove/Replace all special chars in Jquery :

If

str = My name is "Ghanshyam" and from "java" background

and want to remove all special chars (") then use this

str=str.replace(/"/g,' ')

result:

My name is Ghanshyam and from java background

Where g means Global

What are the differences and similarities between ffmpeg, libav, and avconv?

Confusing messages

These messages are rather misleading and understandably a source of confusion. Older Ubuntu versions used Libav which is a fork of the FFmpeg project. FFmpeg returned in Ubuntu 15.04 "Vivid Vervet".

The fork was basically a non-amicable result of conflicting personalities and development styles within the FFmpeg community. It is worth noting that the maintainer for Debian/Ubuntu switched from FFmpeg to Libav on his own accord due to being involved with the Libav fork.

The real ffmpeg vs the fake one

For a while both Libav and FFmpeg separately developed their own version of ffmpeg.

Libav then renamed their bizarro ffmpeg to avconv to distance themselves from the FFmpeg project. During the transition period the "not developed anymore" message was displayed to tell users to start using avconv instead of their counterfeit version of ffmpeg. This confused users into thinking that FFmpeg (the project) is dead, which is not true. A bad choice of words, but I can't imagine Libav not expecting such a response by general users.

This message was removed upstream when the fake "ffmpeg" was finally removed from the Libav source, but, depending on your version, it can still show up in Ubuntu because the Libav source Ubuntu uses is from the ffmpeg-to-avconv transition period.

In June 2012, the message was re-worded for the package libav - 4:0.8.3-0ubuntu0.12.04.1. Unfortunately the new "deprecated" message has caused additional user confusion.

Starting with Ubuntu 15.04 "Vivid Vervet", FFmpeg's ffmpeg is back in the repositories again.

libav vs Libav

To further complicate matters, Libav chose a name that was historically used by FFmpeg to refer to its libraries (libavcodec, libavformat, etc). For example the libav-user mailing list, for questions and discussions about using the FFmpeg libraries, is unrelated to the Libav project.

How to tell the difference

If you are using avconv then you are using Libav. If you are using ffmpeg you could be using FFmpeg or Libav. Refer to the first line in the console output to tell the difference: the copyright notice will either mention FFmpeg or Libav.

Secondly, the version numbering schemes differ. Each of the FFmpeg or Libav libraries contains a version.h header which shows a version number. FFmpeg will end in three digits, such as 57.67.100, and Libav will end in one digit such as 57.67.0. You can also view the library version numbers by running ffmpeg or avconv and viewing the console output.

If you want to use the real ffmpeg

Ubuntu 15.04 "Vivid Vervet" or newer

The real ffmpeg is in the repository, so you can install it with:

apt-get install ffmpeg

For older Ubuntu versions

Your options are:

These methods are non-intrusive, reversible, and will not interfere with the system or any repository packages.

Another possible option is to upgrade to Ubuntu 15.04 "Vivid Vervet" or newer and just use ffmpeg from the repository.

Also see

For an interesting blog article on the situation, as well as a discussion about the main technical differences between the projects, see The FFmpeg/Libav situation.

Python, creating objects

when you create an object using predefine class, at first you want to create a variable for storing that object. Then you can create object and store variable that you created.

class Student:
     def __init__(self):

# creating an object....

   student1=Student()

Actually this init method is the constructor of class.you can initialize that method using some attributes.. In that point , when you creating an object , you will have to pass some values for particular attributes..

class Student:
      def __init__(self,name,age):
            self.name=value
            self.age=value

 # creating an object.......

     student2=Student("smith",25)

How to generate an MD5 file hash in JavaScript?

CryptoJS is a crypto library which can generate md5 hash among others:

Usage with Script tag:

<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/core.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/md5.js"></script>
<script>
   var hash = CryptoJS.MD5("Message");
   alert(hash);
</script>

Alternatively with ES6:

npm install crypto-js

import MD5 from "crypto-js/md5";
console.log(MD5("Message").toString());

You can also use modular imports:

var MD5 = require("crypto-js/md5");
console.log(MD5("Message").toString());

Github: https://github.com/brix/crypto-js

CDN: https://cdnjs.com/libraries/crypto-js

Select first 10 distinct rows in mysql

SELECT  DISTINCT *
FROM    people
WHERE   names = 'Smith'
ORDER BY
        names
LIMIT 10

SQL Server 2000: How to exit a stored procedure?

This seems like a lot of code but the best way i've found to do it.

    ALTER PROCEDURE Procedure
    AS

    BEGIN TRY
        EXEC AnotherProcedure
    END TRY
    BEGIN CATCH
        DECLARE @ErrorMessage NVARCHAR(4000);
        DECLARE @ErrorSeverity INT;
        DECLARE @ErrorState INT;

        SELECT 
            @ErrorMessage = ERROR_MESSAGE(),
            @ErrorSeverity = ERROR_SEVERITY(),
            @ErrorState = ERROR_STATE();

        RAISERROR (@ErrorMessage, -- Message text.
                   @ErrorSeverity, -- Severity.
                   @ErrorState -- State.
                   );
        RETURN --this forces it out
    END CATCH

--Stuff here that you do not want to execute if the above failed.    

    END --end procedure

sql server invalid object name - but tables are listed in SSMS tables list

once you create a new SQL Server object, your newly created object does not get updated in the IntelliSence Local Cache and due to this, it shows red line underneath that object. So you just need to refresh SSMS IntelliSence Local Cache and once you refresh it, IntelliSence will automatically add newly created object in the cache and the red line will disappear. try this

Edit -> IntelliSense -> Refresh Local Cache or Ctrl + Shift + R

enter image description here

How do I execute a *.dll file

To run the functions in a DLL, first find out what those functions are using any PE (Portable Executable) analysis program (e.g. Dependency Walker). Then use RUNDLL32.EXE with this syntax:

 RUNDLL32.EXE <dllname>,<entrypoint> <optional arguments>

dllname is the path and name of your dll file, entrypoint is the function name, and optional arguments are the function arguments

Simple PHP form: Attachment to email (code golf)

A combination of this http://www.webcheatsheet.com/PHP/send_email_text_html_attachment.php#attachment

with the php upload file example would work. In the upload file example instead of using move_uploaded_file to move it from the temporary folder you would just open it:

$attachment = chunk_split(base64_encode(file_get_contents($tmp_file))); 

where $tmp_file = $_FILES['userfile']['tmp_name'];

and send it as an attachment like the rest of the example.

All in one file / self contained:

<? if(isset($_POST['submit'])){
//process and email
}else{
//display form
}
?>

I think its a quick exercise to get what you need working based on the above two available examples.

P.S. It needs to get uploaded somewhere before Apache passes it along to PHP to do what it wants with it. That would be your system's temp folder by default unless it was changed in the config file.

Edit and replay XHR chrome/firefox etc?

No need to install 3rd party extensions!

There exists the javascript-snippet, which you can add as browser-bookmark and then activate on any site to track & modify the requests. It looks like:

enter image description here

For further instructions, review the github page.

Email & Phone Validation in Swift

Swift 3:

private func validate(phoneNumber: String) -> Bool {
    let charcterSet  = NSCharacterSet(charactersIn: "+0123456789").inverted
    let inputString = phoneNumber.components(separatedBy: charcterSet)
    let filtered = inputString.joined(separator: "")
    return  phoneNumber == filtered
}

PHP XML Extension: Not installed

You're close

sudo apt-get install php-xml

Then you need to restart apache so it takes effect

sudo service apache2 restart

Importing JSON into an Eclipse project

on linux pip install library_that_you_need Also on Help/Eclipse MarketPlace, i add PyDev IDE for Eclipse 7, so when i start a new project i create file/New Project/Pydev Project

Upgrade to python 3.8 using conda

You can update your python version to 3.8 in conda using the command

conda install -c anaconda python=3.8

as per https://anaconda.org/anaconda/python. Though not all packages support 3.8 yet, running

conda update --all

may resolve some dependency failures. You can also create a new environment called py38 using this command

conda create -n py38 python=3.8

Edit - note that the conda install option will potentially take a while to solve the environment, and if you try to abort this midway through you will lose your Python installation (usually this means it will resort to non-conda pre-installed system Python installation).

How to convert XML to JSON in Python?

Soviut's advice for lxml objectify is good. With a specially subclassed simplejson, you can turn an lxml objectify result into json.

import simplejson as json
import lxml

class objectJSONEncoder(json.JSONEncoder):
  """A specialized JSON encoder that can handle simple lxml objectify types
      >>> from lxml import objectify
      >>> obj = objectify.fromstring("<Book><price>1.50</price><author>W. Shakespeare</author></Book>")       
      >>> objectJSONEncoder().encode(obj)
      '{"price": 1.5, "author": "W. Shakespeare"}'       
 """


    def default(self,o):
        if isinstance(o, lxml.objectify.IntElement):
            return int(o)
        if isinstance(o, lxml.objectify.NumberElement) or isinstance(o, lxml.objectify.FloatElement):
            return float(o)
        if isinstance(o, lxml.objectify.ObjectifiedDataElement):
            return str(o)
        if hasattr(o, '__dict__'):
            #For objects with a __dict__, return the encoding of the __dict__
            return o.__dict__
        return json.JSONEncoder.default(self, o)

See the docstring for example of usage, essentially you pass the result of lxml objectify to the encode method of an instance of objectJSONEncoder

Note that Koen's point is very valid here, the solution above only works for simply nested xml and doesn't include the name of root elements. This could be fixed.

I've included this class in a gist here: http://gist.github.com/345559

How to clear Facebook Sharer cache?

Facebook treats each url as unique and caches the page based on that url, so if you want to share the latest url the simplest solution is to add a query string with the url being shared. In simple words just add ?v=1 at the end of the url. Any number can be used in place of 1.

Hat tip: Umair Jabbar

DevTools failed to load SourceMap: Could not load content for chrome-extension

include.prepload.js file will have a line something like below. probably as the last line.

//# sourceMappingURL=include.prepload.js.map

Delete it and the error will go away.

Eclipse error ... cannot be resolved to a type

Also If you are using mavenised project then try to update your project by clicking Alt+F5. Or right click on the application and go to maven /update project.

It builds all your components and resolves if any import error is there.

How to create a connection string in asp.net c#

add this in web.config file

           <configuration>
              <appSettings>
                 <add key="ConnectionString" value="Your connection string which contains database id and password"/>
            </appSettings>
            </configuration>

.cs file

 public ConnectionObjects()
 {           
    string connectionstring= ConfigurationManager.AppSettings["ConnectionString"].ToString();
 }

Hope this helps.

Succeeded installing but could not start apache 2.4 on my windows 7 system

So, that is why i do a two (or more) post.

I was having the same problem when starting the service (logs can not be opened).

I thought it was because i was trying to have htdocs inside a VeraCrypt encripted container, absurd since i hace such contained mounted and i use a juntion to not affect paths.

The i read the cause could be low ram: after some tests i get to the next conclusion.

Windows is not sending pages to virtual ram to free enough ram if it is a service, for applications it is doing it, i have more than 200GiB of pagefile ready to be used as virtual ram in a 4GiB 64 Bit windows 10.

My solution:

  1. Run a free utility that free ram (512MiB in my test)
  2. Inmediatly after start the service, it starts with no errors

Real Cause:

  • I was using a virtual machine that uses 1/2 physical free ram (1.5GiB)

Hope this help others.

Difference between Eclipse Europa, Helios, Galileo

Each version has some improvements in certain technologies. For users the biggest difference is whether or not to execute certain plugins, because some were made only for a particular version of Eclipse.

pod install -bash: pod: command not found

it happens to me when I wrote

gem install cocoapods

instead of

sudo gem install cocoapods

if sudo command is not found also, write

export PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:$PATH

before sudo command

Invalid postback or callback argument. Event validation is enabled using '<pages enableEventValidation="true"/>'

After having this problem on remote servers (production, test, qa, staging, etc), but not on local development workstations, I found that the Application Pool was configured with a RequestLimit other than 0.

This caused the app pool to give up and reply with the exception noted in the question.

How do I replace part of a string in PHP?

Simply use str_replace:

$text = str_replace(' ', '_', $text);

You would do this after your previous substr and strtolower calls, like so:

$text = substr($text,0,10);
$text = strtolower($text);
$text = str_replace(' ', '_', $text);

If you want to get fancy, though, you can do it in one line:

$text = strtolower(str_replace(' ', '_', substr($text, 0, 10)));

Extracting double-digit months and days from a Python date

you can use a string formatter to pad any integer with zeros. It acts just like C's printf.

>>> d = datetime.date.today()
>>> '%02d' % d.month
'03'

Updated for py36: Use f-strings! For general ints you can use the d formatter and explicitly tell it to pad with zeros:

 >>> d = datetime.date.today()
 >>> f"{d.month:02d}"
 '07'

But datetimes are special and come with special formatters that are already zero padded:

 >>> f"{d:%d}"  # the day
 '01'
 >>> f"{d:%m}"  # the month
 '07'

mysql count group by having

SELECT COUNT(*) 
FROM   (SELECT COUNT(*) 
        FROM   movies 
        GROUP  BY id 
        HAVING COUNT(genre) = 4) t

Programmatically read from STDIN or input file in Perl

while (<>) {
print;
}

will read either from a file specified on the command line or from stdin if no file is given

If you are required this loop construction in command line, then you may use -n option:

$ perl -ne 'print;'

Here you just put code between {} from first example into '' in second

Best way to do nested case statement logic in SQL Server

I personally do it this way, keeping the embedded CASE expressions confined. I'd also put comments in to explain what is going on. If it is too complex, break it out into function.

SELECT
    col1,
    col2,
    col3,
    CASE WHEN condition THEN
      CASE WHEN condition1 THEN
        CASE WHEN condition2 THEN calculation1
        ELSE calculation2 END
      ELSE
        CASE WHEN condition2 THEN calculation3
        ELSE calculation4 END
      END
    ELSE CASE WHEN condition1 THEN 
      CASE WHEN condition2 THEN calculation5
      ELSE calculation6 END
    ELSE CASE WHEN condition2 THEN calculation7
         ELSE calculation8 END
    END AS 'calculatedcol1',
    col4,
    col5 -- etc
FROM table

How to list processes attached to a shared memory segment in linux?

I don't think you can do this with the standard tools. You can use ipcs -mp to get the process ID of the last process to attach/detach but I'm not aware of how to get all attached processes with ipcs.

With a two-process-attached segment, assuming they both stayed attached, you can possibly figure out from the creator PID cpid and last-attached PID lpid which are the two processes but that won't scale to more than two processes so its usefulness is limited.

The cat /proc/sysvipc/shm method seems similarly limited but I believe there's a way to do it with other parts of the /proc filesystem, as shown below:

When I do a grep on the procfs maps for all processes, I get entries containing lines for the cpid and lpid processes.

For example, I get the following shared memory segment from ipcs -m:

------ Shared Memory Segments --------
key        shmid      owner      perms      bytes      nattch     status      
0x00000000 123456     pax        600        1024       2          dest

and, from ipcs -mp, the cpid is 3956 and the lpid is 9999 for that given shared memory segment (123456).

Then, with the command grep 123456 /proc/*/maps, I see:

/proc/3956/maps: blah blah blah 123456 /SYSV000000 (deleted)
/proc/9999/maps: blah blah blah 123456 /SYSV000000 (deleted)

So there is a way to get the processes that attached to it. I'm pretty certain that the dest status and (deleted) indicator are because the creator has marked the segment for destruction once the final detach occurs, not that it's already been destroyed.

So, by scanning of the /proc/*/maps "files", you should be able to discover which PIDs are currently attached to a given segment.

What is default session timeout in ASP.NET?

It depends on either the configuration or programmatic change.
Therefore the most reliable way to check the current value is at runtime via code.

See the HttpSessionState.Timeout property; default value is 20 minutes.

You can access this propery in ASP.NET via HttpContext:

this.HttpContext.Session.Timeout // ASP.NET MVC controller
Page.Session.Timeout // ASP.NET Web Forms code-behind
HttpContext.Current.Session.Timeout // Elsewhere

How to generate XML file dynamically using PHP?

Hope this code may help you out. Easy and simple solution

$dom = new DOMDocument();
$dom->encoding = 'utf-8';
$dom->xmlVersion = '1.0';
$dom->formatOutput = true;
$xml_file_name = './movies_list.xml'; //You can give your path to save file.
$root = $dom->createElement('Movies');
    $movie_node = $dom->createElement('movie');
    $attr_movie_id = new DOMAttr('movie_id', '5467');
    $movie_node->setAttributeNode($attr_movie_id);
        
        $child_node_title = $dom->createElement('Title', 'The Campaign');
        $movie_node->appendChild($child_node_title);
        
        $child_node_year = $dom->createElement('Year', 2012);
        $movie_node->appendChild($child_node_year);
        
        $child_node_genre = $dom->createElement('Genre', 'The Campaign');
        $movie_node->appendChild($child_node_genre);
        
        $child_node_ratings = $dom->createElement('Ratings', 6.2);
        $movie_node->appendChild($child_node_ratings);
    $root->appendChild($movie_node);
$dom->appendChild($root);
$dom->save($xml_file_name);

For more information visit this to get information in details: https://www.guru99.com/php-and-xml.html

What is username and password when starting Spring Boot with Tomcat?

You can also ask the user for the credentials and set them dynamically once the server starts (very effective when you need to publish the solution on a customer environment):

@EnableWebSecurity
public class SecurityConfig {

    private static final Logger log = LogManager.getLogger();

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        log.info("Setting in-memory security using the user input...");

        Scanner scanner = new Scanner(System.in);
        String inputUser = null;
        String inputPassword = null;
        System.out.println("\nPlease set the admin credentials for this web application");
        while (true) {
            System.out.print("user: ");
            inputUser = scanner.nextLine();
            System.out.print("password: ");
            inputPassword = scanner.nextLine();
            System.out.print("confirm password: ");
            String inputPasswordConfirm = scanner.nextLine();

            if (inputUser.isEmpty()) {
                System.out.println("Error: user must be set - please try again");
            } else if (inputPassword.isEmpty()) {
                System.out.println("Error: password must be set - please try again");
            } else if (!inputPassword.equals(inputPasswordConfirm)) {
                System.out.println("Error: password and password confirm do not match - please try again");
            } else {
                log.info("Setting the in-memory security using the provided credentials...");
                break;
            }
            System.out.println("");
        }
        scanner.close();

        if (inputUser != null && inputPassword != null) {
             auth.inMemoryAuthentication()
                .withUser(inputUser)
                .password(inputPassword)
                .roles("USER");
        }
    }
}

(May 2018) An update - this will work on spring boot 2.x:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private static final Logger log = LogManager.getLogger();

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // Note: 
        // Use this to enable the tomcat basic authentication (tomcat popup rather than spring login page)
        // Note that the CSRf token is disabled for all requests
        log.info("Disabling CSRF, enabling basic authentication...");
        http
        .authorizeRequests()
            .antMatchers("/**").authenticated() // These urls are allowed by any authenticated user
        .and()
            .httpBasic();
        http.csrf().disable();
    }

    @Bean
    public UserDetailsService userDetailsService() {
        log.info("Setting in-memory security using the user input...");

        String username = null;
        String password = null;

        System.out.println("\nPlease set the admin credentials for this web application (will be required when browsing to the web application)");
        Console console = System.console();

        // Read the credentials from the user console: 
        // Note: 
        // Console supports password masking, but is not supported in IDEs such as eclipse; 
        // thus if in IDE (where console == null) use scanner instead:
        if (console == null) {
            // Use scanner:
            Scanner scanner = new Scanner(System.in);
            while (true) {
                System.out.print("Username: ");
                username = scanner.nextLine();
                System.out.print("Password: ");
                password = scanner.nextLine();
                System.out.print("Confirm Password: ");
                String inputPasswordConfirm = scanner.nextLine();

                if (username.isEmpty()) {
                    System.out.println("Error: user must be set - please try again");
                } else if (password.isEmpty()) {
                    System.out.println("Error: password must be set - please try again");
                } else if (!password.equals(inputPasswordConfirm)) {
                    System.out.println("Error: password and password confirm do not match - please try again");
                } else {
                    log.info("Setting the in-memory security using the provided credentials...");
                    break;
                }
                System.out.println("");
            }
            scanner.close();
        } else {
            // Use Console
            while (true) {
                username = console.readLine("Username: ");
                char[] passwordChars = console.readPassword("Password: ");
                password = String.valueOf(passwordChars);
                char[] passwordConfirmChars = console.readPassword("Confirm Password: ");
                String passwordConfirm = String.valueOf(passwordConfirmChars);

                if (username.isEmpty()) {
                    System.out.println("Error: Username must be set - please try again");
                } else if (password.isEmpty()) {
                    System.out.println("Error: Password must be set - please try again");
                } else if (!password.equals(passwordConfirm)) {
                    System.out.println("Error: Password and Password Confirm do not match - please try again");
                } else {
                    log.info("Setting the in-memory security using the provided credentials...");
                    break;
                }
                System.out.println("");
            }
        }

        // Set the inMemoryAuthentication object with the given credentials:
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        if (username != null && password != null) {
            String encodedPassword = passwordEncoder().encode(password);
            manager.createUser(User.withUsername(username).password(encodedPassword).roles("USER").build());
        }
        return manager;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

How to add a progress bar to a shell script?

Most unix commands will not give you the sort of direct feedback from which you can do this. Some will give you output on stdout or stderr that you can use.

For something like tar you could use the -v switch and pipe the output to a program that updates a small animation for each line it reads. As tar writes out a list of files it's unravelled the program can update the animation. To do a percent complete you would have to know the number of files and count the lines.

cp doesn't give this sort of output as far as I know. To monitor the progress of cp you would have to monitor the source and destination files and watch the size of the destination. You could write a small c program using the stat (2) system call to get the file size. This would read the size of the source then poll the destination file and update a % complete bar based on the size of the file written to date.

jQuery datepicker set selected date, on the fly

Check that the date you are trying to set it to lies within the allowed date range if the minDate or maxDate options are set.

Loading all images using imread from a given folder

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

import cv2
import os

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

take(1) vs first()

Operators first() and take(1) aren't the same.

The first() operator takes an optional predicate function and emits an error notification when no value matched when the source completed.

For example this will emit an error:

import { EMPTY, range } from 'rxjs';
import { first, take } from 'rxjs/operators';

EMPTY.pipe(
  first(),
).subscribe(console.log, err => console.log('Error', err));

... as well as this:

range(1, 5).pipe(
  first(val => val > 6),
).subscribe(console.log, err => console.log('Error', err));

While this will match the first value emitted:

range(1, 5).pipe(
  first(),
).subscribe(console.log, err => console.log('Error', err));

On the other hand take(1) just takes the first value and completes. No further logic is involved.

range(1, 5).pipe(
  take(1),
).subscribe(console.log, err => console.log('Error', err));

Then with empty source Observable it won't emit any error:

EMPTY.pipe(
  take(1),
).subscribe(console.log, err => console.log('Error', err));

Jan 2019: Updated for RxJS 6

Cluster analysis in R: determine the optimal number of clusters

Splendid answer from Ben. However I'm surprised that the Affinity Propagation (AP) method has been here suggested just to find the number of cluster for the k-means method, where in general AP do a better job clustering the data. Please see the scientific paper supporting this method in Science here:

Frey, Brendan J., and Delbert Dueck. "Clustering by passing messages between data points." science 315.5814 (2007): 972-976.

So if you are not biased toward k-means I suggest to use AP directly, which will cluster the data without requiring knowing the number of clusters:

library(apcluster)
apclus = apcluster(negDistMat(r=2), data)
show(apclus)

If negative euclidean distances are not appropriate, then you can use another similarity measures provided in the same package. For example, for similarities based on Spearman correlations, this is what you need:

sim = corSimMat(data, method="spearman")
apclus = apcluster(s=sim)

Please note that those functions for similarities in the AP package are just provided for simplicity. In fact, apcluster() function in R will accept any matrix of correlations. The same before with corSimMat() can be done with this:

sim = cor(data, method="spearman")

or

sim = cor(t(data), method="spearman")

depending on what you want to cluster on your matrix (rows or cols).