Programs & Examples On #Knowledge capture

Java Refuses to Start - Could not reserve enough space for object heap

You need to look at upgrading your OS and Java. Java 5.0 is EOL but if you cannot update to Java 6, you could use the latest patch level 22!

32-bit Windows is limited to ~ 1.3 GB so you are doing well to se the maximum to 1.8. Note: this is a problem with continous memory, and as your system runs its memory space can get fragmented so it does not suprise me you have this problem.

A 64-bit OS, doesn't have this problem as it has much more virtual space, you don't even have to upgrade to a 64-bit version of java to take advantage of this.

BTW, in my experience, 32-bit Java 5.0 can be faster than 64-bit Java 5.0. It wasn't until many years later that Java 6 update 10 was faster for 64-bit.

Extract first item of each sublist

lst = [['a','b','c'], [1,2,3], ['x','y','z']]
outputlist = []
for values in lst:
    outputlist.append(values[0])

print(outputlist) 

Output: ['a', 1, 'x']

char initial value in Java

Perhaps 0 or '\u0000' would do?

Is it safe to delete the "InetPub" folder?

If you reconfigure IIS7 to use your new location, then there's no problem. Just test that the new location is working, before deleting the old location.

Change IIS7 Inetpub path

  • Open %windir%\system32\inetsrv\config\applicationhost.config and search for

%SystemDrive%\inetpub\wwwroot

  • Change the path.

horizontal scrollbar on top and bottom of table

Angular version

I combined 2 answers here. (@simo and @bresleveloper)

https://stackblitz.com/edit/angular-double-scroll?file=src%2Fapp%2Fapp.component.html

inline-component

@Component({
  selector: 'app-double-scroll',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <div class="wrapper1" #wrapper1>
      <div class="div1" #div1></div>
    </div>
    <div class="wrapper2" #wrapper2>
        <div class="div2" #div2>
            <ng-content></ng-content>
        </div>
    </div>
  `,
  styles: [
    `
      .wrapper1, .wrapper2 { width: 100%; overflow-x: auto; overflow-y: hidden; }
    `,
    `
      .div1 { overflow: hidden; height: 0.5px;}
    `,
    `
      .div2 { overflow: hidden; min-width: min-content}
    `
  ]
})
export class DoubleScrollComponent implements AfterViewInit {

  @ViewChild('wrapper1') wrapper1: ElementRef<any>;
  @ViewChild('wrapper2') wrapper2: ElementRef<any>;

  @ViewChild('div1') div1: ElementRef<any>;
  @ViewChild('div2') div2: ElementRef<any>;

  constructor(private _r: Renderer2, private _cd: ChangeDetectorRef) {
  }


  ngAfterViewInit() {

    this._cd.detach();

    this._r.setStyle(this.div1.nativeElement, 'width', this.div2.nativeElement.clientWidth + 'px' );

    this.wrapper1.nativeElement.onscroll = e => this.wrapper2.nativeElement.scroll((e.target as HTMLElement).scrollLeft, 0)
    this.wrapper2.nativeElement.onscroll = e => this.wrapper1.nativeElement.scroll((e.target as HTMLElement).scrollLeft, 0)

  }

}

example

<div style="width: 200px; border: 1px black dashed">

  <app-double-scroll>
    <div style="min-width: 400px; background-color: red; word-break: keep-all; white-space: nowrap;">
      long ass text long ass text long ass text long ass text long ass text long ass text long ass text long ass text long ass text 
    </div>
  </app-double-scroll>

  <br>
  <hr>
  <br>

  <app-double-scroll>
    <div style="display: inline-block; background-color: green; word-break: keep-all; white-space: nowrap;">
      short ass text
    </div>
  </app-double-scroll>

  <br>
  <hr>
  <br>

  <app-double-scroll>
    <table width="100%" border="0" cellspacing="0" cellpadding="0">
      <tbody>
        <tr>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
          <td>table cell</td>
        </tr>
      </tbody>
    </table>
  </app-double-scroll>

</div>

Importing large sql file to MySql via command line

Importing large sql file to MySql via command line

  1. first download file .
  2. paste file on home.
  3. use following command in your terminals(CMD)
  4. Syntax: mysql -u username -p databsename < file.sql

Example: mysql -u root -p aanew < aanew.sql

INNER JOIN in UPDATE sql for DB2

Joins in update statements are non-standard and not supported by all vendors. What you're trying to do can be accomplished with a sub-select:

update
  file1
set
  firstfield = (select 'stuff' concat something from file2 where substr(file1.field1, 10, 20) = substr(file2.xxx,1,10) )
where
  file1.foo like 'BLAH%'

How to set my phpmyadmin user session to not time out so quickly?

Once you're logged into phpmyadmin look on the top navigation for "Settings" and click that then:

"Features" >

...and you'll find "Login cookie validity" which is typically set to 1440.

Unfortunately changing it through the UI means that the changes don't persist between logins.

The best node module for XML parsing

This answer concerns developers for Windows. You want to pick an XML parsing module that does NOT depend on node-expat. Node-expat requires node-gyp and node-gyp requires you to install Visual Studio on your machine. If your machine is a Windows Server, you definitely don't want to install Visual Studio on it.

So, which XML parsing module to pick?

Save yourself a lot of trouble and use either xml2js or xmldoc. They depend on sax.js which is a pure Javascript solution that doesn't require node-gyp.

Both libxmljs and xml-stream require node-gyp. Don't pick these unless you already have Visual Studio on your machine installed or you don't mind going down that road.

Update 2015-10-24: it seems somebody found a solution to use node-gyp on Windows without installing VS: https://github.com/nodejs/node-gyp/issues/629#issuecomment-138276692

Import and insert sql.gz file into database with putty

The file is a gzipped (compressed) SQL file, almost certainly a plain text file with .sql as its extension. The first thing you need to do is copy the file to your database server via scp.. I think PuTTY's is pscp.exe

# Copy it to the server via pscp
C:\> pscp.exe numbers.sql.gz user@serverhostname:/home/user

Then SSH into your server and uncompress the file with gunzip

user@serverhostname$  gunzip numbers.sql.gz
user@serverhostname$  ls 

numbers.sql

Finally, import it into your MySQL database using the < input redirection operator:

user@serverhostname$  mysql -u mysqluser -p < numbers.sql

If the numbers.sql file doesn't create a database but expects one to be present already, you will need to include the database in the command as well:

user@serverhostname$  mysql -u mysqluser -p databasename < numbers.sql

If you have the ability to connect directly to your MySQL server from outside, then you could use a local MySQL client instead of having to copy and SSH. In that case, you would just need a utility that can decompress .gz files on Windows. I believe 7zip does so, or you can obtain the gzip/gunzip binaries for Windows.

Responsive Image full screen and centered - maintain aspect ratio, not exceed window

To center it, you can use the technique shown here: Absolute centering.

To make it as big as possible, give it max-width and max-height of 100%.

To maintain the aspect ratio (even when the width is specifically set like in the snippet below), use object-fit as explained here.

_x000D_
_x000D_
.className {
    max-width: 100%;
    max-height: 100%;
    bottom: 0;
    left: 0;
    margin: auto;
    overflow: auto;
    position: fixed;
    right: 0;
    top: 0;
    -o-object-fit: contain;
    object-fit: contain;
}
_x000D_
<img src="https://i.imgur.com/HmezgW6.png" class="className" />

<!-- Slider to control the image width, only to make demo clearer !-->
<input type="range" min="10" max="2000" value="276" step="10" oninput="document.querySelector('img').style.width = (this.value +'px')" style="width: 90%; position: absolute; z-index: 2;" >
_x000D_
_x000D_
_x000D_

Priority queue in .Net

The following implementation of a PriorityQueue uses SortedSet from the System library.

using System;
using System.Collections.Generic;

namespace CDiggins
{
    interface IPriorityQueue<T, K> where K : IComparable<K>
    {
        bool Empty { get; }
        void Enqueue(T x, K key);
        void Dequeue();
        T Top { get; }
    }

    class PriorityQueue<T, K> : IPriorityQueue<T, K> where K : IComparable<K>
    {
        SortedSet<Tuple<T, K>> set;

        class Comparer : IComparer<Tuple<T, K>> {
            public int Compare(Tuple<T, K> x, Tuple<T, K> y) {
                return x.Item2.CompareTo(y.Item2);
            }
        }

        PriorityQueue() { set = new SortedSet<Tuple<T, K>>(new Comparer()); }
        public bool Empty { get { return set.Count == 0;  } }
        public void Enqueue(T x, K key) { set.Add(Tuple.Create(x, key)); }
        public void Dequeue() { set.Remove(set.Max); }
        public T Top { get { return set.Max.Item1; } }
    }
}

Convert base class to derived class

No, there's no built-in way to convert a class like you say. The simplest way to do this would be to do what you suggested: create a DerivedClass(BaseClass) constructor. Other options would basically come out to automate the copying of properties from the base to the derived instance, e.g. using reflection.

The code you posted using as will compile, as I'm sure you've seen, but will throw a null reference exception when you run it, because myBaseObject as DerivedClass will evaluate to null, since it's not an instance of DerivedClass.

Eclipse change project files location

I moved my default git repository folder and therefore had the same problem. I wrote my own Class to manage eclipse location and used it to change the location file.

        File locationfile 
            = new File("<workspace>"
                    +"/.metadata/.plugins/org.eclipse.core.resources/.projects/"
                    +"<project>/"
                    +".location");

        byte data[] = Files.readAllBytes(locationfile.toPath());

        EclipseLocation eclipseLocation = new EclipseLocation(data);

        eclipseLocation.changeUri("<new path to project>");

        byte newData[] = eclipseLocation.getData();

        Files.write(locationfile.toPath(),newData);

Here my EclipseLocation Class:

public class EclipseLocation {

    private byte[] data;
    private int length;
    private String uri;


    public EclipseLocation(byte[] data) {
        init(data);
    }

    public String getUri() {
        return uri;
    }

    public byte[] getData() {
        return data;
    }


    private void init(byte[] data) {

        this.data = data;   
        this.length = (data[16] * 256) + data[17];
        this.uri = new String(data,18,length);  
    }


    public void changeUri(String newUri) {

        int newLength = newUri.length();
        byte[] newdata = new byte[data.length + newLength - length];        


        int y = 0;
        int x = 0;

        //header
        while(y < 16) newdata[y++] = data[x++];

        //length
        newdata[16] = (byte) (newLength / 256);
        newdata[17] = (byte) (newLength % 256);

        y += 2;
        x += 2;

        //Uri
        for(int i = 0;i < newLength;i++)
        {
            newdata[y++] = (byte) newUri.charAt(i);
        }
        x += length;

        //footer
        while(y < newdata.length) newdata[y++] = data[x++];

        if(y != newdata.length)
            throw new IndexOutOfBoundsException();

        if(x != data.length)
            throw new IndexOutOfBoundsException();

        init(newdata);
    }


}

How to write text in ipython notebook?

Change the cell type to Markdown in the menu bar, from Code to Markdown. Currently in Notebook 4.x, the keyboard shortcut for such an action is: Esc (for command mode), then m (for markdown).

printf a variable in C

As Shafik already wrote you need to use the right format because scanf gets you a char. Don't hesitate to look here if u aren't sure about the usage: http://www.cplusplus.com/reference/cstdio/printf/

Hint: It's faster/nicer to write x=x+1; the shorter way: x++;

Sorry for answering what's answered just wanted to give him the link - the site was really useful to me all the time dealing with C.

What is a lambda (function)?

Lambda comes from the Lambda Calculus and refers to anonymous functions in programming.

Why is this cool? It allows you to write quick throw away functions without naming them. It also provides a nice way to write closures. With that power you can do things like this.

Python

def adder(x):
    return lambda y: x + y
add5 = adder(5)
add5(1)
6

As you can see from the snippet of Python, the function adder takes in an argument x, and returns an anonymous function, or lambda, that takes another argument y. That anonymous function allows you to create functions from functions. This is a simple example, but it should convey the power lambdas and closures have.

Examples in other languages

Perl 5

sub adder {
    my ($x) = @_;
    return sub {
        my ($y) = @_;
        $x + $y
    }
}

my $add5 = adder(5);
print &$add5(1) == 6 ? "ok\n" : "not ok\n";

JavaScript

var adder = function (x) {
    return function (y) {
        return x + y;
    };
};
add5 = adder(5);
add5(1) == 6

JavaScript (ES6)

const adder = x => y => x + y;
add5 = adder(5);
add5(1) == 6

Scheme

(define adder
    (lambda (x)
        (lambda (y)
           (+ x y))))
(define add5
    (adder 5))
(add5 1)
6

C# 3.5 or higher

Func<int, Func<int, int>> adder = 
    (int x) => (int y) => x + y; // `int` declarations optional
Func<int, int> add5 = adder(5);
var add6 = adder(6); // Using implicit typing
Debug.Assert(add5(1) == 6);
Debug.Assert(add6(-1) == 5);

// Closure example
int yEnclosed = 1;
Func<int, int> addWithClosure = 
    (x) => x + yEnclosed;
Debug.Assert(addWithClosure(2) == 3);

Swift

func adder(x: Int) -> (Int) -> Int{
   return { y in x + y }
}
let add5 = adder(5)
add5(1)
6

PHP

$a = 1;
$b = 2;

$lambda = fn () => $a + $b;

echo $lambda();

Haskell

(\x y -> x + y) 

Java see this post

// The following is an example of Predicate : 
// a functional interface that takes an argument 
// and returns a boolean primitive type.

Predicate<Integer> pred = x -> x % 2 == 0; // Tests if the parameter is even.
boolean result = pred.test(4); // true

Lua

adder = function(x)
    return function(y)
        return x + y
    end
end
add5 = adder(5)
add5(1) == 6        -- true

Kotlin

val pred = { x: Int -> x % 2 == 0 }
val result = pred(4) // true

Ruby

Ruby is slightly different in that you cannot call a lambda using the exact same syntax as calling a function, but it still has lambdas.

def adder(x)
  lambda { |y| x + y }
end
add5 = adder(5)
add5[1] == 6

Ruby being Ruby, there is a shorthand for lambdas, so you can define adder this way:

def adder(x)
  -> y { x + y }
end

R

adder <- function(x) {
  function(y) x + y
}
add5 <- adder(5)
add5(1)
#> [1] 6

What are the differences between stateless and stateful systems, and how do they impact parallelism?

A stateless system can be seen as a box [black? ;)] where at any point in time the value of the output(s) depends only on the value of the input(s) [after a certain processing time]

A stateful system instead can be seen as a box where at any point in time the value of the output(s) depends on the value of the input(s) and of an internal state, so basicaly a stateful system is like a state machine with "memory" as the same set of input(s) value can generate different output(s) depending on the previous input(s) received by the system.

From the parallel programming point of view, a stateless system, if properly implemented, can be executed by multiple threads/tasks at the same time without any concurrency issue [as an example think of a reentrant function] A stateful system will requires that multiple threads of execution access and update the internal state of the system in an exclusive way, hence there will be a need for a serialization [synchronization] point.

Combine or merge JSON on node.js without jQuery

Underscore's extend is the easiest and quickest way to achieve this, like James commented.

Here's an example using underscore:

var _ = require('underscore'), // npm install underscore to install
  object1 = {name: "John"},
  object2 = {location: "San Jose"};

var target = _.extend(object1, object2);

object 1 will get the properties of object2 and be returned and assigned to target. You could do it like this as well, depending on whether you mind object1 being modified:

var target = {};
_.extend(target, object1, object2);

ASP.Net MVC How to pass data from view to controller

<form action="myController/myAction" method="POST">
 <input type="text" name="valueINeed" />
 <input type="submit" value="View Report" />
</form> 

controller:

[HttpPost]
public ActionResult myAction(string valueINeed)
{
   //....
}

When to use an interface instead of an abstract class and vice versa?

OK, having just "grokked" this myself - here it is in layman's terms (feel free to correct me if I am wrong) - I know this topic is oooooold, but someone else might stumble across it one day...

Abstract classes allow you to create a blueprint, and allow you to additionally CONSTRUCT (implement) properties and methods you want ALL its descendants to possess.

An interface on the other hand only allows you to declare that you want properties and/or methods with a given name to exist in all classes that implement it - but doesn't specify how you should implement it. Also, a class can implement MANY interfaces, but can only extend ONE Abstract class. An Interface is more of a high level architectural tool (which becomes clearer if you start to grasp design patterns) - an Abstract has a foot in both camps and can perform some of the dirty work too.

Why use one over the other? The former allows for a more concrete definition of descendants - the latter allows for greater polymorphism. This last point is important to the end user/coder, who can utilise this information to implement the A.P.I(nterface) in a variety of combinations/shapes to suit their needs.

I think this was the "lightbulb" moment for me - think about interfaces less from the author's perpective and more from that of any coder coming later in the chain who is adding implementation to a project, or extending an API.

How can I pad an integer with zeros on the left?

int x = 1;
System.out.format("%05d",x);

if you want to print the formatted text directly onto the screen.

How can I delay a :hover effect in CSS?

You can use transitions to delay the :hover effect you want, if the effect is CSS-based.

For example

div{
    transition: 0s background-color;
}

div:hover{
    background-color:red;    
    transition-delay:1s;
}

this will delay applying the the hover effects (background-color in this case) for one second.


Demo of delay on both hover on and off:

_x000D_
_x000D_
div{_x000D_
    display:inline-block;_x000D_
    padding:5px;_x000D_
    margin:10px;_x000D_
    border:1px solid #ccc;_x000D_
    transition: 0s background-color;_x000D_
    transition-delay:1s;_x000D_
}_x000D_
div:hover{_x000D_
    background-color:red;_x000D_
}
_x000D_
<div>delayed hover</div>
_x000D_
_x000D_
_x000D_

Demo of delay only on hover on:

_x000D_
_x000D_
div{_x000D_
    display:inline-block;_x000D_
    padding:5px;_x000D_
    margin:10px;_x000D_
    border:1px solid #ccc;_x000D_
    transition: 0s background-color;_x000D_
}_x000D_
div:hover{_x000D_
    background-color:red;    _x000D_
    transition-delay:1s;_x000D_
}
_x000D_
<div>delayed hover</div>
_x000D_
_x000D_
_x000D_


Vendor Specific Extentions for Transitions and W3C CSS3 transitions

Still getting warning : Configuration 'compile' is obsolete and has been replaced with 'implementation'

Using the currently latest version of the google gms services resolved it for me.

In the project level build.gradle:

buildscript {
    ...
    dependencies {
        classpath 'com.google.gms:google-services:3.2.1'
        ...  
    }
}

How to correctly implement custom iterators and const_iterators?

Check this below code, it works

#define MAX_BYTE_RANGE 255

template <typename T>
class string
{
public:
    typedef char *pointer;
    typedef const char *const_pointer;
    typedef __gnu_cxx::__normal_iterator<pointer, string> iterator;
    typedef __gnu_cxx::__normal_iterator<const_pointer, string> const_iterator;

    string() : length(0)
    {
    }
    size_t size() const
    {
        return length;
    }
    void operator=(const_pointer value)
    {
        if (value == nullptr)
            throw std::invalid_argument("value cannot be null");
        auto count = strlen(value);
        if (count > 0)
            _M_copy(value, count);
    }
    void operator=(const string &value)
    {
        if (value.length != 0)
            _M_copy(value.buf, value.length);
    }
    iterator begin()
    {
        return iterator(buf);
    }
    iterator end()
    {
        return iterator(buf + length);
    }
    const_iterator begin() const
    {
        return const_iterator(buf);
    }
    const_iterator end() const
    {
        return const_iterator(buf + length);
    }
    const_pointer c_str() const
    {
        return buf;
    }
    ~string()
    {
    }

private:
    unsigned char length;
    T buf[MAX_BYTE_RANGE];

    void _M_copy(const_pointer value, size_t count)
    {
        memcpy(buf, value, count);
        length = count;
    }
};

How do I clear a C++ array?

Hey i think The fastest way to handle that kind of operation is to memset() the memory.

Example-

memset(&myPage.pageArray[0][0], 0, sizeof(myPage.pageArray));

A similar C++ way would be to use std::fill

char *begin = myPage.pageArray[0][0];
char *end = begin + sizeof(myPage.pageArray);
std::fill(begin, end, 0);

Multiple select in Visual Studio?

In Visual Studio 2019, you can put your caret on the right place and then press SHIFT ALT and . (dot). This will select the next occurrence.

How do I check to see if a value is an integer in MySQL?

What about:

WHERE table.field = "0" or CAST(table.field as SIGNED) != 0

to test for numeric and the corrolary:

WHERE table.field != "0" and CAST(table.field as SIGNED) = 0

Command /Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang failed with exit code 1

Do a clean. product > clean . Terminal purge & reboot didn't work for me, cleaning did.

Value cannot be null. Parameter name: source

My reason was different to the rest here so I thought I'd post it for anyone else who might have this issue.

I was calling Count on an instance of DbSet with a filter of null i.e.

dbSet.Count(null);

I found that passing null here was causing the error so I now call the parameter-less method if the filter is null:

 if (filter == null)
 {
     return dbSet.Count();
 }
 else
 {
     return dbSet.Count(filter);
 }

This sorted the issue for me. This may be an issue for any other methods on DbSet as well.

Could not find method compile() for arguments Gradle

In my case, all the compile statements has somehow arranged in a single line. separating them in individual lines has fixed the issue.

Delaying a jquery script until everything else has loaded

It turns out that because of a peculiar mixture of javascript frameworks that I needed to initiate the script using an event listener provide by one of the other frameworks.

Which @NotNull Java annotation should I use?

One of the nice things about IntelliJ is that you don't need to use their annotations. You can write your own, or you can use those of whatever other tool you like. You're not even limited to a single type. If you're using two libraries that use different @NotNull annotations, you can tell IntelliJ to use both of them. To do this, go to "Configure Inspections", click on the "Constant Conditions & Exceptions" inspection, and hit the "Configure inspections" button. I use the Nullness Checker wherever I can, so I set up IntelliJ to use those annotations, but you can make it work with whatever other tool you want. (I have no opinion on the other tools because I've been using IntelliJ's inspections for years, and I love them.)

Send mail via CMD console

Unless you want to talk to an SMTP server directly via telnet you'd use commandline mailers like blat:

blat -to [email protected] -f [email protected] -s "mail subject" ^
  -server smtp.example.net -body "message text"

or bmail:

bmail -s smtp.example.net -t [email protected] -f [email protected] -h ^
  -a "mail subject" -b "message text"

You could also write your own mailer in VBScript or PowerShell.

How to execute multiple commands in a single line

Googling gives me this:


Command A & Command B

Execute Command A, then execute Command B (no evaluation of anything)


Command A | Command B

Execute Command A, and redirect all its output into the input of Command B


Command A && Command B

Execute Command A, evaluate the errorlevel after running and if the exit code (errorlevel) is 0, only then execute Command B


Command A || Command B

Execute Command A, evaluate the exit code of this command and if it's anything but 0, only then execute Command B


HTML tag inside JavaScript

You will either have to document.write it or use the Document Object Model:

Example using document.write

<script type="text/javascript">
if(document.getElementById('number1').checked) {
    document.write("<h1>Hello member</h1>");
}
</script>

Example using DOM

<h1></h1> <!-- We are targeting this tag with JS. See code below -->
<input type="checkbox" id="number1" checked /><label for="number1">Agree</label>
<div id="container"> <p>Content</p> </div>

<script type="text/javascript">
window.onload = function() {
    if( document.getElementById('number1').checked ) {
        var h1 = document.createElement("h1");
        h1.appendChild(document.createTextNode("Hello member"));
        document.getElementById("container").appendChild(h1);
    }
}
</script>

Firebase FCM force onTokenRefresh() to be called

Guys it has very simple solution

https://developers.google.com/instance-id/guides/android-implementation#generate_a_token

Note: If your app used tokens that were deleted by deleteInstanceID, your app will need to generate replacement tokens.

In stead of deleting instance Id, delete only token:

String authorizedEntity = PROJECT_ID;
String scope = "GCM";
InstanceID.getInstance(context).deleteToken(authorizedEntity,scope);

How can I ask the Selenium-WebDriver to wait for few seconds in Java?

Sometimes implicit wait seems to get overridden and wait time is cut short. [@eugene.polschikov] had good documentation on the whys. I have found in my testing and coding with Selenium 2 that implicit waits are good but occasionally you have to wait explicitly.

It is better to avoid directly calling for a thread to sleep, but sometimes there isn't a good way around it. However, there are other Selenium provided wait options that help. waitForPageToLoad and waitForFrameToLoad have proved especially useful.

How to create JSON Object using String?

If you use the gson.JsonObject you can have something like that:

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

String jsonString = "{'test1':'value1','test2':{'id':0,'name':'testName'}}"
JsonObject jsonObject = (JsonObject) jsonParser.parse(jsonString)

Is there a list of Pytz Timezones?

You can list all the available timezones with pytz.all_timezones:

In [40]: import pytz
In [41]: pytz.all_timezones
Out[42]: 
['Africa/Abidjan',
 'Africa/Accra',
 'Africa/Addis_Ababa',
 ...]

There is also pytz.common_timezones:

In [45]: len(pytz.common_timezones)
Out[45]: 403

In [46]: len(pytz.all_timezones)
Out[46]: 563

How can I count the rows with data in an Excel sheet?

If you don't mind VBA, here is a function that will do it for you. Your call would be something like:

=CountRows(1:10) 
Function CountRows(ByVal range As range) As Long

Application.ScreenUpdating = False
Dim row As range
Dim count As Long

For Each row In range.Rows
    If (Application.WorksheetFunction.CountBlank(row)) - 256 <> 0 Then
        count = count + 1
    End If
Next

CountRows = count
Application.ScreenUpdating = True

End Function

How it works: I am exploiting the fact that there is a 256 row limit. The worksheet formula CountBlank will tell you how many cells in a row are blank. If the row has no cells with values, then it will be 256. So I just minus 256 and if it's not 0 then I know there is a cell somewhere that has some value.

Slicing a dictionary

set intersection and dict comprehension can be used here

# the dictionary
d = {1:2, 3:4, 5:6, 7:8}

# the subset of keys I'm interested in
l = (1,5)

>>>{key:d[key] for key in set(l) & set(d)}
{1: 2, 5: 6}

How to change font-size of a tag using inline css?

Strange it doesn't change, as inline styles are most specific, if style sheet has !important declared, it wont over ride, try this and see

<span style="font-size: 11px !important; color: #aaaaaa;">Hello</span>

How to push elements in JSON from javascript array

You can directly access BODY.values:

for (var ln = 0; ln < names.length; ln++) {
  var item1 = {
    "person": {
      "_path": "/people/"+names[ln],
    },
  };

  BODY.values.push(item1);
}

Declaring variables inside or outside of a loop

I think the size of the object matters as well. In one of my projects, we had declared and initialized a large two dimensional array that was making the application throw an out-of-memory exception. We moved the declaration out of the loop instead and cleared the array at the start of every iteration.

Google Forms file upload complete example

Update: Google Forms can now upload files. This answer was posted before Google Forms had the capability to upload files.

This solution does not use Google Forms. This is an example of using an Apps Script Web App, which is very different than a Google Form. A Web App is basically a website, but you can't get a domain name for it. This is not a modification of a Google Form, which can't be done to upload a file.

NOTE: I did have an example of both the UI Service and HTML Service, but have removed the UI Service example, because the UI Service is deprecated.

NOTE: The only sandbox setting available is now IFRAME. I you want to use an onsubmit attribute in the beginning form tag: <form onsubmit="myFunctionName()">, it may cause the form to disappear from the screen after the form submission.

If you were using NATIVE mode, your file upload Web App may no longer be working. With NATIVE mode, a form submission would not invoke the default behavior of the page disappearing from the screen. If you were using NATIVE mode, and your file upload form is no longer working, then you may be using a "submit" type button. I'm guessing that you may also be using the "google.script.run" client side API to send data to the server. If you want the page to disappear from the screen after a form submission, you could do that another way. But you may not care, or even prefer to have the page stay on the screen. Depending upon what you want, you'll need to configure the settings and code a certain way.

If you are using a "submit" type button, and want to continue to use it, you can try adding event.preventDefault(); to your code in the submit event handler function. Or you'll need to use the google.script.run client side API.


A custom form for uploading files from a users computer drive, to your Google Drive can be created with the Apps Script HTML Service. This example requires writing a program, but I've provide all the basic code here.

This example shows an upload form with Google Apps Script HTML Service.

What You Need

  • Google Account
  • Google Drive
  • Google Apps Script - also called Google Script

Google Apps Script

There are various ways to end up at the Google Apps Script code editor.

I mention this because if you are not aware of all the possibilities, it could be a little confusing. Google Apps Script can be embedded in a Google Site, Sheets, Docs or Forms, or used as a stand alone app.

Apps Script Overview

This example is a "Stand Alone" app with HTML Service.

HTML Service - Create a web app using HTML, CSS and Javascript

Google Apps Script only has two types of files inside of a Project:

  • Script
  • HTML

Script files have a .gs extension. The .gs code is a server side code written in JavaScript, and a combination of Google's own API.

  • Copy and Paste the following code

  • Save It

  • Create the first Named Version

  • Publish it

  • Set the Permissions

    and you can start using it.

Start by:

  • Create a new Blank Project in Apps Script
  • Copy and Paste in this code:

Upload a file with HTML Service:

Code.gs file (Created by Default)

//For this to work, you need a folder in your Google drive named:
// 'For Web Hosting'
// or change the hard coded folder name to the name of the folder
// you want the file written to

function doGet(e) {
  return HtmlService.createTemplateFromFile('Form')
    .evaluate() // evaluate MUST come before setting the Sandbox mode
    .setTitle('Name To Appear in Browser Tab')
    .setSandboxMode();//Defaults to IFRAME which is now the only mode available
}

function processForm(theForm) {
  var fileBlob = theForm.picToLoad;
  
  Logger.log("fileBlob Name: " + fileBlob.getName())
  Logger.log("fileBlob type: " + fileBlob.getContentType())
  Logger.log('fileBlob: ' + fileBlob);

  var fldrSssn = DriveApp.getFolderById(Your Folder ID);
    fldrSssn.createFile(fileBlob);
    
  return true;
}

Create an html file:

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <h1 id="main-heading">Main Heading</h1>
    <br/>
    <div id="formDiv">

      <form id="myForm">
    
        <input name="picToLoad" type="file" /><br/>
        <input type="button" value="Submit" onclick="picUploadJs(this.parentNode)" />
          
      </form>
    </div>


  <div id="status" style="display: none">
  <!-- div will be filled with innerHTML after form submission. -->
  Uploading. Please wait...
</div>

</body>
<script>

function picUploadJs(frmData) {

  document.getElementById('status').style.display = 'inline';

  google.script.run
    .withSuccessHandler(updateOutput)
    .processForm(frmData)
};
  // Javascript function called by "submit" button handler,
  // to show results.
  
  function updateOutput() {
  
    var outputDiv = document.getElementById('status');
    outputDiv.innerHTML = "The File was UPLOADED!";
  }

</script>
</html>

This is a full working example. It only has two buttons and one <div> element, so you won't see much on the screen. If the .gs script is successful, true is returned, and an onSuccess function runs. The onSuccess function (updateOutput) injects inner HTML into the div element with the message, "The File was UPLOADED!"

  • Save the file, give the project a name
  • Using the menu: File, Manage Version then Save the first Version
  • Publish, Deploy As Web App then Update

When you run the Script the first time, it will ask for permissions because it's saving files to your drive. After you grant permissions that first time, the Apps Script stops, and won't complete running. So, you need to run it again. The script won't ask for permissions again after the first time.

The Apps Script file will show up in your Google Drive. In Google Drive you can set permissions for who can access and use the script. The script is run by simply providing the link to the user. Use the link just as you would load a web page.

Another example of using the HTML Service can be seen at this link here on StackOverflow:

File Upload with HTML Service

NOTES about deprecated UI Service:

There is a difference between the UI Service, and the Ui getUi() method of the Spreadsheet Class (Or other class) The Apps Script UI Service was deprecated on Dec. 11, 2014. It will continue to work for some period of time, but you are encouraged to use the HTML Service.

Google Documentation - UI Service

Even though the UI Service is deprecated, there is a getUi() method of the spreadsheet class to add custom menus, which is NOT deprecated:

Spreadsheet Class - Get UI method

I mention this because it could be confusing because they both use the terminology UI.

The UI method returns a Ui return type.

You can add HTML to a UI Service, but you can't use a <button>, <input> or <script> tag in the HTML with the UI Service.

Here is a link to a shared Apps Script Web App file with an input form:

Shared File - Contact Form

Add directives from directive in AngularJS

A simple solution that could work in some cases is to create and $compile a wrapper and then append your original element to it.

Something like...

link: function(scope, elem, attr){
    var wrapper = angular.element('<div tooltip></div>');
    elem.before(wrapper);
    $compile(wrapper)(scope);
    wrapper.append(elem);
}

This solution has the advantage that it keeps things simple by not recompiling the original element.

This wouldn't work if any of the added directive's require any of the original element's directives or if the original element has absolute positioning.

Sending XML data using HTTP POST with PHP

you can use cURL library for posting data: http://www.php.net/curl

$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_URL, "http://websiteURL");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "XML=".$xmlcontent."&password=".$password."&etc=etc");
$content=curl_exec($ch);

where postfield contains XML you need to send - you will need to name the postfield the API service (Clickatell I guess) expects

For each row in an R dataframe

you can do something for a list object,

data("mtcars")
rownames(mtcars)
data <- list(mtcars ,mtcars, mtcars, mtcars);data

out1 <- NULL 
for(i in seq_along(data)) { 
  out1[[i]] <- data[[i]][rownames(data[[i]]) != "Volvo 142E", ] } 
out1

Or a data frame,

data("mtcars")
df <- mtcars
out1 <- NULL 
for(i in 1:nrow(df)) {
  row <- rownames(df[i,])
  # do stuff with row
  out1 <- df[rownames(df) != "Volvo 142E",]
  
}
out1 

Switching the order of block elements with CSS

Here is a "simple as possible" example, for changing the order of div-elements (when resizing the browser window):

<!DOCTYPE html>
<html>
  <head>
    <title>foobar</title>
    <style>
      @media screen and (max-width:300px){
        #parent{
          display:flex;
          flex-flow: column;
        }
        #a{order:2;}
        #c{order:1;}
        #b{order:3;}
      }
    </style>
  </head>
  <body>
    <div id="parent">
      <div id="a">one</div>
      <div id="b">two</div>
      <div id="c">three</div>
    </div>
  </body>
</html>

Example: http://jsfiddle.net/devnull/qyroxexv/ (change window-width to see the effect of changing the order of the divs)

nodejs - How to read and output jpg image?

Two things to keep in mind Content-Type and the Encoding

1) What if the file is css

if (/.(css)$/.test(path)) {
  res.writeHead(200, {'Content-Type': 'text/css'}); 
  res.write(data, 'utf8');
} 

2) What if the file is jpg/png

if (/.(jpg)$/.test(path)) {
  res.writeHead(200, {'Content-Type': 'image/jpg'});
  res.end(data,'Base64');
}

Above one is just a sample code to explain the answer and not the exact code pattern.

Convert hex string to int

Try with this:

long abc=convertString2Hex("1A2A3B");

private  long  convertString2Hex(String numberHexString)
{
    char[] ChaArray = numberHexString.toCharArray();
    long HexSum=0;
    long cChar =0;

    for(int i=0;i<numberHexString.length();i++ )
    {
        if( (ChaArray[i]>='0') && (ChaArray[i]<='9') )
            cChar = ChaArray[i] - '0';
        else
            cChar = ChaArray[i]-'A'+10;
        HexSum = 16 * HexSum + cChar;
    }
    return  HexSum;
}

Convert Python ElementTree to string

Non-Latin Answer Extension

Extension to @Stevoisiak's answer and dealing with non-Latin characters. Only one way will display the non-Latin characters to you. The one method is different on both Python 3 and Python 2.

Input

xml = ElementTree.fromstring('<Person Name="???" />')
xml = ElementTree.Element("Person", Name="???")  # Read Note about Python 2

NOTE: In Python 2, when calling the toString(...) code, assigning xml with ElementTree.Element("Person", Name="???")will raise an error...

UnicodeDecodeError: 'ascii' codec can't decode byte 0xed in position 0: ordinal not in range(128)

Output

ElementTree.tostring(xml)
# Python 3 (???): b'<Person Name="&#53356;&#47532;&#49828;" />'
# Python 3 (John): b'<Person Name="John" />'

# Python 2 (???): <Person Name="&#53356;&#47532;&#49828;" />
# Python 2 (John): <Person Name="John" />


ElementTree.tostring(xml, encoding='unicode')
# Python 3 (???): <Person Name="???" />             <-------- Python 3
# Python 3 (John): <Person Name="John" />

# Python 2 (???): LookupError: unknown encoding: unicode
# Python 2 (John): LookupError: unknown encoding: unicode

ElementTree.tostring(xml, encoding='utf-8')
# Python 3 (???): b'<Person Name="\xed\x81\xac\xeb\xa6\xac\xec\x8a\xa4" />'
# Python 3 (John): b'<Person Name="John" />'

# Python 2 (???): <Person Name="???" />             <-------- Python 2
# Python 2 (John): <Person Name="John" />

ElementTree.tostring(xml).decode()
# Python 3 (???): <Person Name="&#53356;&#47532;&#49828;" />
# Python 3 (John): <Person Name="John" />

# Python 2 (???): <Person Name="&#53356;&#47532;&#49828;" />
# Python 2 (John): <Person Name="John" />

Force “landscape” orientation mode

screen.orientation.lock('landscape');

Will force it to change to and stay in landscape mode. Tested on Nexus 5.

http://www.w3.org/TR/screen-orientation/#examples

Can I append an array to 'formdata' in javascript?

Function:

function appendArray(form_data, values, name){
    if(!values && name)
        form_data.append(name, '');
    else{
        if(typeof values == 'object'){
            for(key in values){
                if(typeof values[key] == 'object')
                    appendArray(form_data, values[key], name + '[' + key + ']');
                else
                    form_data.append(name + '[' + key + ']', values[key]);
            }
        }else
            form_data.append(name, values);
    }

    return form_data;
}

Use:

var form = document.createElement('form');// or document.getElementById('my_form_id');
var formdata = new FormData(form);

appendArray(formdata, {
    sefgusyg: {
        sujyfgsujyfsg: 'srkisgfisfsgsrg',
    },
    test1: 5,
    test2: 6,
    test3: 8,
    test4: 3,
    test5: [
        'sejyfgjy',
        'isdyfgusygf',
    ],
});

Debugging Spring configuration

Yes, Spring framework logging is very detailed, You did not mention in your post, if you are already using a logging framework or not. If you are using log4j then just add spring appenders to the log4j config (i.e to log4j.xml or log4j.properties), If you are using log4j xml config you can do some thing like this

<category name="org.springframework.beans">
    <priority value="debug" />
</category>

or

<category name="org.springframework">
    <priority value="debug" />
</category>

I would advise you to test this problem in isolation using JUnit test, You can do this by using spring testing module in conjunction with Junit. If you use spring test module it will do the bulk of the work for you it loads context file based on your context config and starts container so you can just focus on testing your business logic. I have a small example here

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:springContext.xml"})
@Transactional
public class SpringDAOTest 
{
    @Autowired
    private SpringDAO dao;

    @Autowired
    private ApplicationContext appContext;

    @Test
    public void checkConfig()
    {
        AnySpringBean bean =  appContext.getBean(AnySpringBean.class);
        Assert.assertNotNull(bean);
    }
}

UPDATE

I am not advising you to change the way you load logging but try this in your dev environment, Add this snippet to your web.xml file

<context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>/WEB-INF/log4j.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>

UPDATE log4j config file


I tested this on my local tomcat and it generated a lot of logging on application start up. I also want to make a correction: use debug not info as @Rayan Stewart mentioned.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
    <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
        <param name="Threshold" value="debug" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern"
                value="%d{HH:mm:ss} %p [%t]:%c{3}.%M()%L - %m%n" />
        </layout>
    </appender>

    <appender name="springAppender" class="org.apache.log4j.RollingFileAppender"> 
        <param name="file" value="C:/tomcatLogs/webApp/spring-details.log" /> 
        <param name="append" value="true" /> 
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern"
                value="%d{MM/dd/yyyy HH:mm:ss}  [%t]:%c{5}.%M()%L %m%n" />
        </layout>
    </appender>

    <category name="org.springframework">
        <priority value="debug" />
    </category>

    <category name="org.springframework.beans">
        <priority value="debug" />
    </category>

    <category name="org.springframework.security">
        <priority value="debug" />
    </category>

    <category
        name="org.springframework.beans.CachedIntrospectionResults">
        <priority value="debug" />
    </category>

    <category name="org.springframework.jdbc.core">
        <priority value="debug" />
    </category>

    <category name="org.springframework.transaction.support.TransactionSynchronizationManager">
        <priority value="debug" />
    </category>

    <root>
        <priority value="debug" />
        <appender-ref ref="springAppender" />
        <!-- <appender-ref ref="STDOUT"/>  -->
    </root>
</log4j:configuration>

How to clear the canvas for redrawing

Given that canvas is a canvas element,

const context = canvas.getContext('2d');

context.clearRect(0, 0, canvas.width, canvas.height);

Find element's index in pandas Series

you can use Series.idxmax()

>>> import pandas as pd
>>> myseries = pd.Series([1,4,0,7,5], index=[0,1,2,3,4])
>>> myseries.idxmax()
3
>>> 

How to set the locale inside a Debian/Ubuntu Docker container?

Specify the LANG and LC_ALL environment variables using -e when running your command:

docker run -e LANG=C.UTF-8 -e LC_ALL=C.UTF-8 -it --rm <yourimage> <yourcommand>

It's not necessary to modify the Dockerfile.

Bootstrap 3 select input form inline

This is how I made it without extra css or jquery:

<div class="form-group">
    <div class="input-group">
        <label class="sr-only" for="extra3">Extra name 3</label>
        <input type="text" id="extra3" class="form-control" placeholder="Extra name">
        <span class="input-group-addon">
            <label class="checkbox-inline">
               Mandatory? <input type="checkbox" id="inlineCheckbox5" value="option1">
            </label>
        </span>
        <span class="input-group-addon">
             <label class="checkbox-inline">
               Per person? <input type="checkbox" id="inlineCheckbox6" value="option2">
             </label>
        </span>
        <span class="input-group-addon">
            To be paid? 
            <select>
                <option value="online">Online</option>
                <option value="on spot">On Spot</option>
            </select>
        </span>
    </div>
</div>

How to 'foreach' a column in a DataTable using C#?

int countRow = dt.Rows.Count;
int countCol = dt.Columns.Count;

for (int iCol = 0; iCol < countCol; iCol++)
{
     DataColumn col = dt.Columns[iCol];

     for (int iRow = 0; iRow < countRow; iRow++)
     {
         object cell = dt.Rows[iRow].ItemArray[iCol];

     }
}

Best C++ IDE or Editor for Windows

I personally like Visual Studio combined with a third party add-in such as Visual Assist (http://www.wholetomato.com/). I've tried a few of the others and always ended up back with Visual Studio. Plus, Visual Studio is a widely used product in development industries, so having experience using it can only be a plus.

How do I use a char as the case in a switch-case?

public class SwitCase {
    public static void main (String[] args){
        String hello = JOptionPane.showInputDialog("Input a letter: ");
        char hi = hello.charAt(0); //get the first char.
        switch(hi){
            case 'a': System.out.println("a");
        }
    }   
}

How to save all console output to file in R?

If you have access to a command line, you might prefer running your script from the command line with R CMD BATCH.

== begin contents of script.R ==

a <- "a"
a
How come I do not see this in log

== end contents of script.R ==

At the command prompt ("$" in many un*x variants, "C:>" in windows), run

$ R CMD BATCH script.R &

The trailing "&" is optional and runs the command in the background. The default name of the log file has "out" appended to the extension, i.e., script.Rout

== begin contents of script.Rout ==

R version 3.1.0 (2014-04-10) -- "Spring Dance"
Copyright (C) 2014 The R Foundation for Statistical Computing
Platform: i686-pc-linux-gnu (32-bit)

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

  Natural language support but running in an English locale

R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.

[Previously saved workspace restored]

> a <- "a"
> a
[1] "a"
> How come I do not see this in log
Error: unexpected symbol in "How come"
Execution halted

== end contents of script.Rout ==

Setting a property with an EventTrigger

Just create your own action.

namespace WpfUtil
{
    using System.Reflection;
    using System.Windows;
    using System.Windows.Interactivity;


    /// <summary>
    /// Sets the designated property to the supplied value. TargetObject
    /// optionally designates the object on which to set the property. If
    /// TargetObject is not supplied then the property is set on the object
    /// to which the trigger is attached.
    /// </summary>
    public class SetPropertyAction : TriggerAction<FrameworkElement>
    {
        // PropertyName DependencyProperty.

        /// <summary>
        /// The property to be executed in response to the trigger.
        /// </summary>
        public string PropertyName
        {
            get { return (string)GetValue(PropertyNameProperty); }
            set { SetValue(PropertyNameProperty, value); }
        }

        public static readonly DependencyProperty PropertyNameProperty
            = DependencyProperty.Register("PropertyName", typeof(string),
            typeof(SetPropertyAction));


        // PropertyValue DependencyProperty.

        /// <summary>
        /// The value to set the property to.
        /// </summary>
        public object PropertyValue
        {
            get { return GetValue(PropertyValueProperty); }
            set { SetValue(PropertyValueProperty, value); }
        }

        public static readonly DependencyProperty PropertyValueProperty
            = DependencyProperty.Register("PropertyValue", typeof(object),
            typeof(SetPropertyAction));


        // TargetObject DependencyProperty.

        /// <summary>
        /// Specifies the object upon which to set the property.
        /// </summary>
        public object TargetObject
        {
            get { return GetValue(TargetObjectProperty); }
            set { SetValue(TargetObjectProperty, value); }
        }

        public static readonly DependencyProperty TargetObjectProperty
            = DependencyProperty.Register("TargetObject", typeof(object),
            typeof(SetPropertyAction));


        // Private Implementation.

        protected override void Invoke(object parameter)
        {
            object target = TargetObject ?? AssociatedObject;
            PropertyInfo propertyInfo = target.GetType().GetProperty(
                PropertyName,
                BindingFlags.Instance|BindingFlags.Public
                |BindingFlags.NonPublic|BindingFlags.InvokeMethod);

            propertyInfo.SetValue(target, PropertyValue);
        }
    }
}

In this case I'm binding to a property called DialogResult on my viewmodel.

<Grid>

    <Button>
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="Click">
                <wpf:SetPropertyAction PropertyName="DialogResult" TargetObject="{Binding}"
                                       PropertyValue="{x:Static mvvm:DialogResult.Cancel}"/>
            </i:EventTrigger>
        </i:Interaction.Triggers>
        Cancel
    </Button>

</Grid>

Is it possible to get a list of files under a directory of a website? How?

Yes, you can, but you need a few tools first. You need to know a little about basic coding, FTP clients, port scanners and brute force tools, if it has a .htaccess file.

If not just try tgp.linkurl.htm or html, ie default.html, www/home/siteurl/web/, or wap /index/ default /includes/ main/ files/ images/ pics/ vids/, could be possible file locations on the server, so try all of them so www/home/siteurl/web/includes/.htaccess or default.html. You'll hit a file after a few tries then work off that. Yahoo has a site file viewer too: you can try to scan sites file indexes.

Alternatively, try brutus aet, trin00, trinity.x, or whiteshark airtool to crack the site's FTP login (but it's illegal and I do not condone that).

How to check if element is visible after scrolling?

There are over 30 answers to this question, and none of them use the amazingly simple, pure JS solution that I have been using. There is no need to load jQuery just to solve this, as many others are pushing.

In order to tell if the element is within the viewport, we must first determine the elements position within the body. We do not need to do this recursively as I once thought. Instead, we can use element.getBoundingClientRect().

pos = elem.getBoundingClientRect().top - document.body.getBoundingClientRect().top;

This value is the Y difference between the top of the object and the top of the body.

We then must tell if the element is within view. Most implementations ask if the full element is within the viewport, so this is what we shall cover.

First of all, the top position of the window is: window.scrollY.

We can get the bottom position of the window by adding the window's height to its top position:

var window_bottom_position = window.scrollY + window.innerHeight;

Lets create a simple function for getting the element's top position:

function getElementWindowTop(elem){
    return elem && typeof elem.getBoundingClientRect === 'function' ? elem.getBoundingClientRect().top - document.body.getBoundingClientRect().top : 0;
}

This function will return the element's top position within the window or it will return 0 if you pass it something other than an element with the .getBoundingClientRect() method. This method has been around for a long time, so you shouldn't have to worry about your browser not supporting it.

Now, our element's top position is:

var element_top_position = getElementWindowTop(element);

And or element's bottom position is:

var element_bottom_position = element_top_position + element.clientHeight;

Now we can determine if the element is within the viewport by checking if the element's bottom position is lower than the viewport's top position and by checking if the element's top position is higher than the viewport's bottom position:

if(element_bottom_position >= window.scrollY 
&& element_top_position <= window_bottom_position){
    //element is in view
else
    //element is not in view

From there, you can perform the logic to add or remove an in-view class on your element, which you can then handle later with transition effects in your CSS.

I am absolutely amazed that I did not find this solution anywhere else, but I do believe that this is the cleanest and most effective solution, and it doesn't require you to load jQuery!

How to get all table names from a database?

In your example problem is passed table name pattern in getTables function of DatabaseMetaData.

Some database supports Uppercase identifier, some support lower case identifiers. For example oracle fetches the table name in upper case, while postgreSQL fetch it in lower case.

DatabaseMetaDeta provides a method to determine how the database stores identifiers, can be mixed case, uppercase, lowercase see:http://docs.oracle.com/javase/7/docs/api/java/sql/DatabaseMetaData.html#storesMixedCaseIdentifiers()

From below example, you can get all tables and view of providing table name pattern, if you want only tables then remove "VIEW" from TYPES array.

public class DBUtility {
    private static final String[] TYPES = {"TABLE", "VIEW"};
    public static void getTableMetadata(Connection jdbcConnection, String tableNamePattern, String schema, String catalog, boolean isQuoted) throws HibernateException {
            try {
                DatabaseMetaData meta = jdbcConnection.getMetaData();
                ResultSet rs = null;
                try {
                    if ( (isQuoted && meta.storesMixedCaseQuotedIdentifiers())) {
                        rs = meta.getTables(catalog, schema, tableNamePattern, TYPES);
                    } else if ( (isQuoted && meta.storesUpperCaseQuotedIdentifiers())
                        || (!isQuoted && meta.storesUpperCaseIdentifiers() )) {
                        rs = meta.getTables(
                                StringHelper.toUpperCase(catalog),
                                StringHelper.toUpperCase(schema),
                                StringHelper.toUpperCase(tableNamePattern),
                                TYPES
                            );
                    }
                    else if ( (isQuoted && meta.storesLowerCaseQuotedIdentifiers())
                            || (!isQuoted && meta.storesLowerCaseIdentifiers() )) {
                        rs = meta.getTables( 
                                StringHelper.toLowerCase( catalog ),
                                StringHelper.toLowerCase(schema), 
                                StringHelper.toLowerCase(tableNamePattern), 
                                TYPES 
                            );
                    }
                    else {
                        rs = meta.getTables(catalog, schema, tableNamePattern, TYPES);
                    }

                    while ( rs.next() ) {
                        String tableName = rs.getString("TABLE_NAME");
                        System.out.println("table = " + tableName);
                    }



                }
                finally {
                    if (rs!=null) rs.close();
                }
            }
            catch (SQLException sqlException) {
                // TODO 
                sqlException.printStackTrace();
            }

    }

    public static void main(String[] args) {
        Connection jdbcConnection;
        try {
            jdbcConnection = DriverManager.getConnection("", "", "");
            getTableMetadata(jdbcConnection, "tbl%", null, null, false);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Peak detection in a 2D array

There are several and extensive pieces of software available from the astronomy and cosmology community - this is a significant area of research both historically and currently.

Do not be alarmed if you are not an astronomer - some are easy to use outside the field. For example, you could use astropy/photutils:

https://photutils.readthedocs.io/en/stable/detection.html#local-peak-detection

[It seems a bit rude to repeat their short sample code here.]

An incomplete and slightly biased list of techniques/packages/links that might be of interest is given below - do add more in the comments and I will update this answer as necessary. Of course there is a trade-off of accuracy vs compute resources. [Honestly, there are too many to give code examples in a single answer such as this so I am not sure whether this answer will fly or not.]

Source Extractor https://www.astromatic.net/software/sextractor

MultiNest https://github.com/farhanferoz/MultiNest [+ pyMultiNest]

ASKAP/EMU source-finding challenge: https://arxiv.org/abs/1509.03931

You could also search for Planck and/or WMAP source-extraction challenges.

...

Is it possible to declare a variable in Gradle usable in Java?

None of the above answers gave me any guidelines so I had to spend two hours learning about Groovy Methods.

I wanted be able to go against a production, sandbox and local environment. Because I'm lazy, I only wanted to change the URL at one place. Here is what I came up with:

 flavorDimensions 'environment'
    productFlavors {
        production {
            def SERVER_HOST = "evil-company.com"
            buildConfigField 'String', 'API_HOST', "\"${SERVER_HOST}\""
            buildConfigField 'String', 'API_URL', "\"https://${SERVER_HOST}/api/v1/\""
            buildConfigField 'String', 'WEB_URL', "\"https://${SERVER_HOST}/\""
            dimension 'environment'
        }
        rickard {
            def LOCAL_HOST = "192.168.1.107"
            buildConfigField 'String', 'API_HOST', "\"${LOCAL_HOST}\""
            buildConfigField 'String', 'API_URL', "\"https://${LOCAL_HOST}/api/v1/\""
            buildConfigField 'String', 'WEB_URL', "\"https://${LOCAL_HOST}/\""
            applicationIdSuffix ".dev"
        }
    }

Alternative syntax, because you can only use ${variable} with double quotes in Groovy Methods.

    rickard {
        def LOCAL_HOST = "192.168.1.107"
        buildConfigField 'String', 'API_HOST', '"' + LOCAL_HOST + '"'
        buildConfigField 'String', 'API_URL', '"https://' + LOCAL_HOST + '/api/v1/"'
        buildConfigField 'String', 'WEB_URL', '"https://' + LOCAL_HOST + '"'
        applicationIdSuffix ".dev"
    }

What was hard for me to grasp was that strings needs to be declared as strings surrounded by quotes. Because of that restriction, I couldn't use reference API_HOST directly, which was what I wanted to do in the first place.

Make iframe automatically adjust height according to the contents without using scrollbar?

The suggestion by hjpotter92 does not work in safari! I have made a small adjustment to the script so it now works in Safari as well.

Only change made is resetting height to 0 on every load in order to enable some browsers to decrease height.

Add this to <head> tag:

<script type="text/javascript">
  function resizeIframe(obj){
     obj.style.height = 0;
     obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
  }
</script>

And add the following onload attribute to your iframe, like so

<iframe onload='resizeIframe(this)'></iframe>

How to Add Date Picker To VBA UserForm

You could try the "Microsoft Date and Time Picker Control". To use it, in the Toolbox, you right-click and choose "Additional Controls...". Then you check "Microsoft Date and Time Picker Control 6.0" and OK. You will have a new control in the Toolbox to do what you need.

I just found some printscreen of this on : http://www.logicwurks.com/CodeExamplePages/EDatePickerControl.html Forget the procedures, just check the printscreens.

jQuery: enabling/disabling datepicker

$("#from").datepicker('disable'); should work, but you can also try this:

$( "#from" ).datepicker( "option", "disabled", true );

How can I inspect the file system of a failed `docker build`?

What I would do is comment out the Dockerfile below and including the offending line. Then you can run the container and run the docker commands by hand, and look at the logs in the usual way. E.g. if the Dockerfile is

RUN foo
RUN bar
RUN baz

and it's dying at bar I would do

RUN foo
# RUN bar
# RUN baz

Then

$ docker build -t foo .
$ docker run -it foo bash
container# bar
...grep logs...

VBA shorthand for x=x+1?

If you want to call the incremented number directly in a function, this solution works bettter:

Function inc(ByRef data As Integer)
    data = data + 1
    inc = data
End Function

for example:

Wb.Worksheets(mySheet).Cells(myRow, inc(myCol))

If the function inc() returns no value, the above line will generate an error.

Run script with rc.local: script works, but not at boot

It is my understanding that if you place your script in a certain RUN Level, you should use ln -s to link the script to the level you want it to work in.

How do I check if a string contains another string in Objective-C?

So personally I really hate NSNotFound but understand its necessity.

But some people may not understand the complexities of comparing against NSNotFound

For example, this code:

- (BOOL)doesString:(NSString*)string containString:(NSString*)otherString {
    if([string rangeOfString:otherString].location != NSNotFound)
        return YES;
    else
        return NO;
}

has its problems:

1) Obviously if otherString = nil this code will crash. a simple test would be:

NSLog(@"does string contain string - %@", [self doesString:@"hey" containString:nil] ? @"YES": @"NO");

results in !! CRASH !!

2) What is not so obvious to someone new to objective-c is that the same code will NOT crash when string = nil. For example, this code:

NSLog(@"does string contain string - %@", [self doesString:nil containString:@"hey"] ? @"YES": @"NO");

and this code:

NSLog(@"does string contain string - %@", [self doesString:nil containString:nil] ? @"YES": @"NO");

will both result in

does string contains string - YES

Which is clearly NOT what you want.

So the better solution that I believe works is to use the fact that rangeOfString returns the length of 0 so then a better more reliable code is this:

- (BOOL)doesString:(NSString*)string containString:(NSString*)otherString {
    if(otherString && [string rangeOfString:otherString].length)
        return YES;
    else
        return NO;
}

OR SIMPLY:

- (BOOL)doesString:(NSString*)string containString:(NSString*)otherString {
    return (otherString && [string rangeOfString:otherString].length);
}

which will for cases 1 and 2 will return

does string contains string - NO

That's my 2 cents ;-)

Please check out my Gist for more helpful code.

What Process is using all of my disk IO

You're looking for iotop (assuming you've got kernel >2.6.20 and Python 2.5). Failing that, you're looking into hooking into the filesystem. I recommend the former.

Styling HTML email for Gmail

I agree with everyone who supports classes AND inline styles. You might have learned this by now, but if there is a single mistake in your style sheet, Gmail will disregard it.

You might think that your CSS is perfect, because you've done it so often, why would I have mistakes in my CSS? Run it through the CSS Validator (for example http://www.css-validator.org/) and see what happens. I did that after encountering some Gmail display issues, and to my surprise, several Microsoft Outlook specific style declarations showed up as mistakes.

Which made sense to me, so I removed them from the style sheet and put them into a only for Microsoft code block, like so:

<!--[if mso]>
<style type="text/css">
body, table, td, .mobile-text {
font-family: Arial, sans-serif !important;
}
</style>
<xml>
  <o:OfficeDocumentSettings>
    <o:AllowPNG/>
    <o:PixelsPerInch>96</o:PixelsPerInch>
  </o:OfficeDocumentSettings>
</xml>
<![endif]-->

This is just a simple example, but, who know, it might come in handy some time.

Array Size (Length) in C#

If it's a one-dimensional array a,

a.Length

will give the number of elements of a.

If b is a rectangular multi-dimensional array (for example, int[,] b = new int[3, 5];)

b.Rank

will give the number of dimensions (2) and

b.GetLength(dimensionIndex)

will get the length of any given dimension (0-based indexing for the dimensions - so b.GetLength(0) is 3 and b.GetLength(1) is 5).

See System.Array documentation for more info.

As @Lucero points out in the comments, there is a concept of a "jagged array", which is really nothing more than a single-dimensional array of (typically single-dimensional) arrays.

For example, one could have the following:

int[][] c = new int[3][];
c[0] = new int[] {1, 2, 3};
c[1] = new int[] {3, 14};
c[2] = new int[] {1, 1, 2, 3, 5, 8, 13};

Note that the 3 members of c all have different lengths. In this case, as before c.Length will indicate the number of elements of c, (3) and c[0].Length, c[1].Length, and c[2].Length will be 3, 2, and 7, respectively.

Instance member cannot be used on type

For anyone else who stumbles on this make sure you're not attempting to modify the class rather than the instance! (unless you've declared the variable as static)

eg.

MyClass.variable = 'Foo' // WRONG! - Instance member 'variable' cannot be used on type 'MyClass'

instanceOfMyClass.variable = 'Foo' // Right!

How to terminate the script in JavaScript?

If you use any undefined function in the script then script will stop due to "Uncaught ReferenceError". I have tried by following code and first two lines executed.

I think, this is the best way to stop the script. If there's any other way then please comment me. I also want to know another best and simple way. BTW, I didn't get exit or die inbuilt function in Javascript like PHP for terminate the script. If anyone know then please let me know.

alert('Hello');

document.write('Hello User!!!');

die();  //Uncaught ReferenceError: die is not defined

alert('bye');

document.write('Bye User!!!');

Javascript AES encryption

JSAES is a powerful implementation of AES in JavaScript. http://point-at-infinity.org/jsaes/

How to append a newline to StringBuilder

You can also use the line separator character in String.format (See java.util.Formatter), which is also platform agnostic.

i.e.:

result.append(String.format("%n", ""));

If you need to add more line spaces, just use:

result.append(String.format("%n%n", ""));

You can also use StringFormat to format your entire string, with a newline(s) at the end.

result.append(String.format("%10s%n%n", "This is my string."));

Passing data from controller to view in Laravel

$books[] = [
            'title' => 'Mytitle',
            'author' => 'MyAuthor,
            
        ];

//pass data to other view
return view('myView.blade.php')->with('books');
or
return view('myView.blade.php','books');
or
return view('myView.blade.php',compact('books'));

----------------------------------------------------


//to use this on myView.blade.php
<script>
    myVariable = {!! json_encode($books) !!};
    console.log(myVariable);
</script>

Android Fastboot devices not returning device

I had the same issue, but I was running Ubuntu 12.04 through a VM. I am using a Nexus 10. I had added the usb device as a filter for the VM (using virtual box in the virtual machine's settings).

The device I had added was "samsung Nexus 10".

The problem is that once the device is in fastboot mode, it shows up as a different device: "Google, Inc Android 1.0." So doing "lsusb" in the VM showed no device connected, and obviously "fastboot devices" returned nothing until I added the "second" device as a filter for the VM as well.

Hope this helps someone.

Creating a segue programmatically

well , you can create and also can subclass the UIStoryBoardSegue . subclassing is mostly used for giving custom transition animation.

you can see video of wwdc 2011 introducing StoryBoard. its available in youtube also.

http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIStoryboardSegue_Class/Reference/Reference.html#//apple_ref/occ/cl/UIStoryboardSegue

Loop Through All Subfolders Using VBA

And to complement Rich's recursive answer, a non-recursive method.

Public Sub NonRecursiveMethod()
    Dim fso, oFolder, oSubfolder, oFile, queue As Collection

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set queue = New Collection
    queue.Add fso.GetFolder("your folder path variable") 'obviously replace

    Do While queue.Count > 0
        Set oFolder = queue(1)
        queue.Remove 1 'dequeue
        '...insert any folder processing code here...
        For Each oSubfolder In oFolder.SubFolders
            queue.Add oSubfolder 'enqueue
        Next oSubfolder
        For Each oFile In oFolder.Files
            '...insert any file processing code here...
        Next oFile
    Loop

End Sub

You can use a queue for FIFO behaviour (shown above), or you can use a stack for LIFO behaviour which would process in the same order as a recursive approach (replace Set oFolder = queue(1) with Set oFolder = queue(queue.Count) and replace queue.Remove(1) with queue.Remove(queue.Count), and probably rename the variable...)

Write a formula in an Excel Cell using VBA

You can try using FormulaLocal property instead of Formula. Then the semicolon should work.

Difference between database and schema

Schema says what tables are in database, what columns they have and how they are related. Each database has its own schema.

How can I replace every occurrence of a String in a file with PowerShell?

You could try something like this:

$path = "C:\testFile.txt"
$word = "searchword"
$replacement = "ReplacementText"
$text = get-content $path 
$newText = $text -replace $word,$replacement
$newText > $path

Get Country of IP Address with PHP

I run the service at IPLocate.io, which you can hook into for free with one easy call:

<?php
$res = file_get_contents('https://www.iplocate.io/api/lookup/8.8.8.8');
$res = json_decode($res);

echo $res->country; // United States
echo $res->continent; // North America
echo $res->latitude; // 37.751
echo $res->longitude; // -97.822

var_dump($res);

The $res object will contain your geolocation fields like country, city, etc.

Check out the docs for more information.

PHP array value passes to next row

Change the checkboxes so that the name includes the index inside the brackets:

<input type="checkbox" class="checkbox_veh" id="checkbox_addveh<?php echo $i; ?>" <?php if ($vehicle_feature[$i]->check) echo "checked"; ?> name="feature[<?php echo $i; ?>]" value="<?php echo $vehicle_feature[$i]->id; ?>"> 

The checkboxes that aren't checked are never submitted. The boxes that are checked get submitted, but they get numbered consecutively from 0, and won't have the same indexes as the other corresponding input fields.

How to delete multiple pandas (python) dataframes from memory to save RAM?

In python automatic garbage collection deallocates the variable (pandas DataFrame are also just another object in terms of python). There are different garbage collection strategies that can be tweaked (requires significant learning).

You can manually trigger the garbage collection using

import gc
gc.collect()

But frequent calls to garbage collection is discouraged as it is a costly operation and may affect performance.

Reference

How to add google-services.json in Android?

WINDOWS

  1. Open Terminal window in Android Studio (Alt+F12 or View->Tool Windows->Terminal). Then type

"move file_path/google-services.json app/"

without double quotes.

eg

move C:\Users\siva\Downloads\google-services.json app/

LINUX

  1. Open Android Studio Terminal and type this

scp file_path/google-services.json app/

eg:

scp '/home/developer/Desktop/google-services.json' 'app/'

How to bind a List to a ComboBox?

public class Country
{
    public string Name { get; set; }
    public IList<City> Cities { get; set; }

    public Country()
    {
        Cities = new List<City>();
    }
}

public class City 
{
    public string Name { get; set; } 
}

List<Country> Countries = new List<Country>
{
    new Country
    {
        Name = "Germany",
        Cities =
        {
            new City {Name = "Berlin"},
            new City {Name = "Hamburg"}
        }
    },
    new Country
    {
        Name = "England",
        Cities =
        {
            new City {Name = "London"},
            new City {Name = "Birmingham"}
        }
    }
};
bindingSource1.DataSource = Countries;
member_CountryComboBox.DataSource = bindingSource1.DataSource;
member_CountryComboBox.DisplayMember = "Name";
member_CountryCombo

Box.ValueMember = "Name";

This is the code I am using now.

Foreign Key Django Model

You create the relationships the other way around; add foreign keys to the Person type to create a Many-to-One relationship:

class Person(models.Model):
    name = models.CharField(max_length=50)
    birthday = models.DateField()
    anniversary = models.ForeignKey(
        Anniversary, on_delete=models.CASCADE)
    address = models.ForeignKey(
        Address, on_delete=models.CASCADE)

class Address(models.Model):
    line1 = models.CharField(max_length=150)
    line2 = models.CharField(max_length=150)
    postalcode = models.CharField(max_length=10)
    city = models.CharField(max_length=150)
    country = models.CharField(max_length=150)

class Anniversary(models.Model):
    date = models.DateField()

Any one person can only be connected to one address and one anniversary, but addresses and anniversaries can be referenced from multiple Person entries.

Anniversary and Address objects will be given a reverse, backwards relationship too; by default it'll be called person_set but you can configure a different name if you need to. See Following relationships "backward" in the queries documentation.

How to remove the first and the last character of a string

You can use substring method

s = s.substring(0, s.length - 1) //removes last character

another alternative is slice method

how can I enable scrollbars on the WPF Datagrid?

This worked for me. The key is to use * as Row height.

<Grid x:Name="grid">
        <Grid.RowDefinitions>
            <RowDefinition Height="60"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="10"/>
        </Grid.RowDefinitions>

        <TabControl  Grid.Row="1" x:Name="tabItem">
                <TabItem x:Name="ta" 
                        Header="List of all Clients">
                        <DataGrid Name="clientsgrid" AutoGenerateColumns="True" Margin="2" 
                         ></DataGrid>
                </TabItem>
        </TabControl>
    
    </Grid>

Stacked Bar Plot in R

I'm obviosly not a very good R coder, but if you wanted to do this with ggplot2:

data<- rbind(c(480, 780, 431, 295, 670, 360,  190),
             c(720, 350, 377, 255, 340, 615,  345),
             c(460, 480, 179, 560,  60, 735, 1260),
             c(220, 240, 876, 789, 820, 100,   75))

a <- cbind(data[, 1], 1, c(1:4))
b <- cbind(data[, 2], 2, c(1:4))
c <- cbind(data[, 3], 3, c(1:4))
d <- cbind(data[, 4], 4, c(1:4))
e <- cbind(data[, 5], 5, c(1:4))
f <- cbind(data[, 6], 6, c(1:4))
g <- cbind(data[, 7], 7, c(1:4))

data           <- as.data.frame(rbind(a, b, c, d, e, f, g))
colnames(data) <-c("Time", "Type", "Group")
data$Type      <- factor(data$Type, labels = c("A", "B", "C", "D", "E", "F", "G"))

library(ggplot2)

ggplot(data = data, aes(x = Type, y = Time, fill = Group)) + 
       geom_bar(stat = "identity") +
       opts(legend.position = "none")

enter image description here

C# SQL Server - Passing a list to a stored procedure

Yep, make Stored proc parameter as VARCHAR(...) And then pass comma separated values to a stored procedure.

If you are using Sql Server 2008 you can leverage TVP (Table Value Parameters): SQL 2008 TVP and LINQ if structure of QueryTable more complex than array of strings otherwise it would be an overkill because requires table type to be created within SQl Server

How do I configure git to ignore some files locally?

From the relevant Git documentation:

Patterns which are specific to a particular repository but which do not need to be shared with other related repositories (e.g., auxiliary files that live inside the repository but are specific to one user's workflow) should go into the $GIT_DIR/info/exclude file.

The .git/info/exclude file has the same format as any .gitignore file. Another option is to set core.excludesFile to the name of a file containing global patterns.

Note, if you already have unstaged changes you must run the following after editing your ignore-patterns:

git update-index --assume-unchanged <file-list>

Note on $GIT_DIR: This is a notation used all over the git manual simply to indicate the path to the git repository. If the environment variable is set, then it will override the location of whichever repo you're in, which probably isn't what you want.


Edit: Another way is to use:

git update-index --skip-worktree <file-list>

Reverse it by:

git update-index --no-skip-worktree <file-list>

JavaScript open in a new window, not tab

I had this same question but found a relatively simple solution to it.

In JavaScript I was checking for window.opener !=null; to determine if the window was a pop up. If you're using some similar detection code to determine if the window you're site is being rendered in is a pop up you can easily "turn it off" when you want to open a "new" window using the new windows JavaScript.

Just put this at the top of your page you want to always be a "new" window.

<script type="text/javascript">
    window.opener=null;
</script>

I use this on the log in page of my site so users don't get pop up behavior if they use a pop up window to navigate to my site.

You could even create a simple redirect page that does this and then moves to the URL you gave it. Something like,

JavaScript on parent page:

window.open("MyRedirect.html?URL="+URL, "_blank");

And then by using a little javascript from here you can get the URL and redirect to it.

JavaScript on Redirect Page:

 <script type="text/javascript">
        window.opener=null;

    function getSearchParameters() {
          var prmstr = window.location.search.substr(1);
          return prmstr != null && prmstr != "" ? transformToAssocArray(prmstr) : {};
    }

    function transformToAssocArray( prmstr ) {
        var params = {};
        var prmarr = prmstr.split("&");
        for ( var i = 0; i < prmarr.length; i++) {
            var tmparr = prmarr[i].split("=");
            params[tmparr[0]] = tmparr[1];
        }
        return params;
    }

    var params = getSearchParameters();
    window.location = params.URL;
    </script>

DateTime.Now.ToShortDateString(); replace month and day

this.TextBox3.Text = DateTime.Now.ToString("MM.dd.yyyy");

LINQ Where with AND OR condition

from item in db.vw_Dropship_OrderItems
    where (listStatus != null ? listStatus.Contains(item.StatusCode) : true) &&
    (listMerchants != null ? listMerchants.Contains(item.MerchantId) : true)
    select item;

Might give strange behavior if both listMerchants and listStatus are both null.

How can I fill a column with random numbers in SQL? I get the same value in every row

While I do love using CHECKSUM, I feel that a better way to go is using NEWID(), just because you don't have to go through a complicated math to generate simple numbers .

ROUND( 1000 *RAND(convert(varbinary, newid())), 0)

You can replace the 1000 with whichever number you want to set as the limit, and you can always use a plus sign to create a range, let's say you want a random number between 100 and 200, you can do something like :

100 + ROUND( 100 *RAND(convert(varbinary, newid())), 0)

Putting it together in your query :

UPDATE CattleProds 
SET SheepTherapy= ROUND( 1000 *RAND(convert(varbinary, newid())), 0)
WHERE SheepTherapy IS NULL

How to filter a RecyclerView with a SearchView

All you need to do is to add filter method in RecyclerView.Adapter:

public void filter(String text) {
    items.clear();
    if(text.isEmpty()){
        items.addAll(itemsCopy);
    } else{
        text = text.toLowerCase();
        for(PhoneBookItem item: itemsCopy){
            if(item.name.toLowerCase().contains(text) || item.phone.toLowerCase().contains(text)){
                items.add(item);
            }
        }
    }
    notifyDataSetChanged();
}

itemsCopy is initialized in adapter's constructor like itemsCopy.addAll(items).

If you do so, just call filter from OnQueryTextListener:

searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
    @Override
    public boolean onQueryTextSubmit(String query) {
        adapter.filter(query);
        return true;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        adapter.filter(newText);
        return true;
    }
});

It's an example from filtering my phonebook by name and phone number.

What is Linux’s native GUI API?

Wayland is also worth mentioning as it is mostly referred as a "future X11 killer".

Also note that Android and some other mobile operating systems don't include X11 although they have a Linux kernel, so in that sense X11 is not native to all Linux systems.

Being cross-platform has nothing to do with being native. Cocoa has also been ported to other platforms via GNUStep but it is still native to OS X / macOS.

What is the best way to get the count/length/size of an iterator?

Using Guava library, another option is to convert the Iterable to a List.

List list = Lists.newArrayList(some_iterator);
int count = list.size();

Use this if you need also to access the elements of the iterator after getting its size. By using Iterators.size() you no longer can access the iterated elements.

How to store token in Local or Session Storage in Angular 2?

import { Injectable,OpaqueToken } from '@angular/core'; export const localStorage = new OpaqueToken('localStorage');

Place these lines in the top of the file, it should resolve the issue.

See what's in a stash without applying it

From the man git-stash page:

The modifications stashed away by this command can be listed with git stash list, inspected with git stash show

show [<stash>]
       Show the changes recorded in the stash as a diff between the stashed state and
       its original parent. When no <stash> is given, shows the latest one. By default,
       the command shows the diffstat, but it will accept any format known to git diff
       (e.g., git stash show -p stash@{1} to view the second most recent stash in patch
       form).

To list the stashed modifications

git stash list

To show files changed in the last stash

git stash show

So, to view the content of the most recent stash, run

git stash show -p

To view the content of an arbitrary stash, run something like

git stash show -p stash@{1}

Compiler error: memset was not declared in this scope

Whevever you get a problem like this just go to the man page for the function in question and it will tell you what header you are missing, e.g.

$ man memset

MEMSET(3)                BSD Library Functions Manual                MEMSET(3)

NAME
     memset -- fill a byte string with a byte value

LIBRARY
     Standard C Library (libc, -lc)

SYNOPSIS
     #include <string.h>

     void *
     memset(void *b, int c, size_t len);

Note that for C++ it's generally preferable to use the proper equivalent C++ headers, <cstring>/<cstdio>/<cstdlib>/etc, rather than C's <string.h>/<stdio.h>/<stdlib.h>/etc.

How can I run a program from a batch file without leaving the console open after the program starts?

Here is my preferred solution. It is taken from an answer to a similar question.

Use a VBS Script to call the batch file:

Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & "C:\path\to\your\batchfile.bat" & Chr(34), 0
Set WshShell = Nothing

Copy the lines above to an editor and save the file with .VBS extension.

Using python's mock patch.object to change the return value of a method called within another method

There are two ways you can do this; with patch and with patch.object

Patch assumes that you are not directly importing the object but that it is being used by the object you are testing as in the following

#foo.py
def some_fn():
    return 'some_fn'

class Foo(object):
    def method_1(self):
        return some_fn()
#bar.py
import foo
class Bar(object):
    def method_2(self):
        tmp = foo.Foo()
        return tmp.method_1()
#test_case_1.py
import bar
from mock import patch

@patch('foo.some_fn')
def test_bar(mock_some_fn):
    mock_some_fn.return_value = 'test-val-1'
    tmp = bar.Bar()
    assert tmp.method_2() == 'test-val-1'
    mock_some_fn.return_value = 'test-val-2'
    assert tmp.method_2() == 'test-val-2'

If you are directly importing the module to be tested, you can use patch.object as follows:

#test_case_2.py
import foo
from mock import patch

@patch.object(foo, 'some_fn')
def test_foo(test_some_fn):
    test_some_fn.return_value = 'test-val-1'
    tmp = foo.Foo()
    assert tmp.method_1() == 'test-val-1'
    test_some_fn.return_value = 'test-val-2'
    assert tmp.method_1() == 'test-val-2'

In both cases some_fn will be 'un-mocked' after the test function is complete.

Edit: In order to mock multiple functions, just add more decorators to the function and add arguments to take in the extra parameters

@patch.object(foo, 'some_fn')
@patch.object(foo, 'other_fn')
def test_foo(test_other_fn, test_some_fn):
    ...

Note that the closer the decorator is to the function definition, the earlier it is in the parameter list.

resize2fs: Bad magic number in super-block while trying to open

On centos and fedora work with fsadm

fsadm resize /dev/vg_name/root

How to replace all dots in a string using JavaScript

@scripto's made a bit more concise and without prototype:

function strReplaceAll(s, stringToFind, stringToReplace) {
    if (stringToFind === stringToReplace) return s;
    for (let index = s.indexOf(stringToFind); index != -1; index = s.indexOf(stringToFind))
        s = s.replace(stringToFind, stringToReplace);
    return s;
}

Here's how it stacks up: http://jsperf.com/replace-vs-split-join-vs-replaceall/68

How to make a class JSON serializable

There are many approaches to this problem. 'ObjDict' (pip install objdict) is another. There is an emphasis on providing javascript like objects which can also act like dictionaries to best handle data loaded from JSON, but there are other features which can be useful as well. This provides another alternative solution to the original problem.

PHP - iterate on string characters

// Unicode Codepoint Escape Syntax in PHP 7.0
$str = "cat!\u{1F431}";

// IIFE (Immediately Invoked Function Expression) in PHP 7.0
$gen = (function(string $str) {
    for ($i = 0, $len = mb_strlen($str); $i < $len; ++$i) {
        yield mb_substr($str, $i, 1);
    }
})($str);

var_dump(
    true === $gen instanceof Traversable,
    // PHP 7.1
    true === is_iterable($gen)
);

foreach ($gen as $char) {
    echo $char, PHP_EOL;
}

Error: stray '\240' in program

Your Program has invalid/invisible characters in it. You most likely would have picked up these invisible characters when you copy and past code from another website or sometimes a document. Copying the code from the site into another text document and then copying and pasting into your code editor may work, but depending on how long your code is you should just go with typing it out word for word.

Shuffle DataFrame rows

TL;DR: np.random.shuffle(ndarray) can do the job.
So, in your case

np.random.shuffle(DataFrame.values)

DataFrame, under the hood, uses NumPy ndarray as data holder. (You can check from DataFrame source code)

So if you use np.random.shuffle(), it would shuffles the array along the first axis of a multi-dimensional array. But index of the DataFrame remains unshuffled.

Though, there are some points to consider.

  • function returns none. In case you want to keep a copy of the original object, you have to do so before you pass to the function.
  • sklearn.utils.shuffle(), as user tj89 suggested, can designate random_state along with another option to control output. You may want that for dev purpose.
  • sklearn.utils.shuffle() is faster. But WILL SHUFFLE the axis info(index, column) of the DataFrame along with the ndarray it contains.

Benchmark result

between sklearn.utils.shuffle() and np.random.shuffle().

ndarray

nd = sklearn.utils.shuffle(nd)

0.10793248389381915 sec. 8x faster

np.random.shuffle(nd)

0.8897626010002568 sec

DataFrame

df = sklearn.utils.shuffle(df)

0.3183923360193148 sec. 3x faster

np.random.shuffle(df.values)

0.9357550159329548 sec

Conclusion: If it is okay to axis info(index, column) to be shuffled along with ndarray, use sklearn.utils.shuffle(). Otherwise, use np.random.shuffle()

used code

import timeit
setup = '''
import numpy as np
import pandas as pd
import sklearn
nd = np.random.random((1000, 100))
df = pd.DataFrame(nd)
'''

timeit.timeit('nd = sklearn.utils.shuffle(nd)', setup=setup, number=1000)
timeit.timeit('np.random.shuffle(nd)', setup=setup, number=1000)
timeit.timeit('df = sklearn.utils.shuffle(df)', setup=setup, number=1000)
timeit.timeit('np.random.shuffle(df.values)', setup=setup, number=1000)

Recursive directory listing in DOS

dir /s /b /a:d>output.txt will port it to a text file

How to remove new line characters from data rows in mysql?

For new line characters

UPDATE table_name SET field_name = TRIM(TRAILING '\n' FROM field_name);
UPDATE table_name SET field_name = TRIM(TRAILING '\r' FROM field_name);
UPDATE table_name SET field_name = TRIM(TRAILING '\r\n' FROM field_name);

For all white space characters

UPDATE table_name SET field_name = TRIM(field_name);
UPDATE table_name SET field_name = TRIM(TRAILING '\n' FROM field_name);
UPDATE table_name SET field_name = TRIM(TRAILING '\r' FROM field_name);
UPDATE table_name SET field_name = TRIM(TRAILING '\r\n' FROM field_name);
UPDATE table_name SET field_name = TRIM(TRAILING '\t' FROM field_name);

Read more: MySQL TRIM Function

Overriding interface property type defined in Typescript d.ts file

It's funny I spend the day investigating possibility to solve the same case. I found that it not possible doing this way:

// a.ts - module
export interface A {
    x: string | any;
}

// b.ts - module
import {A} from './a';

type SomeOtherType = {
  coolStuff: number
}

interface B extends A {
    x: SomeOtherType;
}

Cause A module may not know about all available types in your application. And it's quite boring port everything from everywhere and doing code like this.

export interface A {
    x: A | B | C | D ... Million Types Later
}

You have to define type later to have autocomplete works well.


So you can cheat a bit:

// a.ts - module
export interface A {
    x: string;
}

Left the some type by default, that allow autocomplete works, when overrides not required.

Then

// b.ts - module
import {A} from './a';

type SomeOtherType = {
  coolStuff: number
}

// @ts-ignore
interface B extends A {
    x: SomeOtherType;
}

Disable stupid exception here using @ts-ignore flag, saying us the we doing something wrong. And funny thing everything works as expected.

In my case I'm reducing the scope vision of type x, its allow me doing code more stricted. For example you have list of 100 properties, and you reduce it to 10, to avoid stupid situations

Resetting a setTimeout

i know this is an old thread but i came up with this today

var timer       = []; //creates a empty array called timer to store timer instances
var afterTimer = function(timerName, interval, callback){
    window.clearTimeout(timer[timerName]); //clear the named timer if exists
    timer[timerName] = window.setTimeout(function(){ //creates a new named timer 
        callback(); //executes your callback code after timer finished
    },interval); //sets the timer timer
}

and you invoke using

afterTimer('<timername>string', <interval in milliseconds>int, function(){
   your code here
});

Difference between Static and final?

final -

1)When we apply "final" keyword to a variable,the value of that variable remains constant. (or) Once we declare a variable as final.the value of that variable cannot be changed.

2)It is useful when a variable value does not change during the life time of a program

static -

1)when we apply "static" keyword to a variable ,it means it belongs to class.
2)When we apply "static" keyword to a method,it means the method can be accessed without creating any instance of the class

How to import image (.svg, .png ) in a React Component

If the images are inside the src/assets folder you can use require with the correct path in the require statement,

var Diamond = require('../../assets/linux_logo.jpg');

 export class ItemCols extends Component {
    render(){
        return (
            <div>
                <section className="one-fourth" id="html">
                    <img src={Diamond} />
                </section>
            </div>
        )
    } 
}

How can I create directory tree in C++/Linux?

This is similar to the previous but works forward through the string instead of recursively backwards. Leaves errno with the right value for last failure. If there's a leading slash, there's an extra time through the loop which could have been avoided via one find_first_of() outside the loop or by detecting the leading / and setting pre to 1. The efficiency is the same whether we get set up by a first loop or a pre loop call, and the complexity would be (slightly) higher when using the pre-loop call.

#include <iostream>
#include <string>
#include <sys/stat.h>

int
mkpath(std::string s,mode_t mode)
{
    size_t pos=0;
    std::string dir;
    int mdret;

    if(s[s.size()-1]!='/'){
        // force trailing / so we can handle everything in loop
        s+='/';
    }

    while((pos=s.find_first_of('/',pos))!=std::string::npos){
        dir=s.substr(0,pos++);
        if(dir.size()==0) continue; // if leading / first time is 0 length
        if((mdret=mkdir(dir.c_str(),mode)) && errno!=EEXIST){
            return mdret;
        }
    }
    return mdret;
}

int main()
{
    int mkdirretval;
    mkdirretval=mkpath("./foo/bar",0755);
    std::cout << mkdirretval << '\n';

}

Using jquery to get all checked checkboxes with a certain class name

I'm not sure if it helps for your particular case, and I'm not sure if in your case, the checkboxes you want to include only are all part of a single form or div or table, but you can always select all checkboxes inside a specific element. For example:

<ul id="selective">
 <li><input type="checkbox" value="..." /></li>
 <li><input type="checkbox" value="..." /></li>
 <li><input type="checkbox" value="..." /></li>
 <li><input type="checkbox" value="..." /></li>
</ul>

Then, using the following jQuery, it ONLY goes through the checkboxes within that UL with id="selective":

$('#selective input:checkbox').each(function () {
 var sThisVal = (this.checked ? $(this).val() : "");
});

PermGen elimination in JDK 8

This is one of the new features of Java 8, part of JDK Enhancement Proposals 122:

Remove the permanent generation from the Hotspot JVM and thus the need to tune the size of the permanent generation.

The list of all the JEPs that will be included in Java 8 can be found on the JDK8 milestones page.

SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance

My issue was that i had multiple versions of MS SQL express installed. I went to installation folder C:/ProgramFiles/MicrosoftSQL Server/ where i found 3 versions of it. I deleted 2 folders, and left only MSSQL13.SQLEXPRESS which solved the problem.

SQL Server - stop or break execution of a SQL script

You can alter the flow of execution using GOTO statements:

IF @ValidationResult = 0
BEGIN
    PRINT 'Validation fault.'
    GOTO EndScript
END

/* our code */

EndScript:

Can I add jars to maven 2 build classpath without installing them?

Using <scope>system</scope> is a terrible idea for reasons explained by others, installing the file manually to your local repository makes the build unreproducible, and using <url>file://${project.basedir}/repo</url> is not a good idea either because (1) that may not be a well-formed file URL (e.g. if the project is checked out in a directory with unusual characters), (2) the result is unusable if this project’s POM is used as a dependency of someone else’s project.

Assuming you are unwilling to upload the artifact to a public repository, Simeon’s suggestion of a helper module does the job. But there is an easier way now…

The Recommendation

Use non-maven-jar-maven-plugin. Does exactly what you were asking for, with none of the drawbacks of the other approaches.

Create an ISO date object in javascript

Try using the ISO string

var isodate = new Date().toISOString()

See also: method definition at MDN.

How do I get into a Docker container's shell?

Use:

docker attach <container name/id here>

The other way, albeit there is a danger to it, is to use attach, but if you Ctrl + C to exit the session, you will also stop the container. If you just want to see what is happening, use docker logs -f.

:~$ docker attach --help
Usage:  docker attach [OPTIONS] CONTAINER

Attach to a running container

Options:
      --detach-keys string   Override the key sequence for detaching a container
      --help                 Print usage
      --no-stdin             Do not attach STDIN
      --sig-proxy            Proxy all received signals to the process (default true)

Download TS files from video stream

You can use Xtreme Download Manager(XDM) software for this. This software can download from any site in this format. Even this software can change the ts file format. You only need to change the format when downloading.

like:https://www.videohelp.com/software/Xtreme-Download-Manager-

How to scroll to specific item using jQuery?

I did this combination. its work for me. but facing one issue if click move that div size is too large that scenerio scroll not down to this particular div.

 var scrollDownTo =$("#show_question_" + nQueId).position().top;
        console.log(scrollDownTo);
        $('#slider_light_box_container').animate({
            scrollTop: scrollDownTo
            }, 1000, function(){
        });

        }

Resetting remote to a certain commit

If you want a previous version of file, I would recommend using git checkout.

git checkout <commit-hash>

Doing this will send you back in time, it does not affect the current state of your project, you can come to mainline git checkout mainline

but when you add a file in the argument, that file is brought back to you from a previous time to your current project time, i.e. your current project is changed and needs to be committed.

git checkout <commit-hash> -- file_name
git add .
git commit -m 'file brought from previous time'
git push

The advantage of this is that it does not delete history, and neither does revert a particular code changes (git revert)

Check more here https://www.atlassian.com/git/tutorials/undoing-changes#git-checkout

Determining the version of Java SDK on the Mac

On modern macOS, the correct path is /Library/Java/JavaVirtualMachines.

You can also avail yourself of the command /usr/libexec/java_home, which will scan that directory for you and return a list.

How to hide .php extension in .htaccess

The other option for using PHP scripts sans extension is

Options +MultiViews

Or even just following in the directories .htaccess:

DefaultType application/x-httpd-php

The latter allows having all filenames without extension script being treated as PHP scripts. While MultiViews makes the webserver look for alternatives, when just the basename is provided (there's a performance hit with that however).

AngularJS: ng-repeat list is not updated when a model element is spliced from the model array

I had the same issue. The problem was because 'ng-controller' was defined twice (in routing and also in the HTML).

JavaScript unit test tools for TDD

The JavaScript section of the Wikipedia entry, List of Unit Testing Frameworks, provides a list of available choices. It indicates whether they work client-side, server-side, or both.

How can I check if a string only contains letters in Python?

(1) Use str.isalpha() when you print the string.

(2) Please check below program for your reference:-

 str = "this";  # No space & digit in this string
 print str.isalpha() # it gives return True

 str = "this is 2";
 print str.isalpha() # it gives return False

Note:- I checked above example in Ubuntu.

HTML Table cellspacing or padding just top / bottom

CSS?

td {
  padding-top: 2px;
  padding-bottom: 2px;
}

How to find the users list in oracle 11g db?

select * from all_users

This will work for sure

Get a particular cell value from HTML table using JavaScript

You can get cell value with JS even when click on the cell:

.......................

      <head>

        <title>Search students by courses/professors</title>

        <script type="text/javascript">

        function ChangeColor(tableRow, highLight)
        {
           if (highLight){
               tableRow.style.backgroundColor = '00CCCC';
           }

        else{
             tableRow.style.backgroundColor = 'white';
            }   
      }

      function DoNav(theUrl)
      {
      document.location.href = theUrl;
      }
      </script>

    </head>
    <body>

         <table id = "c" width="180" border="1" cellpadding="0" cellspacing="0">

                <% for (Course cs : courses){ %>

                <tr onmouseover="ChangeColor(this, true);" 
                    onmouseout="ChangeColor(this, false);" 
                    onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');">

                     <td name = "title" align = "center"><%= cs.getTitle() %></td>

                </tr>
               <%}%>

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

I wrote the HTML table in JSP. Course is is a type. For example Course cs, cs= object of type Course which had 2 attributes: id, title. courses is an ArrayList of Course objects.

The HTML table displays all the courses titles in each cell. So the table has 1 column only: Course1 Course2 Course3 ...... Taking aside:

onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');"

This means that after user selects a table cell, for example "Course2", the title of the course- "Course2" will travel to the page where the URL is directing the user: http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp . "Course2" will arrive in FoundS.jsp page. The identifier of "Course2" is courseId. To declare the variable courseId, in which CourseX will be kept, you put a "?" after the URL and next to it the identifier.

I told you just in case you'll want to use it because I searched a lot for it and I found questions like mine. But now I found out from teacher so I post where people asked.

The example is working.I've seen.

How to delete files recursively from an S3 bucket

In the S3 management console, click on the checkmark for the bucket, and click on the empty button from the top right.

Finding median of list in Python

def midme(list1):

    list1.sort()
    if len(list1)%2>0:
            x = list1[int((len(list1)/2))]
    else:
            x = ((list1[int((len(list1)/2))-1])+(list1[int(((len(list1)/2)))]))/2
    return x


midme([4,5,1,7,2])

How do I print my Java object without getting "SomeType@2f92e0f4"?

In intellij you can auto generate toString method by pressing alt+inset and then selecting toString() here is an out put for a test class:

public class test  {
int a;
char b;
String c;
Test2 test2;

@Override
public String toString() {
    return "test{" +
            "a=" + a +
            ", b=" + b +
            ", c='" + c + '\'' +
            ", test2=" + test2 +
            '}';
 }
}

As you can see, it generates a String by concatenating, several attributes of the class, for primitives it will print their values and for reference types it will use their class type (in this case to string method of Test2).

Run react-native on android emulator

Try

  • brew cask install android-platform-tools
  • adb reverse tcp:9090 tcp:9090
  • run the app

jQuery UI DatePicker to show month year only

<style>
.ui-datepicker table{
    display: none;
}

<script type="text/javascript">
$(function() {
    $( "#manad" ).datepicker({
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        dateFormat: 'yy-mm',
        onClose: function(dateText, inst) { 
            var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
            var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
            $(this).datepicker('setDate', new Date(year, month, 1));
        },
        beforeShow : function(input, inst) {
            if ((datestr = $(this).val()).length > 0) {
                actDate = datestr.split('-');
                year = actDate[0];
                month = actDate[1]-1;
                $(this).datepicker('option', 'defaultDate', new Date(year, month));
                $(this).datepicker('setDate', new Date(year, month));
            }
        }
    });
});

This will solve the problem =) But I wanted the timeFormat yyyy-mm

Only tried in FF4 though

What is a simple C or C++ TCP server and client example?

If the code should be simple, then you probably asking for C example based on traditional BSD sockets. Solutions like boost::asio are imho quite complicated when it comes to short and simple "hello world" example.

To compile examples you mentioned you must make simple fixes, because you are compiling under C++ compiler. I'm referring to following files:
http://www.linuxhowtos.org/data/6/server.c
http://www.linuxhowtos.org/data/6/client.c
from: http://www.linuxhowtos.org/C_C++/socket.htm

  1. Add following includes to both files:

    #include <cstdlib>
    #include <cstring>
    #include <unistd.h>
    
  2. In client.c, change the line:

    if (connect(sockfd,&serv_addr,sizeof(serv_addr)) < 0)
    { ... }
    

    to:

    if (connect(sockfd,(const sockaddr*)&serv_addr,sizeof(serv_addr)) < 0)
    { ... }
    

As you can see in C++ an explicit cast is needed.

How to check if iframe is loaded or it has a content?

A really great method is use jQuery AJAX. The parent frame would look like this:

<iframe src="iframe_load.php" style="width: 100%; height: 100%;"></iframe>

The iframe_load.php file would load the jQuery library and a JavaScript that attempts to load the destination URL in an AJAX GET:

var the_url_to_load = "http://www.your-website.com" ;
$.ajax({
            type: "GET",
            url: the_url_to_load,
            data: "",
            success: function(data){
                // if can load inside iframe, load the URL
                location.href = the_url_to_load ;
            },
            statusCode: {
                500: function() {
                    alert( 'site has errors' ) ;
                }
            },
            error:function (xhr, ajaxOptions, thrownError){
                // if x-frame-options, site is down or web server is down
                alert( 'URL did not load due to x-frame-options' ) ;
            } });

IMPORTANT The destination must have contain the "Access-Control-Allow-Origin" header. Example in PHP:

HEADER( "Access-Control-Allow-Origin: *" ) ;

Getting attribute of element in ng-click function in angularjs

Addition to the answer of Brett DeWoody: (which is updated now)

var dataValue = obj.srcElement.attributes.data.nodeValue;

Works fine in IE(9+) and Chrome, but Firefox does not know the srcElement property. I found:

var dataValue = obj.currentTarget.attributes.data.nodeValue;

Works in IE, Chrome and FF, I did not test Safari.

How do I get an empty array of any size in python?

If by "array" you actually mean a Python list, you can use

a = [0] * 10

or

a = [None] * 10

A fast way to delete all rows of a datatable at once

Here is a clean and modern way to do it using Entity FW and without SQL Injection or TSQL..

using (Entities dbe = new Entities())
{
    dbe.myTable.RemoveRange(dbe.myTable.ToList());
    dbe.SaveChanges();
}

Replace duplicate spaces with a single space in T-SQL

Even tidier:

select string = replace(replace(replace(' select   single       spaces',' ','<>'),'><',''),'<>',' ')

Output:

select single spaces

Passing arrays as url parameter

Edit: Don't miss Stefan's solution above, which uses the very handy http_build_query() function: https://stackoverflow.com/a/1764199/179125

knittl is right on about escaping. However, there's a simpler way to do this:

$url = 'http://example.com/index.php?';
$url .= 'aValues[]=' . implode('&amp;aValues[]=', array_map('urlencode', $aValues));

If you want to do this with an associative array, try this instead:

PHP 5.3+ (lambda function)

$url = 'http://example.com/index.php?';
$url .= implode('&amp;', array_map(function($key, $val) {
    return 'aValues[' . urlencode($key) . ']=' . urlencode($val);
  },
  array_keys($aValues), $aValues)
);

PHP <5.3 (callback)

function urlify($key, $val) {
  return 'aValues[' . urlencode($key) . ']=' . urlencode($val);
}

$url = 'http://example.com/index.php?';
$url .= implode('&amp;', array_map('urlify', array_keys($aValues), $aValues));

ascending/descending in LINQ - can one change the order via parameter?

In addition to the beautiful solution given by @Jon Skeet, I also needed ThenBy and ThenByDescending, so I am adding it based on his solution:

    public static IOrderedEnumerable<TSource> ThenByWithDirection<TSource, TKey>(
         this IOrderedEnumerable<TSource> source, 
         Func<TSource, TKey> keySelector,  
         bool descending)
    {
        return descending ? 
               source.ThenByDescending(keySelector) :
               source.ThenBy(keySelector);
    }

Binary Search Tree - Java Implementation


Here is the complete Implementation of Binary Search Tree In Java insert,search,countNodes,traversal,delete,empty,maximum & minimum node,find parent node,print all leaf node, get level,get height, get depth,print left view, mirror view


import java.util.NoSuchElementException;
import java.util.Scanner;

import org.junit.experimental.max.MaxCore;

class BSTNode {

    BSTNode left = null;
    BSTNode rigth = null;
    int data = 0;

    public BSTNode() {
        super();
    }

    public BSTNode(int data) {
        this.left = null;
        this.rigth = null;
        this.data = data;
    }

    @Override
    public String toString() {
        return "BSTNode [left=" + left + ", rigth=" + rigth + ", data=" + data + "]";
    }

}


class BinarySearchTree {

    BSTNode root = null;

    public BinarySearchTree() {

    }

    public void insert(int data) {
        BSTNode node = new BSTNode(data);
        if (root == null) {
            root = node;
            return;
        }

        BSTNode currentNode = root;
        BSTNode parentNode = null;

        while (true) {
            parentNode = currentNode;
            if (currentNode.data == data)
                throw new IllegalArgumentException("Duplicates nodes note allowed in Binary Search Tree");

            if (currentNode.data > data) {
                currentNode = currentNode.left;
                if (currentNode == null) {
                    parentNode.left = node;
                    return;
                }
            } else {
                currentNode = currentNode.rigth;
                if (currentNode == null) {
                    parentNode.rigth = node;
                    return;
                }
            }
        }
    }

    public int countNodes() {
        return countNodes(root);
    }

    private int countNodes(BSTNode node) {
        if (node == null) {
            return 0;
        } else {
            int count = 1;
            count += countNodes(node.left);
            count += countNodes(node.rigth);
            return count;
        }
    }

    public boolean searchNode(int data) {
        if (empty())
            return empty();
        return searchNode(data, root);
    }

    public boolean searchNode(int data, BSTNode node) {
        if (node != null) {
            if (node.data == data)
                return true;
            else if (node.data > data)
                return searchNode(data, node.left);
            else if (node.data < data)
                return searchNode(data, node.rigth);
        }
        return false;
    }

    public boolean delete(int data) {
        if (empty())
            throw new NoSuchElementException("Tree is Empty");

        BSTNode currentNode = root;
        BSTNode parentNode = root;
        boolean isLeftChild = false;

        while (currentNode.data != data) {
            parentNode = currentNode;
            if (currentNode.data > data) {
                isLeftChild = true;
                currentNode = currentNode.left;
            } else if (currentNode.data < data) {
                isLeftChild = false;
                currentNode = currentNode.rigth;
            }
            if (currentNode == null)
                return false;
        }

        // CASE 1: node with no child
        if (currentNode.left == null && currentNode.rigth == null) {
            if (currentNode == root)
                root = null;
            if (isLeftChild)
                parentNode.left = null;
            else
                parentNode.rigth = null;
        }

        // CASE 2: if node with only one child
        else if (currentNode.left != null && currentNode.rigth == null) {
            if (root == currentNode) {
                root = currentNode.left;
            }
            if (isLeftChild)
                parentNode.left = currentNode.left;
            else
                parentNode.rigth = currentNode.left;
        } else if (currentNode.rigth != null && currentNode.left == null) {
            if (root == currentNode)
                root = currentNode.rigth;
            if (isLeftChild)
                parentNode.left = currentNode.rigth;
            else
                parentNode.rigth = currentNode.rigth;
        }

        // CASE 3: node with two child
        else if (currentNode.left != null && currentNode.rigth != null) {

            // Now we have to find minimum element in rigth sub tree
            // that is called successor
            BSTNode successor = getSuccessor(currentNode);
            if (currentNode == root)
                root = successor;
            if (isLeftChild)
                parentNode.left = successor;
            else
                parentNode.rigth = successor;
            successor.left = currentNode.left;
        }

        return true;
    }

    private BSTNode getSuccessor(BSTNode deleteNode) {

        BSTNode successor = null;
        BSTNode parentSuccessor = null;
        BSTNode currentNode = deleteNode.left;

        while (currentNode != null) {
            parentSuccessor = successor;
            successor = currentNode;
            currentNode = currentNode.left;
        }

        if (successor != deleteNode.rigth) {
            parentSuccessor.left = successor.left;
            successor.rigth = deleteNode.rigth;
        }

        return successor;
    }

    public int nodeWithMinimumValue() {
        return nodeWithMinimumValue(root);
    }

    private int nodeWithMinimumValue(BSTNode node) {
        if (node.left != null)
            return nodeWithMinimumValue(node.left);
        return node.data;
    }

    public int nodewithMaximumValue() {
        return nodewithMaximumValue(root);
    }

    private int nodewithMaximumValue(BSTNode node) {
        if (node.rigth != null)
            return nodewithMaximumValue(node.rigth);
        return node.data;
    }

    public int parent(int data) {
        return parent(root, data);
    }

    private int parent(BSTNode node, int data) {
        if (empty())
            throw new IllegalArgumentException("Empty");
        if (root.data == data)
            throw new IllegalArgumentException("No Parent node found");

        BSTNode parent = null;
        BSTNode current = node;

        while (current.data != data) {
            parent = current;
            if (current.data > data)
                current = current.left;
            else
                current = current.rigth;
            if (current == null)
                throw new IllegalArgumentException(data + " is not a node in tree");
        }
        return parent.data;
    }

    public int sibling(int data) {
        return sibling(root, data);
    }

    private int sibling(BSTNode node, int data) {
        if (empty())
            throw new IllegalArgumentException("Empty");
        if (root.data == data)
            throw new IllegalArgumentException("No Parent node found");

        BSTNode cureent = node;
        BSTNode parent = null;
        boolean isLeft = false;

        while (cureent.data != data) {
            parent = cureent;
            if (cureent.data > data) {
                cureent = cureent.left;
                isLeft = true;
            } else {
                cureent = cureent.rigth;
                isLeft = false;
            }
            if (cureent == null)
                throw new IllegalArgumentException("No Parent node found");
        }
        if (isLeft) {
            if (parent.rigth != null) {
                return parent.rigth.data;
            } else
                throw new IllegalArgumentException("No Sibling is there");
        } else {
            if (parent.left != null)
                return parent.left.data;
            else
                throw new IllegalArgumentException("No Sibling is there");
        }
    }

    public void leafNodes() {
        if (empty())
            throw new IllegalArgumentException("Empty");
        leafNode(root);
    }

    private void leafNode(BSTNode node) {
        if (node == null)
            return;
        if (node.rigth == null && node.left == null)
            System.out.print(node.data + " ");
        leafNode(node.left);
        leafNode(node.rigth);
    }

    public int level(int data) {
        if (empty())
            throw new IllegalArgumentException("Empty");
        return level(root, data, 1);
    }

    private int level(BSTNode node, int data, int level) {
        if (node == null)
            return 0;
        if (node.data == data)
            return level;
        int result = level(node.left, data, level + 1);
        if (result != 0)
            return result;
        result = level(node.rigth, data, level + 1);
        return result;
    }

    public int depth() {
        return depth(root);
    }

    private int depth(BSTNode node) {
        if (node == null)
            return 0;
        else
            return 1 + Math.max(depth(node.left), depth(node.rigth));
    }

    public int height() {
        return height(root);
    }

    private int height(BSTNode node) {
        if (node == null)
            return 0;
        else
            return 1 + Math.max(height(node.left), height(node.rigth));
    }

    public void leftView() {
        leftView(root);
    }

    private void leftView(BSTNode node) {
        if (node == null)
            return;
        int height = height(node);

        for (int i = 1; i <= height; i++) {
            printLeftView(node, i);
        }
    }

    private boolean printLeftView(BSTNode node, int level) {
        if (node == null)
            return false;

        if (level == 1) {
            System.out.print(node.data + " ");
            return true;
        } else {
            boolean left = printLeftView(node.left, level - 1);
            if (left)
                return true;
            else
                return printLeftView(node.rigth, level - 1);
        }
    }

    public void mirroeView() {
        BSTNode node = mirroeView(root);
        preorder(node);
        System.out.println();
        inorder(node);
        System.out.println();
        postorder(node);
        System.out.println();
    }

    private BSTNode mirroeView(BSTNode node) {
        if (node == null || (node.left == null && node.rigth == null))
            return node;

        BSTNode temp = node.left;
        node.left = node.rigth;
        node.rigth = temp;

        mirroeView(node.left);
        mirroeView(node.rigth);
        return node;
    }

    public void preorder() {
        preorder(root);
    }

    private void preorder(BSTNode node) {
        if (node != null) {
            System.out.print(node.data + " ");
            preorder(node.left);
            preorder(node.rigth);
        }
    }

    public void inorder() {
        inorder(root);
    }

    private void inorder(BSTNode node) {
        if (node != null) {
            inorder(node.left);
            System.out.print(node.data + " ");
            inorder(node.rigth);
        }
    }

    public void postorder() {
        postorder(root);
    }

    private void postorder(BSTNode node) {
        if (node != null) {
            postorder(node.left);
            postorder(node.rigth);
            System.out.print(node.data + " ");
        }
    }

    public boolean empty() {
        return root == null;
    }

}

public class BinarySearchTreeTest {
    public static void main(String[] l) {
        System.out.println("Weleome to Binary Search Tree");
        Scanner scanner = new Scanner(System.in);
        boolean yes = true;
        BinarySearchTree tree = new BinarySearchTree();
        do {
            System.out.println("\n1. Insert");
            System.out.println("2. Search Node");
            System.out.println("3. Count Node");
            System.out.println("4. Empty Status");
            System.out.println("5. Delete Node");
            System.out.println("6. Node with Minimum Value");
            System.out.println("7. Node with Maximum Value");
            System.out.println("8. Find Parent node");
            System.out.println("9. Count no of links");
            System.out.println("10. Get the sibling of any node");
            System.out.println("11. Print all the leaf node");
            System.out.println("12. Get the level of node");
            System.out.println("13. Depth of the tree");
            System.out.println("14. Height of Binary Tree");
            System.out.println("15. Left View");
            System.out.println("16. Mirror Image of Binary Tree");
            System.out.println("Enter Your Choice :: ");
            int choice = scanner.nextInt();
            switch (choice) {
            case 1:
                try {
                    System.out.println("Enter Value");
                    tree.insert(scanner.nextInt());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 2:
                System.out.println("Enter the node");
                System.out.println(tree.searchNode(scanner.nextInt()));
                break;

            case 3:
                System.out.println(tree.countNodes());
                break;

            case 4:
                System.out.println(tree.empty());
                break;

            case 5:
                try {
                    System.out.println("Enter the node");
                    System.out.println(tree.delete(scanner.nextInt()));
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }

            case 6:
                try {
                    System.out.println(tree.nodeWithMinimumValue());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 7:
                try {
                    System.out.println(tree.nodewithMaximumValue());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 8:
                try {
                    System.out.println("Enter the node");
                    System.out.println(tree.parent(scanner.nextInt()));
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 9:
                try {
                    System.out.println(tree.countNodes() - 1);
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 10:
                try {
                    System.out.println("Enter the node");
                    System.out.println(tree.sibling(scanner.nextInt()));
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 11:
                try {
                    tree.leafNodes();
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }

            case 12:
                try {
                    System.out.println("Enter the node");
                    System.out.println("Level is : " + tree.level(scanner.nextInt()));
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 13:
                try {
                    System.out.println(tree.depth());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 14:
                try {
                    System.out.println(tree.height());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 15:
                try {
                    tree.leftView();
                    System.out.println();
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 16:
                try {
                    tree.mirroeView();
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            default:
                break;
            }
            tree.preorder();
            System.out.println();
            tree.inorder();
            System.out.println();
            tree.postorder();
        } while (yes);
        scanner.close();
    }
}

Pointer vs. Reference

This ultimately ends up being subjective. The discussion thus far is useful, but I don't think there is a correct or decisive answer to this. A lot will depend on style guidelines and your needs at the time.

While there are some different capabilities (whether or not something can be NULL) with a pointer, the largest practical difference for an output parameter is purely syntax. Google's C++ Style Guide (https://google.github.io/styleguide/cppguide.html#Reference_Arguments), for example, mandates only pointers for output parameters, and allows only references that are const. The reasoning is one of readability: something with value syntax should not have pointer semantic meaning. I'm not suggesting that this is necessarily right or wrong, but I think the point here is that it's a matter of style, not of correctness.

PHP - concatenate or directly insert variables in string

From the point of view of making thinks simple, readable, consistent and easy to understand (since performance doesn't matter here):

  • Using embedded vars in double quotes can lead to complex and confusing situations when you want to embed object properties, multidimentional arrays etc. That is, generally when reading embedded vars, you cannot be instantly 100% sure of the final behavior of what you are reading.

  • You frequently need add crutches such as {} and \, which IMO adds confusion and makes concatenation readability nearly equivalent, if not better.

  • As soon as you need to wrap a function call around the var, for example htmlspecialchars($var), you have to switch to concatenation.

  • AFAIK, you cannot embed constants.

In some specific cases, "double quotes with vars embedding" can be useful, but generally speaking, I would go for concatenation (using single or double quotes when convenient)

Microsoft.ReportViewer.Common Version=12.0.0.0

I worked on this issue for a few days. Installed all packages, modified web.config and still had the same problem. I finally removed

<assemblies>
<add assembly="Microsoft.ReportViewer.Common, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
</assemblies>

from the web.config and it worked. No exactly sure why it didn't work with the tags in the web.config file. My guess there is a conflict with the GAC and the BIN folder.

Here is my web.config file:

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
    <httpHandlers>
      <add verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />     
    </httpHandlers>    
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <add name="ReportViewerWebControlHandler" preCondition="integratedMode" verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />      
    </handlers>
  </system.webServer>
</configuration>

How can I get query string values in JavaScript?

The shortest possible expression in terms of size to obtain a query object seems to be:

var params = {};
location.search.substr(1).replace(/([^&=]*)=([^&]*)&?/g,
  function () { params[decodeURIComponent(arguments[1])] = decodeURIComponent(arguments[2]); });

You can make use of the A element to parse a URI from a string into its location-like components (to get rid of #..., for example):

var a = document.createElement('a');
a.href = url;
// Parse a.search.substr(1)... as above

tomcat - CATALINA_BASE and CATALINA_HOME variables

I can't say I know the best practice, but here's my perspective.

Are you using these variables for anything?

Personally, I haven't needed to change neither, on Linux nor Windows, in environments varying from development to production. Unless you are doing something particular that relies on them, chances are you could leave them alone.

catalina.sh sets the variables that Tomcat needs to work out of the box. It also says that CATALINA_BASE is optional:

#   CATALINA_HOME   May point at your Catalina "build" directory.
#
#   CATALINA_BASE   (Optional) Base directory for resolving dynamic portions
#                   of a Catalina installation.  If not present, resolves to
#                   the same directory that CATALINA_HOME points to.

I'm pretty sure you'll find out whether or not your setup works when you start your server.

How to detect the device orientation using CSS media queries?

In Javascript it is better to use screen.width and screen.height. These two values are available in all modern browsers. They give the real dimensions of the screen, even if the browser has been scaled down when the app fires up. window.innerWidth changes when the browser is scaled down, which can't happen on mobile devices but can happen on PCs and laptops.

The values of screen.width and screen.height change when the mobile device flips between portrait and landscape modes, so it is possible to determine the mode by comparing the values. If screen.width is greater than 1280px you're dealing with a PC or laptop.

You can construct an event listener in Javascript to detect when the two values are flipped. The portrait screen.width values to concentrate on are 320px (mainly iPhones), 360px (most other phones), 768px (small tablets) and 800px (regular tablets).

How do I verify/check/test/validate my SSH passphrase?

If your passphrase is to unlock your SSH key and you don't have ssh-agent, but do have sshd (the SSH daemon) installed on your machine, do:

cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys;
ssh localhost -i ~/.ssh/id_rsa

Where ~/.ssh/id_rsa.pub is the public key, and ~/.ssh/id_rsa is the private key.

How do I query using fields inside the new PostgreSQL JSON datatype?

With postgres 9.3 use -> for object access. 4 example

seed.rb

se = SmartElement.new
se.data = 
{
    params:
    [
        {
            type: 1,
            code: 1,
            value: 2012,
            description: 'year of producction'
        },
        {
            type: 1,
            code: 2,
            value: 30,
            description: 'length'
        }
    ]
}

se.save

rails c

SELECT data->'params'->0 as data FROM smart_elements;

returns

                                 data
----------------------------------------------------------------------
 {"type":1,"code":1,"value":2012,"description":"year of producction"}
(1 row)

You can continue nesting

SELECT data->'params'->0->'type' as data FROM smart_elements;

return

 data
------
 1
(1 row)

How to downgrade or install an older version of Cocoapods

Several notes:

Make sure you first get a list of all installed versions. I actually had the version I wanted to downgrade to already installed, but ended up uninstalling that as well. To see the list of all your versions do:

sudo gem list cocoapods

Then when you want to delete a version, specify that version.

sudo gem uninstall cocoapods -v 1.6.2

You could remove the version specifier -v 1.6.2 and that would delete all versions:

You may try all this and still see that the Cocoapods you expected is still installed. If that's the case then it might be because Cocoaposa is stored in a different directory.

sudo gem uninstall -n /usr/local/bin cocoapods -v 1.6.2

Then you will have to also install it in a different directory, otherwise you may get an error saying You don't have write permissions for the /usr/bin directory

sudo gem install -n /usr/local/bin cocoapods -v 1.6.1

To check which version is your default do:

pod --version

For more on the directory problem see here

Verify ImageMagick installation

If your ISP/hosting service has installed ImageMagick and put its location in the PATH environment variable, you can find what versions are installed and where using:

<?php
echo "<pre>";
system("type -a convert");  
echo "</pre>";
?> 

CSS disable text selection

instead of body type a list of elements you want.

Error converting data types when importing from Excel to SQL Server 2008

Going off of what Derloopkat said, which still can fail on conversion (no offense Derloopkat) because Excel is terrible at this:

  1. Paste from excel into Notepad and save as normal (.txt file).
  2. From within excel, open said .txt file.
  3. Select next as it is obviously tab delimited.
  4. Select "none" for text qualifier, then next again.
  5. Select the first row, hold shift, select the last row, and select the text radial button. Click Finish

It will open, check it to make sure it's accurate and then save as an excel file.

Numpy where function multiple conditions

This should work:

dists[((dists >= r) & (dists <= r+dr))]

The most elegant way~~

Create array of all integers between two numbers, inclusive, in Javascript/jQuery

_x000D_
_x000D_
        function getRange(a,b)_x000D_
        {_x000D_
            ar = new Array();_x000D_
            var y = a - b > 0 ? a - b : b - a;_x000D_
            for (i=1;i<y;i++)_x000D_
            {_x000D_
                ar.push(i+b);_x000D_
            }_x000D_
            return ar;_x000D_
        }
_x000D_
_x000D_
_x000D_

Switch to selected tab by name in Jquery-UI Tabs

$('#tabs a[href="#sample-tab-1"]').click();

or, you can assign an id to the links

<a href="#sample-tab-1" id="tab1">span>One</span></a>

so you can find it's id.

$('#tab1').click();

Equivalent of "continue" in Ruby

Yes, it's called next.

for i in 0..5
   if i < 2
     next
   end
   puts "Value of local variable is #{i}"
end

This outputs the following:

Value of local variable is 2
Value of local variable is 3
Value of local variable is 4
Value of local variable is 5
 => 0..5 

How to resize superview to fit all subviews with autolayout?

Eric Baker's comment tipped me off to the core idea that in order for a view to have its size be determined by the content placed within it, then the content placed within it must have an explicit relationship with the containing view in order to drive its height (or width) dynamically. "Add subview" does not create this relationship as you might assume. You have to choose which subview is going to drive the height and/or width of the container... most commonly whatever UI element you have placed in the lower right hand corner of your overall UI. Here's some code and inline comments to illustrate the point.

Note, this may be of particular value to those working with scroll views since it's common to design around a single content view that determines its size (and communicates this to the scroll view) dynamically based on whatever you put in it. Good luck, hope this helps somebody out there.

//
//  ViewController.m
//  AutoLayoutDynamicVerticalContainerHeight
//

#import "ViewController.h"

@interface ViewController ()
@property (strong, nonatomic) UIView *contentView;
@property (strong, nonatomic) UILabel *myLabel;
@property (strong, nonatomic) UILabel *myOtherLabel;
@end

@implementation ViewController

- (void)viewDidLoad
{
    // INVOKE SUPER
    [super viewDidLoad];

    // INIT ALL REQUIRED UI ELEMENTS
    self.contentView = [[UIView alloc] init];
    self.myLabel = [[UILabel alloc] init];
    self.myOtherLabel = [[UILabel alloc] init];
    NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(_contentView, _myLabel, _myOtherLabel);

    // TURN AUTO LAYOUT ON FOR EACH ONE OF THEM
    self.contentView.translatesAutoresizingMaskIntoConstraints = NO;
    self.myLabel.translatesAutoresizingMaskIntoConstraints = NO;
    self.myOtherLabel.translatesAutoresizingMaskIntoConstraints = NO;

    // ESTABLISH VIEW HIERARCHY
    [self.view addSubview:self.contentView]; // View adds content view
    [self.contentView addSubview:self.myLabel]; // Content view adds my label (and all other UI... what's added here drives the container height (and width))
    [self.contentView addSubview:self.myOtherLabel];

    // LAYOUT

    // Layout CONTENT VIEW (Pinned to left, top. Note, it expects to get its vertical height (and horizontal width) dynamically based on whatever is placed within).
    // Note, if you don't want horizontal width to be driven by content, just pin left AND right to superview.
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_contentView]" options:0 metrics:0 views:viewsDictionary]]; // Only pinned to left, no horizontal width yet
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_contentView]" options:0 metrics:0 views:viewsDictionary]]; // Only pinned to top, no vertical height yet

    /* WHATEVER WE ADD NEXT NEEDS TO EXPLICITLY "PUSH OUT ON" THE CONTAINING CONTENT VIEW SO THAT OUR CONTENT DYNAMICALLY DETERMINES THE SIZE OF THE CONTAINING VIEW */
    // ^To me this is what's weird... but okay once you understand...

    // Layout MY LABEL (Anchor to upper left with default margin, width and height are dynamic based on text, font, etc (i.e. UILabel has an intrinsicContentSize))
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[_myLabel]" options:0 metrics:0 views:viewsDictionary]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[_myLabel]" options:0 metrics:0 views:viewsDictionary]];

    // Layout MY OTHER LABEL (Anchored by vertical space to the sibling label that comes before it)
    // Note, this is the view that we are choosing to use to drive the height (and width) of our container...

    // The LAST "|" character is KEY, it's what drives the WIDTH of contentView (red color)
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[_myOtherLabel]-|" options:0 metrics:0 views:viewsDictionary]];

    // Again, the LAST "|" character is KEY, it's what drives the HEIGHT of contentView (red color)
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_myLabel]-[_myOtherLabel]-|" options:0 metrics:0 views:viewsDictionary]];

    // COLOR VIEWS
    self.view.backgroundColor = [UIColor purpleColor];
    self.contentView.backgroundColor = [UIColor redColor];
    self.myLabel.backgroundColor = [UIColor orangeColor];
    self.myOtherLabel.backgroundColor = [UIColor greenColor];

    // CONFIGURE VIEWS

    // Configure MY LABEL
    self.myLabel.text = @"HELLO WORLD\nLine 2\nLine 3, yo";
    self.myLabel.numberOfLines = 0; // Let it flow

    // Configure MY OTHER LABEL
    self.myOtherLabel.text = @"My OTHER label... This\nis the UI element I'm\narbitrarily choosing\nto drive the width and height\nof the container (the red view)";
    self.myOtherLabel.numberOfLines = 0;
    self.myOtherLabel.font = [UIFont systemFontOfSize:21];
}

@end

How to resize superview to fit all subviews with autolayout.png

Function to check if a string is a date

if (strtotime($date)>strtotime(0)) { echo 'it is a date' }

How can I kill whatever process is using port 8080 so that I can vagrant up?

It can be Cisco AnyConnect. Check if /Library/LaunchDaemons/com.cisco.anyconnect.vpnagentd.plist exists. Then unload it with launchctl and delete from /Library/LaunchDaemons

Disable Chrome strict MIME type checking

Another solution when a file pretends another extension

I use php inside of var.js file with this .htaccess.

<Files var.js>
    AddType application/x-httpd-php .js
</Files>

Then I write php code in the .js file

<?php
// This is a `.js` file but works with php
echo "var js_variable = '$php_variable';";

When I got the MIME type warning on Chrome, I fixed it by adding a Content-Type header line in the .js(but php) file.

<?php
header('Content-Type: application/javascript');        // <- Add this line
// This is a `.js` file but works with php
...

A browser won't execute .js file because apache sends the Content-Type header of the file as application/x-httpd-php that is defined in .htaccess. That's a security reason. But apache won't execute php as far as htaccess commands the impersonation, it's necessary. So we need to overwrite apache's Content-Type header with the php function header(). I guess that apache stops sending its own header when php sends it instead of apache before.

how to check the jdk version used to compile a .class file

Btw, the reason that you're having trouble is that the java compiler recognizes two version flags. There is -source 1.5, which assumes java 1.5 level source code, and -target 1.5, which will emit java 1.5 compatible class files. You'll probably want to use both of these switches, but you definitely need -target 1.5; try double checking that eclipse is doing the right thing.

Escaping double quotes in JavaScript onClick event handler

Did you try

&quot; or \x22

instead of

\"

?

iOS application: how to clear notifications?

In Swift I'm using the following code inside my AppDelegate:

func applicationDidBecomeActive(application: UIApplication) {
    application.applicationIconBadgeNumber = 0
    application.cancelAllLocalNotifications()
}

HTTP Basic Authentication - what's the expected web browser experience?

You can use Postman a plugin for chrome. It gives the ability to choose the authentication type you need for each of the requests. In that menu you can configure user and password. Postman will automatically translate the config to a authentication header that will be sent with your request.

Spring Boot JPA - configuring auto reconnect

In case anyone is using custom DataSource

@Bean(name = "managementDataSource")
@ConfigurationProperties(prefix = "management.datasource")
public DataSource dataSource() {
    return DataSourceBuilder.create().build();
}

Properties should look like the following. Notice the @ConfigurationProperties with prefix. The prefix is everything before the actual property name

management.datasource.test-on-borrow=true
management.datasource.validation-query=SELECT 1

A reference for Spring Version 1.4.4.RELEASE

How to check if input file is empty in jQuery

Just check the length of files property, which is a FileList object contained on the input element

if( document.getElementById("videoUploadFile").files.length == 0 ){
    console.log("no files selected");
}

Quoting backslashes in Python string literals

Another way to end a string with a backslash is to end the string with a backslash followed by a space, and then call the .strip() function on the string.

I was trying to concatenate two string variables and have them separated by a backslash, so i used the following:

newString = string1 + "\ ".strip() + string2

How can I close a login form and show the main form without my application closing?

static class Program
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Login();
    } 

    private static bool logOut;

    private static void Login()
    {
        LoginForm login = new LoginForm();
        MainForm main = new MainForm();
        main.FormClosed += new FormClosedEventHandler(main_FormClosed);
        if (login.ShowDialog(main) == DialogResult.OK)
        {
            Application.Run(main);
            if (logOut)
                Login();
        }
        else
            Application.Exit();
    }

    static void main_FormClosed(object sender, FormClosedEventArgs e)
    {
        logOut= (sender as MainForm).logOut;
    }
}

public partial class MainForm : Form
{
    private void btnLogout_ItemClick(object sender, ItemClickEventArgs e)
    {
        //timer1.Stop();
        this.logOut= true;
        this.Close();
    }
}

Why does my 'git branch' have no master?

if it is a new repo you've cloned, it may still be empty, in which case:

git push -u origin master

should likely sort it out.

(did in my case. not sure this is the same issue, thought i should post this just incase. might help others.)

How to create file execute mode permissions in Git on Windows?

I have no touch and chmod command in my cmd.exe and git update-index --chmod=+x foo.sh doesn't work for me.

I finally resolve it by setting skip-worktree bit:

git update-index --skip-worktree --chmod=+x foo.sh

What is the optimal way to compare dates in Microsoft SQL server?

Converting to a DATE or using an open-ended date range in any case will yield the best performance. FYI, convert to date using an index are the best performers. More testing a different techniques in article: What is the most efficient way to trim time from datetime? Posted by Aaron Bertrand

From that article:

DECLARE @dateVar datetime = '19700204';

-- Quickest when there is an index on t.[DateColumn], 
-- because CONVERT can still use the index.
SELECT t.[DateColumn]
FROM MyTable t
WHERE = CONVERT(DATE, t.[DateColumn]) = CONVERT(DATE, @dateVar);

-- Quicker when there is no index on t.[DateColumn]
DECLARE @dateEnd datetime = DATEADD(DAY, 1, @dateVar);
SELECT t.[DateColumn] 
FROM MyTable t
WHERE t.[DateColumn] >= @dateVar AND 
      t.[DateColumn] < @dateEnd;

Also from that article: using BETWEEN, DATEDIFF or CONVERT(CHAR(8)... are all slower.

Can vue-router open a link in a new tab?

I think that you can do something like this:

let routeData = this.$router.resolve({name: 'routeName', query: {data: "someData"}});
window.open(routeData.href, '_blank');

It worked for me.

How do you check what version of SQL Server for a database using TSQL?

For SQL Server 2000 and above, I prefer the following parsing of Joe's answer:

declare @sqlVers numeric(4,2)
select @sqlVers = left(cast(serverproperty('productversion') as varchar), 4)

Gives results as follows:

Result   Server Version
8.00     SQL 2000
9.00     SQL 2005
10.00    SQL 2008
10.50    SQL 2008R2
11.00    SQL 2012
12.00    SQL 2014

Basic list of version numbers here, or exhaustive list from Microsoft here.

"Application tried to present modally an active controller"?

In my case i was trying to present the viewController (i have the reference of the viewController in the TabBarViewController) from different view controllers and it was crashing with the above message. In that case to avoid presenting you can use

viewController.isBeingPresented

!viewController.isBeingPresented {
          // Present your ViewController only if its not present to the user currently.
}

Might help someone.

Using CSS to insert text

Also check out the attr() function of the CSS content attribute. It outputs a given attribute of the element as a text node. Use it like so:

<div class="Owner Joe" />

div:before {
  content: attr(class);
}

Or even with the new HTML5 custom data attributes:

<div data-employeename="Owner Joe" />

div:before {
  content: attr(data-employeename);
}

Confusing error in R: Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings, : line 1 did not have 42 elements)

read.table wants to return a data.frame, which must have an element in each column. Therefore R expects each row to have the same number of elements and it doesn't fill in empty spaces by default. Try read.table("/PathTo/file.csv" , fill = TRUE ) to fill in the blanks.

e.g.

read.table( text= "Element1 Element2
Element5 Element6 Element7" , fill = TRUE , header = FALSE )
#        V1       V2       V3
#1 Element1 Element2         
#2 Element5 Element6 Element7

A note on whether or not to set header = FALSE... read.table tries to automatically determine if you have a header row thus:

header is set to TRUE if and only if the first row contains one fewer field than the number of columns

Write to custom log file from a Bash script

If you see the man page of logger:

$ man logger

LOGGER(1) BSD General Commands Manual LOGGER(1)

NAME logger — a shell command interface to the syslog(3) system log module

SYNOPSIS logger [-isd] [-f file] [-p pri] [-t tag] [-u socket] [message ...]

DESCRIPTION Logger makes entries in the system log. It provides a shell command interface to the syslog(3) system log module.

It Clearly says that it will log to system log. If you want to log to file, you can use ">>" to redirect to log file.

Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory

@Test annotation must be imported from org.junit.jupiter.api.Test so the Junit5 can read it. Junit4 use @Test annotations imported from org.junit.Test package.

jquery find element by specific class when element has multiple classes

You can select elements with multiple classes like so:

$("element.firstClass.anotherClass");

Simply chain the next class onto the first one, without a space (spaces mean "children of").