Programs & Examples On #Class names

How can I get a precise time, for example in milliseconds in Objective-C?

Please do not use NSDate, CFAbsoluteTimeGetCurrent, or gettimeofday to measure elapsed time. These all depend on the system clock, which can change at any time due to many different reasons, such as network time sync (NTP) updating the clock (happens often to adjust for drift), DST adjustments, leap seconds, and so on.

This means that if you're measuring your download or upload speed, you will get sudden spikes or drops in your numbers that don't correlate with what actually happened; your performance tests will have weird incorrect outliers; and your manual timers will trigger after incorrect durations. Time might even go backwards, and you end up with negative deltas, and you can end up with infinite recursion or dead code (yeah, I've done both of these).

Use mach_absolute_time. It measures real seconds since the kernel was booted. It is monotonically increasing (will never go backwards), and is unaffected by date and time settings. Since it's a pain to work with, here's a simple wrapper that gives you NSTimeIntervals:

// LBClock.h
@interface LBClock : NSObject
+ (instancetype)sharedClock;
// since device boot or something. Monotonically increasing, unaffected by date and time settings
- (NSTimeInterval)absoluteTime;

- (NSTimeInterval)machAbsoluteToTimeInterval:(uint64_t)machAbsolute;
@end

// LBClock.m
#include <mach/mach.h>
#include <mach/mach_time.h>

@implementation LBClock
{
    mach_timebase_info_data_t _clock_timebase;
}

+ (instancetype)sharedClock
{
    static LBClock *g;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        g = [LBClock new];
    });
    return g;
}

- (id)init
{
    if(!(self = [super init]))
        return nil;
    mach_timebase_info(&_clock_timebase);
    return self;
}

- (NSTimeInterval)machAbsoluteToTimeInterval:(uint64_t)machAbsolute
{
    uint64_t nanos = (machAbsolute * _clock_timebase.numer) / _clock_timebase.denom;

    return nanos/1.0e9;
}

- (NSTimeInterval)absoluteTime
{
    uint64_t machtime = mach_absolute_time();
    return [self machAbsoluteToTimeInterval:machtime];
}
@end

How to check if another instance of my shell script is running

Here's one trick you'll see in various places:

status=`ps -efww | grep -w "[a]bc.sh" | awk -vpid=$$ '$2 != pid { print $2 }'`
if [ ! -z "$status" ]; then
    echo "[`date`] : abc.sh : Process is already running"
    exit 1;
fi

The brackets around the [a] (or pick a different letter) prevent grep from finding itself. This makes the grep -v grep bit unnecessary. I also removed the grep -v $$ and fixed the awk part to accomplish the same thing.

Why is super.super.method(); not allowed in Java?

It would seem to be possible to at least get the class of the superclass's superclass, though not necessarily the instance of it, using reflection; if this might be useful, please consider the Javadoc at http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html#getSuperclass()

Change one value based on another value in pandas

You can use map, it can map vales from a dictonairy or even a custom function.

Suppose this is your df:

    ID First_Name Last_Name
0  103          a         b
1  104          c         d

Create the dicts:

fnames = {103: "Matt", 104: "Mr"}
lnames = {103: "Jones", 104: "X"}

And map:

df['First_Name'] = df['ID'].map(fnames)
df['Last_Name'] = df['ID'].map(lnames)

The result will be:

    ID First_Name Last_Name
0  103       Matt     Jones
1  104         Mr         X

Or use a custom function:

names = {103: ("Matt", "Jones"), 104: ("Mr", "X")}
df['First_Name'] = df['ID'].map(lambda x: names[x][0])

Is floating point math broken?

Another way to look at this: Used are 64 bits to represent numbers. As consequence there is no way more than 2**64 = 18,446,744,073,709,551,616 different numbers can be precisely represented.

However, Math says there are already infinitely many decimals between 0 and 1. IEE 754 defines an encoding to use these 64 bits efficiently for a much larger number space plus NaN and +/- Infinity, so there are gaps between accurately represented numbers filled with numbers only approximated.

Unfortunately 0.3 sits in a gap.

How to create and add users to a group in Jenkins for authentication?

You could use Role Strategy plugin for that purpose. It works like a charm, just setup some roles and assign them. Even on project-specific level.

Python speed testing - Time Difference - milliseconds

datetime.timedelta is just the difference between two datetimes ... so it's like a period of time, in days / seconds / microseconds

>>> import datetime
>>> a = datetime.datetime.now()
>>> b = datetime.datetime.now()
>>> c = b - a

>>> c
datetime.timedelta(0, 4, 316543)
>>> c.days
0
>>> c.seconds
4
>>> c.microseconds
316543

Be aware that c.microseconds only returns the microseconds portion of the timedelta! For timing purposes always use c.total_seconds().

You can do all sorts of maths with datetime.timedelta, eg:

>>> c / 10
datetime.timedelta(0, 0, 431654)

It might be more useful to look at CPU time instead of wallclock time though ... that's operating system dependant though ... under Unix-like systems, check out the 'time' command.

Where is the Postgresql config file: 'postgresql.conf' on Windows?

postgresql.conf is located in PostgreSQL's data directory. The data directory is configured during the setup and the setting is saved as PGDATA entry in c:\Program Files\PostgreSQL\<version>\pg_env.bat, for example

@ECHO OFF
REM The script sets environment variables helpful for PostgreSQL

@SET PATH="C:\Program Files\PostgreSQL\<version>\bin";%PATH%
@SET PGDATA=D:\PostgreSQL\<version>\data
@SET PGDATABASE=postgres
@SET PGUSER=postgres
@SET PGPORT=5432
@SET PGLOCALEDIR=C:\Program Files\PostgreSQL\<version>\share\locale

Alternatively you can query your database with SHOW config_file; if you are a superuser.

Add bottom line to view in SwiftUI / Swift / Objective-C / Xamarin

None of these solutions really met my expectations. I wanted to subclass the TextField since I don't want to set the border manually all the time. I also wanted to change the border color e.g. for an error. So here's my solution with Anchors:

class CustomTextField: UITextField {

    var bottomBorder = UIView()

    override func awakeFromNib() {

            // Setup Bottom-Border

            self.translatesAutoresizingMaskIntoConstraints = false

            bottomBorder = UIView.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
            bottomBorder.backgroundColor = UIColor(rgb: 0xE2DCD1) // Set Border-Color
            bottomBorder.translatesAutoresizingMaskIntoConstraints = false

            addSubview(bottomBorder)

            bottomBorder.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
            bottomBorder.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
            bottomBorder.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
            bottomBorder.heightAnchor.constraint(equalToConstant: 1).isActive = true // Set Border-Strength

    }
}

---- Optional ----

To change the color add sth like this to the CustomTextField Class:

@IBInspectable var hasError: Bool = false {
    didSet {

        if (hasError) {

            bottomBorder.backgroundColor = UIColor.red

        } else {

            bottomBorder.backgroundColor = UIColor(rgb: 0xE2DCD1)

        }

    }
}

And to trigger the Error call this after you created an instance of CustomTextField

textField.hasError = !textField.hasError

enter image description here

Hope it helps someone ;)

What's the difference of $host and $http_host in Nginx

$host is a variable of the Core module.

$host

This variable is equal to line Host in the header of request or name of the server processing the request if the Host header is not available.

This variable may have a different value from $http_host in such cases: 1) when the Host input header is absent or has an empty value, $host equals to the value of server_name directive; 2)when the value of Host contains port number, $host doesn't include that port number. $host's value is always lowercase since 0.8.17.

$http_host is also a variable of the same module but you won't find it with that name because it is defined generically as $http_HEADER (ref).

$http_HEADER

The value of the HTTP request header HEADER when converted to lowercase and with 'dashes' converted to 'underscores', e.g. $http_user_agent, $http_referer...;


Summarizing:

  • $http_host equals always the HTTP_HOST request header.
  • $host equals $http_host, lowercase and without the port number (if present), except when HTTP_HOST is absent or is an empty value. In that case, $host equals the value of the server_name directive of the server which processed the request.

Quickly getting to YYYY-mm-dd HH:MM:SS in Perl

if you just want a human readable time string and not that exact format:

$t = localtime;
print "$t\n";

prints

Mon Apr 27 10:16:19 2015

or whatever is configured for your locale.

What is difference between arm64 and armhf?

Update: Yes, I understand that this answer does not explain the difference between arm64 and armhf. There is a great answer that does explain that on this page. This answer was intended to help set the asker on the right path, as they clearly had a misunderstanding about the capabilities of the Raspberry Pi at the time of asking.

Where are you seeing that the architecture is armhf? On my Raspberry Pi 3, I get:

$ uname -a
armv7l

Anyway, armv7 indicates that the system architecture is 32-bit. The first ARM architecture offering 64-bit support is armv8. See this table for reference.

You are correct that the CPU in the Raspberry Pi 3 is 64-bit, but the Raspbian OS has not yet been updated for a 64-bit device. 32-bit software can run on a 64-bit system (but not vice versa). This is why you're not seeing the architecture reported as 64-bit.

You can follow the GitHub issue for 64-bit support here, if you're interested.

cannot open shared object file: No such file or directory

sudo ldconfig

ldconfig creates the necessary links and cache to the most recent shared libraries found in the directories specified on the command line, in the file /etc/ld.so.conf, and in the trusted directories (/lib and /usr/lib).

Generally package manager takes care of this while installing the new library, but not always (specially when you install library with cmake).

And if the output of this is empty

$ echo $LD_LIBRARY_PATH

Please set the default path

$ LD_LIBRARY_PATH=/usr/local/lib

Jquery: how to trigger click event on pressing enter key

This appear to be default behaviour now, so it's enough to do:

$("#press-enter").on("click", function(){alert("You `clicked' or 'Entered' me!")})

You can try it in this JSFiddle

Tested on: Chrome 56.0 and Firefox (Dev Edition) 54.0a2, both with jQuery 2.2.x and 3.x

Eclipse does not start when I run the exe?

Try to install Eclipse into a folder without spaces.

ng-if check if array is empty

post.capabilities.items will still be defined because it's an empty array, if you check post.capabilities.items.length it should work fine because 0 is falsy.

Parsing JSON in Spring MVC using Jackson JSON

I'm using json lib from http://json-lib.sourceforge.net/
json-lib-2.1-jdk15.jar

import net.sf.json.JSONObject;
...

public void send()
{
    //put attributes
    Map m = New HashMap();
    m.put("send_to","[email protected]");
    m.put("email_subject","this is a test email");
    m.put("email_content","test email content");

    //generate JSON Object
    JSONObject json = JSONObject.fromObject(content);
    String message = json.toString();
    ...
}

public void receive(String jsonMessage)
{
    //parse attributes
    JSONObject json = JSONObject.fromObject(jsonMessage);
    String to = (String) json.get("send_to");
    String title = (String) json.get("email_subject");
    String content = (String) json.get("email_content");
    ...
}

More samples here http://json-lib.sourceforge.net/usage.html

How to execute a program or call a system command from Python

There are lots of different libraries which allow you to call external commands with Python. For each library I've given a description and shown an example of calling an external command. The command I used as the example is ls -l (list all files). If you want to find out more about any of the libraries I've listed and linked the documentation for each of them.

Sources:

These are all the libraries:

Hopefully this will help you make a decision on which library to use :)

subprocess

Subprocess allows you to call external commands and connect them to their input/output/error pipes (stdin, stdout, and stderr). Subprocess is the default choice for running commands, but sometimes other modules are better.

subprocess.run(["ls", "-l"]) # Run command
subprocess.run(["ls", "-l"], stdout=subprocess.PIPE) # This will run the command and return any output
subprocess.run(shlex.split("ls -l")) # You can also use the shlex library to split the command

os

os is used for "operating system dependent functionality". It can also be used to call external commands with os.system and os.popen (Note: There is also a subprocess.popen). os will always run the shell and is a simple alternative for people who don't need to, or don't know how to use subprocess.run.

os.system("ls -l") # run command
os.popen("ls -l").read() # This will run the command and return any output

sh

sh is a subprocess interface which lets you call programs as if they were functions. This is useful if you want to run a command multiple times.

sh.ls("-l") # Run command normally
ls_cmd = sh.Command("ls") # Save command as a variable
ls_cmd() # Run command as if it were a function

plumbum

plumbum is a library for "script-like" Python programs. You can call programs like functions as in sh. Plumbum is useful if you want to run a pipeline without the shell.

ls_cmd = plumbum.local("ls -l") # get command
ls_cmd() # run command

pexpect

pexpect lets you spawn child applications, control them and find patterns in their output. This is a better alternative to subprocess for commands that expect a tty on Unix.

pexpect.run("ls -l") # Run command as normal
child = pexpect.spawn('scp foo [email protected]:.') # Spawns child application
child.expect('Password:') # When this is the output
child.sendline('mypassword')

fabric

fabric is a Python 2.5 and 2.7 library. It allows you to execute local and remote shell commands. Fabric is simple alternative for running commands in a secure shell (SSH)

fabric.operations.local('ls -l') # Run command as normal
fabric.operations.local('ls -l', capture = True) # Run command and receive output

envoy

envoy is known as "subprocess for humans". It is used as a convenience wrapper around the subprocess module.

r = envoy.run("ls -l") # Run command
r.std_out # get output

commands

commands contains wrapper functions for os.popen, but it has been removed from Python 3 since subprocess is a better alternative.

The edit was based on J.F. Sebastian's comment.

How do I set environment variables from Java?

Poking around online, it looks like it might be possible to do this with JNI. You'd then have to make a call to putenv() from C, and you'd (presumably) have to do it in a way that worked on both Windows and UNIX.

If all that can be done, it surely wouldn't be too hard for Java itself to support this instead of putting me in a straight jacket.

A Perl-speaking friend elsewhere suggests that this is because environment variables are process global and Java is striving for good isolation for good design.

Getting a random value from a JavaScript array

randojs makes this a little more simple and readable:

_x000D_
_x000D_
console.log( rando(['January', 'February', 'March']).value );
_x000D_
<script src="https://randojs.com/1.0.0.js"></script>
_x000D_
_x000D_
_x000D_

Apache Tomcat Not Showing in Eclipse Server Runtime Environments

Help -> check for updates upon Eclipse update solved the issue

json_decode() expects parameter 1 to be string, array given

json_decode() is used to decode a json string to an array/data object. json_encode() creates a json string from an array or data. You are using the wrong function my friend, try json_encode();

SyntaxError: multiple statements found while compiling a single statement

In the shell, you can't execute more than one statement at a time:

>>> x = 5
y = 6
SyntaxError: multiple statements found while compiling a single statement

You need to execute them one by one:

>>> x = 5
>>> y = 6
>>>

When you see multiple statements are being declared, that means you're seeing a script, which will be executed later. But in the interactive interpreter, you can't do more than one statement at a time.

How do I count the number of occurrences of a char in a String?

A shorter example is

String text = "a.b.c.d";
int count = text.split("\\.",-1).length-1;

What does "xmlns" in XML mean?

It means XML namespace.

Basically, every element (or attribute) in XML belongs to a namespace, a way of "qualifying" the name of the element.

Imagine you and I both invent our own XML. You invent XML to describe people, I invent mine to describe cities. Both of us include an element called name. Yours refers to the person’s name, and mine to the city name—OK, it’s a little bit contrived.

<person>
    <name>Rob</name>
    <age>37</age>
    <homecity>
        <name>London</name>
        <lat>123.000</lat>
        <long>0.00</long>
    </homecity>
</person>

If our two XMLs were combined into a single document, how would we tell the two names apart? As you can see above, there are two name elements, but they both have different meanings.

The answer is that you and I would both assign a namespace to our XML, which we would make unique:

<personxml:person xmlns:personxml="http://www.your.example.com/xml/person"
                  xmlns:cityxml="http://www.my.example.com/xml/cities">
    <personxml:name>Rob</personxml:name>
    <personxml:age>37</personxml:age>
    <cityxml:homecity>
        <cityxml:name>London</cityxml:name>
        <cityxml:lat>123.000</cityxml:lat>
        <cityxml:long>0.00</cityxml:long>
    </cityxml:homecity>
</personxml:person>

Now we’ve fully qualified our XML, there is no ambiguity as to what each name element means. All of the tags that start with personxml: are tags belonging to your XML, all the ones that start with cityxml: are mine.

There are a few points to note:

  • If you exclude any namespace declarations, things are considered to be in the default namespace.

  • If you declare a namespace without the identifier, that is, xmlns="http://somenamespace", rather than xmlns:rob="somenamespace", it specifies the default namespace for the document.

  • The actual namespace itself, often a IRI, is of no real consequence. It should be unique, so people tend to choose a IRI/URI that they own, but it has no greater meaning than that. Sometimes people will place the schema (definition) for the XML at the specified IRI, but that is a convention of some people only.

  • The prefix is of no consequence either. The only thing that matters is what namespace the prefix is defined as. Several tags beginning with different prefixes, all of which map to the same namespace are considered to be the same.

    For instance, if the prefixes personxml and mycityxml both mapped to the same namespace (as in the snippet below), then it wouldn't matter if you prefixed a given element with personxml or mycityxml, they'd both be treated as the same thing by an XML parser. The point is that an XML parser doesn't care what you've chosen as the prefix, only the namespace it maps too. The prefix is just an indirection pointing to the namespace.

    <personxml:person 
         xmlns:personxml="http://example.com/same/url"
         xmlns:mycityxml="http://example.com/same/url" />
    
  • Attributes can be qualified but are generally not. They also do not inherit their namespace from the element they are on, as opposed to elements (see below).

Also, element namespaces are inherited from the parent element. In other words I could equally have written the above XML as

<person xmlns="http://www.your.example.com/xml/person">
    <name>Rob</name>
    <age>37</age>
    <homecity xmlns="http://www.my.example.com/xml/cities">
        <name>London</name>
        <lat>123.000</lat>
        <long>0.00</long>
    </homecity>
</person>

XPath: difference between dot and text()

There is a difference between . and text(), but this difference might not surface because of your input document.

If your input document looked like (the simplest document one can imagine given your XPath expressions)

Example 1

<html>
  <a>Ask Question</a>
</html>

Then //a[text()="Ask Question"] and //a[.="Ask Question"] indeed return exactly the same result. But consider a different input document that looks like

Example 2

<html>
  <a>Ask Question<other/>
  </a>
</html>

where the a element also has a child element other that follows immediately after "Ask Question". Given this second input document, //a[text()="Ask Question"] still returns the a element, while //a[.="Ask Question"] does not return anything!


This is because the meaning of the two predicates (everything between [ and ]) is different. [text()="Ask Question"] actually means: return true if any of the text nodes of an element contains exactly the text "Ask Question". On the other hand, [.="Ask Question"] means: return true if the string value of an element is identical to "Ask Question".

In the XPath model, text inside XML elements can be partitioned into a number of text nodes if other elements interfere with the text, as in Example 2 above. There, the other element is between "Ask Question" and a newline character that also counts as text content.

To make an even clearer example, consider as an input document:

Example 3

<a>Ask Question<other/>more text</a>

Here, the a element actually contains two text nodes, "Ask Question" and "more text", since both are direct children of a. You can test this by running //a/text() on this document, which will return (individual results separated by ----):

Ask Question
-----------------------
more text

So, in such a scenario, text() returns a set of individual nodes, while . in a predicate evaluates to the string concatenation of all text nodes. Again, you can test this claim with the path expression //a[.='Ask Questionmore text'] which will successfully return the a element.


Finally, keep in mind that some XPath functions can only take one single string as an input. As LarsH has pointed out in the comments, if such an XPath function (e.g. contains()) is given a sequence of nodes, it will only process the first node and silently ignore the rest.

What is a monad?

http://mikehadlow.blogspot.com/2011/02/monads-in-c-8-video-of-my-ddd9-monad.html

This is the video you are looking for.

Demonstrating in C# what the problem is with composition and aligning the types, and then implementing them properly in C#. Towards the end he displays how the same C# code looks in F# and finally in Haskell.

Quick Way to Implement Dictionary in C

The quickest way would be to use an already-existing implementation, like uthash.

And, if you really want to code it yourself, the algorithms from uthash can be examined and re-used. It's BSD-licensed so, other than the requirement to convey the copyright notice, you're pretty well unlimited in what you can do with it.

PHP Pass by reference in foreach

This :

$a = array ('zero','one','two', 'three');

foreach ($a as &$v) {

}

foreach ($a as $v) {
    echo $v.PHP_EOL;
}

is the same as

$a = array ('zero','one','two', 'three');

$v = &$a[3];

for ($i = 0; $i < 4; $i++) {
    $v = $a[$i];
    echo $v.PHP_EOL; 
}

OR

$a = array ('zero','one','two', 'three');

for ($i = 0; $i < 4; $i++) {
    $a[3] = $a[$i];
    echo $a[3].PHP_EOL; 
}

OR

$a = array ('zero','one','two', 'three');

$a[3] = $a[0];
echo $a[3].PHP_EOL;

$a[3] = $a[1]; 
echo $a[3].PHP_EOL;

$a[3] = $a[2];
echo $a[3].PHP_EOL;

$a[3] = $a[3]; 
echo $a[3].PHP_EOL;

Set cursor position on contentEditable <div>

After playing around I've modified eyelidlessness' answer above and made it a jQuery plugin so you can just do one of these:

var html = "The quick brown fox";
$div.html(html);

// Select at the text "quick":
$div.setContentEditableSelection(4, 5);

// Select at the beginning of the contenteditable div:
$div.setContentEditableSelection(0);

// Select at the end of the contenteditable div:
$div.setContentEditableSelection(html.length);

Excuse the long code post, but it may help someone:

$.fn.setContentEditableSelection = function(position, length) {
    if (typeof(length) == "undefined") {
        length = 0;
    }

    return this.each(function() {
        var $this = $(this);
        var editable = this;
        var selection;
        var range;

        var html = $this.html();
        html = html.substring(0, position) +
            '<a id="cursorStart"></a>' +
            html.substring(position, position + length) +
            '<a id="cursorEnd"></a>' +
            html.substring(position + length, html.length);
        console.log(html);
        $this.html(html);

        // Populates selection and range variables
        var captureSelection = function(e) {
            // Don't capture selection outside editable region
            var isOrContainsAnchor = false,
                isOrContainsFocus = false,
                sel = window.getSelection(),
                parentAnchor = sel.anchorNode,
                parentFocus = sel.focusNode;

            while (parentAnchor && parentAnchor != document.documentElement) {
                if (parentAnchor == editable) {
                    isOrContainsAnchor = true;
                }
                parentAnchor = parentAnchor.parentNode;
            }

            while (parentFocus && parentFocus != document.documentElement) {
                if (parentFocus == editable) {
                    isOrContainsFocus = true;
                }
                parentFocus = parentFocus.parentNode;
            }

            if (!isOrContainsAnchor || !isOrContainsFocus) {
                return;
            }

            selection = window.getSelection();

            // Get range (standards)
            if (selection.getRangeAt !== undefined) {
                range = selection.getRangeAt(0);

                // Get range (Safari 2)
            } else if (
                document.createRange &&
                selection.anchorNode &&
                selection.anchorOffset &&
                selection.focusNode &&
                selection.focusOffset
            ) {
                range = document.createRange();
                range.setStart(selection.anchorNode, selection.anchorOffset);
                range.setEnd(selection.focusNode, selection.focusOffset);
            } else {
                // Failure here, not handled by the rest of the script.
                // Probably IE or some older browser
            }
        };

        // Slight delay will avoid the initial selection
        // (at start or of contents depending on browser) being mistaken
        setTimeout(function() {
            var cursorStart = document.getElementById('cursorStart');
            var cursorEnd = document.getElementById('cursorEnd');

            // Don't do anything if user is creating a new selection
            if (editable.className.match(/\sselecting(\s|$)/)) {
                if (cursorStart) {
                    cursorStart.parentNode.removeChild(cursorStart);
                }
                if (cursorEnd) {
                    cursorEnd.parentNode.removeChild(cursorEnd);
                }
            } else if (cursorStart) {
                captureSelection();
                range = document.createRange();

                if (cursorEnd) {
                    range.setStartAfter(cursorStart);
                    range.setEndBefore(cursorEnd);

                    // Delete cursor markers
                    cursorStart.parentNode.removeChild(cursorStart);
                    cursorEnd.parentNode.removeChild(cursorEnd);

                    // Select range
                    selection.removeAllRanges();
                    selection.addRange(range);
                } else {
                    range.selectNode(cursorStart);

                    // Select range
                    selection.removeAllRanges();
                    selection.addRange(range);

                    // Delete cursor marker
                    document.execCommand('delete', false, null);
                }
            }

            // Register selection again
            captureSelection();
        }, 10);
    });
};

How to make Java Set?

Like this:

import java.util.*;
Set<Integer> a = new HashSet<Integer>();
a.add( 1);
a.add( 2);
a.add( 3);

Or adding from an Array/ or multiple literals; wrap to a list, first.

Integer[] array = new Integer[]{ 1, 4, 5};
Set<Integer> b = new HashSet<Integer>();
b.addAll( Arrays.asList( b));         // from an array variable
b.addAll( Arrays.asList( 8, 9, 10));  // from literals

To get the intersection:

// copies all from A;  then removes those not in B.
Set<Integer> r = new HashSet( a);
r.retainAll( b);
// and print;   r.toString() implied.
System.out.println("A intersect B="+r);

Hope this answer helps. Vote for it!

How do you run a single query through mysql from the command line?

echo "select * from users;" | mysql -uroot -p -hslavedb.mydomain.com mydb_production

Using Pairs or 2-tuples in Java

I don't think there is a general purpose tuple class in Java but a custom one might be as easy as the following:

public class Tuple<X, Y> { 
  public final X x; 
  public final Y y; 
  public Tuple(X x, Y y) { 
    this.x = x; 
    this.y = y; 
  } 
} 

Of course, there are some important implications of how to design this class further regarding equality, immutability, etc., especially if you plan to use instances as keys for hashing.

Python: For each list element apply a function across the list

Some readable python:

def JoeCalimar(l):
    masterList = []
    for i in l:
        for j in l:
            masterList.append(1.*i/j)
    pos = masterList.index(min(masterList))
    a = pos/len(masterList)
    b = pos%len(masterList)
    return (l[a],l[b])

Let me know if something is not clear.

I lose my data when the container exits

In addition to Unferth's answer, it is recommended to create a Dockerfile.

In an empty directory, create a file called "Dockerfile" with the following contents.

FROM ubuntu
RUN apt-get install ping
ENTRYPOINT ["ping"]

Create an image using the Dockerfile. Let's use a tag so we don't need to remember the hexadecimal image number.

$ docker build -t iman/ping .

And then run the image in a container.

$ docker run iman/ping stackoverflow.com

Change bullets color of an HTML list without using span

If you can use an image then you can do this. And without an image you won't be able to change the color of the bullets only and not the text.

Using an image

li { list-style-image: url(images/yourimage.jpg); }

See

list-style-image

Without using an image

Then you have to edit the HTML markup and include a span inside the list and color the li and span with different colors.

How to determine device screen size category (small, normal, large, xlarge) using code?

private String getDeviceDensity() {
    int density = mContext.getResources().getDisplayMetrics().densityDpi;
    switch (density)
    {
        case DisplayMetrics.DENSITY_MEDIUM:
            return "MDPI";
        case DisplayMetrics.DENSITY_HIGH:
            return "HDPI";
        case DisplayMetrics.DENSITY_LOW:
            return "LDPI";
        case DisplayMetrics.DENSITY_XHIGH:
            return "XHDPI";
        case DisplayMetrics.DENSITY_TV:
            return "TV";
        case DisplayMetrics.DENSITY_XXHIGH:
            return "XXHDPI";
        case DisplayMetrics.DENSITY_XXXHIGH:
            return "XXXHDPI";
        default:
            return "Unknown";
    }
}

Using a PagedList with a ViewModel ASP.Net MVC

I figured out how to do this. I was building an application very similar to the example/tutorial you discussed in your original question.

Here's a snippet of the code that worked for me:

        int pageSize = 4;
        int pageNumber = (page ?? 1);
        //Used the following two formulas so that it doesn't round down on the returned integer
        decimal totalPages = ((decimal)(viewModel.Teachers.Count() /(decimal) pageSize));     
        ViewBag.TotalPages = Math.Ceiling(totalPages);  
        //These next two functions could maybe be reduced to one function....would require some testing and building
        viewModel.Teachers = viewModel.Teachers.ToPagedList(pageNumber, pageSize);
        ViewBag.OnePageofTeachers = viewModel.Teachers;
        ViewBag.PageNumber = pageNumber;

        return View(viewModel);

I added

using.PagedList;

to my controller as the tutorial states.

Now in my view my using statements etc at the top, NOTE i didnt change my using model statement.

@model CSHM.ViewModels.TeacherIndexData
@using PagedList;
@using PagedList.Mvc;
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />

and then at the bottom to build my paged list I used the following and it seems to work. I haven't yet built in the functionality for current sort, showing related data, filters, etc but i dont think it will be that difficult.

Page @ViewBag.PageNumber of @ViewBag.TotalPages

@Html.PagedListPager((IPagedList)ViewBag.OnePageofTeachers, page => Url.Action("Index", new { page }))

Hope that works for you. Let me know if it works!!

How to deal with page breaks when printing a large HTML table

Note: when using the page-break-after:always for the tag it will create a page break after the last bit of the table, creating an entirely blank page at the end every time! To fix this just change it to page-break-after:auto. It will break correctly and not create an extra blank page.

<html>
<head>
<style>
@media print
{
  table { page-break-after:auto }
  tr    { page-break-inside:avoid; page-break-after:auto }
  td    { page-break-inside:avoid; page-break-after:auto }
  thead { display:table-header-group }
  tfoot { display:table-footer-group }
}
</style>
</head>

<body>
....
</body>
</html>

Timestamp Difference In Hours for PostgreSQL

The first things popping up

EXTRACT(EPOCH FROM current_timestamp-somedate)/3600

May not be pretty, but unblocks the road. Could be prettier if division of interval by interval was defined.

Edit: if you want it greater than zero either use abs or greatest(...,0). Whichever suits your intention.

Edit++: the reason why I didn't use age is that age with a single argument, to quote the documentation: Subtract from current_date (at midnight). Meaning you don't get an accurate "age" unless running at midnight. Right now it's almost 1am here:

select age(current_timestamp);
       age        
------------------
 -00:52:40.826309
(1 row)

Overloading and overriding

in C# there is no Java like hidden override, without keyword override on overriding method! see these C# implementations:

variant 1 without override: result is 200

    class Car {
        public int topSpeed() {
            return 200;
        }
    }

    class Ferrari : Car {
        public int topSpeed(){
                return 400;
        }
    }

    static void Main(string[] args){
        Car car = new Ferrari();
        int num= car.topSpeed();
        Console.WriteLine("Top speed for this car is: "+num);
        Console.ReadLine();
    }

variant 2 with override keyword: result is 400

    class Car {
        public virtual int topSpeed() {
            return 200;
        }
    }

    class Ferrari : Car {
        public override int topSpeed(){
                return 400;
        }
    }

    static void Main(string[] args){
        Car car = new Ferrari();
        int num= car.topSpeed();
        Console.WriteLine("Top speed for this car is: "+num);
        Console.ReadLine();
    }

keyword virtual on Car class is opposite for final on Java, means not final, you can override, or implement if Car was abstract

How is a JavaScript hash map implemented?

Should you try this class Map:

_x000D_
_x000D_
var myMap = new Map();_x000D_
_x000D_
// setting the values_x000D_
myMap.set("1", 'value1');_x000D_
myMap.set("2", 'value2');_x000D_
myMap.set("3", 'value3');_x000D_
_x000D_
myMap.size; // 3_x000D_
_x000D_
// getting the values_x000D_
myMap.get("1");    // "value associated with "value1"_x000D_
myMap.get("2");       // "value associated with "value1"_x000D_
myMap.get("3");      // "value associated with "value3"
_x000D_
_x000D_
_x000D_

Notice: key and value can be any type.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

Python: How to keep repeating a program until a specific input is obtained?

you probably want to use a separate value that tracks if the input is valid:

good_input = None
while not good_input:
     user_input = raw_input("enter the right letter : ")
     if user_input in list_of_good_values: 
        good_input = user_input

Passing multiple variables in @RequestBody to a Spring MVC controller using Ajax

I have adapted the solution of Biju:

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;


public class JsonPathArgumentResolver implements HandlerMethodArgumentResolver{

    private static final String JSONBODYATTRIBUTE = "JSON_REQUEST_BODY";

    private ObjectMapper om = new ObjectMapper();

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(JsonArg.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        String jsonBody = getRequestBody(webRequest);

        JsonNode rootNode = om.readTree(jsonBody);
        JsonNode node = rootNode.path(parameter.getParameterName());    

        return om.readValue(node.toString(), parameter.getParameterType());
    }


    private String getRequestBody(NativeWebRequest webRequest){
        HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);

        String jsonBody = (String) webRequest.getAttribute(JSONBODYATTRIBUTE, NativeWebRequest.SCOPE_REQUEST);
        if (jsonBody==null){
            try {
                jsonBody = IOUtils.toString(servletRequest.getInputStream());
                webRequest.setAttribute(JSONBODYATTRIBUTE, jsonBody, NativeWebRequest.SCOPE_REQUEST);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return jsonBody;

    }

}

What's the different:

  • I'm using Jackson to convert json
  • I don't need a value in the annotation, you can read the name of the parameter out of the MethodParameter
  • I also read the type of the parameter out of the Methodparameter => so the solution should be generic (i tested it with string and DTOs)

BR

How to determine if string contains specific substring within the first X characters

This is what you need :

if (Value1.StartsWith("abc"))
{
found = true;
}

Export DataTable to Excel File

Try this to export the data to Excel file same as in DataTable and could customize also.

dtDataTable1 = ds.Tables[0];
    try
    {
        Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application();
        Workbook xlWorkBook = ExcelApp.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);

        for (int i = 1; i > 0; i--)
        {
            Sheets xlSheets = null;
            Worksheet xlWorksheet = null;
            //Create Excel sheet
            xlSheets = ExcelApp.Sheets;
            xlWorksheet = (Worksheet)xlSheets.Add(xlSheets[1], Type.Missing, Type.Missing, Type.Missing);
            xlWorksheet.Name = "MY FIRST EXCEL FILE";
            for (int j = 1; j < dtDataTable1.Columns.Count + 1; j++)
            {
                ExcelApp.Cells[i, j] = dtDataTable1.Columns[j - 1].ColumnName;
                ExcelApp.Cells[1, j].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Green);
                ExcelApp.Cells[i, j].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.WhiteSmoke);
            }
            // for the data of the excel
            for (int k = 0; k < dtDataTable1.Rows.Count; k++)
            {
                for (int l = 0; l < dtDataTable1.Columns.Count; l++)
                {
                    ExcelApp.Cells[k + 2, l + 1] = dtDataTable1.Rows[k].ItemArray[l].ToString();
                }
            }
            ExcelApp.Columns.AutoFit();
        }
        ((Worksheet)ExcelApp.ActiveWorkbook.Sheets[ExcelApp.ActiveWorkbook.Sheets.Count]).Delete();
        ExcelApp.Visible = true;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }

Read file from aws s3 bucket using node fs

I couldn't figure why yet, but the createReadStream/pipe approach didn't work for me. I was trying to download a large CSV file (300MB+) and I got duplicated lines. It seemed a random issue. The final file size varied in each attempt to download it.

I ended up using another way, based on AWS JS SDK examples:

var s3 = new AWS.S3();
var params = {Bucket: 'myBucket', Key: 'myImageFile.jpg'};
var file = require('fs').createWriteStream('/path/to/file.jpg');

s3.getObject(params).
    on('httpData', function(chunk) { file.write(chunk); }).
    on('httpDone', function() { file.end(); }).
    send();

This way, it worked like a charm.

How to insert element as a first child?

Extending on what @vabhatia said, this is what you want in native JavaScript (without JQuery).

ParentNode.insertBefore(<your element>, ParentNode.firstChild);

How do I fix a compilation error for unhandled exception on call to Thread.sleep()?

You can get rid of the first line. You don't need import java.lang.*;

Just change your 5th line to:

public static void main(String [] args) throws Exception

Convert Numeric value to Varchar

i think it should be

select convert(varchar(10),StandardCost) +'S' from DimProduct where ProductKey = 212

or

select cast(StandardCost as varchar(10)) + 'S' from DimProduct where ProductKey = 212

Cut Corners using CSS

If the parent element has a solid color background, you can use pseudo-elements to create the effect:

_x000D_
_x000D_
div {_x000D_
    height: 300px;_x000D_
    background: red;_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
div:before {_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    top: 0; right: 0;_x000D_
    border-top: 80px solid white;_x000D_
    border-left: 80px solid red;_x000D_
    width: 0;_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/2bZAW/


P.S. The upcoming border-corner-shape is exactly what you're looking for. Too bad it might get cut out of the spec, and never make it into any browsers in the wild :(

Cron and virtualenv

I've added the following script as manage.sh inside my Django project, it sources the virtualenv and then runs the manage.py script with whatever arguments you pass to it. It makes it very easy in general to run commands inside the virtualenv (cron, systemd units, basically anywhere):

#! /bin/bash

# this is a convenience script that first sources the venv (assumed to be in
# ../venv) and then executes manage.py with whatever arguments you supply the
# script with. this is useful if you need to execute the manage.py from
# somewhere where the venv isn't sourced (e.g. system scripts)

# get the script's location
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"

# source venv <- UPDATE THE PATH HERE WITH YOUR VENV's PATH
source $DIR/../venv/bin/activate

# run manage.py script
$DIR/manage.py "$@"

Then in your cron entry you can just run:

0 3 * * * /home/user/project/manage.sh command arg

Just remember that you need to make the manage.sh script executable

Comparing strings by their alphabetical order

For alphabetical order following nationalization, use Collator.

//Get the Collator for US English and set its strength to PRIMARY
Collator usCollator = Collator.getInstance(Locale.US);
usCollator.setStrength(Collator.PRIMARY);
if( usCollator.compare("abc", "ABC") == 0 ) {
    System.out.println("Strings are equivalent");
}

For a list of supported locales, see JDK 8 and JRE 8 Supported Locales.

<div style display="none" > inside a table not working

Semantically what you are trying is invalid html, table element cannot have a div element as a direct child. What you can do is, get your div element inside a td element and than try to hide it

Messages Using Command prompt in Windows 7

Type "msg /?" in the command prompt to get various ways of sending meessages to a user.

Type "net send /?" in the command prompt to get another variation of sending messages across.

Read file line by line using ifstream in C++

Expanding on the accepted answer, if the input is:

1,NYC
2,ABQ
...

you will still be able to apply the same logic, like this:

#include <fstream>

std::ifstream infile("thefile.txt");
if (infile.is_open()) {
    int number;
    std::string str;
    char c;
    while (infile >> number >> c >> str && c == ',')
        std::cout << number << " " << str << "\n";
}
infile.close();

jQuery vs document.querySelectorAll

If you are optimizing your page for IE8 or newer, you should really consider whether you need jquery or not. Modern browsers have many assets natively which jquery provides.

If you care for performance, you can have incredible performance benefits (2-10 faster) using native javascript: http://jsperf.com/jquery-vs-native-selector-and-element-style/2

I transformed a div-tagcloud from jquery to native javascript (IE8+ compatible), the results are impressive. 4 times faster with just a little overhead.

                    Number of lines       Execution Time                       
Jquery version :        340                    155ms
Native version :        370                    27ms

You Might Not Need Jquery provides a really nice overview, which native methods replace for which browser version.

http://youmightnotneedjquery.com/


Appendix: Further speed comparisons how native methods compete to jquery

C# - Winforms - Global Variables

One way,

Solution Explorer > Your Project > Properties > Settings.Settings. Click on this file and add define your settings from the IDE.

Access them by

Properties.Settings.Default.MySetting = "hello world";

Fetch frame count with ffmpeg

I use the php_ffmpeg then I can get all the times and all the frames of an movie . As belows

$input_file='/home/strone/workspace/play/CI/abc.rmvb';
$ffmpegObj = new ffmpeg_movie($input_file);
echo $ffmpegObj->getDuration();
    echo $ffmpegObj->getFrameCount();

And then the detail is on the page.

http://ffmpeg-php.sourceforge.net/doc/api/ffmpeg_movie.php

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

np.save('data.npy', num_arr) # save
new_num_arr = np.load('data.npy') # load

is not JSON serializable

class CountryListView(ListView):
     model = Country

    def render_to_response(self, context, **response_kwargs):

         return HttpResponse(json.dumps(list(self.get_queryset().values_list('code', flat=True))),mimetype="application/json") 

fixed the problem

also mimetype is important.

Must declare the scalar variable

-- CREATE OR ALTER PROCEDURE

ALTER PROCEDURE out (

@age INT,
@salary INT OUTPUT)

AS BEGIN

SELECT @salary = (SELECT SALARY FROM new_testing where AGE = @age  ORDER BY AGE OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY);

END

-----------------DECLARE THE OUTPUT VARIABLE---------------------------------

DECLARE @test INT

---------------------THEN EXECUTE THE QUERY---------------------------------

EXECUTE out 25 , @salary = @test OUTPUT

print @test

-------------------same output obtain without procedure------------------------------------------- SELECT * FROM new_testing where AGE = 25 ORDER BY AGE OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY

How can I use xargs to copy files that have spaces and quotes in their names?

find . -print0 | grep --null 'FooBar' | xargs -0 ...

I don't know about whether grep supports --null, nor whether xargs supports -0, on Leopard, but on GNU it's all good.

android - How to get view from context?

Starting with a context, the root view of the associated activity can be had by

View rootView = ((Activity)_context).Window.DecorView.FindViewById(Android.Resource.Id.Content);

In Raw Android it'd look something like:

View rootView = ((Activity)mContext).getWindow().getDecorView().findViewById(android.R.id.content)

Then simply call the findViewById on this

View v = rootView.findViewById(R.id.your_view_id);

Best way to initialize (empty) array in PHP

Initializing a simple array :

<?php $array1=array(10,20,30,40,50); ?>

Initializing array within array :

<?php  $array2=array(6,"santosh","rahul",array("x","y","z")); ?>

Source : Sorce for the code

Passing capturing lambda as function pointer

A shortcut for using a lambda with as a C function pointer is this:

"auto fun = +[](){}"

Using Curl as exmample (curl debug info)

auto callback = +[](CURL* handle, curl_infotype type, char* data, size_t size, void*){ //add code here :-) };
curl_easy_setopt(curlHande, CURLOPT_VERBOSE, 1L);
curl_easy_setopt(curlHande,CURLOPT_DEBUGFUNCTION,callback);

Styles.Render in MVC4

Watch out for case sensitivity. If you have a file

/Content/bootstrap.css

and you redirect in your Bundle.config to

.Include("~/Content/Bootstrap.css")

it will not load the css.

Fastest way to remove first char in a String

You could profile it, if you really cared. Write a loop of many iterations and see what happens. Chances are, however, that this is not the bottleneck in your application, and TrimStart seems the most semantically correct. Strive to write code readably before optimizing.

How can I open a .tex file?

A .tex file should be a LaTeX source file.

If this is the case, that file contains the source code for a LaTeX document. You can open it with any text editor (notepad, notepad++ should work) and you can view the source code. But if you want to view the final formatted document, you need to install a LaTeX distribution and compile the .tex file.

Of course, any program can write any file with any extension, so if this is not a LaTeX document, then we can't know what software you need to install to open it. Maybe if you upload the file somewhere and link it in your question we can see the file and provide more help to you.


Yes, this is the source code of a LaTeX document. If you were able to paste it here, then you are already viewing it. If you want to view the compiled document, you need to install a LaTeX distribution. You can try to install MiKTeX then you can use that to compile the document to a .pdf file.

You can also check out this question and answer for how to do it: How to compile a LaTeX document?

Also, there's an online LaTeX editor and you can paste your code in there to preview the document: https://www.overleaf.com/.

How to uninstall Anaconda completely from macOS

Open the terminal and remove your entire Anaconda directory, which will have a name such as “anaconda2” or “anaconda3”, by entering the following command: rm -rf ~/anaconda3. Then remove conda with command "conda uninstall" https://conda.io/docs/commands/conda-uninstall.html.

How can I see the request headers made by curl when sending a request to the server?

The --trace-ascii option to curl will show the request headers, as well as the response headers and response body.

For example, the command

curl --trace-ascii curl.trace http://www.google.com/ 

produces a file curl.trace that starts as follows:

== Info: About to connect() to www.google.com port 80 (#0)
== Info:   Trying 209.85.229.104... == Info: connected
== Info: Connected to www.google.com (209.85.229.104) port 80 (#0)
=> Send header, 145 bytes (0x91)
0000: GET / HTTP/1.1
0010: User-Agent: curl/7.16.3 (powerpc-apple-darwin9.0) libcurl/7.16.3
0050:  OpenSSL/0.9.7l zlib/1.2.3
006c: Host: www.google.com
0082: Accept: */*
008f: 

It also got a response (a 302 response, to be precise but irrelevant) which was logged.


If you only want to save the response headers, use the --dump-header option:

curl -D file url
curl --dump-header file url

If you need more information about the options available, use curl --help | less (it produces a couple hundred lines of output but mentions a lot of options). Or find the manual page where there is more explanation of what the options mean.

Programmatically set TextBlock Foreground Color

Foreground needs a Brush, so you can use

textBlock.Foreground = Brushes.Navy;

If you want to use the color from RGB or ARGB then

textBlock.Foreground = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(100, 255, 125, 35)); 

or

textBlock.Foreground = new System.Windows.Media.SolidColorBrush(Colors.Navy); 

To get the Color from Hex

textBlock.Foreground = new System.Windows.Media.SolidColorBrush((Color)ColorConverter.ConvertFromString("#FFDFD991")); 

How do I initialize the base (super) class?

How do I initialize the base (super) class?

class SuperClass(object):
    def __init__(self, x):
        self.x = x

class SubClass(SuperClass):
    def __init__(self, y):
        self.y = y

Use a super object to ensure you get the next method (as a bound method) in the method resolution order. In Python 2, you need to pass the class name and self to super to lookup the bound __init__ method:

 class SubClass(SuperClass):
      def __init__(self, y):
          super(SubClass, self).__init__('x')
          self.y = y

In Python 3, there's a little magic that makes the arguments to super unnecessary - and as a side benefit it works a little faster:

 class SubClass(SuperClass):
      def __init__(self, y):
          super().__init__('x')
          self.y = y

Hardcoding the parent like this below prevents you from using cooperative multiple inheritance:

 class SubClass(SuperClass):
      def __init__(self, y):
          SuperClass.__init__(self, 'x') # don't do this
          self.y = y

Note that __init__ may only return None - it is intended to modify the object in-place.

Something __new__

There's another way to initialize instances - and it's the only way for subclasses of immutable types in Python. So it's required if you want to subclass str or tuple or another immutable object.

You might think it's a classmethod because it gets an implicit class argument. But it's actually a staticmethod. So you need to call __new__ with cls explicitly.

We usually return the instance from __new__, so if you do, you also need to call your base's __new__ via super as well in your base class. So if you use both methods:

class SuperClass(object):
    def __new__(cls, x):
        return super(SuperClass, cls).__new__(cls)
    def __init__(self, x):
        self.x = x

class SubClass(object):
    def __new__(cls, y):
        return super(SubClass, cls).__new__(cls)

    def __init__(self, y):
        self.y = y
        super(SubClass, self).__init__('x')

Python 3 sidesteps a little of the weirdness of the super calls caused by __new__ being a static method, but you still need to pass cls to the non-bound __new__ method:

class SuperClass(object):
    def __new__(cls, x):
        return super().__new__(cls)
    def __init__(self, x):
        self.x = x

class SubClass(object):
    def __new__(cls, y):
        return super().__new__(cls)
    def __init__(self, y):
        self.y = y
        super().__init__('x')

Where is the web server root directory in WAMP?

If you use Bitnami installer for wampstack, go to:

c:/Bitnami/wampstack-5.6.24-0/apache/conf (of course your version number may be different)

Open the file: httpd.conf in a text editor like Visual Studio code or Notepad ++

Do a search for "DocumentRoot". See image.

Screenshot

You will be able to change the directory in this file.

How to set a header for a HTTP GET request, and trigger file download?

I'm adding another option. The answers above were very useful for me, but I wanted to use jQuery instead of ic-ajax (it seems to have a dependency with Ember when I tried to install through bower). Keep in mind that this solution only works on modern browsers.

In order to implement this on jQuery I used jQuery BinaryTransport. This is a nice plugin to read AJAX responses in binary format.

Then you can do this to download the file and send the headers:

$.ajax({
    url: url,
    type: 'GET',
    dataType: 'binary',
    headers: headers,
    processData: false,
    success: function(blob) {
        var windowUrl = window.URL || window.webkitURL;
        var url = windowUrl.createObjectURL(blob);
        anchor.prop('href', url);
        anchor.prop('download', fileName);
        anchor.get(0).click();
        windowUrl.revokeObjectURL(url);
    }
});

The vars in the above script mean:

  • url: the URL of the file
  • headers: a Javascript object with the headers to send
  • fileName: the filename the user will see when downloading the file
  • anchor: it is a DOM element that is needed to simulate the download that must be wrapped with jQuery in this case. For example $('a.download-link').

Spring MVC - HttpMediaTypeNotAcceptableException

Please make sure that you have the following in your Spring xml file:

<context:annotation-config/> 

<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
 <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
  <list>
    <ref bean="jacksonMessageConverter"/>
  </list>
</property>
</bean>

and all items of your POJO should have getters/setters. Hope it helps

Cannot load 64-bit SWT libraries on 32-bit JVM ( replacing SWT file )

I removed C:\ProgramData\Oracle\Java\javapath from my path, and it worked for me. Perfect Answer, Thanks Nikil.

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

I've always used the term "magic number" differently, as an obscure value stored within a data structure which can be verified as a quick validity check. For example gzip files contain 0x1f8b08 as their first three bytes, Java class files start with 0xcafebabe, etc.

You often see magic numbers embedded in file formats, because files can be sent around rather promiscuously and lose any metadata about how they were created. However magic numbers are also sometimes used for in-memory data structures, like ioctl() calls.

A quick check of the magic number before processing the file or data structure allows one to signal errors early, rather than schlep all the way through potentially lengthy processing in order to announce that the input was complete balderdash.

Windows equivalent of 'touch' (i.e. the node.js way to create an index.html)

Yes you can use Node for Touch I just use that and its working all fine in windows Cmd or gitbash

enter image description here

How can I use a custom font in Java?

If you include a font file (otf, ttf, etc.) in your package, you can use the font in your application via the method described here:

Oracle Java SE 6: java.awt.Font

There is a tutorial available from Oracle that shows this example:

try {
     GraphicsEnvironment ge = 
         GraphicsEnvironment.getLocalGraphicsEnvironment();
     ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf")));
} catch (IOException|FontFormatException e) {
     //Handle exception
}

I would probably wrap this up in some sort of resource loader though as to not reload the file from the package every time you want to use it.

An answer more closely related to your original question would be to install the font as part of your application's installation process. That process will depend on the installation method you choose. If it's not a desktop app you'll have to look into the links provided.

How to find sum of multiple columns in a table in SQL Server 2005?

use a trigges it will work:-

->CREATE TRIGGER trigger_name BEFORE INSERT ON table_name

FOR EACH ROW SET NEW.column_name3 = NEW.column_name1 + NEW.column_name2;

this will only work only when you will insert a row in table not when you will be updating your table for such a pupose create another trigger of different name and use UPDATE on the place of INSERT in the above syntax

Change an image with onclick()

How about this? It doesn't require so much coding.

_x000D_
_x000D_
$(".plus").click(function(){
 $(this).toggleClass("minus")  ; 
})
_x000D_
.plus{
    background-image: url("https://cdn0.iconfinder.com/data/icons/ie_Bright/128/plus_add_blue.png");
    width:130px;
    height:130px;
    background-repeat:no-repeat;
}

.plus.minus{
    background-image: url("https://cdn0.iconfinder.com/data/icons/ie_Bright/128/plus_add_minus.png");
    width:130px;
    height:130px;
    background-repeat:no-repeat;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#"><div class="plus">CHANGE</div></a>
_x000D_
_x000D_
_x000D_

how to remove multiple columns in r dataframe?

Basic subsetting:

album2 <- album2[, -5] #delete column 5
album2 <- album2[, -c(5:7)] # delete columns 5 through 7

How do you update a DateTime field in T-SQL?

Using a DateTime parameter is the best way. However, if you still want to pass a DateTime as a string, then the CAST should not be necessary provided that a language agnostic format is used.

e.g.

Given a table created like :

create table t1 (id int, EndDate DATETIME)
insert t1 (id, EndDate) values (1, GETDATE())

The following should always work :

update t1 set EndDate = '20100525' where id = 1 -- YYYYMMDD is language agnostic

The following will work :

SET LANGUAGE us_english
update t1 set EndDate = '2010-05-25' where id = 1

However, this won't :

SET LANGUAGE british
update t1 set EndDate = '2010-05-25' where id = 1  

This is because 'YYYY-MM-DD' is not a language agnostic format (from SQL server's point of view) .

The ISO 'YYYY-MM-DDThh:mm:ss' format is also language agnostic, and useful when you need to pass a non-zero time.

More info : http://karaszi.com/the-ultimate-guide-to-the-datetime-datatypes

How to view the committed files you have not pushed yet?

Here you'll find your answer:

Using Git how do I find changes between local and remote

For the lazy:

  1. Use "git log origin..HEAD"
  2. Use "git fetch" followed by "git log HEAD..origin". You can cherry-pick individual commits using the listed commit ids.

The above assumes, of course, that "origin" is the name of your remote tracking branch (which it is if you've used clone with default options).

Determine whether an array contains a value

jQuery has a utility function for this:

$.inArray(value, array)

Returns index of value in array. Returns -1 if array does not contain value.

See also How do I check if an array includes an object in JavaScript?

Real time face detection OpenCV, Python

Your line:

img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.

Try

cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

Simple way to copy or clone a DataRow?

But to make sure that your new row is accessible in the new table, you need to close the table:

DataTable destination = new DataTable(source.TableName);
destination = source.Clone();
DataRow sourceRow = source.Rows[0];
destination.ImportRow(sourceRow);

Does a favicon have to be 32x32 or 16x16?

As I learned, no one of those several solutions are perfects. Using a favicon generator is indeed a good solution but their number is overwhelming and it's hard to choose. I d'like to add that if you want your website to be PWA enabled, you need to provide also a 512x512 icon as stated by Google Devs :

icons including a 192px and a 512px version

I didn't met a lot of favicon generators enforcing that criteria (firebase does, but there is a lot of things it doesn't do). So the solution must be a mix of many other solutions.

I don't know, today at the begining of 2020 if providing a 16x16, 32x32 still relevant. I guess it still matters in certain context like, for example, if your users still use IE for some reason (this stills happen in some privates companies which doesn't migrate to a newer browser for some reasons)

How to show first commit by 'git log'?

Not the most beautiful way of doing it I guess:

git log --pretty=oneline | wc -l

This gives you a number then

git log HEAD~<The number minus one>

C# equivalent of the IsNull() function in SQL Server

Use the Equals method:

object value2 = null;
Console.WriteLine(object.Equals(value2,null));

How to configure Visual Studio to use Beyond Compare

In Visual Studio 2008 + , go to the

Tools menu -->  select Options 

enter image description here

In Options Window --> expand Source Control --> Select Subversion User Tools --> Select Beyond Compare

and click OK button..

Javascript ES6 export const vs export let

In ES6, imports are live read-only views on exported-values. As a result, when you do import a from "somemodule";, you cannot assign to a no matter how you declare a in the module.

However, since imported variables are live views, they do change according to the "raw" exported variable in exports. Consider the following code (borrowed from the reference article below):

//------ lib.js ------
export let counter = 3;
export function incCounter() {
    counter++;
}

//------ main1.js ------
import { counter, incCounter } from './lib';

// The imported value `counter` is live
console.log(counter); // 3
incCounter();
console.log(counter); // 4

// The imported value can’t be changed
counter++; // TypeError

As you can see, the difference really lies in lib.js, not main1.js.


To summarize:

  • You cannot assign to import-ed variables, no matter how you declare the corresponding variables in the module.
  • The traditional let-vs-const semantics applies to the declared variable in the module.
    • If the variable is declared const, it cannot be reassigned or rebound in anywhere.
    • If the variable is declared let, it can only be reassigned in the module (but not the user). If it is changed, the import-ed variable changes accordingly.

Reference: http://exploringjs.com/es6/ch_modules.html#leanpub-auto-in-es6-imports-are-live-read-only-views-on-exported-values

Entity Framework vs LINQ to SQL

There are a number of obvious differences outlined in that article @lars posted, but short answer is:

  • L2S is tightly coupled - object property to specific field of database or more correctly object mapping to a specific database schema
  • L2S will only work with SQL Server (as far as I know)
  • EF allows mapping a single class to multiple tables
  • EF will handle M-M relationships
  • EF will have ability to target any ADO.NET data provider

The original premise was L2S is for Rapid Development, and EF for more "enterprisey" n-tier applications, but that is selling L2S a little short.

Why can't static methods be abstract in Java?

An abstract class cannot have a static method because abstraction is done to achieve DYNAMIC BINDING while static methods are statically binded to their functionality.A static method means behavior not dependent on an instance variable, so no instance/object is required.Just the class.Static methods belongs to class and not object. They are stored in a memory area known as PERMGEN from where it is shared with every object. Methods in abstract class are dynamically binded to their functionality.

Putting a simple if-then-else statement on one line

count = 0 if count == N else N+1

- the ternary operator. Although I'd say your solution is more readable than this.

OS X Terminal UTF-8 issues

To make nano work as you want it to, try:

export LANG="UTF-8"

Or get a newer version of nano via MacPorts:

# cf. http://www.macports.org/install.php
port info nano
port variants nano
sudo port install nano +utf8 +color +no_wrap

With respect to ssh & UTF-8 issues comment out SendEnv LANG LC_* in /etc/ssh_config.

See: Terminal in OS X Lion: can't write åäö on remote machine

Determining the path that a yum package installed to

Not in Linux at the moment, so can't double check, but I think it's:

rpm -ql ffmpeg

That should list all the files installed as part of the ffmpeg package.

When should I create a destructor?

Destructors provide an implicit way of freeing unmanaged resources encapsulated in your class, they get called when the GC gets around to it and they implicitly call the Finalize method of the base class. If you're using a lot of unmanaged resources it is better to provide an explicit way of freeing those resources via the IDisposable interface. See the C# programming guide: http://msdn.microsoft.com/en-us/library/66x5fx1b.aspx

How do I fix 'ImportError: cannot import name IncompleteRead'?

For CentOS I used this and it worked please use the following commands:

sudo pip uninstall requests
sudo pip uninstall urllib3
sudo yum remove python-urllib3
sudo yum remove python-requests

(confirm that all those libraries have been removed)

sudo yum install python-urllib3
sudo yum install python-requests

Free tool to Create/Edit PNG Images?

Paint.NET will create and edit PNGs with gusto. It's an excellent program in many respects. It's free as in beer and speech.

Error message "Unable to install or run the application. The application requires stdole Version 7.0.3300.0 in the GAC"

I my case, I solved this issue going to the Publish tab in the project properties and then select the Application Files button. Then just:

Note: Before you apply this solution, make sure that you have already (as I did), checked all your solution's projects and found no references to stdole.dll assembly.

1 - Located stdole.dll file;

2 - Changed its Publish status to Exclude

3 - After that you need to republish your application.

This issue happened on a Visual Studio 2012, after its migration from Visual Studio 2010.

Hope it helps.

Can I underline text in an Android layout?

I had a problem where I'm using a custom font and the underline created with the resource file trick (<u>Underlined text</u>) did work but Android managed to transform the underline to a sort of strike trough.

I used this answer to draw a border below the textview myself: https://stackoverflow.com/a/10732993/664449. Obviously this doesn't work for partial underlined text or multilined text.

How to get all the values of input array element jquery

You can use .map().

Pass each element in the current matched set through a function, producing a new jQuery object containing the return value.

As the return value is a jQuery object, which contains an array, it's very common to call .get() on the result to work with a basic array.

Use

var arr = $('input[name="pname[]"]').map(function () {
    return this.value; // $(this).val()
}).get();

How to manually send HTTP POST requests from Firefox or Chrome browser?

Check out http-tool for firefox ..

https://addons.mozilla.org/en-US/firefox/addon/http-tool/

Aimed at web developers who need to debug HTTP requests and responses.
Can be extremely useful while developing REST based api.

Features:
* GET
* HEAD
* POST
* PUT
* DELETE

Add header(s) to request.
Add body content to request.

View header(s) in response.
View body content in response.
View status code of response.
View status text of response.

disable viewport zooming iOS 10+ safari?

I checked all above answers in practice with my page on iOS (iPhone 6, iOS 10.0.2), but with no success. This is my working solution:

$(window).bind('gesturestart touchmove', function(event) {
    event = event.originalEvent || event;
    if (event.scale !== 1) {
         event.preventDefault();
         document.body.style.transform = 'scale(1)'
    }
});

jquery save json data object in cookie

It is not good practice to save the value that is returned from JSON.stringify(userData) to a cookie; it can lead to a bug in some browsers.

Before using it, you should convert it to base64 (using btoa), and when reading it, convert from base64 (using atob).

val = JSON.stringify(userData)
val = btoa(val)

write_cookie(val)

Python: Figure out local timezone

In Python 3.x, local timezone can be figured out like this:

import datetime
LOCAL_TIMEZONE = datetime.datetime.now(datetime.timezone.utc).astimezone().tzinfo

It's a tricky use of datetime's code .

For python >= 3.6, you'll need

import datetime
LOCAL_TIMEZONE = datetime.datetime.now(datetime.timezone(datetime.timedelta(0))).astimezone().tzinfo

Searching for file in directories recursively

I tried some of the other solutions listed here, but during unit testing the code would throw exceptions I wanted to ignore. I ended up creating the following recursive search method that will ignore certain exceptions like PathTooLongException and UnauthorizedAccessException.

    private IEnumerable<string> RecursiveFileSearch(string path, string pattern, ICollection<string> filePathCollector = null)
    {
        try
        {
            filePathCollector = filePathCollector ?? new LinkedList<string>();

            var matchingFilePaths = Directory.GetFiles(path, pattern);

            foreach(var matchingFile in matchingFilePaths)
            {
                filePathCollector.Add(matchingFile);
            }

            var subDirectories = Directory.EnumerateDirectories(path);

            foreach (var subDirectory in subDirectories)
            {
                RecursiveFileSearch(subDirectory, pattern, filePathCollector);
            }

            return filePathCollector;
        }
        catch (Exception error)
        {
            bool isIgnorableError = error is PathTooLongException ||
                error is UnauthorizedAccessException;

            if (isIgnorableError)
            {
                return Enumerable.Empty<string>();
            }

            throw error;
        }
    }

How to change heatmap.2 color range in R?

You could try to create your own color palette using the RColorBrewer package

my_palette <- colorRampPalette(c("green", "black", "red"))(n = 1000)

and see how this looks like. But I assume in your case only scaling would help if you really want to keep the black in "the middle". You can simply use my_palette instead of the redgreen()

I recommend that you check out the RColorBrewer package, they have pretty nice in-built palettes, and see interactive website for colorbrewer.

Mockito, JUnit and Spring

Your question seems to be asking about which of the three examples you have given is the preferred approach.

Example 1 using the Reflection TestUtils is not a good approach for Unit testing. You really don't want to be loading the spring context at all for a unit test. Just mock and inject what is required as shown by your other examples.

You do want to load the spring context if you want to do some Integration testing, however I would prefer using @RunWith(SpringJUnit4ClassRunner.class) to perform the loading of the context along with @Autowired if you need access to its' beans explicitly.

Example 2 is a valid approach and the use of @RunWith(MockitoJUnitRunner.class) will remove the need to specify a @Before method and an explicit call to MockitoAnnotations.initMocks(this);

Example 3 is another valid approach that doesn't use @RunWith(...). You haven't instantiated your class under test HelloFacadeImpl explicitly, but you could have done the same with Example 2.

My suggestion is to use Example 2 for your unit testing as it reduces the code clutter. You can fall back to the more verbose configuration if and when you're forced to do so.

compare two files in UNIX

I got the solution by using comm

comm -23 file1 file2 

will give you the desired output.

The files need to be sorted first anyway.

IOError: [Errno 2] No such file or directory trying to open a file

Um...

with open(os.path.join(src_dir, f)) as fin:
    for line in fin:

Also, you never output to a new file.

Have nginx access_log and error_log log to STDOUT and STDERR of master process

When running Nginx in a Docker container, be aware that a volume mounted over the log dir defeats the purpose of creating a softlink between the log files and stdout/stderr in your Dockerfile, as described in @Boeboe 's answer.

In that case you can either create the softlink in your entrypoint (executed after volumes are mounted) or not use a volume at all (e.g. when logs are already collected by a central logging system).

Can't draw Histogram, 'x' must be numeric

Because of the thousand separator, the data will have been read as 'non-numeric'. So you need to convert it:

 we <- gsub(",", "", we)   # remove comma
 we <- as.numeric(we)      # turn into numbers

and now you can do

 hist(we)

and other numeric operations.

Get refresh token google api

If I may expand on user987361's answer:

From the offline access portion of the OAuth2.0 docs:

When your application receives a refresh token, it is important to store that refresh token for future use. If your application loses the refresh token, it will have to re-prompt the user for consent before obtaining another refresh token. If you need to re-prompt the user for consent, include the approval_prompt parameter in the authorization code request, and set the value to force.

So, when you have already granted access, subsequent requests for a grant_type of authorization_code will not return the refresh_token, even if access_type was set to offline in the query string of the consent page.

As stated in the quote above, in order to obtain a new refresh_token after already receiving one, you will need to send your user back through the prompt, which you can do by setting approval_prompt to force.

Cheers,

PS This change was announced in a blog post as well.

Why is "cursor:pointer" effect in CSS not working

For the last few hours, I was scratching my head why my CSS wasn't working! I was trying to show row-resize as cursor but it was showing the default cursor but for s-resize browser was showing the correct cursor. I tried changing z-index but that also didn't solve my problem.

So after trying few more solutions from the internet, I called one of my co-workers and shared my screen via Google meet and he told me that he was seeing the row-resize icon when I was seeing the default icon!!! He even sent me the screenshot of my screencast.

So after further investigation, I found out the as I was using Remote Desktop Connection to connect to my office PC, for some reason RDC doesn't show some type of cursors.

Here is the list of cursor's I couldn't see on my remote PC,

none, cell, crosshair, text, vertical-text, alias, copy, col-resize, row-resize,

How to set socket timeout in C when making multiple connections?

am not sure if I fully understand the issue, but guess it's related to the one I had, am using Qt with TCP socket communication, all non-blocking, both Windows and Linux..

wanted to get a quick notification when an already connected client failed or completely disappeared, and not waiting the default 900+ seconds until the disconnect signal got raised. The trick to get this working was to set the TCP_USER_TIMEOUT socket option of the SOL_TCP layer to the required value, given in milliseconds.

this is a comparably new option, pls see http://tools.ietf.org/html/rfc5482, but apparently it's working fine, tried it with WinXP, Win7/x64 and Kubuntu 12.04/x64, my choice of 10 s turned out to be a bit longer, but much better than anything else I've tried before ;-)

the only issue I came across was to find the proper includes, as apparently this isn't added to the standard socket includes (yet..), so finally I defined them myself as follows:

#ifdef WIN32
    #include <winsock2.h>
#else
    #include <sys/socket.h>
#endif

#ifndef SOL_TCP
    #define SOL_TCP 6  // socket options TCP level
#endif
#ifndef TCP_USER_TIMEOUT
    #define TCP_USER_TIMEOUT 18  // how long for loss retry before timeout [ms]
#endif

setting this socket option only works when the client is already connected, the lines of code look like:

int timeout = 10000;  // user timeout in milliseconds [ms]
setsockopt (fd, SOL_TCP, TCP_USER_TIMEOUT, (char*) &timeout, sizeof (timeout));

and the failure of an initial connect is caught by a timer started when calling connect(), as there will be no signal of Qt for this, the connect signal will no be raised, as there will be no connection, and the disconnect signal will also not be raised, as there hasn't been a connection yet..

Iterating over ResultSet and adding its value in an ArrayList

If I've understood your problem correctly, there are two possible problems here:

  • resultset is null - I assume that this can't be the case as if it was you'd get an exception in your while loop and nothing would be output.
  • The second problem is that resultset.getString(i++) will get columns 1,2,3 and so on from each subsequent row.

I think that the second point is probably your problem here.

Lets say you only had 1 row returned, as follows:

Col 1, Col 2, Col 3 
A    ,     B,     C

Your code as it stands would only get A - it wouldn't get the rest of the columns.

I suggest you change your code as follows:

ResultSet resultset = ...;
ArrayList<String> arrayList = new ArrayList<String>(); 
while (resultset.next()) {                      
    int i = 1;
    while(i <= numberOfColumns) {
        arrayList.add(resultset.getString(i++));
    }
    System.out.println(resultset.getString("Col 1"));
    System.out.println(resultset.getString("Col 2"));
    System.out.println(resultset.getString("Col 3"));                    
    System.out.println(resultset.getString("Col n"));
}

Edit:

To get the number of columns:

ResultSetMetaData metadata = resultset.getMetaData();
int numberOfColumns = metadata.getColumnCount();

Convert List<T> to ObservableCollection<T> in WP7

ObservableCollection<FacebookUser_WallFeed> result = new ObservableCollection<FacebookUser_WallFeed>(FacebookHelper.facebookWallFeeds);

Equivalent of String.format in jQuery

This violates DRY principle, but it's a concise solution:

var button = '<a href="{link}" class="btn">{text}</a>';
button = button.replace('{text}','Authorize on GitHub').replace('{link}', authorizeUrl);

SSIS package creating Hresult: 0x80004005 Description: "Login timeout expired" error

The answer here is not clear, so I wanted to add more detail.

Using the link provided above, I performed the following step.

In my XML config manager I changed the "Provider" to SQLOLEDB.1 rather than SQLNCLI.1. This got me past this error.

This information is available at the link the OP posted in the Answer.

The link the got me there: http://social.msdn.microsoft.com/Forums/en-US/sqlintegrationservices/thread/fab0e3bf-4adf-4f17-b9f6-7b7f9db6523c/

Simple CSS: Text won't center in a button

As a more brute force method that I found worked for me:

First wrap the text inside the button in a span, and then apply this css to that span

var spanStyle = {
      position: "absolute",
      top: "50%",
      left: "50%",
      transform: "translate(-50%, -50%)"
    }

*above setup for inline styling

Convert List<Object> to String[] in Java

There is a simple way available in Kotlin

var lst: List<Object> = ...
    
listOFStrings: ArrayList<String> = (lst!!.map { it.name })

Log4j: How to configure simplest possible file logging?

Here's a simple one that I often use:

# Set up logging to include a file record of the output
# Note: the file is always created, even if there is 
# no actual output.
log4j.rootLogger=error, stdout, R

# Log format to standard out
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=   %5p\t[%d] [%t] (%F:%L)\n     \t%m%n\n

# File based log output
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=owls_conditions.log
log4j.appender.R.MaxFileSize=10000KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=   %5p\t[%d] [%t] (%F:%L)\n     \t%m%n\n

The format of the log is as follows:

ERROR   [2009-09-13 09:56:01,760] [main] (RDFDefaultErrorHandler.java:44)
        http://www.xfront.com/owl/ontologies/camera/#(line 1 column 1): Content is not allowed in prolog.

Such a format is defined by the string %5p\t[%d] [%t] (%F:%L)\n \t%m%n\n. You can read the meaning of conversion characters in log4j javadoc for PatternLayout.

Included comments should help in understanding what it does. Further notes:

  • it logs both to console and to file; in this case the file is named owls_conditions.log: change it according to your needs;
  • files are rotated when they reach 10000KB, and one back-up file is kept

How to find a min/max with Ruby

You can do

[5, 10].min

or

[4, 7].max

They come from the Enumerable module, so anything that includes Enumerable will have those methods available.

v2.4 introduces own Array#min and Array#max, which are way faster than Enumerable's methods because they skip calling #each.

@nicholasklick mentions another option, Enumerable#minmax, but this time returning an array of [min, max].

[4, 5, 7, 10].minmax
=> [4, 10]

Enable 'xp_cmdshell' SQL Server

As listed in other answers, the trick (in SQL 2005 or later) is to change the global configuration settings for show advanced options and xp_cmdshell to 1, in that order.

Adding to this, if you want to preserve the previous values, you can read them from sys.configurations first, then apply them in reverse order at the end. We can also avoid unnecessary reconfigure calls:

declare @prevAdvancedOptions int
declare @prevXpCmdshell int

select @prevAdvancedOptions = cast(value_in_use as int) from sys.configurations where name = 'show advanced options'
select @prevXpCmdshell = cast(value_in_use as int) from sys.configurations where name = 'xp_cmdshell'

if (@prevAdvancedOptions = 0)
begin
    exec sp_configure 'show advanced options', 1
    reconfigure
end

if (@prevXpCmdshell = 0)
begin
    exec sp_configure 'xp_cmdshell', 1
    reconfigure
end

/* do work */

if (@prevXpCmdshell = 0)
begin
    exec sp_configure 'xp_cmdshell', 0
    reconfigure
end

if (@prevAdvancedOptions = 0)
begin
    exec sp_configure 'show advanced options', 0
    reconfigure
end

Note that this relies on SQL Server version 2005 or later (original question was for 2008).

Access multiple viewchildren using @viewchild

Use @ViewChildren from @angular/core to get a reference to the components

template

<div *ngFor="let v of views">
    <customcomponent #cmp></customcomponent>
</div>

component

import { ViewChildren, QueryList } from '@angular/core';

/** Get handle on cmp tags in the template */
@ViewChildren('cmp') components:QueryList<CustomComponent>;

ngAfterViewInit(){
    // print array of CustomComponent objects
    console.log(this.components.toArray());
}

l?i?v?e? ?d?e?m?o?

How can I setup & run PhantomJS on Ubuntu?

If you want to use phantomjs easily, you can use it at phantomjscloud.com You can get the result just by http request.

How to debug apk signed for release?

Add the following to your app build.gradle and select the specified release build variant and run

signingConfigs {
        config {
            keyAlias 'keyalias'
            keyPassword 'keypwd'
            storeFile file('<<KEYSTORE-PATH>>.keystore')
            storePassword 'pwd'
        }
    }
    buildTypes {
      release {
          debuggable true
          signingConfig signingConfigs.config
          proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }

Cannot run emulator in Android Studio

It is possible that you really have no system images. Double-check that $ANDROID_HOME/system-images/android-<YOUR DESIRED API>/armeabi-v7a exists and is not empty. If they really are missing - install/reinstall with SDK manager.

How to set a default entity property value with Hibernate

You can use the java class constructor to set the default values. For example:

public class Entity implements Serializable{
 private Double field1
 private Integer field2;
 private T fieldN;

 public Entity(){
  this.field1=0.0;
  this.field2=0;
  ...
  this.fieldN= <your default value>
 }

 //Setters and Getters
...

}

Tomcat started in Eclipse but unable to connect to http://localhost:8085/

Right-click on your project's name in Eclipse's Project Explorer, then click Run As followed by Run on Server. Click the Next button. Make sure your project's name is listed in the Configured: column on the right. If it is, then you should be able to access it with this URL:

http://localhost:8085/projectname/

Additionally, whenever you make new additions (such as new JSPs, graphics or other resources) to your project, be sure to refresh the project by clicking on its name and then hitting F5. Otherwise Eclipse does not know that those new resources are available and will not make them available to Tomcat to serve.

Clear MySQL query cache without restarting server

I believe you can use...

RESET QUERY CACHE;

...if the user you're running as has reload rights. Alternatively, you can defragment the query cache via...

FLUSH QUERY CACHE;

See the Query Cache Status and Maintenance section of the MySQL manual for more information.

How do I disable a href link in JavaScript?

Install this plugin for jquery and use it

http://plugins.jquery.com/project/jqueryenabledisable

It allows you to disable/enable pretty much any field in the page.

If you want to open a page on some condition write a java script function and call it from href. If the condition satisfied you open page otherwise just do nothing.

code looks like this:

<a href="javascript: openPage()" >Click here</a>

and function:
function openPage()
{
if(some conditon)
opener.document.location = "http://www.google.com";
}
}

You can also put the link in a div and set the display property of the Style attribute to none. this will hide the div. For eg.,

<div id="divid" style="display:none">
<a href="Hiding Link" />
</div>

This will hide the link. Use a button or an image to make this div visible now by calling this function in onclick as:

<a href="Visible Link" onclick="showDiv()">

and write the js code as:

function showDiv(){
document.getElememtById("divid").style.display="block";
}

You can also put an id tag to the html tag, so it would be

<a id="myATag" href="whatever"></a>

And get this id on your javascript by using

document.getElementById("myATag").value="#"; 

One of this must work for sure haha

How can I show dots ("...") in a span with hidden overflow?

If you are using text-overflow:ellipsis, the browser will show the contents whatever possible within that container. But if you want to specifiy the number of letters before the dots or strip some contents and add dots, you can use the below function.

function add3Dots(string, limit)
{
  var dots = "...";
  if(string.length > limit)
  {
    // you can also use substr instead of substring
    string = string.substring(0,limit) + dots;
  }
 
    return string;
}

call like

add3Dots("Hello World",9);

outputs

Hello Wor...

See it in action here

_x000D_
_x000D_
function add3Dots(string, limit)
{
  var dots = "...";
  if(string.length > limit)
  {
    // you can also use substr instead of substring
    string = string.substring(0,limit) + dots;
  }

    return string;
}



console.log(add3Dots("Hello, how are you doing today?", 10));
_x000D_
_x000D_
_x000D_

Disable browser 'Save Password' functionality

Is there a way for a site to tell the browser not to offer to remember passwords?

The website tells the browser that it is a password by using <input type="password">. So if you must do this from a website perspective then you would have to change that. (Obviously I don't recommend this).

The best solution would be to have the user configure their browser so it won't remember passwords.

SQL Server Format Date DD.MM.YYYY HH:MM:SS

A quick way to do it in sql server 2012 is as follows:

SELECT FORMAT(GETDATE() , 'dd/MM/yyyy HH:mm:ss')

Printing Python version in output

Try

python --version 

or

python -V

This will return a current python version in terminal.

What's wrong with overridable method calls in constructors?

In the specific case of Wicket: This is the very reason why I asked the Wicket devs to add support for an explicit two phase component initialization process in the framework's lifecycle of constructing a component i.e.

  1. Construction - via constructor
  2. Initialization - via onInitilize (after construction when virtual methods work!)

There was quite an active debate about whether it was necessary or not (it fully is necessary IMHO) as this link demonstrates http://apache-wicket.1842946.n4.nabble.com/VOTE-WICKET-3218-Component-onInitialize-is-broken-for-Pages-td3341090i20.html)

The good news is that the excellent devs at Wicket did end up introducing two phase initialization (to make the most aweseome Java UI framework even more awesome!) so with Wicket you can do all your post construction initialization in the onInitialize method that is called by the framework automatically if you override it - at this point in the lifecycle of your component its constructor has completed its work so virtual methods work as expected.

Select all text inside EditText when it gets focus

SelectAllOnFocus works the first time the EditText gets focus, but if you want to select the text every time the user clicks on it, you need to call editText.clearFocus() in between times.

For example, if your app has one EditText and one button, clicking the button after changing the EditText leaves the focus in the EditText. Then the user has to use the cursor handle and the backspace key to delete what's in the EditText before they can enter a new value. So call editText.clearFocus() in the Button's onClick method.

What is the syntax meaning of RAISERROR()

according to MSDN

RAISERROR ( { msg_id | msg_str | @local_variable }
    { ,severity ,state }
    [ ,argument [ ,...n ] ] )
    [ WITH option [ ,...n ] ]

16 would be the severity.
1 would be the state.

The error you get is because you have not properly supplied the required parameters for the RAISEERROR function.

How to submit form on change of dropdown list?

other than using this.form.submit() you also submiting by id or name. example i have form like this : <form action="" name="PostName" id="IdName">

  1. By Name : <select onchange="PostName.submit()">

  2. By Id : <select onchange="IdName.submit()">

Proper way to renew distribution certificate for iOS

This was a really a helpful thread, I followed the same steps as @junjie mentioned but for me something weird happened, the below are the steps I did.

  1. Went to developer portal and revoked the certificate which was about to expire.
  2. Went to XCode6.4 and in the Account settings, the certificate still showed valid, I went crazy.
  3. Then I opened XCode7, there the certificate was shown with "Reset" button instead of create and I hit the reset button and later in the portal I was able to see an extended certificate present. This is what Apple says about Reset button

If Xcode detects an issue with a signing identity, it displays an appropriate action in Accounts preferences. If Xcode displays a Create button, the signing identity doesn’t exist in Member Center or on your Mac. If Xcode displays a Reset button, the signing identity is not usable on your Mac—for example, it is missing the private key. If you click the Reset button, Xcode revokes and requests the corresponding certificate.

  1. I tried creating an Appstore ipa with that, just to test and it worked fine so I am saved, but still not sure what has happened. May be I had multiple accounts configured in my Mac, dont know.

Free Online Team Foundation Server

Upto five team members it is free. Try it :)

http://tfs.visualstudio.com/

What is a user agent stylesheet?

Regarding the concept “user agent style sheet”, consult section Cascade in the CSS 2.1 spec.

User agent style sheets are overridden by anything that you set in your own style sheet. They are just the rock bottom: in the absence of any style sheets provided by the page or by the user, the browser still has to render the content somehow, and the user agent style sheet just describes this.

So if you think you have a problem with a user agent style sheet, then you really have a problem with your markup, or your style sheet, or both (about which you wrote nothing).

ProgressDialog spinning circle

Try this.........

ProgressDialog pd1;
pd1=new ProgressDialog(<current context reference here>);
pd1.setMessage("Loading....");
pd1.setCancelable(false);
pd1.show();

To dismiss....

if(pd1!=null)
 pd1.dismiss(); 

Can't access object property, even though it shows up in a console log

Check if inside the object there's an array of objects. I had a similar issue with a JSON:

    "terms": {
        "category": [
            {
                "ID": 4,
                "name": "Cirugia",
                "slug": "cirugia",
                "description": "",
                "taxonomy": "category",
                "parent": null,
                "count": 68,
                "link": "http://distritocuatro.mx/enarm/category/cirugia/"
            }
        ]
    }

I tried to access the 'name' key from 'category' and I got the undefined error, because I was using:

var_name = obj_array.terms.category.name

Then I realised it has got square brackets, that means that it has an array of objects inside the category key, because it can have more than one category object. So, in order to get the 'name' key I used this:

var_name = obj_array.terms.category[0].name

And That does the trick.

Maybe it's too late for this answer, but I hope someone with the same problem will find this as I did before finding the Solution :)

Load CSV data into MySQL in Python

Fastest way is to use MySQL bulk loader by "load data infile" statement. It is the fastest way by far than any way you can come up with in Python. If you have to use Python, you can call statement "load data infile" from Python itself.

Detect if a jQuery UI dialog box is open

Actually, you have to explicitly compare it to true. If the dialog doesn't exist yet, it will not return false (as you would expect), it will return a DOM object.

if ($('#mydialog').dialog('isOpen') === true) {
    // true
} else {
    // false
}

optional parameters in SQL Server stored proc?

You can declare like this

CREATE PROCEDURE MyProcName
    @Parameter1 INT = 1,
    @Parameter2 VARCHAR (100) = 'StringValue',
    @Parameter3 VARCHAR (100) = NULL
AS

/* check for the NULL / default value (indicating nothing was passed */
if (@Parameter3 IS NULL)
BEGIN
    /* whatever code you desire for a missing parameter*/
    INSERT INTO ........
END

/* and use it in the query as so*/
SELECT *
FROM Table
WHERE Column = @Parameter

HTML 5 Geo Location Prompt in Chrome

For an easy workaround, just copy the HTML file to some cloud share, such as Dropbox, and use the shared link in your browser. Easy.

Get int value from enum in C#

Just cast the enum, e.g.

int something = (int) Question.Role;

The above will work for the vast majority of enums you see in the wild, as the default underlying type for an enum is int.

However, as cecilphillip points out, enums can have different underlying types. If an enum is declared as a uint, long, or ulong, it should be cast to the type of the enum; e.g. for

enum StarsInMilkyWay:long {Sun = 1, V645Centauri = 2 .. Wolf424B = 2147483649};

you should use

long something = (long)StarsInMilkyWay.Wolf424B;

Java code for getting current time

new Date().getTime() is bugged.

    Date date = new Date();
    System.out.println(date);
    System.out.println(date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds());
    long t1 = date.getTime();
    System.out.println((t1 / 1000 / 60 / 60) % 24 + ":" + (t1 / 1000 / 60) % 60 + ":" + (t1 / 1000) % 60);
    long t2 = System.currentTimeMillis();
    System.out.println((t2 / 1000 / 60 / 60) % 24 + ":" + (t2 / 1000 / 60) % 60 + ":" + (t2 / 1000) % 60);

It returns me the wrong time millis. System.currentTimeMillis() too. Since I ask the Date instance to tell me the corresponding time millis it must return the matching ones not others from a different time zone. Funny how deprecated methods are the only ones which return correct values.

How to position a div in the middle of the screen when the page is bigger than the screen

I think this is a simple solution:

_x000D_
_x000D_
<div style="_x000D_
    display: inline-block;_x000D_
    position: fixed;_x000D_
    top: 0;_x000D_
    bottom: 0;_x000D_
    left: 0;_x000D_
    right: 0;_x000D_
    width: 200px;_x000D_
    height: 100px;_x000D_
    margin: auto;_x000D_
    background-color: #f3f3f3;">Full Center ON Page_x000D_
</div>
_x000D_
_x000D_
_x000D_

Select an Option from the Right-Click Menu in Selenium Webdriver - Java

We will take the help of WebDriver action class and perform Right Click. the below is the syntax :

Actions action = new Actions(driver).contextClick(element);
action.build().perform();

Below are the Steps we have followed in the example:

  1. Identify the element
  2. Wait for the presence of Element
  3. Now perform Context click
  4. After that we need to select the required link.

package com.pack.rightclick;

    import org.openqa.selenium.Alert;
    import org.openqa.selenium.By;
    import org.openqa.selenium.NoSuchElementException;
    import org.openqa.selenium.StaleElementReferenceException;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.interactions.Actions;
    import org.openqa.selenium.support.ui.ExpectedConditions;
    import org.openqa.selenium.support.ui.WebDriverWait;
    import org.testng.Assert;
    import org.testng.annotations.AfterClass;
    import org.testng.annotations.BeforeClass;
    import org.testng.annotations.Test;

public class RightClickExample {

    WebDriver driver;

    String URL = "http://medialize.github.io/jQuery-contextMenu/demo.html";

    @BeforeClass
    public void Setup() {
        driver = new FirefoxDriver();
        driver.manage().window().maximize();
    }

    @Test
    public void rightClickTest() {
        driver.navigate().to(URL);
        By locator = By.cssSelector(".context-menu-one.box");
        WebDriverWait wait = new WebDriverWait(driver, 5);
        wait.until(ExpectedConditions.presenceOfElementLocated(locator)); 
        WebElement element=driver.findElement(locator);
        rightClick(element);
        WebElement elementEdit =driver.findElement(By.cssSelector(".context-menu-item.icon.icon-edit>span"));
        elementEdit.click();
        Alert alert=driver.switchTo().alert();
        String textEdit = alert.getText();
        Assert.assertEquals(textEdit, "clicked: edit", "Failed to click on Edit link");
    }

    public void rightClick(WebElement element) {
        try {
            Actions action = new Actions(driver).contextClick(element);
            action.build().perform();

            System.out.println("Sucessfully Right clicked on the element");
        } catch (StaleElementReferenceException e) {
            System.out.println("Element is not attached to the page document "
                    + e.getStackTrace());
        } catch (NoSuchElementException e) {
            System.out.println("Element " + element + " was not found in DOM "
                    + e.getStackTrace());
        } catch (Exception e) {
            System.out.println("Element " + element + " was not clickable "
                    + e.getStackTrace());
        }
    }

    @AfterClass
    public void tearDown() {
        driver.quit();
    }


}

How does the bitwise complement operator (~ tilde) work?

here, 2 in binary(8 bit) is 00000010 and its 1's complement is 11111101, subtract 1 from that 1's complement we get 11111101-1 = 11111100, here the sign is - as 8th character (from R to L) is 1 find 1's complement of that no. i.e. 00000011 = 3 and the sign is negative that's why we get -3 here.

Could not load type from assembly error

The solution to this for me was not mentioned above, so I thought I would add my answer to the long tail...

I ended up having an old reference to a class (an HttpHandler) in web.config that was no longer being used (and was no longer a valid reference). For some reason it was ignored while running in Studio (or maybe I have that class still accessible within my dev setup?) and so I only got this error once I tried deploying to IIS. I searched on the assembly name in web.config, removed the unused handler reference, then this error went away and everything works great. Hope this helps someone else.

How to create empty data frame with column names specified in R?

Perhaps:

> data.frame(aname=NA, bname=NA)[numeric(0), ]
[1] aname bname
<0 rows> (or 0-length row.names)

C++ - Hold the console window open?

Roughly the same kinds of things you've done in C#. Calling getch() is probably the simplest.

Difference in days between two dates in Java?

I did it this way. it's easy :)

Date d1 = jDateChooserFrom.getDate();
Date d2 = jDateChooserTo.getDate();

Calendar day1 = Calendar.getInstance();
day1.setTime(d1);

Calendar day2 = Calendar.getInstance();
day2.setTime(d2);

int from = day1.get(Calendar.DAY_OF_YEAR);
int to = day2.get(Calendar.DAY_OF_YEAR);

int difference = to-from;

Using Rsync include and exclude options to include directory and file by pattern

Add -m to the recommended answer above to prune empty directories.

remove empty lines from text file with PowerShell

This will remove empty lines or lines with only whitespace characters (tabs/spaces).

[IO.File]::ReadAllText("FileWithEmptyLines.txt") -replace '\s+\r\n+', "`r`n" | Out-File "c:\FileWithNoEmptyLines.txt"

Default settings Raspberry Pi /etc/network/interfaces

These are the default settings I have for /etc/network/interfaces (including WiFi settings) for my Raspberry Pi 1:

auto lo

iface lo inet loopback
iface eth0 inet dhcp

allow-hotplug wlan0
iface wlan0 inet manual
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
iface default inet dhcp

How to pass an array into a function, and return the results with an array

I always return multiple values by using a combination of list() and array()s:

function DecideStuffToReturn() {
    $IsValid = true;
    $AnswerToLife = 42;

    // Build the return array.
    return array($IsValid, $AnswerToLife);
}

// Part out the return array in to multiple variables.
list($IsValid, $AnswerToLife) = DecideStuffToReturn();

You can name them whatever you like. I chose to keep the function variables and the return variables the same for consistency but you can call them whatever you like.

See list() for more information.

sort csv by column

The reader acts like a generator. On a file with some fake data:

>>> import sys, csv
>>> data = csv.reader(open('data.csv'),delimiter=';')
>>> data
<_csv.reader object at 0x1004a11a0>
>>> data.next()
['a', ' b', ' c']
>>> data.next()
['x', ' y', ' z']
>>> data.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

Using operator.itemgetter as Ignacio suggests:

>>> data = csv.reader(open('data.csv'),delimiter=';')
>>> import operator
>>> sortedlist = sorted(data, key=operator.itemgetter(2), reverse=True)
>>> sortedlist
[['x', ' y', ' z'], ['a', ' b', ' c']]

jQuery count child elements

$('#selected ul').children().length;

or even better

 $('#selected li').length;

Curl : connection refused

Make sure you have a service started and listening on the port.

netstat -ln | grep 8080

and

sudo netstat -tulpn

rm: cannot remove: Permission denied

The code says everything:

max@serv$ chmod 777 .

Okay, it doesn't say everything.

In UNIX and Linux, the ability to remove a file is not determined by the access bits of that file. It is determined by the access bits of the directory which contains the file.

Think of it this way -- deleting a file doesn't modify that file. You aren't writing to the file, so why should "w" on the file matter? Deleting a file requires editing the directory that points to the file, so you need "w" on the that directory.

Could not find a declaration file for module 'module-name'. '/path/to/module-name.js' implicitly has an 'any' type

You have to do is edit your TypeScript Config file (tsconfig.json) and add a new key-value pair as:

"noImplicitAny": false

For Example: "noImplicitAny": false, "allowJs": true, "skipLibCheck": true, "esModuleInterop": true, continue....

How to use '-prune' option of 'find' in sh?

Adding to the advice given in other answers (I have no rep to create replies)...

When combining -prune with other expressions, there is a subtle difference in behavior depending on which other expressions are used.

@Laurence Gonsalves' example will find the "*.foo" files that aren't under ".snapshot" directories:-

find . -name .snapshot -prune -o -name '*.foo' -print

However, this slightly different short-hand will, perhaps inadvertently, also list the .snapshot directory (and any nested .snapshot directories):-

find . -name .snapshot -prune -o -name '*.foo'

The reason is (according to the manpage on my system):-

If the given expression does not contain any of the primaries -exec, -ls, -ok, or -print, the given expression is effectively replaced by:

( given_expression ) -print

That is, the second example is the equivalent of entering the following, thereby modifying the grouping of terms:-

find . \( -name .snapshot -prune -o -name '*.foo' \) -print

This has at least been seen on Solaris 5.10. Having used various flavors of *nix for approx 10 years, I've only recently searched for a reason why this occurs.

How to fix homebrew permissions?

As a first option to whomever lands here like I did, follow whatever this suggests you to do:

brew doctor

It's the safest path, and amongst other things, it suggested me to:

sudo chown -R $(whoami) /usr/local

which solved that permissions issue.

The OP did just that but apparently didn't get the above suggestion; you might, and it's always better to start there, and only then look for non trivial solutions if it didn't help.

default web page width - 1024px or 980px?

This is a bit of an open ended question since screen sizes are changing all the time and what might have been correct two years ago would likely be out of date now.

I use Twitter Bootstrap 3 at present and it uses a fluid grid system designed to work at sizes ranging from mobile/very small all the way up to the huge wide screen monitors that are now available.

Currently the upper default in BS3 is 1200px which translates to a container width of 1144px after taking account of margins and padding of the grids elements.

In my experience, modern designers are working to a width of around 1366px for desktop. All recent designs I've been given to implement have been 1366px.

Note also that you can customise the BS3 grid quite heavily. For example we will use a 32 column grid with 4px gutter in our sites/designs going forwards.

Ultimately the decision on page width needs to be made based on your website analytics and the screen sizes that your visitors typically use.

Differences between C++ string == and compare()?

If you just want to check string equality, use the == operator. Determining whether two strings are equal is simpler than finding an ordering (which is what compare() gives,) so it might be better performance-wise in your case to use the equality operator.

Longer answer: The API provides a method to check for string equality and a method to check string ordering. You want string equality, so use the equality operator (so that your expectations and those of the library implementors align.) If performance is important then you might like to test both methods and find the fastest.

Laravel - Eloquent or Fluent random row

Laravel has a built-in method to shuffle the order of the results.

Here is a quote from the documentation:

shuffle()

The shuffle method randomly shuffles the items in the collection:

$collection = collect([1, 2, 3, 4, 5]);

$shuffled = $collection->shuffle();

$shuffled->all();

// [3, 2, 5, 1, 4] - (generated randomly)

You can see the documentation here.

How can I check whether a radio button is selected with JavaScript?

The scripts in this page helped me come up with the script below, which I think is more complete and universal. Basically it will validate any number of radio buttons in a form, meaning that it will make sure that a radio option has been selected for each one of the different radio groups within the form. e.g in the test form below:

   <form id="FormID">

    Yes <input type="radio" name="test1" value="Yes">
    No <input type="radio" name="test1" value="No">

    <br><br>

    Yes <input type="radio" name="test2" value="Yes">
    No <input type="radio" name="test2" value="No">

   <input type="submit" onclick="return RadioValidator();">

The RadioValidator script will make sure that an answer has been given for both 'test1' and 'test2' before it submits. You can have as many radio groups in the form, and it will ignore any other form elements. All missing radio answers will show inside a single alert popup. Here it goes, I hope it helps people. Any bug fixings or helpful modifications welcome :)

<SCRIPT LANGUAGE="JAVASCRIPT">
function RadioValidator()
{
    var ShowAlert = '';
    var AllFormElements = window.document.getElementById("FormID").elements;
    for (i = 0; i < AllFormElements.length; i++) 
    {
        if (AllFormElements[i].type == 'radio') 
        {
            var ThisRadio = AllFormElements[i].name;
            var ThisChecked = 'No';
            var AllRadioOptions = document.getElementsByName(ThisRadio);
            for (x = 0; x < AllRadioOptions.length; x++)
            {
                 if (AllRadioOptions[x].checked && ThisChecked == 'No')
                 {
                     ThisChecked = 'Yes';
                     break;
                 } 
            }   
            var AlreadySearched = ShowAlert.indexOf(ThisRadio);
            if (ThisChecked == 'No' && AlreadySearched == -1)
            {
            ShowAlert = ShowAlert + ThisRadio + ' radio button must be answered\n';
            }     
        }
    }
    if (ShowAlert != '')
    {
    alert(ShowAlert);
    return false;
    }
    else
    {
    return true;
    }
}
</SCRIPT>

Reading *.wav files in Python

If you want to procces an audio block by block, some of the given solutions are quite awful in the sense that they imply loading the whole audio into memory producing many cache misses and slowing down your program. python-wavefile provides some pythonic constructs to do NumPy block-by-block processing using efficient and transparent block management by means of generators. Other pythonic niceties are context manager for files, metadata as properties... and if you want the whole file interface, because you are developing a quick prototype and you don't care about efficency, the whole file interface is still there.

A simple example of processing would be:

import sys
from wavefile import WaveReader, WaveWriter

with WaveReader(sys.argv[1]) as r :
    with WaveWriter(
            'output.wav',
            channels=r.channels,
            samplerate=r.samplerate,
            ) as w :

        # Just to set the metadata
        w.metadata.title = r.metadata.title + " II"
        w.metadata.artist = r.metadata.artist

        # This is the prodessing loop
        for data in r.read_iter(size=512) :
            data[1] *= .8     # lower volume on the second channel
            w.write(data)

The example reuses the same block to read the whole file, even in the case of the last block that usually is less than the required size. In this case you get an slice of the block. So trust the returned block length instead of using a hardcoded 512 size for any further processing.

How to show an empty view with a RecyclerView?

One more way is to use addOnChildAttachStateChangeListener which handles appearing/disappearing child views in RecyclerView.

recyclerView.addOnChildAttachStateChangeListener(new RecyclerView.OnChildAttachStateChangeListener() {
            @Override
            public void onChildViewAttachedToWindow(@NonNull View view) {
                forEmptyTextView.setVisibility(View.INVISIBLE);
            }

            @Override
            public void onChildViewDetachedFromWindow(@NonNull View view) {
                forEmptyTextView.setVisibility(View.VISIBLE);
            }
        });

A required class was missing while executing org.apache.maven.plugins:maven-war-plugin:2.1.1:war

In my case the situation was this: I had an offline server on which I had to perform the build. For that I had compiled everything locally first and then transferred repository folder to the offline server.

Problem - build works locally but not on the server, even thou they both have same maven version, same repository folder, same JDK.

Cause: on my local machine I had additional custom "" entry in settings.xml. When I added same to the settings.xml on the server then my issues disappeared.

How to resize an Image C#

I use ImageProcessorCore, mostly because it works .Net Core.

And it have more option such as converting types, cropping images and more

http://imageprocessor.org/imageprocessor/

HTML img scaling

No Javascript required.

IE6 Internet Explorer 6

Percent only works for the width of an element, but height:100%; does not work without the correct code.

CSS

html, body { height:100%; } 

Then using a percentage works properly, and dynamically updates on window resize.

<img src="image.jpg" style="height:80%;">

You do not need a width attribute, the width scales proportionately as the browser window size is changed.

And this little gem, is in case the image is scaled up, it will not look (overly) blocky (it interpolates).

img { -ms-interpolation-mode: bicubic; }

Props go to this source: Ultimate IE6 Cheatsheet: How To Fix 25+ Internet Explorer 6 Bugs

Resolve promises one after another (i.e. in sequence)?

Array push and pop method can be used for sequence of promises. You can also push new promises when you need additional data. This is the code, I will use in React Infinite loader to load sequence of pages.

_x000D_
_x000D_
var promises = [Promise.resolve()];_x000D_
_x000D_
function methodThatReturnsAPromise(page) {_x000D_
 return new Promise((resolve, reject) => {_x000D_
  setTimeout(() => {_x000D_
   console.log(`Resolve-${page}! ${new Date()} `);_x000D_
   resolve();_x000D_
  }, 1000);_x000D_
 });_x000D_
}_x000D_
_x000D_
function pushPromise(page) {_x000D_
 promises.push(promises.pop().then(function () {_x000D_
  return methodThatReturnsAPromise(page)_x000D_
 }));_x000D_
}_x000D_
_x000D_
pushPromise(1);_x000D_
pushPromise(2);_x000D_
pushPromise(3);
_x000D_
_x000D_
_x000D_

Update one MySQL table with values from another

It depends what is a use of those tables, but you might consider putting trigger on original table on insert and update. When insert or update is done, update the second table based on only one item from the original table. It will be quicker.

Passing arrays as parameters in bash

As ugly as it is, here is a workaround that works as long as you aren't passing an array explicitly, but a variable corresponding to an array:

function passarray()
{
    eval array_internally=("$(echo '${'$1'[@]}')")
    # access array now via array_internally
    echo "${array_internally[@]}"
    #...
}

array=(0 1 2 3 4 5)
passarray array # echo's (0 1 2 3 4 5) as expected

I'm sure someone can come up with a clearner implementation of the idea, but I've found this to be a better solution than passing an array as "{array[@]"} and then accessing it internally using array_inside=("$@"). This becomes complicated when there are other positional/getopts parameters. In these cases, I've had to first determine and then remove the parameters not associated with the array using some combination of shift and array element removal.

A purist perspective likely views this approach as a violation of the language, but pragmatically speaking, this approach has saved me a whole lot of grief. On a related topic, I also use eval to assign an internally constructed array to a variable named according to a parameter target_varname I pass to the function:

eval $target_varname=$"(${array_inside[@]})"

Hope this helps someone.

What is the easiest way to clear a database from the CLI with manage.py in Django?

You can use the Django-Truncate library to delete all data of a table without destroying the table structure.

Example:

  1. First, install django-turncate using your terminal/command line:
pip install django-truncate
  1. Add "django_truncate" to your INSTALLED_APPS in the settings.py file:
INSTALLED_APPS = [
    ...
    'django_truncate',
]
  1. Use this command in your terminal to delete all data of the table from the app.
python manage.py truncate --apps app_name --models table_name

Check if a variable exists in a list in Bash

Consider exploiting the keys of associative arrays. I would presume this outperforms both regex/pattern matching and looping, although I haven't profiled it.

declare -A list=( [one]=1 [two]=two [three]='any non-empty value' )
for value in one two three four
do
    echo -n "$value is "
    # a missing key expands to the null string, 
    # and we've set each interesting key to a non-empty value
    [[ -z "${list[$value]}" ]] && echo -n '*not* '
    echo "a member of ( ${!list[*]} )"
done

Output:

one is a member of ( one two three )
two is a member of ( one two three )
three is a member of ( one two three )
four is *not* a member of ( one two three )

How can I make a link from a <td> table cell

I would recommend using an actual anchor element, and set it as block.

<div class="divBox">
    <a href="#">Link</a>
</div>

.divBox
{
    width: 300px;
    height: 100px;
}
.divBox a
{
    width: 100%;
    height: 100%;
    display: block;
}

This will set the anchor to the same dimensions of the parent div.

error LNK2001: unresolved external symbol (C++)

That means that the definition of your function is not present in your program. You forgot to add that one.cpp to your program.

What "to add" means in this case depends on your build environment and its terminology. In MSVC (since you are apparently use MSVC) you'd have to add one.cpp to the project.

In more practical terms, applicable to all typical build methodologies, when you link you program, the object file created form one.cpp is missing.

Setting graph figure size

The properties that can be set for a figure is referenced here.

You could then use:

figure_number = 1;
x      = 0;   % Screen position
y      = 0;   % Screen position
width  = 600; % Width of figure
height = 400; % Height of figure (by default in pixels)

figure(figure_number, 'Position', [x y width height]);

How to pass an object into a state using UI-router?

No, the URL will always be updated when params are passed to transitionTo.

This happens on state.js:698 in ui-router.

Redirect echo output in shell script to logfile

LOG_LOCATION="/path/to/logs"    
exec >> $LOG_LOCATION/mylogfile.log 2>&1

Connecting to remote MySQL server using PHP

I just solved this kind of a problem. What I've learned is:

  1. you'll have to edit the my.cnf and set the bind-address = your.mysql.server.address under [mysqld]
  2. comment out skip-networking field
  3. restart mysqld
  4. check if it's running

    mysql -u root -h your.mysql.server.address –p 
    
  5. create a user (usr or anything) with % as domain and grant her access to the database in question.

    mysql> CREATE USER 'usr'@'%' IDENTIFIED BY 'some_pass';
    mysql> GRANT ALL PRIVILEGES ON testDb.* TO 'monty'@'%' WITH GRANT OPTION;
    
  6. open firewall for port 3306 (you can use iptables. make sure to open port for eithe reveryone, or if you're in tight securety, then only allow the client address)

  7. restart firewall/iptables

you should be able to now connect mysql server form your client server php script.

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

If changing target sdk version doesn't help then if you have any dependency with version 3.0.2 then change it to 3.0.1.

e.g change

androidTestImplementation 'com.android.support.test.espresso:espresso-contrib:3.0.2'

to

androidTestImplementation 'com.android.support.test.espresso:espresso-contrib:3.0.1'

Mysql database sync between two databases

three different approaches:

  1. Classic client/server approach: don't put any database in the shops; simply have the applications access your server. Of course it's better if you set a VPN, but simply wrapping the connection in SSL or ssh is reasonable. Pro: it's the way databases were originally thought. Con: if you have high latency, complex operations could get slow, you might have to use stored procedures to reduce the number of round trips.

  2. replicated master/master: as @Book Of Zeus suggested. Cons: somewhat more complex to setup (especially if you have several shops), breaking in any shop machine could potentially compromise the whole system. Pros: better responsivity as read operations are totally local and write operations are propagated asynchronously.

  3. offline operations + sync step: do all work locally and from time to time (might be once an hour, daily, weekly, whatever) write a summary with all new/modified records from the last sync operation and send to the server. Pros: can work without network, fast, easy to check (if the summary is readable). Cons: you don't have real-time information.

How can I get a character in a string by index?

Do you mean like this

int index = 2;
string s = "hello";
Console.WriteLine(s[index]);

string also implements IEnumberable<char> so you can also enumerate it like this

foreach (char c in s)
    Console.WriteLine(c);