Programs & Examples On #Medial axis

Defining and using a variable in batch file

input location.bat

@echo off
cls

set /p "location"="bob"
echo We're working with %location%
pause

output

We're working with bob

(mistakes u done : space and " ")

Is there a jQuery unfocus method?

Based on your question, I believe the answer is how to trigger a blur, not just (or even) set the event:

 $('#textArea').trigger('blur');

Golang append an item to a slice

Explanation (read inline comments):


package main

import (
    "fmt"
)

var a = make([]int, 7, 8)
// A slice is a descriptor of an array segment. 
// It consists of a pointer to the array, the length of the segment, and its capacity (the maximum length of the segment).
// The length is the number of elements referred to by the slice.
// The capacity is the number of elements in the underlying array (beginning at the element referred to by the slice pointer).
// |-> Refer to: https://blog.golang.org/go-slices-usage-and-internals -> "Slice internals" section

func Test(slice []int) {
    // slice receives a copy of slice `a` which point to the same array as slice `a`
    slice[6] = 10
    slice = append(slice, 100)
    // since `slice` capacity is 8 & length is 7, it can add 100 and make the length 8
    fmt.Println(slice, len(slice), cap(slice), " << Test 1")
    slice = append(slice, 200)
    // since `slice` capacity is 8 & length also 8, slice has to make a new slice 
    // - with double of size with point to new array (see Reference 1 below).
    // (I'm also confused, why not (n+1)*2=20). But make a new slice of 16 capacity).
    slice[6] = 13 // make sure, it's a new slice :)
    fmt.Println(slice, len(slice), cap(slice), " << Test 2")
}

func main() {
    for i := 0; i < 7; i++ {
        a[i] = i
    }

    fmt.Println(a, len(a), cap(a))
    Test(a)
    fmt.Println(a, len(a), cap(a))
    fmt.Println(a[:cap(a)], len(a), cap(a))
    // fmt.Println(a[:cap(a)+1], len(a), cap(a)) -> this'll not work
}

Output:

[0 1 2 3 4 5 6] 7 8
[0 1 2 3 4 5 10 100] 8 8  << Test 1
[0 1 2 3 4 5 13 100 200] 9 16  << Test 2
[0 1 2 3 4 5 10] 7 8
[0 1 2 3 4 5 10 100] 7 8

Reference 1: https://blog.golang.org/go-slices-usage-and-internals

func AppendByte(slice []byte, data ...byte) []byte {
    m := len(slice)
    n := m + len(data)
    if n > cap(slice) { // if necessary, reallocate
        // allocate double what's needed, for future growth.
        newSlice := make([]byte, (n+1)*2)
        copy(newSlice, slice)
        slice = newSlice
    }
    slice = slice[0:n]
    copy(slice[m:n], data)
    return slice
}

How do I create a slug in Django?

If you don't want to set the slugfield to Not be editable, then I believe you'll want to set the Null and Blank properties to False. Otherwise you'll get an error when trying to save in Admin.

So a modification to the above example would be::

class test(models.Model):
    q = models.CharField(max_length=30)
    s = models.SlugField(null=True, blank=True) # Allow blank submission in admin.

    def save(self):
        if not self.id:
            self.s = slugify(self.q)

        super(test, self).save()

How to return a string value from a Bash function

You could have the function take a variable as the first arg and modify the variable with the string you want to return.

#!/bin/bash
set -x
function pass_back_a_string() {
    eval "$1='foo bar rab oof'"
}

return_var=''
pass_back_a_string return_var
echo $return_var

Prints "foo bar rab oof".

Edit: added quoting in the appropriate place to allow whitespace in string to address @Luca Borrione's comment.

Edit: As a demonstration, see the following program. This is a general-purpose solution: it even allows you to receive a string into a local variable.

#!/bin/bash
set -x
function pass_back_a_string() {
    eval "$1='foo bar rab oof'"
}

return_var=''
pass_back_a_string return_var
echo $return_var

function call_a_string_func() {
     local lvar=''
     pass_back_a_string lvar
     echo "lvar='$lvar' locally"
}

call_a_string_func
echo "lvar='$lvar' globally"

This prints:

+ return_var=
+ pass_back_a_string return_var
+ eval 'return_var='\''foo bar rab oof'\'''
++ return_var='foo bar rab oof'
+ echo foo bar rab oof
foo bar rab oof
+ call_a_string_func
+ local lvar=
+ pass_back_a_string lvar
+ eval 'lvar='\''foo bar rab oof'\'''
++ lvar='foo bar rab oof'
+ echo 'lvar='\''foo bar rab oof'\'' locally'
lvar='foo bar rab oof' locally
+ echo 'lvar='\'''\'' globally'
lvar='' globally

Edit: demonstrating that the original variable's value is available in the function, as was incorrectly criticized by @Xichen Li in a comment.

#!/bin/bash
set -x
function pass_back_a_string() {
    eval "echo in pass_back_a_string, original $1 is \$$1"
    eval "$1='foo bar rab oof'"
}

return_var='original return_var'
pass_back_a_string return_var
echo $return_var

function call_a_string_func() {
     local lvar='original lvar'
     pass_back_a_string lvar
     echo "lvar='$lvar' locally"
}

call_a_string_func
echo "lvar='$lvar' globally"

This gives output:

+ return_var='original return_var'
+ pass_back_a_string return_var
+ eval 'echo in pass_back_a_string, original return_var is $return_var'
++ echo in pass_back_a_string, original return_var is original return_var
in pass_back_a_string, original return_var is original return_var
+ eval 'return_var='\''foo bar rab oof'\'''
++ return_var='foo bar rab oof'
+ echo foo bar rab oof
foo bar rab oof
+ call_a_string_func
+ local 'lvar=original lvar'
+ pass_back_a_string lvar
+ eval 'echo in pass_back_a_string, original lvar is $lvar'
++ echo in pass_back_a_string, original lvar is original lvar
in pass_back_a_string, original lvar is original lvar
+ eval 'lvar='\''foo bar rab oof'\'''
++ lvar='foo bar rab oof'
+ echo 'lvar='\''foo bar rab oof'\'' locally'
lvar='foo bar rab oof' locally
+ echo 'lvar='\'''\'' globally'
lvar='' globally

How do you change the size of figures drawn with matplotlib?

This resizes the figure immediately even after the figure has been drawn (at least using Qt4Agg/TkAgg - but not MacOSX - with matplotlib 1.4.0):

matplotlib.pyplot.get_current_fig_manager().resize(width_px, height_px)

How to update primary key

You shouldn't really do this but insert in a new record instead and update it that way.
But, if you really need to, you can do the following:

  • Disable enforcing FK constraints temporarily (e.g. ALTER TABLE foo WITH NOCHECK CONSTRAINT ALL)
  • Then update your PK
  • Then update your FKs to match the PK change
  • Finally enable back enforcing FK constraints

Create a circular button in BS3

Use font-awesome stacked icons (alternative to bootstrap badges). Here are more examples: http://fontawesome.io/examples/

_x000D_
_x000D_
 .no-border {_x000D_
        border: none;_x000D_
        background-color: white;_x000D_
        outline: none;_x000D_
        cursor: pointer;_x000D_
    }_x000D_
.color-no-focus {_x000D_
        color: grey;_x000D_
    }_x000D_
  .hover:hover {_x000D_
        color: blue;_x000D_
    }_x000D_
 .white {_x000D_
        color: white;_x000D_
    }
_x000D_
<button type="button" (click)="doSomething()" _x000D_
class="hover color-no-focus no-border fa-stack fa-lg">_x000D_
<i class="color-focus fa fa-circle fa-stack-2x"></i>_x000D_
<span class="white fa-stack-1x">1</span>_x000D_
</button>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
_x000D_
_x000D_
_x000D_

ScriptManager.RegisterStartupScript code not working - why?

I came across a similar issue. However this issue was caused because of the way i designed the pages to bring the requests in. I placed all of my .js files as the last thing to be applied to the page, therefore they are at the end of my document. The .js files have all my functions include. The script manager seems that to be able to call this function it needs the js file already present with the function being called at the time of load. Hope this helps anyone else.

How do I supply an initial value to a text field?

You can use a TextFormField instead of TextField, and use the initialValue property. for example

TextFormField(initialValue: "I am smart")

Redirect on Ajax Jquery Call

JQuery is looking for a json type result, but because the redirect is processed automatically, it will receive the generated html source of your login.htm page.

One idea is to let the the browser know that it should redirect by adding a redirect variable to to the resulting object and checking for it in JQuery:

$(document).ready(function(){ 
    jQuery.ajax({ 
        type: "GET", 
        url: "populateData.htm", 
        dataType:"json", 
        data:"userId=SampleUser", 
        success:function(response){ 
            if (response.redirect) {
                window.location.href = response.redirect;
            }
            else {
                // Process the expected results...
            }
        }, 
     error: function(xhr, textStatus, errorThrown) { 
            alert('Error!  Status = ' + xhr.status); 
         } 

    }); 
}); 

You could also add a Header Variable to your response and let your browser decide where to redirect. In Java, instead of redirecting, do response.setHeader("REQUIRES_AUTH", "1") and in JQuery you do on success(!):

//....
        success:function(response){ 
            if (response.getResponseHeader('REQUIRES_AUTH') === '1'){ 
                window.location.href = 'login.htm'; 
            }
            else {
                // Process the expected results...
            }
        }
//....

Hope that helps.

My answer is heavily inspired by this thread which shouldn't left any questions in case you still have some problems.

apache and httpd running but I can't see my website

Did you restart the server after you changed the config file?

Can you telnet to the server from a different machine?

Can you telnet to the server from the server itself?

telnet <ip address> 80

telnet localhost 80

How to post data using HttpClient?

You need to use:

await client.PostAsync(uri, content);

Something like that:

var comment = "hello world";
var questionId = 1;

var formContent = new FormUrlEncodedContent(new[]
{
    new KeyValuePair<string, string>("comment", comment), 
    new KeyValuePair<string, string>("questionId", questionId) 
});

var myHttpClient = new HttpClient();
var response = await myHttpClient.PostAsync(uri.ToString(), formContent);

And if you need to get the response after post, you should use:

var stringContent = await response.Content.ReadAsStringAsync();

Hope it helps ;)

Difference between Width:100% and width:100vw?

Havengard's answer doesn't seem to be strictly true. I've found that vw fills the viewport width, but doesn't account for the scrollbars. So, if your content is taller than the viewport (so that your site has a vertical scrollbar), then using vw results in a small horizontal scrollbar. I had to switch out width: 100vw for width: 100% to get rid of the horizontal scrollbar.

Best programming based games

The game in question was definitely Robowar for the Mac. My son had a lot of fun with it and went on to program real robots.

As mentioned earlier by Proud, there is a wiki page for it: http://en.wikipedia.org/wiki/RoboWar

Although there has not been a lot of activity surrounding the game over the last few years, there was a tournament held recently, and there is a yahoo email group.

Finding the max/min value in an array of primitives using Java

You can simply use the new Java 8 Streams but you have to work with int.

The stream method of the utility class Arrays gives you an IntStream on which you can use the min method. You can also do max, sum, average,...

The getAsInt method is used to get the value from the OptionalInt

import java.util.Arrays;

public class Test {
    public static void main(String[] args){
        int[] tab = {12, 1, 21, 8};
        int min = Arrays.stream(tab).min().getAsInt();
        int max = Arrays.stream(tab).max().getAsInt();
        System.out.println("Min = " + min);
        System.out.println("Max = " + max)
    }

}

==UPDATE==

If execution time is important and you want to go through the data only once you can use the summaryStatistics() method like this

import java.util.Arrays;
import java.util.IntSummaryStatistics;

public class SOTest {
    public static void main(String[] args){
        int[] tab = {12, 1, 21, 8};
        IntSummaryStatistics stat = Arrays.stream(tab).summaryStatistics();
        int min = stat.getMin();
        int max = stat.getMax();
        System.out.println("Min = " + min);
        System.out.println("Max = " + max);
    }
}

This approach can give better performance than classical loop because the summaryStatistics method is a reduction operation and it allows parallelization.

The equivalent of a GOTO in python

Disclaimer: I have been exposed to a significant amount of F77

The modern equivalent of goto (arguable, only my opinion, etc) is explicit exception handling:

Edited to highlight the code reuse better.

Pretend pseudocode in a fake python-like language with goto:

def myfunc1(x)
    if x == 0:
        goto LABEL1
    return 1/x

def myfunc2(z)
    if z == 0:
        goto LABEL1
    return 1/z

myfunc1(0) 
myfunc2(0)

:LABEL1
print 'Cannot divide by zero'.

Compared to python:

def myfunc1(x):
    return 1/x

def myfunc2(y):
    return 1/y


try:
    myfunc1(0)
    myfunc2(0)
except ZeroDivisionError:
    print 'Cannot divide by zero'

Explicit named exceptions are a significantly better way to deal with non-linear conditional branching.

Check for file exists or not in sql server?

Not tested but you can try something like this :

Declare @count as int
Set @count=1
Declare @inputFile varchar(max)
Declare @Sample Table
(id int,filepath varchar(max) ,Isexists char(3))

while @count<(select max(id) from yourTable)
BEGIN
Set @inputFile =(Select filepath from yourTable where id=@count)
DECLARE @isExists INT
exec master.dbo.xp_fileexist @inputFile , 
@isExists OUTPUT
insert into @Sample
Select @count,@inputFile ,case @isExists 
when 1 then 'Yes' 
else 'No' 
end as isExists
set @count=@count+1
END

How do I put two increment statements in a C++ 'for' loop?

Try this

for(int i = 0; i != 5; ++i, ++j)
    do_something(i,j);

bootstrap datepicker setDate format dd/mm/yyyy

"As with bootstrap’s own plugins, datepicker provides a data-api that can be used to instantiate datepickers without the need for custom javascript..."

Boostrap DatePicker Documentation

Maybe you want to set format without DatePicker instance, for that, you have to add the property data-date-format="DateFormat" to main Div tag, for example:

<div class="input-group date" data-provide="datepicker" data-date-format="yyyy-mm-dd">
    <div class="input-group-addon">
        <span class="glyphicon glyphicon-th"></span>
    </div>

    <input type="text" name="YourName" id="YourId" class="YourClass">
</div>

ASP.NET GridView RowIndex As CommandArgument

Here is a very simple way:

<asp:ButtonField ButtonType="Button" CommandName="Edit" Text="Edit" Visible="True" 
                 CommandArgument='<%# Container.DataItemIndex %>' />

Java 8, Streams to find the duplicate elements

If you only need to detect the presence of duplicates (instead of listing them, which is what the OP wanted), just convert them into both a List and Set, then compare the sizes:

    List<Integer> list = ...;
    Set<Integer> set = new HashSet<>(list);
    if (list.size() != set.size()) {
      // duplicates detected
    }

I like this approach because it has less places for mistakes.

MongoDB logging all queries

I wrote a script that will print out the system.profile log in real time as queries come in. You need to enable logging first as stated in other answers. I needed this because I'm using Windows Subsystem for Linux, for which tail still doesn't work.

https://github.com/dtruel/mongo-live-logger

Align nav-items to right side in bootstrap-4

TL;DR:

Create another <ul class="navbar-nav ml-auto"> for the navbar items you want on the right.
ml-auto will pull your navbar-nav to the right where mr-auto will pull it to the left.

Tested against Bootstrap v4.5.2

_x000D_
_x000D_
<!DOCTYPE html>
<html lang="en">
<head>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"/>
  <style>
    /* Stackoverflow preview fix, please ignore */
    .navbar-nav {
      flex-direction: row;
    }
    
    .nav-link {
      padding-right: .5rem !important;
      padding-left: .5rem !important;
    }
    
    /* Fixes dropdown menus placed on the right side */
    .ml-auto .dropdown-menu {
      left: auto !important;
      right: 0px;
    }
  </style>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-primary rounded">
  <a class="navbar-brand" href="#">Navbar</a>
  <ul class="navbar-nav mr-auto">
    <li class="nav-item active">
      <a class="nav-link">Left Link 1</a>
    </li>
    <li class="nav-item">
      <a class="nav-link">Left Link 2</a>
    </li>
  </ul>
  <ul class="navbar-nav ml-auto">
    <li class="nav-item">
      <a class="nav-link">Right Link 1</a>
    </li>
    <li class="nav-item dropdown">
      <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">            Dropdown on Right</a>
      <div class="dropdown-menu" aria-labelledby="navbarDropdown">
        <a class="dropdown-item" href="#">Action</a>
        <a class="dropdown-item" href="#">Another action with a lot of text inside of an item</a>
      </div>
    </li>
  </ul>
</nav>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
</body>
</html>
_x000D_
_x000D_
_x000D_

As you can see additional styling rules have been added to account for some oddities in Stackoverflows preview box.
You should be able to safely ignore those rules in your project.

As of v4.0.0 this seems to be the official way to do it.

EDIT: I modified the Post to include a dropdown placed on the right side of the navbar as suggested by @Bruno. It needs its left and right attributes to be inverted. I added an extra snippet of css to the beginning of the example code.
Please note, that the example shows the mobile version when you click the Run code snippet button. To view the desktop version you must click the Expand snippet button.

.ml-auto .dropdown-menu {
    left: auto !important;
    right: 0px;
}

Including this in your stylesheet should do the trick.

Simplest way to detect a pinch

Hammer.js all the way! It handles "transforms" (pinches). http://eightmedia.github.com/hammer.js/

But if you wish to implement it youself, i think that Jeffrey's answer is pretty solid.

How to load a model from an HDF5 file in Keras?

If you stored the complete model, not only the weights, in the HDF5 file, then it is as simple as

from keras.models import load_model
model = load_model('model.h5')

Can I write or modify data on an RFID tag?

Some RFID chips are read-write, the majority are read-only. You can find out if your chip is read-only by checking the datasheet.

Firefox and SSL: sec_error_unknown_issuer

As @user126810 said, the problem can be fixed with a proper SSLCertificateChainFile directive in the config file.

But after fixing the config and restarting the webserver, I also had to restart Firefox. Without that, Firefox continued to complain about bad certificate (looks like it used a cached one).

How do you check whether a number is divisible by another number (Python)?

The simplest way is to test whether a number is an integer is int(x) == x. Otherwise, what David Heffernan said.

failed to lazily initialize a collection of role

Try swich fetchType from LAZY to EAGER

...
@OneToMany(fetch=FetchType.EAGER)
private Set<NodeValue> nodeValues;
...

But in this case your app will fetch data from DB anyway. If this query very hard - this may impact on performance. More here: https://docs.oracle.com/javaee/6/api/javax/persistence/FetchType.html

==> 73

How to get device make and model on iOS?

I've made the plist file to help you to get the complete name for each device (source code right at the end of my answer)

Based on OhhMee's answer, you can use it like this:

Swift 4.0

static func deviceName() -> String {

        var systemInfo = utsname()
        uname(&systemInfo)

        guard let iOSDeviceModelsPath = Bundle.main.path(forResource: "iOSDeviceModelMapping", ofType: "plist") else { return "" }
        guard let iOSDevices = NSDictionary(contentsOfFile: iOSDeviceModelsPath) else { return "" }

        let machineMirror = Mirror(reflecting: systemInfo.machine)
        let identifier = machineMirror.children.reduce("") { identifier, element in
            guard let value = element.value as? Int8, value != 0 else { return identifier }
            return identifier + String(UnicodeScalar(UInt8(value)))
        }

        return iOSDevices.value(forKey: identifier) as! String
    }

Don't forget to add #import <sys/utsname.h> in your Bridging Header.

Objective C

#import <sys/utsname.h>

NSString *machineName()
{
    struct utsname systemInfo;
    uname(&systemInfo);

    NSString *iOSDeviceModelsPath = [[NSBundle mainBundle] pathForResource:@"iOSDeviceModelMapping" ofType:@"plist"];
    NSDictionary *iOSDevices = [NSDictionary dictionaryWithContentsOfFile:iOSDeviceModelsPath];

    NSString* deviceModel = [NSString stringWithCString:systemInfo.machine
                                               encoding:NSUTF8StringEncoding];

    return [iOSDevices valueForKey:deviceModel];
}

The plist file :

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>x86_64</key>
    <string>Simulator</string>
    <key>i386</key>
    <string>Simulator</string>
    <key>iPod1,1</key>
    <string>iPod Touch 1st Gen</string>
    <key>iPod2,1</key>
    <string>iPod Touch 2nd Gen</string>
    <key>iPod3,1</key>
    <string>iPod Touch 3rd Gen</string>
    <key>iPod4,1</key>
    <string>iPod Touch 4th Gen</string>
    <key>iPod5,1</key>
    <string>iPod Touch 5th Gen</string>
    <key>iPod7,1</key>
    <string>iPod Touch 6th Gen</string>
    <key>iPhone1,1</key>
    <string>iPhone</string>
    <key>iPhone1,2</key>
    <string>iPhone 3G</string>
    <key>iPhone2,1</key>
    <string>iPhone 3GS</string>
    <key>iPhone3,1</key>
    <string>iPhone 4</string>
    <key>iPhone3,2</key>
    <string>iPhone 4</string>
    <key>iPhone3,3</key>
    <string>iPhone 4</string>
    <key>iPhone4,1</key>
    <string>iPhone 4S</string>
    <key>iPhone5,1</key>
    <string>iPhone 5 model A1428</string>
    <key>iPhone5,2</key>
    <string>iPhone 5 model A1429</string>
    <key>iPhone5,3</key>
    <string>iPhone 5C</string>
    <key>iPhone5,4</key>
    <string>iPhone 5C</string>
    <key>iPhone6,1</key>
    <string>iPhone 5S</string>
    <key>iPhone6,2</key>
    <string>iPhone 5S</string>
    <key>iPhone7,2</key>
    <string>iPhone 6</string>
    <key>iPhone7,1</key>
    <string>iPhone 6 Plus</string>
    <key>iPhone8,1</key>
    <string>iPhone 6S</string>
    <key>iPhone8,2</key>
    <string>iPhone 6S Plus</string>
    <key>iPhone8,4</key>
    <string>iPhone SE</string>
    <key>iPhone9,1</key>
    <string>iPhone 7</string>
    <key>iPhone9,2</key>
    <string>iPhone 7 Plus</string>
    <key>iPhone9,3</key>
    <string>iPhone 7</string>
    <key>iPhone9,4</key>
    <string>iPhone 7 Plus</string>
    <key>iPhone10,1</key>
    <string>iPhone 8</string>
    <key>iPhone10,4</key>
    <string>iPhone 8</string>
    <key>iPhone10,2</key>
    <string>iPhone 8 Plus</string>
    <key>iPhone10,5</key>
    <string>iPhone 8 Plus</string>
    <key>iPhone10,3</key>
    <string>iPhone X</string>
    <key>iPhone10,6</key>
    <string>iPhone X</string>
    <key>iPhone11,2</key>
    <string>iPhone XS</string>
    <key>iPhone11,4</key>
    <string>iPhone XS Max</string>
    <key>iPhone11,6</key>
    <string>iPhone XS Max</string>
    <key>iPhone11,8</key>
    <string>iPhone XR</string>
    <key>iPad1,1</key>
    <string>iPad</string>
    <key>iPad2,1</key>
    <string>iPad 2</string>
    <key>iPad2,2</key>
    <string>iPad 2</string>
    <key>iPad2,3</key>
    <string>iPad 2</string>
    <key>iPad2,4</key>
    <string>iPad 2</string>
    <key>iPad3,1</key>
    <string>iPad 3rd Gen</string>
    <key>iPad3,2</key>
    <string>iPad 3rd Gen</string>
    <key>iPad3,3</key>
    <string>iPad 3rd Gen</string>
    <key>iPad3,4</key>
    <string>iPad 4th Gen</string>
    <key>iPad3,5</key>
    <string>iPad 4th Gen</string>
    <key>iPad3,6</key>
    <string>iPad 4th Gen</string>
    <key>iPad4,1</key>
    <string>iPad Air</string>
    <key>iPad4,2</key>
    <string>iPad Air</string>
    <key>iPad4,3</key>
    <string>iPad Air</string>
    <key>iPad2,5</key>
    <string>iPad Mini 1st Gen</string>
    <key>iPad2,6</key>
    <string>iPad Mini 1st Gen</string>
    <key>iPad2,7</key>
    <string>iPad Mini 1st Gen</string>
    <key>iPad4,4</key>
    <string>iPad Mini 2nd Gen</string>
    <key>iPad4,5</key>
    <string>iPad Mini 2nd Gen</string>
    <key>iPad4,6</key>
    <string>iPad Mini 2nd Gen</string>
    <key>iPad4,7</key>
    <string>iPad Mini 3rd Gen</string>
    <key>iPad4,8</key>
    <string>iPad Mini 3rd Gen</string>
    <key>iPad4,9</key>
    <string>iPad Mini 3rd Gen</string>
    <key>iPad5,1</key>
    <string>iPad Mini 4</string>
    <key>iPad5,2</key>
    <string>iPad Mini 4</string>
    <key>iPad5,3</key>
    <string>iPad Air 2</string>
    <key>iPad5,4</key>
    <string>iPad Air 2</string>
    <key>iPad6,3</key>
    <string>iPad Pro 9.7 inch</string>
    <key>iPad6,4</key>
    <string>iPad Pro 9.7 inch</string>
    <key>iPad6,7</key>
    <string>iPad Pro 12.9 inch</string>
    <key>iPad6,8</key>
    <string>iPad Pro 12.9 inch</string>
    <key>iPad7,1</key>
    <string>iPad Pro 12.9 inch 2nd Gen</string>
    <key>iPad7,2</key>
    <string>iPad Pro 12.9 inch 2nd Gen</string>
    <key>iPad7,3</key>
    <string>iPad Pro 10.5 inch</string>
    <key>iPad7,4</key>
    <string>iPad Pro 10.5 inch</string>
    <key>iPad8,1</key>
    <string>iPad Pro 11 inch</string>
    <key>iPad8,2</key>
    <string>iPad Pro 11 inch</string>
    <key>iPad8,3</key>
    <string>iPad Pro 11 inch</string>
    <key>iPad8,4</key>
    <string>iPad Pro 11 inch</string>
    <key>iPad8,5</key>
    <string>iPad Pro 12.9 inch 3rd Gen</string>
    <key>iPad8,6</key>
    <string>iPad Pro 12.9 inch 3rd Gen</string>
    <key>iPad8,7</key>
    <string>iPad Pro 12.9 inch 3rd Gen</string>
    <key>iPad8,8</key>
    <string>iPad Pro 12.9 inch 3rd Gen</string>
</dict>
</plist>

Java: How to access methods from another class

public class WeatherResponse {

private int cod;
private String base;
private Weather main;

public int getCod(){
    return this.cod;
}

public void setCod(int cod){
    this.cod = cod;
}

public String getBase(){
    return base;
}

public void setBase(String base){
    this.base = base;
}

public Weather getWeather() {
    return main;
}

// default constructor, getters and setters
}

another class

public class Weather {

private int id;
private String main;
private String description;

public String getMain(){
    return main;
}

public void setMain(String main){
    this.main = main;
}

public String getDescription(){
    return description;
}

public void setDescription(String description){
    this.description = description;
}

// default constructor, getters and setters
}

// accessing methods
// success!

    Log.i("App", weatherResponse.getBase());
    Log.i("App", weatherResponse.getWeather().getMain());
    Log.i("App", weatherResponse.getWeather().getDescription());

R: `which` statement with multiple conditions

The && function is not vectorized. You need the & function:

EUR <- PCs[which(PCs$V13 < 9 & PCs$V13 > 3), ]

Sorting rows in a data table

It turns out there is a special case where this can be achieved. The trick is when building the DataTable, collect all the rows in a list, sort them, then add them. This case just came up here.

Angularjs: Get element in controller

You can pass in the element to the controller, just like the scope:

function someControllerFunc($scope, $element){

}

Change :hover CSS properties with JavaScript

I'd recommend to replace all :hover properties to :active when you detect that device supports touch. Just call this function when you do so as touch()

   function touch() {
      if ('ontouchstart' in document.documentElement) {
        for (var sheetI = document.styleSheets.length - 1; sheetI >= 0; sheetI--) {
          var sheet = document.styleSheets[sheetI];
          if (sheet.cssRules) {
            for (var ruleI = sheet.cssRules.length - 1; ruleI >= 0; ruleI--) {
              var rule = sheet.cssRules[ruleI];

              if (rule.selectorText) {
                rule.selectorText = rule.selectorText.replace(':hover', ':active');
              }
            }
          }
        }
      }
    }

Select max value of each group

SELECT DISTINCT (t1.ProdId), t1.Quantity FROM Dummy t1 INNER JOIN
       (SELECT ProdId, MAX(Quantity) as MaxQuantity FROM Dummy GROUP BY ProdId) t2
    ON t1.ProdId = t2.ProdId
   AND t1.Quantity = t2.MaxQuantity
 ORDER BY t1.ProdId

this will give you the idea.

What does hash do in python?

The Python docs for hash() state:

Hash values are integers. They are used to quickly compare dictionary keys during a dictionary lookup.

Python dictionaries are implemented as hash tables. So any time you use a dictionary, hash() is called on the keys that you pass in for assignment, or look-up.

Additionally, the docs for the dict type state:

Values that are not hashable, that is, values containing lists, dictionaries or other mutable types (that are compared by value rather than by object identity) may not be used as keys.

Possible heap pollution via varargs parameter

When you use varargs, it can result in the creation of an Object[] to hold the arguments.

Due to escape analysis, the JIT can optimise away this array creation. (One of the few times I have found it does so) Its not guaranteed to be optimised away, but I wouldn't worry about it unless you see its an issue in your memory profiler.

AFAIK @SafeVarargs suppresses a warning by the compiler and doesn't change how the JIT behaves.

How to disable Excel's automatic cell reference change after copy/paste?

From http://spreadsheetpage.com/index.php/tip/making_an_exact_copy_of_a_range_of_formulas_take_2:

  1. Put Excel in formula view mode. The easiest way to do this is to press Ctrl+` (that character is a "backwards apostrophe," and is usually on the same key that has the ~ (tilde).
  2. Select the range to copy.
  3. Press Ctrl+C
  4. Start Windows Notepad
  5. Press Ctrl+V to past the copied data into Notepad
  6. In Notepad, press Ctrl+A followed by Ctrl+C to copy the text
  7. Activate Excel and activate the upper left cell where you want to paste the formulas. And, make sure that the sheet you are copying to is in formula view mode.
  8. Press Ctrl+V to paste.
  9. Press Ctrl+` to toggle out of formula view mode.

Note: If the paste operation back to Excel doesn't work correctly, chances are that you've used Excel's Text-to-Columns feature recently, and Excel is trying to be helpful by remembering how you last parsed your data. You need to fire up the Convert Text to Columns Wizard. Choose the Delimited option and click Next. Clear all of the Delimiter option checkmarks except Tab.

Or, from http://spreadsheetpage.com/index.php/tip/making_an_exact_copy_of_a_range_of_formulas/:

If you're a VBA programmer, you can simply execute the following code: 
With Sheets("Sheet1")
 .Range("A11:D20").Formula = .Range("A1:D10").Formula
End With

How to set the background image of a html 5 canvas to .png image

You can draw the image on the canvas and let the user draw on top of that.

The drawImage() function will help you with that, see https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Using_images

Linq order by, group by and order by each group?

Sure:

var query = grades.GroupBy(student => student.Name)
                  .Select(group => 
                        new { Name = group.Key,
                              Students = group.OrderByDescending(x => x.Grade) })
                  .OrderBy(group => group.Students.First().Grade);

Note that you can get away with just taking the first grade within each group after ordering, because you already know the first entry will be have the highest grade.

Then you could display them with:

foreach (var group in query)
{
    Console.WriteLine("Group: {0}", group.Name);
    foreach (var student in group.Students)
    {
        Console.WriteLine("  {0}", student.Grade);
    }
}

Need to list all triggers in SQL Server database with table name and table's schema

The just above code is incorrect as shown:

SELECT 
    sysobjects.name AS trigger_name 
    --,USER_NAME(sysobjects.uid) AS trigger_owner 
    --,s.name AS table_schema 
    --,OBJECT_NAME(parent_obj) AS table_name 
    --,OBJECTPROPERTY( id, 'ExecIsUpdateTrigger') AS isupdate 
    --,OBJECTPROPERTY( id, 'ExecIsDeleteTrigger') AS isdelete 
    --,OBJECTPROPERTY( id, 'ExecIsInsertTrigger') AS isinsert 
    --,OBJECTPROPERTY( id, 'ExecIsAfterTrigger') AS isafter 
    --,OBJECTPROPERTY( id, 'ExecIsInsteadOfTrigger') AS isinsteadof 
    --,OBJECTPROPERTY(id, 'ExecIsTriggerDisabled') AS [disabled] 
FROM sysobjects 
/*
INNER JOIN sysusers 
    ON sysobjects.uid = sysusers.uid 
*/  
INNER JOIN sys.tables t 
    ON sysobjects.parent_obj = t.object_id 

INNER JOIN sys.schemas s 
    ON t.schema_id = s.schema_id 
WHERE sysobjects.type = 'TR' 
EXCEPT
SELECT OBJECT_NAME(parent_id) as Table_Name FROM sys.triggers

Error:java: javacTask: source release 8 requires target release 1.8

Under compiler.xml file you will find :

<bytecodeTargetLevel>
  <module name="your_project_name_main" target="1.8" />
  <module name="your_project_name_test" target="1.8" />
</bytecodeTargetLevel>

and you can change the target value from your old to the new for me i needed to change it from 1.5 to 1.8

Warning: Null value is eliminated by an aggregate or other SET operation in Aqua Data Studio

You would mostly be using COUNT to summarize over a UID. Therefore

COUNT([uid]) will produce the warning:

Warning: Null value is eliminated by an aggregate or other SET operation.

whilst being used with a left join, where the counted object does not exist.

Using COUNT(*) in this case would also render incorrect results, as you would then be counting the total number of results (ie parents) that exist.

Using COUNT([uid]) IS a valid way of counting, and the warning is nothing more than a warning. However if you are concerned, and you want to get a true count of uids in this case then you could use:

SUM(CASE WHEN [uid] IS NULL THEN 0 ELSE 1 END) AS [new_count]

This would not add a lot of overheads to your query. (tested mssql 2008)

SELECT where row value contains string MySQL

Use the % wildcard, which matches any number of characters.

SELECT * FROM Accounts WHERE Username LIKE '%query%'

SSL received a record that exceeded the maximum permissible length. (Error code: ssl_error_rx_record_too_long)

This seems to be the result you see from Firefox when the server is not configured properly for SSL. Chrome, BTW, just gave a generic "ssl failed" code.

What happens is that the browser sends a SSL handshake when the server is expecting an HTTP request. Server responds with a 400 code and an error message that is much bigger that the handshake message that the browser expects. Hence the FF message.

As we can see from the responses here there are many things that can break the SSL configuration but not stop the server starting or give any hints in error.log.

What I did was systematically check down all the answers until I finally found the right one, right at the bottom.

Here is what I had in the access logs:

rfulton.actrix.co.nz:80 192.168.1.3 - - [09/Oct/2016:13:39:32 +1300] "\x16\x03\x01" 400 0 "-" "-"
rfulton.actrix.co.nz:80 192.168.1.3 - - [09/Oct/2016:13:39:46 +1300] "\x16\x03\x01" 400 0 "-" "-"
rfulton.actrix.co.nz:80 192.168.1.3 - - [09/Oct/2016:13:49:13 +1300] "\x16\x03\x01" 400 0 "-" "-"

Internal Error 500 Apache, but nothing in the logs?

Why are the 500 Internal Server Errors not being logged into your apache error logs?

The errors that cause your 500 Internal Server Error are coming from a PHP module. By default, PHP does NOT log these errors. Reason being you want web requests go as fast as physically possible and it's a security hazard to log errors to screen where attackers can observe them.

These instructions to enable Internal Server Error Logging are for Ubuntu 12.10 with PHP 5.3.10 and Apache/2.2.22.

Make sure PHP logging is turned on:

  1. Locate your php.ini file:

    el@apollo:~$ locate php.ini
    /etc/php5/apache2/php.ini
    
  2. Edit that file as root:

    sudo vi /etc/php5/apache2/php.ini
    
  3. Find this line in php.ini:

    display_errors = Off
    
  4. Change the above line to this:

    display_errors = On
    
  5. Lower down in the file you'll see this:

    ;display_startup_errors
    ;   Default Value: Off
    ;   Development Value: On
    ;   Production Value: Off
    
    ;error_reporting
    ;   Default Value: E_ALL & ~E_NOTICE
    ;   Development Value: E_ALL | E_STRICT
    ;   Production Value: E_ALL & ~E_DEPRECATED
    
  6. The semicolons are comments, that means the lines don't take effect. Change those lines so they look like this:

    display_startup_errors = On
    ;   Default Value: Off
    ;   Development Value: On
    ;   Production Value: Off
    
    error_reporting = E_ALL
    ;   Default Value: E_ALL & ~E_NOTICE
    ;   Development Value: E_ALL | E_STRICT
    ;   Production Value: E_ALL & ~E_DEPRECATED
    

    What this communicates to PHP is that we want to log all these errors. Warning, there will be a large performance hit, so you don't want this enabled on production because logging takes work and work takes time, time costs money.

  7. Restarting PHP and Apache should apply the change.

  8. Do what you did to cause the 500 Internal Server error again, and check the log:

    tail -f /var/log/apache2/error.log
    
  9. You should see the 500 error at the end, something like this:

    [Wed Dec 11 01:00:40 2013] [error] [client 192.168.11.11] PHP Fatal error:  
    Call to undefined function Foobar\\byob\\penguin\\alert() in /yourproject/
    your_src/symfony/Controller/MessedUpController.php on line 249, referer: 
    https://nuclearreactor.com/abouttoblowup
    

Page redirect with successful Ajax request

Another option is:

window.location.replace("your_url")

Declaring & Setting Variables in a Select Statement

I have tried this and it worked:

define PROPp_START_DT = TO_DATE('01-SEP-1999')

select * from proposal where prop_start_dt = &PROPp_START_DT

 

Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6

For Gradle with Kotlin language (*.gradle.kts files), add this:

android {
    [...]
    kotlinOptions {
        this as KotlinJvmOptions
        jvmTarget = "1.8"
    }
}

Incorrect integer value: '' for column 'id' at row 1

To let MySql generate sequence numbers for an AUTO_INCREMENT field you have three options:

  1. specify list a column list and omit your auto_incremented column from it as njk suggested. That would be the best approach. See comments.
  2. explicitly assign NULL
  3. explicitly assign 0

3.6.9. Using AUTO_INCREMENT:

...No value was specified for the AUTO_INCREMENT column, so MySQL assigned sequence numbers automatically. You can also explicitly assign NULL or 0 to the column to generate sequence numbers.

These three statements will produce the same result:

$insertQuery = "INSERT INTO workorders (`priority`, `request_type`) VALUES('$priority', '$requestType', ...)";
$insertQuery = "INSERT INTO workorders VALUES(NULL, '$priority', ...)";
$insertQuery = "INSERT INTO workorders VALUES(0, '$priority', ...";

How to supply value to an annotation from a Constant java

You can use enum and refer that enum in annotation field

How does Java resolve a relative path in new File()?

There is a concept of a working directory.
This directory is represented by a . (dot).
In relative paths, everything else is relative to it.

Simply put the . (the working directory) is where you run your program.
In some cases the working directory can be changed but in general this is
what the dot represents. I think this is C:\JavaForTesters\ in your case.

So test\..\test.txt means: the sub-directory test
in my working directory, then one level up, then the
file test.txt. This is basically the same as just test.txt.

For more details check here.

http://docs.oracle.com/javase/7/docs/api/java/io/File.html

http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html

Regex: match everything but specific pattern

Not a regexp expert, but I think you could use a negative lookahead from the start, e.g. ^(?!foo).*$ shouldn't match anything starting with foo.

Add animated Gif image in Iphone UIImageView

If you must load the gif image from URL, you can always embed the gif in an image tag in a UIWebView.

db.collection is not a function when using MongoClient v3.0

I did a little experimenting to see if I could keep the database name as part of the url. I prefer the promise syntax but it should still work for the callback syntax. Notice below that client.db() is called without passing any parameters.

MongoClient.connect(
    'mongodb://localhost:27017/mytestingdb', 
    { useNewUrlParser: true}
)
.then(client => {

    // The database name is part of the url.  client.db() seems 
    // to know that and works even without a parameter that 
    // relays the db name.
    let db = client.db(); 

    console.log('the current database is: ' + db.s.databaseName);
    // client.close() if you want to

})
.catch(err => console.log(err));

My package.json lists monbodb ^3.2.5.

The 'useNewUrlParser' option is not required if you're willing to deal with a deprecation warning. But it is wise to use at this point until version 4 comes out where presumably the new driver will be the default and you won't need the option anymore.

What is the iOS 6 user agent string?

Some more:

Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_3 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B329 Safari/8536.25

Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_4 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B350 Safari/8536.25

Handling data in a PHP JSON Object

If you use json_decode($string, true), you will get no objects, but everything as an associative or number indexed array. Way easier to handle, as the stdObject provided by PHP is nothing but a dumb container with public properties, which cannot be extended with your own functionality.

$array = json_decode($string, true);

echo $array['trends'][0]['name'];

Minimum Hardware requirements for Android development

Hey, I have used the same software on an AMD 3Ghz chip, dual core. had 2gbs of ram at the time, and i noticed the emulator ran at an alright speed, but took a ridiculous amount of time to load. I have not done enough development on Android to tell you if this is a common, or even still existing problem, but it is certainly something I remember from my experience.

HowTo Generate List of SQL Server Jobs and their owners

A colleague told me about this stored procedure...

USE msdb

EXEC dbo.sp_help_job

How to create an integer-for-loop in Ruby?

If you're doing this in your erb view (for Rails), be mindful of the <% and <%= differences. What you'd want is:

<% (1..x).each do |i| %>
  Code to display using <%= stuff %> that you want to display    
<% end %>

For plain Ruby, you can refer to: http://www.tutorialspoint.com/ruby/ruby_loops.htm

How to detect when a UIScrollView has finished scrolling

I think scrollViewDidEndDecelerating is the one you want. Its UIScrollViewDelegates optional method:

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView

Tells the delegate that the scroll view has ended decelerating the scrolling movement.

UIScrollViewDelegate documentation

Button Width Match Parent

you can do that wit MaterialButton

MaterialButton(
     padding: EdgeInsets.all(12.0),
     minWidth: double.infinity,
     onPressed: () {},
    child: Text("Btn"),
)

How to show a running progress bar while page is loading

In this sample, I created a JavaScript progress bar (with percentage display), you can control it and hide it with JavaScript.

In this sample, the progress bar advances every 100ms. You can see it in JSFiddle

var elapsedTime = 0;
var interval = setInterval(function() {
  timer()
}, 100);

function progressbar(percent) {
  document.getElementById("prgsbarcolor").style.width = percent + '%';
  document.getElementById("prgsbartext").innerHTML = percent + '%';
}

function timer() {
  if (elapsedTime > 100) {
    document.getElementById("prgsbartext").style.color = "#FFF";
    document.getElementById("prgsbartext").innerHTML = "Completed.";
    if (elapsedTime >= 107) {
      clearInterval(interval);
      history.go(-1);
    }
  } else {
    progressbar(elapsedTime);
  }
  elapsedTime++;
}

postgresql - add boolean column to table set default

If you are using postgresql then you have to use column type BOOLEAN in lower case as boolean.

ALTER TABLE users ADD "priv_user" boolean DEFAULT false;

How can I shuffle an array?

You could use the Fisher-Yates Shuffle (code adapted from this site):

function shuffle(array) {
    let counter = array.length;

    // While there are elements in the array
    while (counter > 0) {
        // Pick a random index
        let index = Math.floor(Math.random() * counter);

        // Decrease counter by 1
        counter--;

        // And swap the last element with it
        let temp = array[counter];
        array[counter] = array[index];
        array[index] = temp;
    }

    return array;
}

Xcode 10, Command CodeSign failed with a nonzero exit code

None of the listed solutions worked for me. In another thread it was pointed out that including a folder named "resources" in the project causes this error. After renaming my "resources" folder, the error went away.

Getting time elapsed in Objective-C

For percise time measurements (like GetTickCount), also take a look at mach_absolute_time and this Apple Q&A: http://developer.apple.com/qa/qa2004/qa1398.html.

A general tree implementation?

I've published a Python [3] tree implementation on my site: http://www.quesucede.com/page/show/id/python_3_tree_implementation.

Hope it is of use,

Ok, here's the code:

import uuid

def sanitize_id(id):
    return id.strip().replace(" ", "")

(_ADD, _DELETE, _INSERT) = range(3)
(_ROOT, _DEPTH, _WIDTH) = range(3)

class Node:

    def __init__(self, name, identifier=None, expanded=True):
        self.__identifier = (str(uuid.uuid1()) if identifier is None else
                sanitize_id(str(identifier)))
        self.name = name
        self.expanded = expanded
        self.__bpointer = None
        self.__fpointer = []

    @property
    def identifier(self):
        return self.__identifier

    @property
    def bpointer(self):
        return self.__bpointer

    @bpointer.setter
    def bpointer(self, value):
        if value is not None:
            self.__bpointer = sanitize_id(value)

    @property
    def fpointer(self):
        return self.__fpointer

    def update_fpointer(self, identifier, mode=_ADD):
        if mode is _ADD:
            self.__fpointer.append(sanitize_id(identifier))
        elif mode is _DELETE:
            self.__fpointer.remove(sanitize_id(identifier))
        elif mode is _INSERT:
            self.__fpointer = [sanitize_id(identifier)]

class Tree:

    def __init__(self):
        self.nodes = []

    def get_index(self, position):
        for index, node in enumerate(self.nodes):
            if node.identifier == position:
                break
        return index

    def create_node(self, name, identifier=None, parent=None):

        node = Node(name, identifier)
        self.nodes.append(node)
        self.__update_fpointer(parent, node.identifier, _ADD)
        node.bpointer = parent
        return node

    def show(self, position, level=_ROOT):
        queue = self[position].fpointer
        if level == _ROOT:
            print("{0} [{1}]".format(self[position].name, self[position].identifier))
        else:
            print("\t"*level, "{0} [{1}]".format(self[position].name, self[position].identifier))
        if self[position].expanded:
            level += 1
            for element in queue:
                self.show(element, level)  # recursive call

    def expand_tree(self, position, mode=_DEPTH):
        # Python generator. Loosly based on an algorithm from 'Essential LISP' by
        # John R. Anderson, Albert T. Corbett, and Brian J. Reiser, page 239-241
        yield position
        queue = self[position].fpointer
        while queue:
            yield queue[0]
            expansion = self[queue[0]].fpointer
            if mode is _DEPTH:
                queue = expansion + queue[1:]  # depth-first
            elif mode is _WIDTH:
                queue = queue[1:] + expansion  # width-first

    def is_branch(self, position):
        return self[position].fpointer

    def __update_fpointer(self, position, identifier, mode):
        if position is None:
            return
        else:
            self[position].update_fpointer(identifier, mode)

    def __update_bpointer(self, position, identifier):
        self[position].bpointer = identifier

    def __getitem__(self, key):
        return self.nodes[self.get_index(key)]

    def __setitem__(self, key, item):
        self.nodes[self.get_index(key)] = item

    def __len__(self):
        return len(self.nodes)

    def __contains__(self, identifier):
        return [node.identifier for node in self.nodes if node.identifier is identifier]

if __name__ == "__main__":

    tree = Tree()
    tree.create_node("Harry", "harry")  # root node
    tree.create_node("Jane", "jane", parent = "harry")
    tree.create_node("Bill", "bill", parent = "harry")
    tree.create_node("Joe", "joe", parent = "jane")
    tree.create_node("Diane", "diane", parent = "jane")
    tree.create_node("George", "george", parent = "diane")
    tree.create_node("Mary", "mary", parent = "diane")
    tree.create_node("Jill", "jill", parent = "george")
    tree.create_node("Carol", "carol", parent = "jill")
    tree.create_node("Grace", "grace", parent = "bill")
    tree.create_node("Mark", "mark", parent = "jane")

    print("="*80)
    tree.show("harry")
    print("="*80)
    for node in tree.expand_tree("harry", mode=_WIDTH):
        print(node)
    print("="*80)

MySQL - Get row number on select

Swamibebop's solution works, but by taking advantage of table.* syntax, we can avoid repeating the column names of the inner select and get a simpler/shorter result:

SELECT @r := @r+1 , 
       z.* 
FROM(/* your original select statement goes in here */)z, 
(SELECT @r:=0)y;

So that will give you:

SELECT @r := @r+1 , 
       z.* 
FROM(
     SELECT itemID, 
     count(*) AS ordercount
     FROM orders
     GROUP BY itemID
     ORDER BY ordercount DESC
    )z,
    (SELECT @r:=0)y;

Backup/Restore a dockerized PostgreSQL database

This is the command worked for me.

cat your_dump.sql | sudo docker exec -i {docker-postgres-container} psql -U {user} -d {database_name}

for example

cat table_backup.sql | docker exec -i 03b366004090 psql -U postgres -d postgres

Reference: Solution given by GMartinez-Sisti in this discussion. https://gist.github.com/gilyes/525cc0f471aafae18c3857c27519fc4b

If two cells match, return value from third

All you have to do is write an IF condition in the column d like this:

=IF(A1=C1;B1;" ")

After that just apply this formula to all rows above that one.

How can I clear the Scanner buffer in Java?

Other people have suggested using in.nextLine() to clear the buffer, which works for single-line input. As comments point out, however, sometimes System.in input can be multi-line.

You can instead create a new Scanner object where you want to clear the buffer if you are using System.in and not some other InputStream.

in = new Scanner(System.in);

If you do this, don't call in.close() first. Doing so will close System.in, and so you will get NoSuchElementExceptions on subsequent calls to in.nextInt(); System.in probably shouldn't be closed during your program.

(The above approach is specific to System.in. It might not be appropriate for other input streams.)

If you really need to close your Scanner object before creating a new one, this StackOverflow answer suggests creating an InputStream wrapper for System.in that has its own close() method that doesn't close the wrapped System.in stream. This is overkill for simple programs, though.

PowerShell script to return versions of .NET Framework on a machine?

If you're going to use the registry you have to recurse in order to get the full version for the 4.x Framework. The earlier answers both return the root number on my system for .NET 3.0 (where the WCF and WPF numbers, which are nested under 3.0, are higher -- I can't explain that), and fail to return anything for 4.0 ...

EDIT: For .Net 4.5 and up, this changed slightly again, so there's now a nice MSDN article here explaining how to convert the Release value to a .Net version number, it's a total train wreck :-(

This looks right to me (note that it outputs separate version numbers for WCF & WPF on 3.0. I don't know what that's about). It also outputs both Client and Full on 4.0 (if you have them both installed):

Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -recurse |
Get-ItemProperty -name Version,Release -EA 0 |
Where { $_.PSChildName -match '^(?!S)\p{L}'} |
Select PSChildName, Version, Release

Based on the MSDN article, you could build a lookup table and return the marketing product version number for releases after 4.5:

$Lookup = @{
    378389 = [version]'4.5'
    378675 = [version]'4.5.1'
    378758 = [version]'4.5.1'
    379893 = [version]'4.5.2'
    393295 = [version]'4.6'
    393297 = [version]'4.6'
    394254 = [version]'4.6.1'
    394271 = [version]'4.6.1'
    394802 = [version]'4.6.2'
    394806 = [version]'4.6.2'
    460798 = [version]'4.7'
    460805 = [version]'4.7'
    461308 = [version]'4.7.1'
    461310 = [version]'4.7.1'
    461808 = [version]'4.7.2'
    461814 = [version]'4.7.2'
    528040 = [version]'4.8'
    528049 = [version]'4.8'
}

# For One True framework (latest .NET 4x), change the Where-Object match 
# to PSChildName -eq "Full":
Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -Recurse |
  Get-ItemProperty -name Version, Release -EA 0 |
  Where-Object { $_.PSChildName -match '^(?!S)\p{L}'} |
  Select-Object @{name = ".NET Framework"; expression = {$_.PSChildName}}, 
@{name = "Product"; expression = {$Lookup[$_.Release]}}, 
Version, Release

In fact, since I keep having to update this answer, here's a script to generate the script above (with a little extra) from the markdown source for that web page. This will probably break at some point, so I'm keeping the current copy above.

# Get the text from github
$url = "https://raw.githubusercontent.com/dotnet/docs/master/docs/framework/migration-guide/how-to-determine-which-versions-are-installed.md"
$md = Invoke-WebRequest $url -UseBasicParsing
$OFS = "`n"
# Replace the weird text in the tables, and the padding
# Then trim the | off the front and end of lines
$map = $md -split "`n" -replace " installed [^|]+" -replace "\s+\|" -replace "\|$" |
    # Then we can build the table by looking for unique lines that start with ".NET Framework"
    Select-String "^.NET" | Select-Object -Unique |
    # And flip it so it's key = value
    # And convert ".NET FRAMEWORK 4.5.2" to  [version]4.5.2
    ForEach-Object { 
        [version]$v, [int]$k = $_ -replace "\.NET Framework " -split "\|"
        "    $k = [version]'$v'"
    }

# And output the whole script
@"
`$Lookup = @{
$map
}

# For extra effect we could get the Windows 10 OS version and build release id:
try {
    `$WinRelease, `$WinVer = Get-ItemPropertyValue "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" ReleaseId, CurrentMajorVersionNumber, CurrentMinorVersionNumber, CurrentBuildNumber, UBR
    `$WindowsVersion = "`$(`$WinVer -join '.') (`$WinRelease)"
} catch {
    `$WindowsVersion = [System.Environment]::OSVersion.Version
}

Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -Recurse |
    Get-ItemProperty -name Version, Release -EA 0 |
    # For The One True framework (latest .NET 4x), change match to PSChildName -eq "Full":
    Where-Object { `$_.PSChildName -match '^(?!S)\p{L}'} |
    Select-Object @{name = ".NET Framework"; expression = {`$_.PSChildName}}, 
                @{name = "Product"; expression = {`$Lookup[`$_.Release]}}, 
                Version, Release,
    # Some OPTIONAL extra output: PSComputerName and WindowsVersion
    # The Computer name, so output from local machines will match remote machines:
    @{ name = "PSComputerName"; expression = {`$Env:Computername}},
    # The Windows Version (works on Windows 10, at least):
    @{ name = "WindowsVersion"; expression = { `$WindowsVersion }}
"@

Iterate over elements of List and Map using JSTL <c:forEach> tag

Mark, this is already answered in your previous topic. But OK, here it is again:

Suppose ${list} points to a List<Object>, then the following

<c:forEach items="${list}" var="item">
    ${item}<br>
</c:forEach>

does basically the same as as following in "normal Java":

for (Object item : list) {
    System.out.println(item);
}

If you have a List<Map<K, V>> instead, then the following

<c:forEach items="${list}" var="map">
    <c:forEach items="${map}" var="entry">
        ${entry.key}<br>
        ${entry.value}<br>
    </c:forEach>
</c:forEach>

does basically the same as as following in "normal Java":

for (Map<K, V> map : list) {
    for (Entry<K, V> entry : map.entrySet()) {
        System.out.println(entry.getKey());
        System.out.println(entry.getValue());
    }
}

The key and value are here not special methods or so. They are actually getter methods of Map.Entry object (click at the blue Map.Entry link to see the API doc). In EL (Expression Language) you can use the . dot operator to access getter methods using "property name" (the getter method name without the get prefix), all just according the Javabean specification.

That said, you really need to cleanup the "answers" in your previous topic as they adds noise to the question. Also read the comments I posted in your "answers".

MySQL Workbench: How to keep the connection alive

in mysql-workbech 5.7 edit->preference-> SSH -> SSH Connect timeout (for SSH DB connection) enter image description here

A simple explanation of Naive Bayes Classification

I try to explain the Bayes rule with an example.

What is the chance that a random person selected from the society is a smoker?

You may reply 10%, and let's assume that's right.

Now, what if I say that the random person is a man and is 15 years old?

You may say 15 or 20%, but why?.

In fact, we try to update our initial guess with new pieces of evidence ( P(smoker) vs. P(smoker | evidence) ). The Bayes rule is a way to relate these two probabilities.

P(smoker | evidence) = P(smoker)* p(evidence | smoker)/P(evidence)

Each evidence may increase or decrease this chance. For example, this fact that he is a man may increase the chance provided that this percentage (being a man) among non-smokers is lower.

In the other words, being a man must be an indicator of being a smoker rather than a non-smoker. Therefore, if an evidence is an indicator of something, it increases the chance.

But how do we know that this is an indicator?

For each feature, you can compare the commonness (probability) of that feature under the given conditions with its commonness alone. (P(f | x) vs. P(f)).

P(smoker | evidence) / P(smoker) = P(evidence | smoker)/P(evidence)

For example, if we know that 90% of smokers are men, it's not still enough to say whether being a man is an indicator of being smoker or not. For example if the probability of being a man in the society is also 90%, then knowing that someone is a man doesn't help us ((90% / 90%) = 1. But if men contribute to 40% of the society, but 90% of the smokers, then knowing that someone is a man increases the chance of being a smoker (90% / 40%) = 2.25, so it increases the initial guess (10%) by 2.25 resulting 22.5%.

However, if the probability of being a man was 95% in the society, then regardless of the fact that the percentage of men among smokers is high (90%)! the evidence that someone is a man decreases the chance of him being a smoker! (90% / 95%) = 0.95).

So we have:

P(smoker | f1, f2, f3,... ) = P(smoker) * contribution of f1* contribution of f2 *... 
=
P(smoker)* 
(P(being a man | smoker)/P(being a man))*
(P(under 20 | smoker)/ P(under 20))

Note that in this formula we assumed that being a man and being under 20 are independent features so we multiplied them, it means that knowing that someone is under 20 has no effect on guessing that he is man or woman. But it may not be true, for example maybe most adolescence in a society are men...

To use this formula in a classifier

The classifier is given with some features (being a man and being under 20) and it must decide if he is an smoker or not (these are two classes). It uses the above formula to calculate the probability of each class under the evidence (features), and it assigns the class with the highest probability to the input. To provide the required probabilities (90%, 10%, 80%...) it uses the training set. For example, it counts the people in the training set that are smokers and find they contribute 10% of the sample. Then for smokers checks how many of them are men or women .... how many are above 20 or under 20....In the other words, it tries to build the probability distribution of the features for each class based on the training data.

mssql '5 (Access is denied.)' error during restoring database

this happened to me earlier today, i was a member of the local server's admin group and have unimpeded access, or i thought so. I also ticked the "replace" option, even though there is no such DB in the instance.

Found out that there used to be DB of the same name there, and the MDF and LDF files are still physically located at the data and log folders of the server, but the actual metadata is missing in the sys.databases. the service account of SQL server also can't ovewrwrite the existing files. Found out also that the files' owner is "unknown", i had to change ownership, to the 2 files above so that it is now owned by the local server's admin group, then renamed it.

Then finally, it worked.

How to center a <p> element inside a <div> container?

To get left/right centering, then applying text-align: center to the div and margin: auto to the p.

For vertical positioning you should make sure you understand the different ways of doing so, this is a commonly asked problem: Vertical alignment of elements in a div

How to open Visual Studio Code from the command line on OSX?

Added this to /usr/local/bin/code, you might have to modify the path if they are different.

#!/usr/bin/env bash

CONTENTS="/Applications/Visual Studio Code.app/Contents"
ELECTRON="$CONTENTS/MacOS/Electron"
CLI="$CONTENTS/Resources/app/out/cli.js"
ATOM_SHELL_INTERNAL_RUN_AS_NODE=1 "$ELECTRON" "$CLI" "$@"
exit $?

Make executable afterwards

sudo chmod +x /usr/local/bin/code

For Restful API, can GET method use json data?

In theory, there's nothing preventing you from sending a request body in a GET request. The HTTP protocol allows it, but have no defined semantics, so it's up to you to document what exactly is going to happen when a client sends a GET payload. For instance, you have to define if parameters in a JSON body are equivalent to querystring parameters or something else entirely.

However, since there are no clearly defined semantics, you have no guarantee that implementations between your application and the client will respect it. A server or proxy might reject the whole request, or ignore the body, or anything else. The REST way to deal with broken implementations is to circumvent it in a way that's decoupled from your application, so I'd say you have two options that can be considered best practices.

The simple option is to use POST instead of GET as recommended by other answers. Since POST is not standardized by HTTP, you'll have to document how exactly that's supposed to work.

Another option, which I prefer, is to implement your application assuming the GET payload is never tampered with. Then, in case something has a broken implementation, you allow clients to override the HTTP method with the X-HTTP-Method-Override, which is a popular convention for clients to emulate HTTP methods with POST. So, if a client has a broken implementation, it can write the GET request as a POST, sending the X-HTTP-Method-Override: GET method, and you can have a middleware that's decoupled from your application implementation and rewrites the method accordingly. This is the best option if you're a purist.

How do you UrlEncode without using System.Web?

The answers here are very good, but still insufficient for me.

I wrote a small loop that compares Uri.EscapeUriString with Uri.EscapeDataString for all characters from 0 to 255.

NOTE: Both functions have the built-in intelligence that characters above 0x80 are first UTF-8 encoded and then percent encoded.

Here is the result:

******* Different *******

'#' -> Uri "#" Data "%23"
'$' -> Uri "$" Data "%24"
'&' -> Uri "&" Data "%26"
'+' -> Uri "+" Data "%2B"
',' -> Uri "," Data "%2C"
'/' -> Uri "/" Data "%2F"
':' -> Uri ":" Data "%3A"
';' -> Uri ";" Data "%3B"
'=' -> Uri "=" Data "%3D"
'?' -> Uri "?" Data "%3F"
'@' -> Uri "@" Data "%40"


******* Not escaped *******

'!' -> Uri "!" Data "!"
''' -> Uri "'" Data "'"
'(' -> Uri "(" Data "("
')' -> Uri ")" Data ")"
'*' -> Uri "*" Data "*"
'-' -> Uri "-" Data "-"
'.' -> Uri "." Data "."
'_' -> Uri "_" Data "_"
'~' -> Uri "~" Data "~"

'0' -> Uri "0" Data "0"
.....
'9' -> Uri "9" Data "9"

'A' -> Uri "A" Data "A"
......
'Z' -> Uri "Z" Data "Z"

'a' -> Uri "a" Data "a"
.....
'z' -> Uri "z" Data "z"

******* UTF 8 *******

.....
'Ò' -> Uri "%C3%92" Data "%C3%92"
'Ó' -> Uri "%C3%93" Data "%C3%93"
'Ô' -> Uri "%C3%94" Data "%C3%94"
'Õ' -> Uri "%C3%95" Data "%C3%95"
'Ö' -> Uri "%C3%96" Data "%C3%96"
.....

EscapeUriString is to be used to encode URLs, while EscapeDataString is to be used to encode for example the content of a Cookie, because Cookie data must not contain the reserved characters '=' and ';'.

java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex in Android Studio 3.0

Enable Multidex through build.gradle of your app module

multiDexEnabled true

Same as below -

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.xx.xxx"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        multiDexEnabled true //Add this
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            shrinkResources true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

Then follow below steps -

  1. From the Build menu -> press the Clean Project button.
  2. When task completed, press the Rebuild Project button from the Build menu.
  3. From menu File -> Invalidate cashes / Restart

compile is now deprecated so it's better to use implementation or api

Is JavaScript guaranteed to be single-threaded?

Well, Chrome is multiprocess, and I think every process deals with its own Javascript code, but as far as the code knows, it is "single-threaded".

There is no support whatsoever in Javascript for multi-threading, at least not explicitly, so it does not make a difference.

Are 64 bit programs bigger and faster than 32 bit versions?

Unless you need to access more memory that 32b addressing will allow you, the benefits will be small, if any.

When running on 64b CPU, you get the same memory interface no matter if you are running 32b or 64b code (you are using the same cache and same BUS).

While x64 architecture has a few more registers which allows easier optimizations, this is often counteracted by the fact pointers are now larger and using any structures with pointers results in a higher memory traffic. I would estimate the increase in the overall memory usage for a 64b application compared to a 32b one to be around 15-30 %.

Angular 2 - How to navigate to another route using this.router.parent.navigate('/about')?

You should use

this.router.parent.navigate(['/About']);

As well as specifying the route path, you can also specify your route's name:

{ path:'/About', name: 'About',   ... }

this.router.parent.navigate(['About']);

What is "stdafx.h" used for in Visual Studio?

I just ran into this myself since I'm trying to create myself a bare bones framework but started out by creating a new Win32 Program option in Visual Studio 2017. "stdafx.h" is unnecessary and should be removed. Then you can remove the stupid "stdafx.h" and "stdafx.cpp" that is in your Solution Explorer as well as the files from your project. In it's place, you'll need to put

#include <Windows.h>

instead.

Remove all whitespace in a string

Be careful:

strip does a rstrip and lstrip (removes leading and trailing spaces, tabs, returns and form feeds, but it does not remove them in the middle of the string).

If you only replace spaces and tabs you can end up with hidden CRLFs that appear to match what you are looking for, but are not the same.

How to turn off word wrapping in HTML?

If you want a HTML only solution, we can just use the pre tag. It defines "preformatted text" which means that it does not format word-wrapping. Here is a quick example to explain:

_x000D_
_x000D_
div {
    width: 200px;
    height: 200px;
    padding: 20px;
    background: #adf;
}
pre {
    width: 200px;
    height: 200px;
    padding: 20px;
    font: inherit;
    background: #fda;
}
_x000D_
<div>Look at this, this text is very neat, isn't it? But it's not quite what we want, though, is it? This text shouldn't be here! It should be all the way over there! What can we do?</div>
<pre>The pre tag has come to the rescue! Yay! However, we apologise in advance for any horizontal scrollbars that may be caused. If you need support, please raise a support ticket.</pre>
_x000D_
_x000D_
_x000D_

Exponentiation in Python - should I prefer ** operator instead of math.pow and math.sqrt?

math.sqrt is the C implementation of square root and is therefore different from using the ** operator which implements Python's built-in pow function. Thus, using math.sqrt actually gives a different answer than using the ** operator and there is indeed a computational reason to prefer numpy or math module implementation over the built-in. Specifically the sqrt functions are probably implemented in the most efficient way possible whereas ** operates over a large number of bases and exponents and is probably unoptimized for the specific case of square root. On the other hand, the built-in pow function handles a few extra cases like "complex numbers, unbounded integer powers, and modular exponentiation".

See this Stack Overflow question for more information on the difference between ** and math.sqrt.

In terms of which is more "Pythonic", I think we need to discuss the very definition of that word. From the official Python glossary, it states that a piece of code or idea is Pythonic if it "closely follows the most common idioms of the Python language, rather than implementing code using concepts common to other languages." In every single other language I can think of, there is some math module with basic square root functions. However there are languages that lack a power operator like ** e.g. C++. So ** is probably more Pythonic, but whether or not it's objectively better depends on the use case.

Find the most frequent number in a NumPy array

Expanding on this method, applied to finding the mode of the data where you may need the index of the actual array to see how far away the value is from the center of the distribution.

(_, idx, counts) = np.unique(a, return_index=True, return_counts=True)
index = idx[np.argmax(counts)]
mode = a[index]

Remember to discard the mode when len(np.argmax(counts)) > 1

How to implement a lock in JavaScript

Some addition to JoshRiver's answer according to my case;

var functionCallbacks = [];
    var functionLock = false;
    var getData = function (url, callback) {
                   if (functionLock) {
                        functionCallbacks.push(callback);
                   } else {
                       functionLock = true;
                       functionCallbacks.push(callback);
                        $.getJSON(url, function (data) {
                            while (functionCallbacks.length) {
                                var thisCallback = functionCallbacks.pop();
                                thisCallback(data);
                            }
                            functionLock = false;
                        });
                    }
                };

// Usage
getData("api/orders",function(data){
    barChart(data);
});
getData("api/orders",function(data){
  lineChart(data);
});

There will be just one api call and these two function will consume same result.

how we add or remove readonly attribute from textbox on clicking radion button in cakephp using jquery?

In your Case you can write the following jquery code:

$(document).ready(function(){

   $('.staff_on_site').click(function(){

     var rBtnVal = $(this).val();

     if(rBtnVal == "yes"){
         $("#no_of_staff").attr("readonly", false); 
     }
     else{ 
         $("#no_of_staff").attr("readonly", true); 
     }
   });
});

Here is the Fiddle: http://jsfiddle.net/P4QWx/3/

SQL count rows in a table

select sum([rows])
from sys.partitions
where object_id=object_id('tablename')
 and index_id in (0,1)

is very fast but very rarely inaccurate.

What is logits, softmax and softmax_cross_entropy_with_logits?

Short version:

Suppose you have two tensors, where y_hat contains computed scores for each class (for example, from y = W*x +b) and y_true contains one-hot encoded true labels.

y_hat  = ... # Predicted label, e.g. y = tf.matmul(X, W) + b
y_true = ... # True label, one-hot encoded

If you interpret the scores in y_hat as unnormalized log probabilities, then they are logits.

Additionally, the total cross-entropy loss computed in this manner:

y_hat_softmax = tf.nn.softmax(y_hat)
total_loss = tf.reduce_mean(-tf.reduce_sum(y_true * tf.log(y_hat_softmax), [1]))

is essentially equivalent to the total cross-entropy loss computed with the function softmax_cross_entropy_with_logits():

total_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(y_hat, y_true))

Long version:

In the output layer of your neural network, you will probably compute an array that contains the class scores for each of your training instances, such as from a computation y_hat = W*x + b. To serve as an example, below I've created a y_hat as a 2 x 3 array, where the rows correspond to the training instances and the columns correspond to classes. So here there are 2 training instances and 3 classes.

import tensorflow as tf
import numpy as np

sess = tf.Session()

# Create example y_hat.
y_hat = tf.convert_to_tensor(np.array([[0.5, 1.5, 0.1],[2.2, 1.3, 1.7]]))
sess.run(y_hat)
# array([[ 0.5,  1.5,  0.1],
#        [ 2.2,  1.3,  1.7]])

Note that the values are not normalized (i.e. the rows don't add up to 1). In order to normalize them, we can apply the softmax function, which interprets the input as unnormalized log probabilities (aka logits) and outputs normalized linear probabilities.

y_hat_softmax = tf.nn.softmax(y_hat)
sess.run(y_hat_softmax)
# array([[ 0.227863  ,  0.61939586,  0.15274114],
#        [ 0.49674623,  0.20196195,  0.30129182]])

It's important to fully understand what the softmax output is saying. Below I've shown a table that more clearly represents the output above. It can be seen that, for example, the probability of training instance 1 being "Class 2" is 0.619. The class probabilities for each training instance are normalized, so the sum of each row is 1.0.

                      Pr(Class 1)  Pr(Class 2)  Pr(Class 3)
                    ,--------------------------------------
Training instance 1 | 0.227863   | 0.61939586 | 0.15274114
Training instance 2 | 0.49674623 | 0.20196195 | 0.30129182

So now we have class probabilities for each training instance, where we can take the argmax() of each row to generate a final classification. From above, we may generate that training instance 1 belongs to "Class 2" and training instance 2 belongs to "Class 1".

Are these classifications correct? We need to measure against the true labels from the training set. You will need a one-hot encoded y_true array, where again the rows are training instances and columns are classes. Below I've created an example y_true one-hot array where the true label for training instance 1 is "Class 2" and the true label for training instance 2 is "Class 3".

y_true = tf.convert_to_tensor(np.array([[0.0, 1.0, 0.0],[0.0, 0.0, 1.0]]))
sess.run(y_true)
# array([[ 0.,  1.,  0.],
#        [ 0.,  0.,  1.]])

Is the probability distribution in y_hat_softmax close to the probability distribution in y_true? We can use cross-entropy loss to measure the error.

Formula for cross-entropy loss

We can compute the cross-entropy loss on a row-wise basis and see the results. Below we can see that training instance 1 has a loss of 0.479, while training instance 2 has a higher loss of 1.200. This result makes sense because in our example above, y_hat_softmax showed that training instance 1's highest probability was for "Class 2", which matches training instance 1 in y_true; however, the prediction for training instance 2 showed a highest probability for "Class 1", which does not match the true class "Class 3".

loss_per_instance_1 = -tf.reduce_sum(y_true * tf.log(y_hat_softmax), reduction_indices=[1])
sess.run(loss_per_instance_1)
# array([ 0.4790107 ,  1.19967598])

What we really want is the total loss over all the training instances. So we can compute:

total_loss_1 = tf.reduce_mean(-tf.reduce_sum(y_true * tf.log(y_hat_softmax), reduction_indices=[1]))
sess.run(total_loss_1)
# 0.83934333897877944

Using softmax_cross_entropy_with_logits()

We can instead compute the total cross entropy loss using the tf.nn.softmax_cross_entropy_with_logits() function, as shown below.

loss_per_instance_2 = tf.nn.softmax_cross_entropy_with_logits(y_hat, y_true)
sess.run(loss_per_instance_2)
# array([ 0.4790107 ,  1.19967598])

total_loss_2 = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(y_hat, y_true))
sess.run(total_loss_2)
# 0.83934333897877922

Note that total_loss_1 and total_loss_2 produce essentially equivalent results with some small differences in the very final digits. However, you might as well use the second approach: it takes one less line of code and accumulates less numerical error because the softmax is done for you inside of softmax_cross_entropy_with_logits().

How can I execute Shell script in Jenkinsfile?

Based on the number of views this question has, it looks like a lot of people are visiting this to see how to set up a job that executes a shell script.

These are the steps to execute a shell script in Jenkins:

  • In the main page of Jenkins select New Item.
  • Enter an item name like "my shell script job" and chose Freestyle project. Press OK.
  • On the configuration page, in the Build block click in the Add build step dropdown and select Execute shell.
  • In the textarea you can either paste a script or indicate how to run an existing script. So you can either say:

    #!/bin/bash
    
    echo "hello, today is $(date)" > /tmp/jenkins_test
    

    or just

    /path/to/your/script.sh
    
  • Click Save.

Now the newly created job should appear in the main page of Jenkins, together with the other ones. Open it and select Build now to see if it works. Once it has finished pick that specific build from the build history and read the Console output to see if everything happened as desired.

You can get more details in the document Create a Jenkins shell script job in GitHub.

vagrant primary box defined but commands still run against all boxes

The primary flag seems to only work for vagrant ssh for me.

In the past I have used the following method to hack around the issue.

# stage box intended for configuration closely matching production if ARGV[1] == 'stage'     config.vm.define "stage" do |stage|         box_setup stage, \         "10.9.8.31", "deploy/playbook_full_stack.yml", "deploy/hosts/vagrant_stage.yml"     end end 

Mocking Logger and LoggerFactory with PowerMock and Mockito

I think you can reset the invocations using Mockito.reset(mockLog). You should call this before every test, so inside @Before would be a good place.

Show/Hide Div on Scroll

<div>
  <div class="a">
    A
  </div>
</div>?


$(window).scroll(function() {
  if ($(this).scrollTop() > 0) {
    $('.a').fadeOut();
  } else {
    $('.a').fadeIn();
  }
});

Sample

Redirecting to a certain route based on condition

    $routeProvider
 .when('/main' , {templateUrl: 'partials/main.html',  controller: MainController})
 .when('/login', {templateUrl: 'partials/login.html', controller: LoginController}).
 .when('/login', {templateUrl: 'partials/index.html', controller: IndexController})
 .otherwise({redirectTo: '/index'});

Extract substring using regexp in plain bash

Using pure :

$ cat file.txt
US/Central - 10:26 PM (CST)
$ while read a b time x; do [[ $b == - ]] && echo $time; done < file.txt

another solution with bash regex :

$ [[ "US/Central - 10:26 PM (CST)" =~ -[[:space:]]*([0-9]{2}:[0-9]{2}) ]] &&
    echo ${BASH_REMATCH[1]}

another solution using grep and look-around advanced regex :

$ echo "US/Central - 10:26 PM (CST)" | grep -oP "\-\s+\K\d{2}:\d{2}"

another solution using sed :

$ echo "US/Central - 10:26 PM (CST)" |
    sed 's/.*\- *\([0-9]\{2\}:[0-9]\{2\}\).*/\1/'

another solution using perl :

$ echo "US/Central - 10:26 PM (CST)" |
    perl -lne 'print $& if /\-\s+\K\d{2}:\d{2}/'

and last one using awk :

$ echo "US/Central - 10:26 PM (CST)" |
    awk '{for (i=0; i<=NF; i++){if ($i == "-"){print $(i+1);exit}}}'

How to Batch Rename Files in a macOS Terminal?

Using mmv

mmv '*_*_*' '#1_#3' *.png

Replace tabs with spaces in vim

IIRC, something like:

set tabstop=2 shiftwidth=2 expandtab

should do the trick. If you already have tabs, then follow it up with a nice global RE to replace them with double spaces.

If you already have tabs you want to replace,

:retab

Iterating through directories with Python

Another way of returning all files in subdirectories is to use the pathlib module, introduced in Python 3.4, which provides an object oriented approach to handling filesystem paths (Pathlib is also available on Python 2.7 via the pathlib2 module on PyPi):

from pathlib import Path

rootdir = Path('C:/Users/sid/Desktop/test')
# Return a list of regular files only, not directories
file_list = [f for f in rootdir.glob('**/*') if f.is_file()]

# For absolute paths instead of relative the current dir
file_list = [f for f in rootdir.resolve().glob('**/*') if f.is_file()]

Since Python 3.5, the glob module also supports recursive file finding:

import os
from glob import iglob

rootdir_glob = 'C:/Users/sid/Desktop/test/**/*' # Note the added asterisks
# This will return absolute paths
file_list = [f for f in iglob(rootdir_glob, recursive=True) if os.path.isfile(f)]

The file_list from either of the above approaches can be iterated over without the need for a nested loop:

for f in file_list:
    print(f) # Replace with desired operations

How to combine results of two queries into a single dataset

How about,

select
        col1, 
        col2, 
        null col3, 
        null col4 
    from Table1
union all
select 
        null col1, 
        null col2,
        col4 col3, 
        col5 col4 
    from Table2;

How to read strings from a Scanner in a Java console application?

You are entering a null value to nextInt, it will fail if you give a null value...

i have added a null check to the piece of code

Try this code:

import java.util.Scanner;
class MyClass
{
     public static void main(String args[]){

                Scanner scanner = new Scanner(System.in);
                int eid,sid;
                String ename;
                System.out.println("Enter Employeeid:");
                     eid=(scanner.nextInt());
                System.out.println("Enter EmployeeName:");
                     ename=(scanner.next());
                System.out.println("Enter SupervisiorId:");
                    if(scanner.nextLine()!=null&&scanner.nextLine()!=""){//null check
                     sid=scanner.nextInt();
                     }//null check
        }
}

How can I detect browser type using jQuery?

You can use this code to find correct browser and you can make changes for any target browser.....

_x000D_
_x000D_
function myFunction() { _x000D_
        if((navigator.userAgent.indexOf("Opera") || navigator.userAgent.indexOf('OPR')) != -1 ){_x000D_
            alert('Opera');_x000D_
        }_x000D_
        else if(navigator.userAgent.indexOf("Chrome") != -1 ){_x000D_
            alert('Chrome');_x000D_
        }_x000D_
        else if(navigator.userAgent.indexOf("Safari") != -1){_x000D_
            alert('Safari');_x000D_
        }_x000D_
        else if(navigator.userAgent.indexOf("Firefox") != -1 ){_x000D_
             alert('Firefox');_x000D_
        }_x000D_
        else if((navigator.userAgent.indexOf("MSIE") != -1 ) || (!!document.documentMode == true )){_x000D_
          alert('IE'); _x000D_
        }  _x000D_
        else{_x000D_
           alert('unknown');_x000D_
        }_x000D_
    }
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
 <title>Browser detector</title>_x000D_
_x000D_
</head>_x000D_
<body onload="myFunction()">_x000D_
// your code here _x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Loop through a comma-separated shell variable

If you set a different field separator, you can directly use a for loop:

IFS=","
for v in $variable
do
   # things with "$v" ...
done

You can also store the values in an array and then loop through it as indicated in How do I split a string on a delimiter in Bash?:

IFS=, read -ra values <<< "$variable"
for v in "${values[@]}"
do
   # things with "$v"
done

Test

$ variable="abc,def,ghij"
$ IFS=","
$ for v in $variable
> do
> echo "var is $v"
> done
var is abc
var is def
var is ghij

You can find a broader approach in this solution to How to iterate through a comma-separated list and execute a command for each entry.

Examples on the second approach:

$ IFS=, read -ra vals <<< "abc,def,ghij"
$ printf "%s\n" "${vals[@]}"
abc
def
ghij
$ for v in "${vals[@]}"; do echo "$v --"; done
abc --
def --
ghij --

ConfigurationManager.AppSettings - How to modify and save?

Perhaps you should look at adding a Settings File. (e.g. App.Settings) Creating this file will allow you to do the following:

string mysetting = App.Default.MySetting;
App.Default.MySetting = "my new setting";

This means you can edit and then change items, where the items are strongly typed, and best of all... you don't have to touch any xml before you deploy!

The result is a Application or User contextual setting.

Have a look in the "add new item" menu for the setting file.

How do I get client IP address in ASP.NET CORE?

First, in .Net Core 1.0 Add using Microsoft.AspNetCore.Http.Features; to the controller Then inside the relevant method:

var ip = HttpContext.Features.Get<IHttpConnectionFeature>()?.RemoteIpAddress?.ToString();

I read several other answers which failed to compile because it was using a lowercase httpContext, leading the VS to add using Microsoft.AspNetCore.Http, instead of the appropriate using, or with HttpContext (compiler is also mislead).

java.net.SocketException: Connection reset by peer: socket write error When serving a file

This problem is usually caused by writing to a connection that had already been closed by the peer. In this case it could indicate that the user cancelled the download for example.

Convert seconds to hh:mm:ss in Python

Just be careful when dividing by 60: division between integers returns an integer -> 12/60 = 0 unless you import division from future. The following is copy and pasted from Python 2.6.2:

IDLE 2.6.2      
>>> 12/60
0
>>> from __future__ import division
>>> 12/60
0.20000000000000001

"Could not find Developer Disk Image"

1) I have experienced same issue, my Xcode version was 7.0.1, and I updated my iPhone to version 9.2, then upon using Xcode, my iPhone was shown in the section of unavailable device. Just like in image below:

enter image description here

2) But then I somehow managed to select my iPhone by clicking at
Product -> Destination -> Unavailable Device

enter image description here

3) But that didn't solved my problem, and it started showing:

Could not find Developer Disk Image

enter image description here

Solution) Then finally I downloaded latest version of Xcode version 7.2 from here and everything has worked fine for me.

Update: Whenever version of iPhone device is higher than version of Xcode, you may experience same issue, so you should update your Xcode version to remove this error.

SQL Server "cannot perform an aggregate function on an expression containing an aggregate or a subquery", but Sybase can

One option is to put the subquery in a LEFT JOIN:

select sum ( t.graduates ) - t1.summedGraduates 
from table as t
    left join 
     ( 
        select sum ( graduates ) summedGraduates, id
        from table  
        where group_code not in ('total', 'others' )
        group by id 
    ) t1 on t.id = t1.id
where t.group_code = 'total'
group by t1.summedGraduates 

Perhaps a better option would be to use SUM with CASE:

select sum(case when group_code = 'total' then graduates end) -
    sum(case when group_code not in ('total','others') then graduates end)
from yourtable

SQL Fiddle Demo with both

Deleting an object in C++

if it crashes on the delete line then you have almost certainly somehow corrupted the heap. We would need to see more code to diagnose the problem since the example you presented has no errors.

Perhaps you have a buffer overflow on the heap which corrupted the heap structures or even something as simple as a "double free" (or in the c++ case "double delete").

Also, as The Fuzz noted, you may have an error in your destructor as well.

And yes, it is completely normal and expected for delete to invoke the destructor, that is in fact one of its two purposes (call destructor then free memory).

How to find the kth largest element in an unsorted array of length n in O(n)?

If you want a true O(n) algorithm, as opposed to O(kn) or something like that, then you should use quickselect (it's basically quicksort where you throw out the partition that you're not interested in). My prof has a great writeup, with the runtime analysis: (reference)

The QuickSelect algorithm quickly finds the k-th smallest element of an unsorted array of n elements. It is a RandomizedAlgorithm, so we compute the worst-case expected running time.

Here is the algorithm.

QuickSelect(A, k)
  let r be chosen uniformly at random in the range 1 to length(A)
  let pivot = A[r]
  let A1, A2 be new arrays
  # split into a pile A1 of small elements and A2 of big elements
  for i = 1 to n
    if A[i] < pivot then
      append A[i] to A1
    else if A[i] > pivot then
      append A[i] to A2
    else
      # do nothing
  end for
  if k <= length(A1):
    # it's in the pile of small elements
    return QuickSelect(A1, k)
  else if k > length(A) - length(A2)
    # it's in the pile of big elements
    return QuickSelect(A2, k - (length(A) - length(A2))
  else
    # it's equal to the pivot
    return pivot

What is the running time of this algorithm? If the adversary flips coins for us, we may find that the pivot is always the largest element and k is always 1, giving a running time of

T(n) = Theta(n) + T(n-1) = Theta(n2)

But if the choices are indeed random, the expected running time is given by

T(n) <= Theta(n) + (1/n) ?i=1 to nT(max(i, n-i-1))

where we are making the not entirely reasonable assumption that the recursion always lands in the larger of A1 or A2.

Let's guess that T(n) <= an for some a. Then we get

T(n) 
 <= cn + (1/n) ?i=1 to nT(max(i-1, n-i))
 = cn + (1/n) ?i=1 to floor(n/2) T(n-i) + (1/n) ?i=floor(n/2)+1 to n T(i)
 <= cn + 2 (1/n) ?i=floor(n/2) to n T(i)
 <= cn + 2 (1/n) ?i=floor(n/2) to n ai

and now somehow we have to get the horrendous sum on the right of the plus sign to absorb the cn on the left. If we just bound it as 2(1/n) ?i=n/2 to n an, we get roughly 2(1/n)(n/2)an = an. But this is too big - there's no room to squeeze in an extra cn. So let's expand the sum using the arithmetic series formula:

?i=floor(n/2) to n i  
 = ?i=1 to n i - ?i=1 to floor(n/2) i  
 = n(n+1)/2 - floor(n/2)(floor(n/2)+1)/2  
 <= n2/2 - (n/4)2/2  
 = (15/32)n2

where we take advantage of n being "sufficiently large" to replace the ugly floor(n/2) factors with the much cleaner (and smaller) n/4. Now we can continue with

cn + 2 (1/n) ?i=floor(n/2) to n ai,
 <= cn + (2a/n) (15/32) n2
 = n (c + (15/16)a)
 <= an

provided a > 16c.

This gives T(n) = O(n). It's clearly Omega(n), so we get T(n) = Theta(n).

Check if a variable is a string in JavaScript

The following method will check if any variable is a string (including variables that do not exist).

const is_string = value => {
  try {
    return typeof value() === 'string';
  } catch (error) {
    return false;
  }
};

let example = 'Hello, world!';

console.log(is_string(() => example)); // true
console.log(is_string(() => variable_doesnt_exist)); // false

JavaScript equivalent to printf/String.Format

For use with jQuery.ajax() success functions. Pass only a single argument and string replace with the properties of that object as {propertyName}:

String.prototype.format = function () {
    var formatted = this;
    for (var prop in arguments[0]) {
        var regexp = new RegExp('\\{' + prop + '\\}', 'gi');
        formatted = formatted.replace(regexp, arguments[0][prop]);
    }
    return formatted;
};

Example:

var userInfo = ("Email: {Email} - Phone: {Phone}").format({ Email: "[email protected]", Phone: "123-123-1234" });

Subtract one day from datetime

SELECT DATEDIFF (
    DAY, 
    DATEDIFF(DAY, @CreatedDate, -1), 
    GETDATE())

Composer killed while updating

Run composer self-update and composer clearcache remove vendor and composer.lock restart your local environment and then run php -d memory_limit=-1 /usr/local/bin/composer install

UTF-8 output from PowerShell

Set the [Console]::OuputEncoding as encoding whatever you want, and print out with [Console]::WriteLine.

If powershell ouput method has a problem, then don't use it. It feels bit bad, but works like a charm :)

How to print to console when using Qt

I found this most useful:

#include <QTextStream>

QTextStream out(stdout);
foreach(QString x, strings)
    out << x << endl;

How to prevent errno 32 broken pipe?

It depends on how you tested it, and possibly on differences in the TCP stack implementation of the personal computer and the server.

For example, if your sendall always completes immediately (or very quickly) on the personal computer, the connection may simply never have broken during sending. This is very likely if your browser is running on the same machine (since there is no real network latency).


In general, you just need to handle the case where a client disconnects before you're finished, by handling the exception.

Remember that TCP communications are asynchronous, but this is much more obvious on physically remote connections than on local ones, so conditions like this can be hard to reproduce on a local workstation. Specifically, loopback connections on a single machine are often almost synchronous.

Why does 'git commit' not save my changes?

You should do:

git commit . -m "save arezzo files"

'module' object is not callable - calling method in another file

The problem is in the import line. You are importing a module, not a class. Assuming your file is named other_file.py (unlike java, again, there is no such rule as "one class, one file"):

from other_file import findTheRange

if your file is named findTheRange too, following java's convenions, then you should write

from findTheRange import findTheRange

you can also import it just like you did with random:

import findTheRange
operator = findTheRange.findTheRange()

Some other comments:

a) @Daniel Roseman is right. You do not need classes here at all. Python encourages procedural programming (when it fits, of course)

b) You can build the list directly:

  randomList = [random.randint(0, 100) for i in range(5)]

c) You can call methods in the same way you do in java:

largestInList = operator.findLargest(randomList)
smallestInList = operator.findSmallest(randomList)

d) You can use built in function, and the huge python library:

largestInList = max(randomList)
smallestInList = min(randomList)

e) If you still want to use a class, and you don't need self, you can use @staticmethod:

class findTheRange():
    @staticmethod
    def findLargest(_list):
        #stuff...

How do CORS and Access-Control-Allow-Headers work?

Yes, you need to have the header Access-Control-Allow-Origin: http://domain.com:3000 or Access-Control-Allow-Origin: * on both the OPTIONS response and the POST response. You should include the header Access-Control-Allow-Credentials: true on the POST response as well.

Your OPTIONS response should also include the header Access-Control-Allow-Headers: origin, content-type, accept to match the requested header.

What does @media screen and (max-width: 1024px) mean in CSS?

Also worth noting you can use 'em' as well as 'px' - blogs and text based sites do it because then the browser makes layout decisions more relative to the text content.

On Wordpress twentysixteen I wanted my tagline to display on mobiles as well as desktops, so I put this in my child theme style.css

@media screen and (max-width:59em){
    p.site-description {
        display:    block;
    }
}

how to make a div to wrap two float divs inside?

overflow:hidden (as mentioned by @Mikael S) doesn't work in every situation, but it should work in most situations.

Another option is to use the :after trick:

<div class="wrapper">
  <div class="col"></div>
  <div class="col"></div>
</div>

.wrapper {
  min-height: 1px; /* Required for IE7 */
  }

.wrapper:after {
  clear: both;
  display: block;
  height: 0;
  overflow: hidden;
  visibility: hidden;
  content: ".";
  font-size: 0;
  }

.col {
  display: inline;
  float: left;
  }

And for IE6:

.wrapper { height: 1px; }

ReactJS: Warning: setState(...): Cannot update during an existing state transition

This same warning will be emitted on any state changes done in a render() call.

An example of a tricky to find case: When rendering a multi-select GUI component based on state data, if state has nothing to display, a call to resetOptions() is considered state change for that component.

The obvious fix is to do resetOptions() in componentDidUpdate() instead of render().

How can I display the current branch and folder path in terminal?

The git package installed on your system includes bash files to aid you in creating an informative prompt. To create colors, you will need to insert terminal escape sequences into your prompt. And, the final ingredient is to update your prompt after each command gets executed by using the built-in variable PROMPT_COMMAND.

Edit your ~/.bashrc to include the following, and you should get the prompt in your question, modulo some color differences.

#
# Git provides a bash file to create an informative prompt. This is its standard
# location on Linux. On Mac, you should be able to find it under your Git
# installation. If you are unable to find the file, I have a copy of it on my GitHub.
#
# https://github.com/chadversary/home/blob/42cf697ba69d4d474ca74297cdf94186430f1384/.config/kiwi-profile/40-git-prompt.sh
#
source /usr/share/git/completion/git-prompt.sh

#
# Next, we need to define some terminal escape sequences for colors. For a fuller
# list of colors, and an example how to use them, see my bash color file on my GitHub
# and my coniguration for colored man pages.
#
# https://github.com/chadversary/home/blob/42cf697ba69d4d474ca74297cdf94186430f1384/.config/kiwi-profile/10-colors.sh
# https://github.com/chadversary/home/blob/42cf697ba69d4d474ca74297cdf94186430f1384/.config/kiwi-profile/40-less.sh
#
color_start='\e['
color_end='m'
color_reset='\e[0m'
color_bg_blue='44'

#
# To get a fancy git prompt, it's not sufficient to set PS1. Instead, we set PROMPT_COMMAND,
# a built in Bash variable that gets evaluated before each render of the prompt.
#
export PROMPT_COMMAND="PS1=\"\${color_start}\${color_bg_blue}\${color_end}\u@\h [\w\$(__git_ps1 \" - %s\")]\${color_reset}\n\$ \""

#
# If you find that the working directory that appears in the prompt is ofter too long,
# then trim it.
#
export PROMPT_DIRTRIM=3

How to get the background color of an HTML element?

As with all css properties that contain hyphens, their corresponding names in JS is to remove the hyphen and make the following letter capital: backgroundColor

alert(myDiv.style.backgroundColor);

Deserialize from string instead TextReader

Shamelessly copied from Generic deserialization of an xml string

    public static T DeserializeFromXmlString<T>(string xmlString)
    {
        var serializer = new XmlSerializer(typeof(T));
        using (TextReader reader = new StringReader(xmlString))
        {
            return (T) serializer.Deserialize(reader);
        }
    }

Error: Can't set headers after they are sent to the client

I had this issue when I was nesting promises. A promise inside of a promise would return 200 to the server, but then the outer promise's catch statement would return a 500. Once I fixed this, the problem went away.

foreach vs someList.ForEach(){}

You could name the anonymous delegate :-)

And you can write the second as:

someList.ForEach(s => s.ToUpper())

Which I prefer, and saves a lot of typing.

As Joachim says, parallelism is easier to apply to the second form.

Rails: Check output of path helper from console

you can also

include Rails.application.routes.url_helpers

from inside a console sessions to access the helpers:

url_for controller: :users, only_path: true
users_path
# => '/users'

or

Rails.application.routes.url_helpers.users_path

Does reading an entire file leave the file handle open?

Instead of retrieving the file content as a single string, it can be handy to store the content as a list of all lines the file comprises:

with open('Path/to/file', 'r') as content_file:
    content_list = content_file.read().strip().split("\n")

As can be seen, one needs to add the concatenated methods .strip().split("\n") to the main answer in this thread.

Here, .strip() just removes whitespace and newline characters at the endings of the entire file string, and .split("\n") produces the actual list via splitting the entire file string at every newline character \n.

Moreover, this way the entire file content can be stored in a variable, which might be desired in some cases, instead of looping over the file line by line as pointed out in this previous answer.

Angular directive how to add an attribute to the element?

You can try this:

<div ng-app="app">
    <div ng-controller="AppCtrl">
        <a my-dir ng-repeat="user in users" ng-click="fxn()">{{user.name}}</a>
    </div>
</div>

<script>
var app = angular.module('app', []);

function AppCtrl($scope) {
        $scope.users = [{ name: 'John', id: 1 }, { name: 'anonymous' }];
        $scope.fxn = function () {
            alert('It works');
        };
    }

app.directive("myDir", function ($compile) {
    return {
        scope: {ngClick: '='}
    };
});
</script>

Oracle to_date, from mm/dd/yyyy to dd-mm-yyyy

You don't need to muck about with extracting parts of the date. Just cast it to a date using to_date and the format in which its stored, then cast that date to a char in the format you want. Like this:

select to_char(to_date('1/10/2011','mm/dd/yyyy'),'mm-dd-yyyy') from dual

Printing Java Collections Nicely (toString Doesn't Return Pretty Output)

Just Modified the previous example to print even collection containing user defined objects.

public class ToStringHelper {

    private  static String separator = "\n";

    public ToStringHelper(String seperator) {
        super();
        ToStringHelper.separator = seperator;

    }

    public  static String toString(List<?> l) {
        StringBuilder sb = new StringBuilder();
        String sep = "";
        for (Object object : l) {
            String v = ToStringBuilder.reflectionToString(object);
            int start = v.indexOf("[");
            int end = v.indexOf("]");
            String st =  v.substring(start,end+1);
            sb.append(sep).append(st);
            sep = separator;
        }
        return sb.toString();
    }

    public static String toString(Map<?,?> m) {
        StringBuilder sb = new StringBuilder();
        String sep = "";
        for (Object object : m.keySet()) {
            String v = ToStringBuilder.reflectionToString(m.get(object));
            int start = v.indexOf("[");
            int end = v.indexOf("]");
            String st =  v.substring(start,end+1);
            sb.append(sep).append(st);
            sep = separator;
        }
        return sb.toString();
    }

    public static String toString(Set<?> s) {
        StringBuilder sb = new StringBuilder();
        String sep = "";
        for (Object object : s) {
            String v = ToStringBuilder.reflectionToString(object);
            int start = v.indexOf("[");
            int end = v.indexOf("]");
            String st =  v.substring(start,end+1);
            sb.append(sep).append(st);
            sep = separator;
        }
        return sb.toString();
    }

    public static void print(List<?> l) {
        System.out.println(toString(l));    
    }
    public static void print(Map<?,?> m) {
        System.out.println(toString(m));    
    }
    public static void print(Set<?> s) {
        System.out.println(toString(s));    
    }

}

Getting attribute using XPath

You can also get it by

string(//bookstore/book[1]/title/@lang)    
string(//bookstore/book[2]/title/@lang)

although if you are using XMLDOM with JavaScript you can code something like

var n1 = uXmlDoc.selectSingleNode("//bookstore/book[1]/title/@lang");

and n1.text will give you the value "eng"

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-jar-plugin:2.3.2 or one of its dependencies could not be resolved

Jotting down some steps which help:

Writing answer from eclipse perspective as base logic will remain the same whether done by Intellij or command line

  1. Rt click your project -> Maven -> Update project -> Select Force update -> Click OK
  2. Under properties tag , add :
>  <maven.compiler.source>1.8</maven.compiler.source> 
> <maven.compiler.target>1.8</maven.compiler.target>
  1. In some instance , you will start seeing error as we tried force update , saying , failure to transfer X dependency from Y path , resolutions will not be reattempted , bla bla bla **In such case quickly fix it by cd to .m2/repository folder and run following command :

for /r %i in (*.lastUpdated) do del %i**

Python loop counter in a for loop

I'll sometimes do this:

def draw_menu(options, selected_index):
    for i in range(len(options)):
        if i == selected_index:
            print " [*] %s" % options[i]
        else:
            print " [ ] %s" % options[i]

Though I tend to avoid this if it means I'll be saying options[i] more than a couple of times.

Generating random numbers in Objective-C

Use the arc4random_uniform(upper_bound) function to generate a random number within a range. The following will generate a number between 0 and 73 inclusive.

arc4random_uniform(74)

arc4random_uniform(upper_bound) avoids modulo bias as described in the man page:

arc4random_uniform() will return a uniformly distributed random number less than upper_bound. arc4random_uniform() is recommended over constructions like ``arc4random() % upper_bound'' as it avoids "modulo bias" when the upper bound is not a power of two.

The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication

I had the same problem while trying to consume net.tcp wcf service endpoint in a http asmx service.

As I saw no one wrote specific answer WHY is this problem occurring, but only how to be handled properly.

I've been struggling with it several days in a row and finally I found out where the problem comes from in my case.

Initially I thought that when you make a reference to a service the config file will be configured regarding security tag the same way as it's in the source, but that was not the case and I should take care of it manually. In my case I had only

<netTcpBinding>
    <binding name="NetTcpBinding_IAuthenticationLoggerService"
    </binding>
</netTcpBinding>`

Later I saw that the security part is missing and it should looks like this

<netTcpBinding>
    <binding name="NetTcpBinding_IAuthenticationLoggerService" transferMode="Buffered">
      <security mode="None">
        <transport clientCredentialType="None"/>
      </security>
    </binding>
  </netTcpBinding>

The second problem in my case was that I was using transferMode="Streamed" on my source WCF service and in the client I had nothing specific about it, which was bad, because the default transferMode is Buffered and it's important on both places source and client to be configured in the same way.

Is it possible to implement a Python for range loop without an iterator variable?

May be answer would depend on what problem you have with using iterator? may be use

i = 100
while i:
    print i
    i-=1

or

def loop(N, doSomething):
    if not N:
        return
    print doSomething(N)
    loop(N-1, doSomething)

loop(100, lambda a:a)

but frankly i see no point in using such approaches

How to display a pdf in a modal window?

You can have an iframe inside the modal markup and give the src attribute of it as the link to your pdf. On click of the link you can show this modal markup.

How to extract the first two characters of a string in shell scripting?

easiest way is

${string:position:length}

Where this extracts $length substring from $string at $position.

This is a bash builtin so awk or sed is not required.

How can I specify the schema to run an sql file against in the Postgresql command line

Main Example

The example below will run myfile.sql on database mydatabase using schema myschema.

psql "dbname=mydatabase options=--search_path=myschema" -a -f myfile.sql

The way this works is the first argument to the psql command is the dbname argument. The docs mention a connection string can be provided.

If this parameter contains an = sign or starts with a valid URI prefix (postgresql:// or postgres://), it is treated as a conninfo string

The dbname keyword specifies the database to connect to and the options keyword lets you specify command-line options to send to the server at connection startup. Those options are detailed in the server configuration chapter. The option we are using to select the schema is search_path.

Another Example

The example below will connect to host myhost on database mydatabase using schema myschema. The = special character must be url escaped with the escape sequence %3D.

psql postgres://myuser@myhost?options=--search_path%3Dmyschema

GitHub: invalid username or password

You might be getting this error because you have updated your password. So on Terminal first make sure you clear your GitHub credentials from the keychain and then push your changes to your repo, terminal will ask for your username and password.

Sending email with attachments from C#, attachments arrive as Part 1.2 in Thunderbird

Simple code to send email with attachement.

source: http://www.coding-issues.com/2012/11/sending-email-with-attachments-from-c.html

using System.Net;
using System.Net.Mail;

public void email_send()
{
    MailMessage mail = new MailMessage();
    SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
    mail.From = new MailAddress("your [email protected]");
    mail.To.Add("[email protected]");
    mail.Subject = "Test Mail - 1";
    mail.Body = "mail with attachment";

    System.Net.Mail.Attachment attachment;
    attachment = new System.Net.Mail.Attachment("c:/textfile.txt");
    mail.Attachments.Add(attachment);

    SmtpServer.Port = 587;
    SmtpServer.Credentials = new System.Net.NetworkCredential("your [email protected]", "your password");
    SmtpServer.EnableSsl = true;

    SmtpServer.Send(mail);

}

Populate a Drop down box from a mySQL table in PHP

At the top first set up database connection as follow:

<?php
$mysqli = new mysqli("localhost", "username", "password", "database") or die($this->mysqli->error);
$query= $mysqli->query("SELECT PcID from PC");
?> 

Then include the following code in HTML inside form

<select name="selected_pcid" id='selected_pcid'>

            <?php 

             while ($rows = $query->fetch_array(MYSQLI_ASSOC)) {
                        $value= $rows['id'];
                ?>
                 <option value="<?= $value?>"><?= $value?></option>
                <?php } ?>
             </select>

However, if you are using materialize css or any other out of the box css, make sure that select field is not hidden or disabled.

Clearing the terminal screen?

The Arduino serial monitor isn't a regular terminal so its not possible to clear the screen using standard terminal commands. I suggest using an actual terminal emulator, like Putty.

The command for clearing a terminal screen is ESC[2J

To accomplish in Arduino code:

  Serial.write(27);       // ESC command
  Serial.print("[2J");    // clear screen command
  Serial.write(27);
  Serial.print("[H");     // cursor to home command

Source:
http://www.instructables.com/id/A-Wirelessly-Controlled-Arduino-Powered-Message-B/step6/Useful-Code-Explained-Clearing-a-Serial-Terminal/

jQuery find() method not working in AngularJS directive

find() - Limited to lookups by tag name you can see more information https://docs.angularjs.org/api/ng/function/angular.element

Also you can access by name or id or call please following example:

angular.element(document.querySelector('#txtName')).attr('class', 'error');

PostgreSQL ERROR: canceling statement due to conflict with recovery

There's no need to start idle transactions on the master. In postgresql-9.1 the most direct way to solve this problem is by setting

hot_standby_feedback = on

This will make the master aware of long-running queries. From the docs:

The first option is to set the parameter hot_standby_feedback, which prevents VACUUM from removing recently-dead rows and so cleanup conflicts do not occur.

Why isn't this the default? This parameter was added after the initial implementation and it's the only way that a standby can affect a master.

convert xml to java object using jaxb (unmarshal)

Tests

On the Tests class we will add an @XmlRootElement annotation. Doing this will let your JAXB implementation know that when a document starts with this element that it should instantiate this class. JAXB is configuration by exception, this means you only need to add annotations where your mapping differs from the default. Since the testData property differs from the default mapping we will use the @XmlElement annotation. You may find the following tutorial helpful: http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted

package forum11221136;

import javax.xml.bind.annotation.*;

@XmlRootElement
public class Tests {

    TestData testData;

    @XmlElement(name="test-data")
    public TestData getTestData() {
        return testData;
    }

    public void setTestData(TestData testData) {
        this.testData = testData;
    }

}

TestData

On this class I used the @XmlType annotation to specify the order in which the elements should be ordered in. I added a testData property that appeared to be missing. I also used an @XmlElement annotation for the same reason as in the Tests class.

package forum11221136;

import java.util.List;
import javax.xml.bind.annotation.*;

@XmlType(propOrder={"title", "book", "count", "testData"})
public class TestData {
    String title;
    String book;
    String count;
    List<TestData> testData;

    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getBook() {
        return book;
    }
    public void setBook(String book) {
        this.book = book;
    }
    public String getCount() {
        return count;
    }
    public void setCount(String count) {
        this.count = count;
    }
    @XmlElement(name="test-data")
    public List<TestData> getTestData() {
        return testData;
    }
    public void setTestData(List<TestData> testData) {
        this.testData = testData;
    }
}

Demo

Below is an example of how to use the JAXB APIs to read (unmarshal) the XML and populate your domain model and then write (marshal) the result back to XML.

package forum11221136;

import java.io.File;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Tests.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum11221136/input.xml");
        Tests tests = (Tests) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(tests, System.out);
    }

}

How does Google reCAPTCHA v2 work behind the scenes?

Please remember that Google also use reCaptcha together with

Canvas fingerprinting 

to uniquely recognize User/Browsers without cookies!

Matrix Transpose in Python

def transpose(matrix):
   x=0
   trans=[]
   b=len(matrix[0])
   while b!=0:
       trans.append([])
       b-=1
   for list in matrix:
       for element in list:
          trans[x].append(element)
          x+=1
       x=0
   return trans

Process escape sequences in a string in Python

The ast.literal_eval function comes close, but it will expect the string to be properly quoted first.

Of course Python's interpretation of backslash escapes depends on how the string is quoted ("" vs r"" vs u"", triple quotes, etc) so you may want to wrap the user input in suitable quotes and pass to literal_eval. Wrapping it in quotes will also prevent literal_eval from returning a number, tuple, dictionary, etc.

Things still might get tricky if the user types unquoted quotes of the type you intend to wrap around the string.

C# list.Orderby descending

Yes. Use OrderByDescending instead of OrderBy.

SQL to add column and comment in table in single command

You can use below query to update or create comment on already created table.

SYNTAX:

COMMENT ON COLUMN TableName.ColumnName IS 'comment text';

Example:

COMMENT ON COLUMN TAB_SAMBANGI.MY_COLUMN IS 'This is a comment on my column...';

How to run a program without an operating system?

How do you run a program all by itself without an operating system running?

You place your binary code to a place where processor looks for after rebooting (e.g. address 0 on ARM).

Can you create assembly programs that the computer can load and run at startup ( e.g. boot the computer from a flash drive and it runs the program that is on the drive)?

General answer to the question: it can be done. It's often referred to as "bare metal programming". To read from flash drive, you want to know what's USB, and you want to have some driver to work with this USB. The program on this drive would also have to be in some particular format, on some particular filesystem... This is something that boot loaders usually do, but your program could include its own bootloader so it's self-contained, if the firmware will only load a small block of code.

Many ARM boards let you do some of those things. Some have boot loaders to help you with basic setup.

Here you may find a great tutorial on how to do a basic operating system on a Raspberry Pi.

Edit: This article, and the whole wiki.osdev.org will anwer most of your questions http://wiki.osdev.org/Introduction

Also, if you don't want to experiment directly on hardware, you can run it as a virtual machine using hypervisors like qemu. See how to run "hello world" directly on virtualized ARM hardware here.

How to call a function within class?

That doesn't work because distToPoint is inside your class, so you need to prefix it with the classname if you want to refer to it, like this: classname.distToPoint(self, p). You shouldn't do it like that, though. A better way to do it is to refer to the method directly through the class instance (which is the first argument of a class method), like so: self.distToPoint(p).

How do I trim whitespace?

For whitespace on both sides use str.strip:

s = "  \t a string example\t  "
s = s.strip()

For whitespace on the right side use rstrip:

s = s.rstrip()

For whitespace on the left side lstrip:

s = s.lstrip()

As thedz points out, you can provide an argument to strip arbitrary characters to any of these functions like this:

s = s.strip(' \t\n\r')

This will strip any space, \t, \n, or \r characters from the left-hand side, right-hand side, or both sides of the string.

The examples above only remove strings from the left-hand and right-hand sides of strings. If you want to also remove characters from the middle of a string, try re.sub:

import re
print(re.sub('[\s+]', '', s))

That should print out:

astringexample

Converting an int or String to a char array on Arduino

None of that stuff worked. Here's a much simpler way .. the label str is the pointer to what IS an array...

String str = String(yourNumber, DEC); // Obviously .. get your int or byte into the string

str = str + '\r' + '\n'; // Add the required carriage return, optional line feed

byte str_len = str.length();

// Get the length of the whole lot .. C will kindly
// place a null at the end of the string which makes
// it by default an array[].
// The [0] element is the highest digit... so we
// have a separate place counter for the array...

byte arrayPointer = 0;

while (str_len)
{
    // I was outputting the digits to the TX buffer

    if ((UCSR0A & (1<<UDRE0))) // Is the TX buffer empty?
    {
        UDR0 = str[arrayPointer];
        --str_len;
        ++arrayPointer;
    }
}

How do I remove quotes from a string?

str_replace('"', "", $string);
str_replace("'", "", $string);

I assume you mean quotation marks?

Otherwise, go for some regex, this will work for html quotes for example:

preg_replace("/<!--.*?-->/", "", $string);

C-style quotes:

preg_replace("/\/\/.*?\n/", "\n", $string);

CSS-style quotes:

preg_replace("/\/*.*?\*\//", "", $string);

bash-style quotes:

preg-replace("/#.*?\n/", "\n", $string);

Etc etc...

git clone from another directory

It is worth mentioning that the command works similarly on Linux:

git clone path/to/source/folder path/to/destination/folder

Only detect click event on pseudo-element

No,but you can do like this

In html file add this section

<div class="arrow">
</div>

In css you can do like this

p div.arrow {
    content: '';
    position: absolute;
    left:100%;
    width: 10px;
    height: 100%;
    background-color: red;
} 

Hope it will help you

How to use vertical align in bootstrap

You mean you want 1b and 1b to be side by side?

 <div class="col-lg-6 col-md-6 col-12 child1">
      <div class="col-6 child1a">Child content 1a</div>
      <div class="col-6 child1b">Child content 1b</div>
 </div>

Display current date and time without punctuation

Here you go:

date +%Y%m%d%H%M%S

As man date says near the top, you can use the date command like this:

date [OPTION]... [+FORMAT]

That is, you can give it a format parameter, starting with a +. You can probably guess the meaning of the formatting symbols I used:

  • %Y is for year
  • %m is for month
  • %d is for day
  • ... and so on

You can find this, and other formatting symbols in man date.

how to call a variable in code behind to aspx page

In your code behind file, have a public variable

public partial class _Default : System.Web.UI.Page
{
    public string clients;

    protected void Page_Load(object sender, EventArgs e)
    {
        // your code that at one points sets the variable
        this.clients = "abc";
    }
}

now in your design code, just assign that to something, like:

<div>
    <p><%= clients %></p>
</div>

or even a javascript variable

<script type="text/javascript">

    var clients = '<%= clients %>';

</script>

Difference between timestamps with/without time zone in PostgreSQL

Here is an example that should help. If you have a timestamp with a timezone, you can convert that timestamp into any other timezone. If you haven't got a base timezone it won't be converted correctly.

SELECT now(),
   now()::timestamp,
   now() AT TIME ZONE 'CST',
   now()::timestamp AT TIME ZONE 'CST'

Output:

-[ RECORD 1 ]---------------------------
now      | 2018-09-15 17:01:36.399357+03
now      | 2018-09-15 17:01:36.399357
timezone | 2018-09-15 08:01:36.399357
timezone | 2018-09-16 02:01:36.399357+03

How to get the xml node value in string

The problem in your code is xml.LoadXml(filePath);

LoadXml method take parameter as xml data not the xml file path

Try this code

   string xmlFile = File.ReadAllText(@"D:\Work_Time_Calculator\10-07-2013.xml");
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.LoadXml(xmlFile);
                XmlNodeList nodeList = xmldoc.GetElementsByTagName("Short_Fall");
                string Short_Fall=string.Empty;
                foreach (XmlNode node in nodeList)
                {
                    Short_Fall = node.InnerText;
                }

Edit

Seeing the last edit of your question i found the solution,

Just replace the below 2 lines

XmlNode node = xml.SelectSingleNode("/Data[@*]/Short_Fall");
string id = node["Short_Fall"].InnerText; // Exception occurs here ("Object reference not set to an instance of an object.")

with

string id = xml.SelectSingleNode("Data/Short_Fall").InnerText;

It should solve your problem or you can use the solution i provided earlier.

Importing modules from parent folder

same sort of style as the past answer - but in fewer lines :P

import os,sys
parentdir = os.path.dirname(__file__)
sys.path.insert(0,parentdir)

file returns the location you are working in

What would be the best method to code heading/title for <ul> or <ol>, Like we have <caption> in <table>?

h3 is absolutly a better solution than h2, h1 or h6 !

  1. You have to use specific level : if you're in a h1, use h2, if you're in a h5, use h6 (if you're in a h6... hum, use strong or em for exemple). It not a obligation but a question of accessibility (Here, green part).

  2. You don't have to give title to list... because this element it doesn't exist. So screen reader will not use something special.

Therefore, using Hn is probably one of the best solution, but surely not a specific level.

How to add Android Support Repository to Android Studio?

You are probably hit by this bug which prevents the Android Gradle Plugin from automatically adding the "Android Support Repository" to the list of Gradle repositories. The work-around, as mentioned in the bug report, is to explicitly add the m2repository directory as a local Maven directory in the top-level build.gradle file as follows:

allprojects {
    repositories {
        // Work around https://code.google.com/p/android/issues/detail?id=69270.
        def androidHome = System.getenv("ANDROID_HOME")
        maven {
            url "$androidHome/extras/android/m2repository/"
        }
    }
}

PHP Fatal error: Call to undefined function json_decode()

The same issue with 7.1

apt-get install php7.1-json sudo nano /etc/php/7.1/mods-available/json.ini

  • Add json.so to the new file
  • Add the appropriate sym link under conf.d
  • Restart apache2 service (if needed)

Python group by

Do it in 2 steps. First, create a dictionary.

>>> input = [('11013331', 'KAT'), ('9085267', 'NOT'), ('5238761', 'ETH'), ('5349618', 'ETH'), ('11788544', 'NOT'), ('962142', 'ETH'), ('7795297', 'ETH'), ('7341464', 'ETH'), ('9843236', 'KAT'), ('5594916', 'ETH'), ('1550003', 'ETH')]
>>> from collections import defaultdict
>>> res = defaultdict(list)
>>> for v, k in input: res[k].append(v)
...

Then, convert that dictionary into the expected format.

>>> [{'type':k, 'items':v} for k,v in res.items()]
[{'items': ['9085267', '11788544'], 'type': 'NOT'}, {'items': ['5238761', '5349618', '962142', '7795297', '7341464', '5594916', '1550003'], 'type': 'ETH'}, {'items': ['11013331', '9843236'], 'type': 'KAT'}]

It is also possible with itertools.groupby but it requires the input to be sorted first.

>>> sorted_input = sorted(input, key=itemgetter(1))
>>> groups = groupby(sorted_input, key=itemgetter(1))
>>> [{'type':k, 'items':[x[0] for x in v]} for k, v in groups]
[{'items': ['5238761', '5349618', '962142', '7795297', '7341464', '5594916', '1550003'], 'type': 'ETH'}, {'items': ['11013331', '9843236'], 'type': 'KAT'}, {'items': ['9085267', '11788544'], 'type': 'NOT'}]

Note both of these do not respect the original order of the keys. You need an OrderedDict if you need to keep the order.

>>> from collections import OrderedDict
>>> res = OrderedDict()
>>> for v, k in input:
...   if k in res: res[k].append(v)
...   else: res[k] = [v]
... 
>>> [{'type':k, 'items':v} for k,v in res.items()]
[{'items': ['11013331', '9843236'], 'type': 'KAT'}, {'items': ['9085267', '11788544'], 'type': 'NOT'}, {'items': ['5238761', '5349618', '962142', '7795297', '7341464', '5594916', '1550003'], 'type': 'ETH'}]

JQuery, Spring MVC @RequestBody and JSON - making it work together

I'm pretty sure you only have to register MappingJacksonHttpMessageConverter

(the easiest way to do that is through <mvc:annotation-driven /> in XML or @EnableWebMvc in Java)

See:


Here's a working example:

Maven POM

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion><groupId>test</groupId><artifactId>json</artifactId><packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version><name>json test</name>
    <dependencies>
        <dependency><!-- spring mvc -->
            <groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>3.0.5.RELEASE</version>
        </dependency>
        <dependency><!-- jackson -->
            <groupId>org.codehaus.jackson</groupId><artifactId>jackson-mapper-asl</artifactId><version>1.4.2</version>
        </dependency>
    </dependencies>
    <build><plugins>
            <!-- javac --><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version><configuration><source>1.6</source><target>1.6</target></configuration></plugin>
            <!-- jetty --><plugin><groupId>org.mortbay.jetty</groupId><artifactId>jetty-maven-plugin</artifactId>
            <version>7.4.0.v20110414</version></plugin>
    </plugins></build>
</project>

in folder src/main/webapp/WEB-INF

web.xml

<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4">
    <servlet><servlet-name>json</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>json</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
</web-app>

json-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <import resource="classpath:mvc-context.xml" />

</beans>

in folder src/main/resources:

mvc-context.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <mvc:annotation-driven />
    <context:component-scan base-package="test.json" />
</beans>

In folder src/main/java/test/json

TestController.java

@Controller
@RequestMapping("/test")
public class TestController {

    @RequestMapping(method = RequestMethod.POST, value = "math")
    @ResponseBody
    public Result math(@RequestBody final Request request) {
        final Result result = new Result();
        result.setAddition(request.getLeft() + request.getRight());
        result.setSubtraction(request.getLeft() - request.getRight());
        result.setMultiplication(request.getLeft() * request.getRight());
        return result;
    }

}

Request.java

public class Request implements Serializable {
    private static final long serialVersionUID = 1513207428686438208L;
    private int left;
    private int right;
    public int getLeft() {return left;}
    public void setLeft(int left) {this.left = left;}
    public int getRight() {return right;}
    public void setRight(int right) {this.right = right;}
}

Result.java

public class Result implements Serializable {
    private static final long serialVersionUID = -5054749880960511861L;
    private int addition;
    private int subtraction;
    private int multiplication;

    public int getAddition() { return addition; }
    public void setAddition(int addition) { this.addition = addition; }
    public int getSubtraction() { return subtraction; }
    public void setSubtraction(int subtraction) { this.subtraction = subtraction; }
    public int getMultiplication() { return multiplication; }
    public void setMultiplication(int multiplication) { this.multiplication = multiplication; }
}

You can test this setup by executing mvn jetty:run on the command line, and then sending a POST request:

URL:        http://localhost:8080/test/math
mime type:  application/json
post body:  { "left": 13 , "right" : 7 }

I used the Poster Firefox plugin to do this.

Here's what the response looks like:

{"addition":20,"subtraction":6,"multiplication":91}

Character reading from file in Python

Leaving aside the fact that your text file is broken (U+2018 is a left quotation mark, not an apostrophe): iconv can be used to transliterate unicode characters to ascii.

You'll have to google for "iconvcodec", since the module seems not to be supported anymore and I can't find a canonical home page for it.

>>> import iconvcodec
>>> from locale import setlocale, LC_ALL
>>> setlocale(LC_ALL, '')
>>> u'\u2018'.encode('ascii//translit')
"'"

Alternatively you can use the iconv command line utility to clean up your file:

$ xxd foo
0000000: e280 980a                                ....
$ iconv -t 'ascii//translit' foo | xxd
0000000: 270a                                     '.

"Exception has been thrown by the target of an invocation" error (mscorlib)

Encounter the same error when tried to connect to SQLServer2017 through Management Studio 2014

enter image description here

The reason was backward compatibility

So I just downloaded the Management Studio 2017 and tried to connect to SQLServer2017.

Problem Solve!!

Add/Delete table rows dynamically using JavaScript

This seems a lot cleaner than the answer above...

<script>
var maxID = 0;
function getTemplateRow() {
var x = document.getElementById("templateRow").cloneNode(true);
x.id = "";
x.style.display = "";
x.innerHTML = x.innerHTML.replace(/{id}/, ++maxID);
return x;
}
function addRow() {
var t = document.getElementById("theTable");
var rows = t.getElementsByTagName("tr");
var r = rows[rows.length - 1];
r.parentNode.insertBefore(getTemplateRow(), r);

}
</script>


<table id="theTable">
<tr>
<td>id</td>
<td>name</td>
</tr>
<tr id="templateRow" style="display:none">
<td>{id}</td>
<td><input /></td>
</tr>
</table>


<button onclick="addRow();">Go</button>

Wait until all jQuery Ajax requests are done?

I highly recommend using $.when() if you're starting from scratch.

Even though this question has over million answers, I still didn't find anything useful for my case. Let's say you have to deal with an existing codebase, already making some ajax calls and don't want to introduce the complexity of promises and/or redo the whole thing.

We can easily take advantage of jQuery .data, .on and .trigger functions which have been a part of jQuery since forever.

Codepen

The good stuff about my solution is:

  • it's obvious what the callback exactly depends on

  • the function triggerNowOrOnLoaded doesn't care if the data has been already loaded or we're still waiting for it

  • it's super easy to plug it into an existing code

_x000D_
_x000D_
$(function() {_x000D_
_x000D_
  // wait for posts to be loaded_x000D_
  triggerNowOrOnLoaded("posts", function() {_x000D_
    var $body = $("body");_x000D_
    var posts = $body.data("posts");_x000D_
_x000D_
    $body.append("<div>Posts: " + posts.length + "</div>");_x000D_
  });_x000D_
_x000D_
_x000D_
  // some ajax requests_x000D_
  $.getJSON("https://jsonplaceholder.typicode.com/posts", function(data) {_x000D_
    $("body").data("posts", data).trigger("posts");_x000D_
  });_x000D_
_x000D_
  // doesn't matter if the `triggerNowOrOnLoaded` is called after or before the actual requests _x000D_
  $.getJSON("https://jsonplaceholder.typicode.com/users", function(data) {_x000D_
    $("body").data("users", data).trigger("users");_x000D_
  });_x000D_
_x000D_
_x000D_
  // wait for both types_x000D_
  triggerNowOrOnLoaded(["posts", "users"], function() {_x000D_
    var $body = $("body");_x000D_
    var posts = $body.data("posts");_x000D_
    var users = $body.data("users");_x000D_
_x000D_
    $body.append("<div>Posts: " + posts.length + " and Users: " + users.length + "</div>");_x000D_
  });_x000D_
_x000D_
  // works even if everything has already loaded!_x000D_
  setTimeout(function() {_x000D_
_x000D_
    // triggers immediately since users have been already loaded_x000D_
    triggerNowOrOnLoaded("users", function() {_x000D_
      var $body = $("body");_x000D_
      var users = $body.data("users");_x000D_
_x000D_
      $body.append("<div>Delayed Users: " + users.length + "</div>");_x000D_
    });_x000D_
_x000D_
  }, 2000); // 2 seconds_x000D_
_x000D_
});_x000D_
_x000D_
// helper function_x000D_
function triggerNowOrOnLoaded(types, callback) {_x000D_
  types = $.isArray(types) ? types : [types];_x000D_
_x000D_
  var $body = $("body");_x000D_
_x000D_
  var waitForTypes = [];_x000D_
  $.each(types, function(i, type) {_x000D_
_x000D_
    if (typeof $body.data(type) === 'undefined') {_x000D_
      waitForTypes.push(type);_x000D_
    }_x000D_
  });_x000D_
_x000D_
  var isDataReady = waitForTypes.length === 0;_x000D_
  if (isDataReady) {_x000D_
    callback();_x000D_
    return;_x000D_
  }_x000D_
_x000D_
  // wait for the last type and run this function again for the rest of the types_x000D_
  var waitFor = waitForTypes.pop();_x000D_
  $body.on(waitFor, function() {_x000D_
    // remove event handler - we only want the stuff triggered once_x000D_
    $body.off(waitFor);_x000D_
_x000D_
    triggerNowOrOnLoaded(waitForTypes, callback);_x000D_
  });_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<body>Hi!</body>
_x000D_
_x000D_
_x000D_

Travel/Hotel API's?

In my search for hotel APIs I have found only one API giving unrestricted open access to their hotel database and allowing you to book their hotels:

Expedia's EAN http://developer.ean.com/

You need to sign for their affiliate program, which is very easy. You get immediate access to their hotel databases plus you can make availability/booking requests with several response options, including JSON, which is more convenient and lightweight than the (unfortunately) more widespread XML.

As you immediately access their API, you can start developing and testing, but still need their approval to launch the site, basically to make sure it provides the needed quality and security, which is reasonable.

They also offer "deep linking", i.e. you may customize your requests by adding parameters. Then if it sufficient for your purpose (for mine it is not), you don't even need to store their content on your server.


I have also signed for HotelsCombined program: (link removed as this site doesn't seem to let me put more links)

However, they do not immediately allow you to use their API even for testing. From their answer:

"Apologies for the inconvenience caused, but it’s simply a business decision to limit access to our rich hotel content. Please kindly check back within the next 2-3 months, where we will be able to judge your traffic, and in turn judge your status on standard data feeds."


I have also signed for Booking.com affiliate program: (link removed as this site doesn't seem to let me put more links)

Unfortunately, again, they limit access, from their answer: "Please do note that, since there's a high amount of time and cost involved in the XML integration, we are only able to offer the XML integration to a small amount of partners with a high potential."


I did not explore Tripadvisor as they seem only to offer top 10 hotels and only as widgets, but most importantly for me, they wouldn't allow booking through them.

I've checked the hotelbase.org mentioned above, they have very extensive list but not as rich as by Expedia, also they don't seem to have images and don't allow booking either.

How to hide code from cells in ipython notebook visualized with nbviewer?

(Paper) Printing or Saving as HTML

For those of you wishing to print to paper the outputs the above answers alone seem not to give a nice final output. However, taking @Max Masnick's code and adding the following allows one to print it on a full A4 page.

from IPython.display import display
from IPython.display import HTML
import IPython.core.display as di

di.display_html('<script>jQuery(function() {if (jQuery("body.notebook_app").length == 0) { jQuery(".input_area").toggle(); jQuery(".prompt").toggle();}});</script>', raw=True)

CSS = """#notebook div.output_subarea {max-width:100%;}""" #changes output_subarea width to 100% (from 100% - 14ex)
HTML('<style>{}</style>'.format(CSS))

The reason for the indent is that the prompt section removed by Max Masnick means everything shifts to the left on output. This however did nothing for the maximum width of the output which was restricted to max-width:100%-14ex;. This changes the max width of the output_subarea to max-width:100%;.

Insert an item into sorted list in Python

This is a possible solution for you:

a = [15, 12, 10]
b = sorted(a)
print b # --> b = [10, 12, 15]
c = 13
for i in range(len(b)):
    if b[i] > c:
        break
d = b[:i] + [c] + b[i:]
print d # --> d = [10, 12, 13, 15]

Import XXX cannot be resolved for Java SE standard classes

If the project is Maven, you can try this way :

  1. right click the "Maven Dependencies"-->"Build Path"-->"Remove from the build path";
  2. right click the project ,navigate to "Maven"--->"Update project....";

Then the import issue should be solved .

How to retrieve available RAM from Windows command line?

This cannot be done in pure java. But you can run external programs using java and get the result.

Process p=Runtime.getRuntime().exec("systeminfo");
Scanner scan=new Scanner(p.getInputStream());
while(scan.hasNext()){
    String temp=scan.nextLine();
    if(temp.equals("Available Physical Memmory")){
       System.out.println("RAM :"temp.split(":")[1]);
       break;
    }
}

Can I use VARCHAR as the PRIMARY KEY?

Of course you can, in the sense that your RDBMS will let you do it. The answer to a question of whether or not you should do it is different, though: in most situations, values that have a meaning outside your database system should not be chosen to be a primary key.

If you know that the value is unique in the system that you are modeling, it is appropriate to add a unique index or a unique constraint to your table. However, your primary key should generally be some "meaningless" value, such as an auto-incremented number or a GUID.

The rationale for this is simple: data entry errors and infrequent changes to things that appear non-changeable do happen. They become much harder to fix on values which are used as primary keys.

Number input type that takes only integers?

I was working oh Chrome and had some problems, even though I use html attributes. I ended up with this js code

$("#element").on("input", function(){
        var value = $(this).val();

        $(this).val("");
        $(this).val(parseInt(value));

        return true;
});

How do I add indices to MySQL tables?

ALTER TABLE TABLE_NAME ADD INDEX (COLUMN_NAME);

Why can't I find SQL Server Management Studio after installation?

Generally if the installation went smoothly, it will create the desktop icons/folders. Maybe check the installation summary log to see if there's any underlying errors.

It should be located C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log(date stamp)\

Loading basic HTML in Node.js

You can load HTML directly in end method

response.end('...<p>blahblahblah</p>...')

It's the same as

response.write('...<p>blahblahblah</p>...')
response.end()

SQL Server Insert if not exists

I would use a merge:

create PROCEDURE [dbo].[EmailsRecebidosInsert]
  (@_DE nvarchar(50),
   @_ASSUNTO nvarchar(50),
   @_DATA nvarchar(30) )
AS
BEGIN
   with data as (select @_DE as de, @_ASSUNTO as assunto, @_DATA as data)
   merge EmailsRecebidos t
   using data s
      on s.de = t.de
     and s.assunte = t.assunto
     and s.data = t.data
    when not matched by target
    then insert (de, assunto, data) values (s.de, s.assunto, s.data);
END

Automatically accept all SDK licences

For the newest Android Studio (2.3) the best way to update/accept all licenses is to run:

cd $ANDROID_HOME
tools/bin/sdkmanager --licenses

you might still need to copy the licence files to other locations based on your setup.

Status bar and navigation bar appear over my view's bounds in iOS 7

I would like to expand on Stunner's answer, and add an if statement to check if it is iOS-7, because when I tested it on iOS 6 my app would crash.

The addition would be adding:

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)

So I would suggest adding this method to your MyViewControler.m file:

- (void) viewDidLayoutSubviews {
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
        CGRect viewBounds = self.view.bounds;
        CGFloat topBarOffset = self.topLayoutGuide.length;
        viewBounds.origin.y = topBarOffset * -1;
        self.view.bounds = viewBounds;
    }
}