Programs & Examples On #Httpexception

HttpException or HTTPException are exception classes defined by various object oriented libraries that signal a problem during processing of a http request.

Why do I get "Cannot redirect after HTTP headers have been sent" when I call Response.Redirect()?

Just check if you have set the buffering option to false (by default its true). For response.redirect to work,

  1. Buffering should be true,
  2. you should not have sent more data using response.write which exceeds the default buffer size (in which case it will flush itself causing the headers to be sent) therefore disallowing you to redirect.

Catching "Maximum request length exceeded"

As GateKiller said you need to change the maxRequestLength. You may also need to change the executionTimeout in case the upload speed is too slow. Note that you don't want either of these settings to be too big otherwise you'll be open to DOS attacks.

The default for the executionTimeout is 360 seconds or 6 minutes.

You can change the maxRequestLength and executionTimeout with the httpRuntime Element.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.web>
        <httpRuntime maxRequestLength="102400" executionTimeout="1200" />
    </system.web>
</configuration>

EDIT:

If you want to handle the exception regardless then as has been stated already you'll need to handle it in Global.asax. Here's a link to a code example.

Error:Failed to open zip file. Gradle's dependency cache may be corrupt

I was upgrading gradle from 4.1 to 4.10 and my internet connection timed out.

So I fixed this issue by deleting "gradle-4.10-all" folder in .gradle/wrapper/dists

Importing variables from another file?

script1.py

title="Hello world"

script2.py is where we using script1 variable

Method 1:

import script1
print(script1.title)

Method 2:

from script1 import title
print(title)

Reading data from XML

Alternatively, you can use XPathNavigator:

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XPathNavigator navigator = doc.CreateNavigator();

string books = GetStringValues("Books: ", navigator, "//Book/Title");
string authors = GetStringValues("Authors: ", navigator, "//Book/Author");

..

/// <summary>
/// Gets the string values.
/// </summary>
/// <param name="description">The description.</param>
/// <param name="navigator">The navigator.</param>
/// <param name="xpath">The xpath.</param>
/// <returns></returns>
private static string GetStringValues(string description,
                                      XPathNavigator navigator, string xpath) {
    StringBuilder sb = new StringBuilder();
    sb.Append(description);
    XPathNodeIterator bookNodesIterator = navigator.Select(xpath);
    while (bookNodesIterator.MoveNext())
       sb.Append(string.Format("{0} ", bookNodesIterator.Current.Value));
    return sb.ToString();
}

Single TextView with multiple colored text

It's better to use the string in the strings file, as such:

    <string name="some_text">
<![CDATA[
normal color <font color=\'#06a7eb\'>special color</font>]]>
    </string>

Usage:

textView.text=HtmlCompat.fromHtml(getString(R.string.some_text), HtmlCompat.FROM_HTML_MODE_LEGACY)

ScriptManager.RegisterStartupScript code not working - why?

Try this code...

ScriptManager.RegisterClientScriptBlock(UpdatePanel1, this.GetType(), "script", "alert('Hi');", true);

Where UpdatePanel1 is the id for Updatepanel on your page

Changing image size in Markdown

Just use:

<img src="Assets/icon.png" width="200">

instead of:

![](Assets/icon.png)

Rotate image with javascript

Based on Anuga answer I have extended it to multiple images.

Keep track of the rotation angle of the image as an attribute of the image.

_x000D_
_x000D_
function rotate(image) {_x000D_
  let rotateAngle = Number(image.getAttribute("rotangle")) + 90;_x000D_
  image.setAttribute("style", "transform: rotate(" + rotateAngle + "deg)");_x000D_
  image.setAttribute("rotangle", "" + rotateAngle);_x000D_
}
_x000D_
.rotater {_x000D_
  transition: all 0.3s ease;_x000D_
  border: 0.0625em solid black;_x000D_
  border-radius: 3.75em;_x000D_
}
_x000D_
<img class="rotater" onclick="rotate(this)" src="https://upload.wikimedia.org/wikipedia/en/e/e0/Iron_Man_bleeding_edge.jpg"/>_x000D_
<img class="rotater" onclick="rotate(this)" src="https://upload.wikimedia.org/wikipedia/en/e/e0/Iron_Man_bleeding_edge.jpg"/>_x000D_
<img class="rotater" onclick="rotate(this)" src="https://upload.wikimedia.org/wikipedia/en/e/e0/Iron_Man_bleeding_edge.jpg"/>
_x000D_
_x000D_
_x000D_

Edit

Removed the modulo, looks strange.

How to tell a Mockito mock object to return something different the next time it is called?

First of all don't make the mock static. Make it a private field. Just put your setUp class in the @Before not @BeforeClass. It might be run a bunch, but it's cheap.

Secondly, the way you have it right now is the correct way to get a mock to return something different depending on the test.

How do I make CMake output into a 'bin' dir?

$ cat CMakeLists.txt
project (hello)
set(EXECUTABLE_OUTPUT_PATH "bin")
add_executable (hello hello.c)

Calendar Recurring/Repeating Events - Best Storage Method

I developed an esoteric programming language just for this case. The best part about it is that it is schema less and platform independent. You just have to write a selector program, for your schedule, syntax of which is constrained by the set of rules described here -

https://github.com/tusharmath/sheql/wiki/Rules

The rules are extendible and you can add any sort of customization based on the kind of repetition logic you want to perform, without worrying about schema migrations etc.

This is a completely different approach and might have some disadvantages of its own.

How to understand nil vs. empty vs. blank in Ruby

I made this useful table with all the cases:

enter image description here

blank?, present? are provided by Rails.

How to solve npm install throwing fsevents warning on non-MAC OS?

Instead of using --no-optional every single time, we can just add it to npm or yarn config.

For Yarn, there is a default no-optional config, so we can just edit that:

yarn config set ignore-optional true

For npm, there is no default config set, so we can create one:

npm config set ignore-optional true

How to set a class attribute to a Symfony2 form input

You can do this from the twig template:

{{ form_widget(form.birthdate, { 'attr': {'class': 'calendar'} }) }}

From http://symfony.com/doc/current/book/forms.html#rendering-each-field-by-hand

Can Google Chrome open local links?

Hopefully this helps others in an enterprise setting looking for a solution. My solution after much tinkering was the following:

Follow the steps in the following link to install legacy browser extension and gpo settings: https://support.google.com/chrome/a/answer/3019558?hl=en&ref_topic=3062034

Enabled legacy browser redirect for "file://" through chrome gpo configuration Google Chrome -> Legacy Browser Support -> "Websites to open in alternative browser"

Configure gpo to also install extension: https://chrome.google.com/webstore/detail/enable-local-file-links/nikfmfgobenbhmocjaaboihbeocackld that redirects file:// links to bypass chrome file:// link block.

The extension opens the links which then triggers google chrome to open the link in internet explorer. The result is IE opens a window, then opens the file/folder for the user, then IE closes itself.

what is right way to do API call in react js?

It would be great to use axios for the api request which supports cancellation, interceptors etc. Along with axios, l use react-redux for state management and redux-saga/redux-thunk for the side effects.

Body of Http.DELETE request in Angular2

If you use Angular 6 we can put body in http.request method.

Reference from github

You can try this, for me it works.

import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {

  constructor(
    private http: HttpClient
  ) {
    http.request('delete', url, {body: body}).subscribe();
  }
}

How is returning the output of a function different from printing it?

def add(x, y):
    return x+y

That way it can then become a variable.

sum = add(3, 5)

print(sum)

But if the 'add' function print the output 'sum' would then be None as action would have already taken place after it being assigned.

How to copy files across computers using SSH and MAC OS X Terminal

You can do this with the scp command, which uses the ssh protocol to copy files across machines. It extends the syntax of cp to allow references to other systems:

scp username1@hostname1:/path/to/file username2@hostname2:/path/to/other/file

Copy something from this machine to some other machine:

scp /path/to/local/file username@hostname:/path/to/remote/file

Copy something from another machine to this machine:

scp username@hostname:/path/to/remote/file /path/to/local/file

Copy with a port number specified:

scp -P 1234 username@hostname:/path/to/remote/file /path/to/local/file

MySQL direct INSERT INTO with WHERE clause

INSERT syntax cannot have WHERE clause. The only time you will find INSERT has WHERE clause is when you are using INSERT INTO...SELECT statement.

The first syntax is already correct.

HTML5 Pre-resize images before uploading

The accepted answer works great, but the resize logic ignores the case in which the image is larger than the maximum in only one of the axes (for example, height > maxHeight but width <= maxWidth).

I think the following code takes care of all cases in a more straight-forward and functional way (ignore the typescript type annotations if using plain javascript):

private scaleDownSize(width: number, height: number, maxWidth: number, maxHeight: number): {width: number, height: number} {
    if (width <= maxWidth && height <= maxHeight)
      return { width, height };
    else if (width / maxWidth > height / maxHeight)
      return { width: maxWidth, height: height * maxWidth / width};
    else
      return { width: width * maxHeight / height, height: maxHeight };
  }

How can I disable a specific LI element inside a UL?

Using CSS3: http://www.w3schools.com/cssref/sel_nth-child.asp

If that's not an option for any reason, you could try giving the list items classes:

<ul>
<li class="one"></li>
<li class="two"></li>
<li class="three"></li>
...
</ul>

Then in your css:

li.one{display:none}/*hide first li*/
li.three{display:none}/*hide third li*/

Convert all strings in a list to int

If your list contains pure integer strings, the accepted awnswer is the way to go. This solution will crash if you give it things that are not integers.

So: if you have data that may contain ints, possibly floats or other things as well - you can leverage your own function with errorhandling:

def maybeMakeNumber(s):
    """Returns a string 's' into a integer if possible, a float if needed or
    returns it as is."""

    # handle None, "", 0
    if not s:
        return s
    try:
        f = float(s)
        i = int(f)
        return i if f == i else f
    except ValueError:
        return s

data = ["unkind", "data", "42", 98, "47.11", "of mixed", "types"]

converted = list(map(maybeMakeNumber, data))
print(converted)

Output:

['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']

To also handle iterables inside iterables you can use this helper:

from collections.abc import Iterable, Mapping

def convertEr(iterab):
    """Tries to convert an iterable to list of floats, ints or the original thing
    from the iterable. Converts any iterable (tuple,set, ...) to itself in output.
    Does not work for Mappings  - you would need to check abc.Mapping and handle 
    things like {1:42, "1":84} when converting them - so they come out as is."""

    if isinstance(iterab, str):
        return maybeMakeNumber(iterab)

    if isinstance(iterab, Mapping):
        return iterab

    if isinstance(iterab, Iterable):
        return  iterab.__class__(convertEr(p) for p in iterab)


data = ["unkind", {1: 3,"1":42}, "data", "42", 98, "47.11", "of mixed", 
        ("0", "8", {"15", "things"}, "3.141"), "types"]

converted = convertEr(data)
print(converted)

Output:

['unkind', {1: 3, '1': 42}, 'data', 42, 98, 47.11, 'of mixed', 
 (0, 8, {'things', 15}, 3.141), 'types'] # sets are unordered, hence diffrent order

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

set "PathName=X:\Web Content Mgmt\Completed Filtering\2013_Folder"
set "comd=dir /b /s *.zip"
cd /d "%PathName%"
%comd%

java.io.StreamCorruptedException: invalid stream header: 54657374

You can't expect ObjectInputStream to automagically convert text into objects. The hexadecimal 54657374 is "Test" as text. You must be sending it directly as bytes.

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");
        }
    }   
}

Is there an Eclipse plugin to run system shell in the Console?

... just a little bit late :) you might give a try at http://code.google.com/p/tarlog-plugins/. It gives you options like open shell and open explorer from Project Explorer context menu.

There's also http://sourceforge.net/projects/explorerplugin/ but it seems kind of stuck at 2009.

What's the difference between equal?, eql?, ===, and ==?

I love jtbandes answer, but since it is pretty long, I will add my own compact answer:

==, ===, eql?, equal?
are 4 comparators, ie. 4 ways to compare 2 objects, in Ruby.
As, in Ruby, all comparators (and most operators) are actually method-calls, you can change, overwrite, and define the semantics of these comparing methods yourself. However, it is important to understand, when Ruby's internal language constructs use which comparator:

== (value comparison)
Ruby uses :== everywhere to compare the values of 2 objects, eg. Hash-values:

{a: 'z'}  ==  {a: 'Z'}    # => false
{a: 1}    ==  {a: 1.0}    # => true

=== (case comparison)
Ruby uses :=== in case/when constructs. The following code snippets are logically identical:

case foo
  when bar;  p 'do something'
end

if bar === foo
  p 'do something'
end

eql? (Hash-key comparison)
Ruby uses :eql? (in combination with the method hash) to compare Hash-keys. In most classes :eql? is identical with :==.
Knowledge about :eql? is only important, when you want to create your own special classes:

class Equ
  attr_accessor :val
  alias_method  :initialize, :val=
  def hash()           self.val % 2             end
  def eql?(other)      self.hash == other.hash  end
end

h = {Equ.new(3) => 3,  Equ.new(8) => 8,  Equ.new(15) => 15}    #3 entries, but 2 are :eql?
h.size            # => 2
h[Equ.new(27)]    # => 15

Note: The commonly used Ruby-class Set also relies on Hash-key-comparison.

equal? (object identity comparison)
Ruby uses :equal? to check if two objects are identical. This method (of class BasicObject) is not supposed to be overwritten.

obj = obj2 = 'a'
obj.equal? obj2       # => true
obj.equal? obj.dup    # => false

'Property does not exist on type 'never'

In my case (I'm using typescript) I was trying to simulate response with fake data where the data is assigned later on. My first attempt was with:

let response = {status: 200, data: []};

and later, on the assignment of the fake data it starts complaining that it is not assignable to type 'never[]'. Then I defined the response like follows and it accepted it..

let dataArr: MyClass[] = [];
let response = {status: 200, data: dataArr};

and assigning of the fake data:

response.data = fakeData;

How can I use Guzzle to send a POST request in JSON?

@user3379466 is correct, but here I rewrite in full:

-package that you need:

 "require": {
    "php"  : ">=5.3.9",
    "guzzlehttp/guzzle": "^3.8"
},

-php code (Digest is a type so pick different type if you need to, i have to include api server for authentication in this paragraph, some does not need to authenticate. If you use json you will need to replace any text 'xml' with 'json' and the data below should be a json string too):

$client = new Client('https://api.yourbaseapiserver.com/incidents.xml', array('version' => 'v1.3', 'request.options' => array('headers' => array('Accept' => 'application/vnd.yourbaseapiserver.v1.1+xml', 'Content-Type' => 'text/xml'), 'auth' => array('[email protected]', 'password', 'Digest'),)));

_x000D_
_x000D_
$url          = "https://api.yourbaseapiserver.com/incidents.xml";_x000D_
        _x000D_
$data = '<incident>_x000D_
<name>Incident Title2a</name>_x000D_
<priority>Medium</priority>_x000D_
<requester><email>[email protected]</email></requester>_x000D_
<description>description2a</description>_x000D_
</incident>';
_x000D_
_x000D_
_x000D_

    $request = $client->post($url, array('content-type' => 'application/xml',));

    $request->setBody($data); #set body! this is body of request object and not a body field in the header section so don't be confused.

    $response = $request->send(); #you must do send() method!
    echo $response->getBody(); #you should see the response body from the server on success
    die;

--- Solution for * Guzzle 6 * --- -package that you need:

 "require": {
    "php"  : ">=5.5.0",
    "guzzlehttp/guzzle": "~6.0"
},

$client = new Client([
                             // Base URI is used with relative requests
                             'base_uri' => 'https://api.compay.com/',
                             // You can set any number of default request options.
                             'timeout'  => 3.0,
                             'auth'     => array('[email protected]', 'dsfddfdfpassword', 'Digest'),
                             'headers' => array('Accept'        => 'application/vnd.comay.v1.1+xml',
                                                'Content-Type'  => 'text/xml'),
                         ]);

$url = "https://api.compay.com/cases.xml";
    $data string variable is defined same as above.


    // Provide the body as a string.
    $r = $client->request('POST', $url, [
        'body' => $data
    ]);

    echo $r->getBody();
    die;

How do I resolve git saying "Commit your changes or stash them before you can merge"?

I tried the first answer: git stash with the highest score but the error message still popped up, and then I found this article to commit the changes instead of stash 'Reluctant Commit'

and the error message disappeared finally:

1: git add .

2: git commit -m "this is an additional commit"

3: git checkout the-other-file-name

then it worked. hope this answer helps.:)

How can I start an interactive console for Perl?

I think you're asking about a REPL (Read, Evaluate, Print, Loop) interface to perl. There are a few ways to do this:

  • Matt Trout has an article that describes how to write one
  • Adriano Ferreira has described some options
  • and finally, you can hop on IRC at irc.perl.org and try out one of the eval bots in many of the popular channels. They will evaluate chunks of perl that you pass to them.

Is it safe to shallow clone with --depth 1, create commits, and pull updates again?

See some of the answers to my similar question why-cant-i-push-from-a-shallow-clone and the link to the recent thread on the git list.

Ultimately, the 'depth' measurement isn't consistent between repos, because they measure from their individual HEADs, rather than (a) your Head, or (b) the commit(s) you cloned/fetched, or (c) something else you had in mind.

The hard bit is getting one's Use Case right (i.e. self-consistent), so that distributed, and therefore probably divergent repos will still work happily together.

It does look like the checkout --orphan is the right 'set-up' stage, but still lacks clean (i.e. a simple understandable one line command) guidance on the "clone" step. Rather it looks like you have to init a repo, set up a remote tracking branch (you do want the one branch only?), and then fetch that single branch, which feels long winded with more opportunity for mistakes.

Edit: For the 'clone' step see this answer

What is a segmentation fault?

According to Wikipedia:

A segmentation fault occurs when a program attempts to access a memory location that it is not allowed to access, or attempts to access a memory location in a way that is not allowed (for example, attempting to write to a read-only location, or to overwrite part of the operating system).

Adding a regression line on a ggplot

The simple solution using geom_abline:

geom_abline(slope = coef(data.lm)[[2]], intercept = coef(data.lm)[[1]])

Where data.lm is an lm object, and coef(data.lm) looks something like this:

> coef(data.lm)
(Intercept)    DepDelay 
  -2.006045    1.025109 

The numeric indexing assumes that (Intercept) is listed first, which is the case if the model includes an intercept. If you have some other linear model object, just plug in the slope and intercept values similarly.

How can I get the data type of a variable in C#?

check out one of the simple way to do this

// Read string from console
        string line = Console.ReadLine(); 
        int valueInt;
        float valueFloat;
        if (int.TryParse(line, out valueInt)) // Try to parse the string as an integer
        {
            Console.Write("This input is of type Integer.");
        }
        else if (float.TryParse(line, out valueFloat)) 
        {
            Console.Write("This input is of type Float.");
        }
        else
        {
            Console.WriteLine("This input is of type string.");
        }

Difference between Inheritance and Composition

Are Composition and Inheritance the same?

They are not same.

Composition : It enables a group of objects have to be treated in the same way as a single instance of an object. The intent of a composite is to "compose" objects into tree structures to represent part-whole hierarchies

Inheritance: A class inherits fields and methods from all its superclasses, whether direct or indirect. A subclass can override methods that it inherits, or it can hide fields or methods that it inherits.

If I want to implement the composition pattern, how can I do that in Java?

Wikipedia article is good enough to implement composite pattern in java.

enter image description here

Key Participants:

Component:

  1. Is the abstraction for all components, including composite ones
  2. Declares the interface for objects in the composition

Leaf:

  1. Represents leaf objects in the composition
  2. Implements all Component methods

Composite:

  1. Represents a composite Component (component having children)
  2. Implements methods to manipulate children
  3. Implements all Component methods, generally by delegating them to its children

Code example to understand Composite pattern:

import java.util.List;
import java.util.ArrayList;

interface Part{
    public double getPrice();
    public String getName();
}
class Engine implements Part{
    String name;
    double price;
    public Engine(String name,double price){
        this.name = name;
        this.price = price;
    }
    public double getPrice(){
        return price;
    }
    public String getName(){
        return name;
    }
}
class Trunk implements Part{
    String name;
    double price;
    public Trunk(String name,double price){
        this.name = name;
        this.price = price;
    }
    public double getPrice(){
        return price;
    }
    public String getName(){
        return name;
    }
}
class Body implements Part{
    String name;
    double price;
    public Body(String name,double price){
        this.name = name;
        this.price = price;
    }
    public double getPrice(){
        return price;
    }
    public String getName(){
        return name;
    }
}
class Car implements Part{
    List<Part> parts;
    String name;

    public Car(String name){
        this.name = name;
        parts = new ArrayList<Part>();
    }
    public void addPart(Part part){
        parts.add(part);
    }
    public String getName(){
        return name;
    }
    public String getPartNames(){
        StringBuilder sb = new StringBuilder();
        for ( Part part: parts){
            sb.append(part.getName()).append(" ");
        }
        return sb.toString();
    }
    public double getPrice(){
        double price = 0;
        for ( Part part: parts){
            price += part.getPrice();
        }
        return price;
    }   
}

public class CompositeDemo{
    public static void main(String args[]){
        Part engine = new Engine("DiselEngine",15000);
        Part trunk = new Trunk("Trunk",10000);
        Part body = new Body("Body",12000);

        Car car = new Car("Innova");
        car.addPart(engine);
        car.addPart(trunk);
        car.addPart(body);

        double price = car.getPrice();

        System.out.println("Car name:"+car.getName());
        System.out.println("Car parts:"+car.getPartNames());
        System.out.println("Car price:"+car.getPrice());
    }

}

output:

Car name:Innova
Car parts:DiselEngine Trunk Body
Car price:37000.0

Explanation:

  1. Part is a leaf
  2. Car contains many Parts
  3. Different Parts of the car have been added to Car
  4. The price of Car = sum of ( Price of each Part )

Refer to below question for Pros and Cons of Composition and Inheritance.

Prefer composition over inheritance?

Call async/await functions in parallel

    // A generic test function that can be configured 
    // with an arbitrary delay and to either resolve or reject
    const test = (delay, resolveSuccessfully) => new Promise((resolve, reject) => setTimeout(() => {
        console.log(`Done ${ delay }`);
        resolveSuccessfully ? resolve(`Resolved ${ delay }`) : reject(`Reject ${ delay }`)
    }, delay));

    // Our async handler function
    const handler = async () => {
        // Promise 1 runs first, but resolves last
        const p1 = test(10000, true);
        // Promise 2 run second, and also resolves
        const p2 = test(5000, true);
        // Promise 3 runs last, but completes first (with a rejection) 
        // Note the catch to trap the error immediately
        const p3 = test(1000, false).catch(e => console.log(e));
        // Await all in parallel
        const r = await Promise.all([p1, p2, p3]);
        // Display the results
        console.log(r);
    };

    // Run the handler
    handler();
    /*
    Done 1000
    Reject 1000
    Done 5000
    Done 10000
    */

Whilst setting p1, p2 and p3 is not strictly running them in parallel, they do not hold up any execution and you can trap contextual errors with a catch.

Sending Email in Android using JavaMail API without using the default/built-in app

For those who want to use JavaMail with Kotlin in 2020:

First: Add these dependencies to your build.gradle file (official JavaMail Maven Dependencies)

implementation 'com.sun.mail:android-mail:1.6.5'

implementation 'com.sun.mail:android-activation:1.6.5'

implementation "org.bouncycastle:bcmail-jdk15on:1.65"

implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.7"

implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.7"

BouncyCastle is for security reasons.

Second: Add these permissions to your AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Third: When using SMTP, create a Config file

object Config {
    const val EMAIL_FROM = "[email protected]"
    const val PASS_FROM = "Your_Sender_Password"

    const val EMAIL_TO = "[email protected]"
}

Fourth: Create your Mailer Object

object Mailer {

init {
    Security.addProvider(BouncyCastleProvider())
}

private fun props(): Properties = Properties().also {
        // Smtp server
        it["mail.smtp.host"] = "smtp.gmail.com"
        // Change when necessary
        it["mail.smtp.auth"] = "true"
        it["mail.smtp.port"] = "465"
        // Easy and fast way to enable ssl in JavaMail
        it["mail.smtp.ssl.enable"] = true
    }

// Dont ever use "getDefaultInstance" like other examples do!
private fun session(emailFrom: String, emailPass: String): Session = Session.getInstance(props(), object : Authenticator() {
    override fun getPasswordAuthentication(): PasswordAuthentication {
        return PasswordAuthentication(emailFrom, emailPass)
    }
})

private fun builtMessage(firstName: String, surName: String): String {
    return """
            <b>Name:</b> $firstName  <br/>
            <b>Surname:</b> $surName <br/>
        """.trimIndent()
}

private fun builtSubject(issue: String, firstName: String, surName: String):String {
    return """
            $issue | $firstName, $surName
        """.trimIndent()
}

private fun sendMessageTo(emailFrom: String, session: Session, message: String, subject: String) {
    try {
        MimeMessage(session).let { mime ->
            mime.setFrom(InternetAddress(emailFrom))
            // Adding receiver
            mime.addRecipient(Message.RecipientType.TO, InternetAddress(Config.EMAIL_TO))
            // Adding subject
            mime.subject = subject
            // Adding message
            mime.setText(message)
            // Set Content of Message to Html if needed
            mime.setContent(message, "text/html")
            // send mail
            Transport.send(mime)
        }

    } catch (e: MessagingException) {
        Log.e("","") // Or use timber, it really doesn't matter
    }
}

fun sendMail(firstName: String, surName: String) {
        // Open a session
        val session = session(Config.EMAIL_FROM, Config.PASSWORD_FROM)

        // Create a message
        val message = builtMessage(firstName, surName)

        // Create subject
        val subject = builtSubject(firstName, surName)

        // Send Email
        CoroutineScope(Dispatchers.IO).launch { sendMessageTo(Config.EMAIL_FROM, session, message, subject) }
}

Note

Foreach loop in java for a custom object list

If this code fails to operate on every item in the list, it must be because something is throwing an exception before you have completed the list; the likeliest candidate is the method called "insertOrThrow". You could wrap that call in a try-catch structure to handle the exception for whichever items are failing without exiting the loop and the method prematurely.

Bootstrap modal appearing under background

This worked for me:

sass: 
  .modal-backdrop
    display: none
  #yourModal.modal.fade.in
    background: rgba(0, 0, 0, 0.5)

How to parse XML using vba

Update

The procedure presented below gives an example of parsing XML with VBA using the XML DOM objects. Code is based on a beginners guide of the XML DOM.

Public Sub LoadDocument()
    Dim xDoc As MSXML.DOMDocument
    Set xDoc = New MSXML.DOMDocument
    xDoc.validateOnParse = False
    If xDoc.Load("C:\My Documents\sample.xml") Then
        ' The document loaded successfully.
        ' Now do something intersting.
        DisplayNode xDoc.childNodes, 0
    Else
        ' The document failed to load.
        ' See the previous listing for error information.
    End If
End Sub

Public Sub DisplayNode(ByRef Nodes As MSXML.IXMLDOMNodeList, _
   ByVal Indent As Integer)

   Dim xNode As MSXML.IXMLDOMNode
   Indent = Indent + 2

   For Each xNode In Nodes
      If xNode.nodeType = NODE_TEXT Then
         Debug.Print Space$(Indent) & xNode.parentNode.nodeName & _
            ":" & xNode.nodeValue
      End If

      If xNode.hasChildNodes Then
         DisplayNode xNode.childNodes, Indent
      End If
   Next xNode
End Sub

Nota Bene - This initial answer shows the simplest possible thing I could imagine (at the time I was working on a very specific issue) . Naturally using the XML facilities built into the VBA XML Dom would be much better. See the updates above.

Original Response

I know this is a very old post but I wanted to share my simple solution to this complicated question. Primarily I've used basic string functions to access the xml data.

This assumes you have some xml data (in the temp variable) that has been returned within a VBA function. Interestingly enough one can also see how I am linking to an xml web service to retrieve the value. The function shown in the image also takes a lookup value because this Excel VBA function can be accessed from within a cell using = FunctionName(value1, value2) to return values via the web service into a spreadsheet.

sample function


openTag = ""
closeTag = "" 

' Locate the position of the enclosing tags startPos = InStr(1, temp, openTag) endPos = InStr(1, temp, closeTag) startTagPos = InStr(startPos, temp, ">") + 1 ' Parse xml for returned value Data = Mid(temp, startTagPos, endPos - startTagPos)

Eclipse: Error ".. overlaps the location of another project.." when trying to create new project

Go to the actual FILE menu and create a new general project.

If the project type isn't recognized, preventing one of these import methods from working, then try this. Once you add the generic project, you can then add support for whatever language you require.

SignalR - Sending a message to a specific user using (IUserIdProvider) *NEW 2.0.0*

Old thread, but just came across this in a sample:

services.AddSignalR()
            .AddAzureSignalR(options =>
        {
            options.ClaimsProvider = context => new[]
            {
                new Claim(ClaimTypes.NameIdentifier, context.Request.Query["username"])
            };
        });

How do I assert my exception message with JUnit Test annotation?

You could use the @Rule annotation with ExpectedException, like this:

@Rule
public ExpectedException expectedEx = ExpectedException.none();

@Test
public void shouldThrowRuntimeExceptionWhenEmployeeIDisNull() throws Exception {
    expectedEx.expect(RuntimeException.class);
    expectedEx.expectMessage("Employee ID is null");

    // do something that should throw the exception...
    System.out.println("=======Starting Exception process=======");
    throw new NullPointerException("Employee ID is null");
}

Note that the example in the ExpectedException docs is (currently) wrong - there's no public constructor, so you have to use ExpectedException.none().

How do I exit a while loop in Java?

break is what you're looking for:

while (true) {
    if (obj == null) break;
}

alternatively, restructure your loop:

while (obj != null) {
    // do stuff
}

or:

do {
    // do stuff
} while (obj != null);

Dynamically create Bootstrap alerts box through JavaScript

I created this VERY SIMPLE and basic plugin:

(function($){
    $.fn.extend({
        bs_alert: function(message, title){
            var cls='alert-danger';
            var html='<div class="alert '+cls+' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>';
            if(typeof title!=='undefined' &&  title!==''){
                html+='<h4>'+title+'</h4>';
            }
            html+='<span>'+message+'</span></div>';
            $(this).html(html);
        },
        bs_warning: function(message, title){
            var cls='alert-warning';
            var html='<div class="alert '+cls+' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>';
            if(typeof title!=='undefined' &&  title!==''){
                html+='<h4>'+title+'</h4>';
            }
            html+='<span>'+message+'</span></div>';
            $(this).html(html);
        },
        bs_info: function(message, title){
            var cls='alert-info';
            var html='<div class="alert '+cls+' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>';
            if(typeof title!=='undefined' &&  title!==''){
                html+='<h4>'+title+'</h4>';
            }
            html+='<span>'+message+'</span></div>';
            $(this).html(html);
        }
    });
})(jQuery);

Usage is

<div id="error_container"></div>
<script>
$('#error_container').bs_alert('YOUR ERROR MESSAGE HERE !!', 'title');
</script>

first plugin EVER and it can be easily made better

What does git rev-parse do?

git rev-parse Also works for getting the current branch name using the --abbrev-ref flag like:

git rev-parse --abbrev-ref HEAD

How to execute XPath one-liners from shell?

Sorry to be yet another voice in the fray. I tried all the tools in this thread and found none of them to be satisfactory for my needs, so I wrote my own. You can find it here: https://github.com/charmparticle/xpe

It's been uploaded to pypi, so you can easily install it with pip3 like so:

sudo pip3 install xpe

Once installed, you can use it to run xpath expressions against various kinds of input with the same level of flexibility you would get from using xpaths in selenium or javascript. Yeah, you can use xpaths against HTML with this. One caviat: if you run it against xml that has the encoding specified on the first line, it will fail. The solution for now is to pipe it to sed to remove the first line like so:

cat specified_encoding.xml | sed '1d' | xpe '//text()'

I may post an update at some point to address this issue to avoid the need for sed.

'pip' is not recognized as an internal or external command

You need to add the path of your pip installation to your PATH system variable. By default, pip is installed to C:\Python34\Scripts\pip (pip now comes bundled with new versions of python), so the path "C:\Python34\Scripts" needs to be added to your PATH variable.

To check if it is already in your PATH variable, type echo %PATH% at the CMD prompt

To add the path of your pip installation to your PATH variable, you can use the Control Panel or the setx command. For example:

setx PATH "%PATH%;C:\Python34\Scripts"

Note: According to the official documentation, "[v]ariables set with setx variables are available in future command windows only, not in the current command window". In particular, you will need to start a new cmd.exe instance after entering the above command in order to utilize the new environment variable.

Thanks to Scott Bartell for pointing this out.

how to get the host url using javascript from the current page

Keep in mind before use window and location

1.use window and location in client side render (Note:don't use in ssr)

window.location.host; 

or

var host = window.location.protocol + "//" + window.location.host;

2.server side render

if your using nuxt.js(vue) or next.js(react) refer docs

For nuxt js Framework

req.headers.host

code:

async asyncData ({ req, res }) {
        if (process.server) {
         return { host: req.headers.host }
        }

Code In router:

export function createRouter (ssrContext) {



console.log(ssrContext.req.headers.host)   
      return new Router({
        middleware: 'route',
        routes:checkRoute(ssrContext),
        mode: 'history'
      })
    }

For next.js framework

Home.getInitalProps = async(context) => {
   const { req, query, res, asPath, pathname } = context;
   if (req) {
      let host = req.headers.host // will give you localhost:3000
     }
  }

For node.js users

var os = require("os");
var hostname = os.hostname();

or

request.headers.host

For laravel users

public function yourControllerFun(Request $request) {

    $host = $request->getHttpHost();

  

    dd($host);

}

or

directly use in web.php

Request::getHost();

Note :

both csr and ssr app you manually check example ssr render

if(req.server){
host=req.host;
}
if(req.client){
host=window.location.host; 
}

How to Programmatically Add Views to Views

One more way to add view from Activity

ViewGroup rootLayout = findViewById(android.R.id.content);
rootLayout.addView(view);

GZIPInputStream reading line by line

here is with one line

try (BufferedReader br = new BufferedReader(
        new InputStreamReader(
           new GZIPInputStream(
              new FileInputStream(
                 "F:/gawiki-20090614-stub-meta-history.xml.gz"))))) 
     {br.readLine();}

Convert a float64 to an int in Go

If its simply from float64 to int, this should work

package main

import (
    "fmt"
)

func main() {
    nf := []float64{-1.9999, -2.0001, -2.0, 0, 1.9999, 2.0001, 2.0}

    //round
    fmt.Printf("Round : ")
    for _, f := range nf {
        fmt.Printf("%d ", round(f))
    }
    fmt.Printf("\n")

    //rounddown ie. math.floor
    fmt.Printf("RoundD: ")
    for _, f := range nf {
        fmt.Printf("%d ", roundD(f))
    }
    fmt.Printf("\n")

    //roundup ie. math.ceil
    fmt.Printf("RoundU: ")
    for _, f := range nf {
        fmt.Printf("%d ", roundU(f)) 
    }
    fmt.Printf("\n")

}

func roundU(val float64) int {
    if val > 0 { return int(val+1.0) }
    return int(val)
}

func roundD(val float64) int {
    if val < 0 { return int(val-1.0) }
    return int(val)
}

func round(val float64) int {
    if val < 0 { return int(val-0.5) }
    return int(val+0.5)
}

Outputs:

Round : -2 -2 -2 0 2 2 2 
RoundD: -2 -3 -3 0 1 2 2 
RoundU: -1 -2 -2 0 2 3 3 

Here's the code in the playground - https://play.golang.org/p/HmFfM6Grqh

How to access List elements

Tried list[:][0] to show all first member of each list inside list is not working. Result is unknowingly will same as list[0][:]

So i use list comprehension like this:

[i[0] for i in list] which return first element value for each list inside list.

How to get the selected radio button’s value?

This works with any explorer.

document.querySelector('input[name="genderS"]:checked').value;

This is a simple way to get the value of any input type. You also do not need to include jQuery path.

Create an ISO date object in javascript

Try using the ISO string

var isodate = new Date().toISOString()

See also: method definition at MDN.

CSS '>' selector; what is it?

As others have said, it's a direct child, but it's worth noting that this is different to just leaving a space... a space is for any descendant.

<div>
  <span>Some text</span>
</div>

div>span would match this, but it would not match this:

<div>
  <p><span>Some text</span></p>
</div>

To match that, you could do div>p>span or div span.

Changing cursor to waiting in javascript/jquery

You don't need JavaScript for this. You can change the cursor to anything you want using CSS :

selector {
    cursor: url(myimage.jpg), auto;
}

See here for browser support as there are some subtle differences depending on browser

Avoiding NullPointerException in Java

I highly disregard answers that suggest using the null objects in every situation. This pattern may break the contract and bury problems deeper and deeper instead of solving them, not mentioning that used inappropriately will create another pile of boilerplate code that will require future maintenance.

In reality if something returned from a method can be null and the calling code has to make decision upon that, there should an earlier call that ensures the state.

Also keep in mind, that null object pattern will be memory hungry if used without care. For this - the instance of a NullObject should be shared between owners, and not be an unigue instance for each of these.

Also I would not recommend using this pattern where the type is meant to be a primitive type representation - like mathematical entities, that are not scalars: vectors, matrices, complex numbers and POD(Plain Old Data) objects, which are meant to hold state in form of Java built-in types. In the latter case you would end up calling getter methods with arbitrary results. For example what should a NullPerson.getName() method return?

It's worth considering such cases in order to avoid absurd results.

How to change the minSdkVersion of a project?

This is what worked for me:

In the build.gradle file, setting the minSdkVersion under defaultConfig:

enter image description here

Good Luck...

Vue component event after render

updated might be what you're looking for. https://vuejs.org/v2/api/#updated

What is the difference between JDK and JRE?

If you want to run Java programs, but not develop them, download the Java Run-time Environment, or JRE. If you want to develop them, download the Java Development kit, or JDK

JDK

Let's called JDK is a kit, which include what are those things need to developed and run java applications.

JDK is given as development environment for building applications, component s and applets.

JRE

It contains everything you need to run Java applications in compiled form. You don't need any libraries and other stuffs. All things you need are compiled.

JRE is can not used for development, only used for run the applications.

Set min-width either by content or 200px (whichever is greater) together with max-width

The problem is that flex: 1 sets flex-basis: 0. Instead, you need

.container .box {
  min-width: 200px;
  max-width: 400px;
  flex-basis: auto; /* default value */
  flex-grow: 1;
}

_x000D_
_x000D_
.container {_x000D_
  display: -webkit-flex;_x000D_
  display: flex;_x000D_
  -webkit-flex-wrap: wrap;_x000D_
  flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
.container .box {_x000D_
  -webkit-flex-grow: 1;_x000D_
  flex-grow: 1;_x000D_
  min-width: 100px;_x000D_
  max-width: 400px;_x000D_
  height: 200px;_x000D_
  background-color: #fafa00;_x000D_
  overflow: hidden;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What does "commercial use" exactly mean?

"Commercial use" in cases like this is actually just a shorthand to indicate that the product is dual-licensed under both an open source and a traditional paid-for commercial license.

Any "true" open source license will not discriminate against commercial use. (See clause 6 of the Open Source Definition.) However, open source licenses like the GPL contain clauses that are incompatible with most companies' approach to commercial software (since the GPL requires that you make your source code available if you incorporate GPL'ed code into your product).

Duel-licensing is a way to accommodate this and also provides a revenue stream for the company providing the software. For users that don't mind the restrictions of the GPL and don't need support, the product is available under an open source license. For users for whom the GPL's restrictions would be incompatible with their business model, and for users that do need support, a commercial license is available.

You gave the specific example of the Screwturn wiki, which is dual-licensed under the GPL and a commercial license. Under the terms of the GPL (i.e., without getting a "commercial" license), you can do the following:

  • Use it internally as much as you want (see here)
  • Run it on your internal servers for external users / clients / customers, or run it on your internal servers for paying clients if you're an ISP / hosting provider. (If Screwturn were licensed under the AGPL instead of the GPL, that might restrict this.)
  • Distribute it to others, either free of charge or for a payment that covers the shipping, as long as you're willing to also distribute the source code
  • Incorporate it into your product, as long as you're willing to also distribute the source code, and as long as either (a) it remains a separate program that you merely aggregate with your product or (b) you release the source code to your product under an open source license compatible with the GPL

In other words, there's a lot that you can do without getting a commercial license. This is especially true for web-based software, since people can use web-based software without it being distributed to them. Screwturn's web site even acknowledges this: they state that the commercial license is for "either integrating it in a commercial application, or using it in an enterprise environment where free software is not allowed," not for any use related to commerce.

All of the preceding is merely my understanding and is not intended to be legal advice. Consult your lawyer to be certain.

How to get PID of process I've just started within java program?

Since Java 9 class Process has new method long pid(), so it is as simple as

ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "path");
try {
    Process p = pb.start();
    long pid = p.pid();      
} catch (IOException ex) {
    // ...
}

jQuery Event Keypress: Which key was pressed?

Actually this is better:

 var code = e.keyCode || e.which;
 if(code == 13) { //Enter keycode
   //Do something
 }

What is the native keyword in Java for?

NATIVE is Non access modifier.it can be applied only to METHOD. It indicates the PLATFORM-DEPENDENT implementation of method or code.

Better way to find control in ASP.NET

The following example defines a Button1_Click event handler. When invoked, this handler uses the FindControl method to locate a control with an ID property of TextBox2 on the containing page. If the control is found, its parent is determined using the Parent property and the parent control's ID is written to the page. If TextBox2 is not found, "Control Not Found" is written to the page.

private void Button1_Click(object sender, EventArgs MyEventArgs)
{
      // Find control on page.
      Control myControl1 = FindControl("TextBox2");
      if(myControl1!=null)
      {
         // Get control's parent.
         Control myControl2 = myControl1.Parent;
         Response.Write("Parent of the text box is : " + myControl2.ID);
      }
      else
      {
         Response.Write("Control not found");
      }
}

Easiest way to pass an AngularJS scope variable from directive to controller?

Edited on 2014/8/25: Here was where I forked it.

Thanks @anvarik.

Here is the JSFiddle. I forgot where I forked this. But this is a good example showing you the difference between = and @

<div ng-controller="MyCtrl">
    <h2>Parent Scope</h2>
    <input ng-model="foo"> <i>// Update to see how parent scope interacts with component scope</i>    
    <br><br>
    <!-- attribute-foo binds to a DOM attribute which is always
    a string. That is why we are wrapping it in curly braces so
    that it can be interpolated. -->
    <my-component attribute-foo="{{foo}}" binding-foo="foo"
        isolated-expression-foo="updateFoo(newFoo)" >
        <h2>Attribute</h2>
        <div>
            <strong>get:</strong> {{isolatedAttributeFoo}}
        </div>
        <div>
            <strong>set:</strong> <input ng-model="isolatedAttributeFoo">
            <i>// This does not update the parent scope.</i>
        </div>
        <h2>Binding</h2>
        <div>
            <strong>get:</strong> {{isolatedBindingFoo}}
        </div>
        <div>
            <strong>set:</strong> <input ng-model="isolatedBindingFoo">
            <i>// This does update the parent scope.</i>
        </div>
        <h2>Expression</h2>    
        <div>
            <input ng-model="isolatedFoo">
            <button class="btn" ng-click="isolatedExpressionFoo({newFoo:isolatedFoo})">Submit</button>
            <i>// And this calls a function on the parent scope.</i>
        </div>
    </my-component>
</div>
var myModule = angular.module('myModule', [])
    .directive('myComponent', function () {
        return {
            restrict:'E',
            scope:{
                /* NOTE: Normally I would set my attributes and bindings
                to be the same name but I wanted to delineate between
                parent and isolated scope. */                
                isolatedAttributeFoo:'@attributeFoo',
                isolatedBindingFoo:'=bindingFoo',
                isolatedExpressionFoo:'&'
            }        
        };
    })
    .controller('MyCtrl', ['$scope', function ($scope) {
        $scope.foo = 'Hello!';
        $scope.updateFoo = function (newFoo) {
            $scope.foo = newFoo;
        }
    }]);

How to change checkbox's border style in CSS?

Styling checkboxes (and many other input elements for that mater) is not really possible with pure css if you want to drastically change the visual appearance.

Your best bet is to implement something like jqTransform does which actually replaces you inputs with images and applies javascript behaviour to it to mimic a checkbox (or other element for that matter)

How can I generate a unique ID in Python?

Perhaps uuid.uuid4() might do the job. See uuid for more information.

How can I obtain the element-wise logical NOT of a pandas Series?

In support to the excellent answers here, and for future convenience, there may be a case where you want to flip the truth values in the columns and have other values remain the same (nan values for instance)

In[1]: series = pd.Series([True, np.nan, False, np.nan])
In[2]: series = series[series.notna()] #remove nan values
 
In[3]: series # without nan                                            
Out[3]: 
0     True
2    False
dtype: object

# Out[4] expected to be inverse of Out[3], pandas applies bitwise complement 
# operator instead as in `lambda x : (-1*x)-1`

In[4]: ~series
Out[4]: 
0    -2
2    -1
dtype: object

as a simple non-vectorized solution you can just, 1. check types2. inverse bools

In[1]: series = pd.Series([True, np.nan, False, np.nan])

In[2]: series = series.apply(lambda x : not x if x is bool else x)
Out[2]: 
Out[2]: 
0     True
1      NaN
2    False
3      NaN
dtype: object

How to change value for innodb_buffer_pool_size in MySQL on Mac OS?

In the earlier versions of MySQL ( < 5.7.5 ) the only way to set

'innodb_buffer_pool_size'

variable was by writing it to my.cnf (for linux) and my.ini (for windows) under [mysqld] section :

[mysqld]

innodb_buffer_pool_size = 2147483648

You need to restart your mysql server to have it's effect in action.

UPDATE :

As of MySQL 5.7.5, the innodb_buffer_pool_size configuration option can be set dynamically using a SET statement, allowing you to resize the buffer pool without restarting the server. For example:

mysql> SET GLOBAL innodb_buffer_pool_size=402653184;

Reference : https://dev.mysql.com/doc/refman/5.7/en/innodb-buffer-pool-resize.html

What is the precise meaning of "ours" and "theirs" in git?

I'll post my memo here, because I have to come back here again and again.

SCENARIO 1. Normal developer: You are developer who can't merge to master and have to play with feature branches only.

Case 1: master is a king. You want to refresh your feature branch (= rebase to master), because master contains new updates of dependencies and you want to overwrite your modest changes.

git checkout master
git pull

git checkout feature
git rebase -X ours master

Case 2: you are a king. You want to rebase your feature branch to master changes. But you did more than your colleagues had and want to use your own changes in a priority.

git checkout master
git pull

git checkout feature
git rebase -X theirs master

IMPORTANT: As you can see normal developers should prefer rebase and repeat it every morning like exercises/coffee.

SCENARIO 2. Merging-sensei: You are a team-lead and want to merge other branches and push a merged result directly to a master. master is a branch you will change.

Case 1: master is a king You want to merge third-party branch, but master is a priority. feature is a branch that your senior did.

git checkout feature
git pull

git checkout master
git merge -X ours feature

Case 2: new changes is a king When your senior developer released a cool feature and you want to overwrite the old s**t in the master branch.

git checkout feature
git pull

git checkout master
git merge -X theirs feature

REMEMBER: To remember in a midnight which one to choose: master is ours ALWAYS. And theirs is a feature that theirs have done.

VBA EXCEL Multiple Nested FOR Loops that Set two variable for expression

I can't get to your google docs file at the moment but there are some issues with your code that I will try to address while answering

Sub stituterangersNEW()
Dim t As Range
Dim x As Range
Dim dify As Boolean
Dim difx As Boolean
Dim time2 As Date
Dim time1 As Date

    'You said time1 doesn't change, so I left it in a singe cell.
    'If that is not correct, you will have to play with this some more.
    time1 = Range("A6").Value

    'Looping through each of our output cells.
    For Each t In Range("B7:E9") 'Change these to match your real ranges.

        'Looping through each departure date/time.
        '(Only one row in your example. This can be adjusted if needed.)
        For Each x In Range("B2:E2") 'Change these to match your real ranges.
            'Check to see if our dep time corresponds to
            'the matching column in our output
            If t.Column = x.Column Then
                'If it does, then check to see what our time value is
                If x > 0 Then
                    time2 = x.Value
                    'Apply the change to the output cell.
                    t.Value = time1 - time2
                    'Exit out of this loop and move to the next output cell.
                    Exit For
                End If
            End If
            'If the columns don't match, or the x value is not a time
            'then we'll move to the next dep time (x)
        Next x
    Next t

End Sub

EDIT

I changed you worksheet to play with (see above for the new Sub). This probably does not suite your needs directly, but hopefully it will demonstrate the conept behind what I think you want to do. Please keep in mind that this code does not follow all the coding best preactices I would recommend (e.g. validating the time is actually a TIME and not some random other data type).

     A                      B                   C                   D                  E
1    LOAD_NUMBER            1                   2                   3                  4
2    DEPARTURE_TIME_DATE    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 20:00                
4    Dry_Refrig 7585.1  0   10099.8 16700
6    1/4/2012 19:30

Using the sub I got this output:

    A           B             C             D             E
7   Friday      1272:00:00    1272:00:00    1272:00:00    1271:30:00
8   Saturday    1272:00:00    1272:00:00    1272:00:00    1271:30:00
9   Thursday    1272:00:00    1272:00:00    1272:00:00    1271:30:00

Grep only the first match and stop

You can use below command if you want to print entire line and file name if the occurrence of particular word in current directory you are searching.

grep -m 1 -r "Not caching" * | head -1

How to do a Jquery Callback after form submit?

I just did this -

 $("#myform").bind('ajax:complete', function() {

         // tasks to do 


   });

And things worked perfectly .

See this api documentation for more specific details.

Full width layout with twitter bootstrap

Update:

Bootstrap 3 has been released since this question was originally answered in January, so if you are a BS3 user, please refer to the BS3 documentation. For those still on BS2, the original answer still applies. If you are interested in switching from 2 to 3, see the migration guide.

Original answer:

From the bootstrap 2 docs:

Make any row "fluid" by changing .row to .row-fluid. The column classes stay the exact same, making it easy to flip between fixed and fluid grids.

Code

<div class="row-fluid">
  <div class="span4">...</div>
  <div class="span8">...</div>
</div>

This, in conjunction with setting the width of your container to a fluid value, should allow you to get your desired layout.

How to use onBlur event on Angular2?

Use (eventName) for while binding event to DOM, basically () is used for event binding. Also use ngModel to get two way binding for myModel variable.

Markup

<input type="text" [(ngModel)]="myModel" (blur)="onBlurMethod()">

Code

export class AppComponent { 
  myModel: any;
  constructor(){
    this.myModel = '123';
  }
  onBlurMethod(){
   alert(this.myModel) 
  }
}

Demo

Alternative(not preferable)

<input type="text" #input (blur)="onBlurMethod($event.target.value)">

Demo


For model driven form to fire validation on blur, you could pass updateOn parameter.

ctrl = new FormControl('', {
   updateOn: 'blur', //default will be change
   validators: [Validators.required]
}); 

Design Docs

Spring get current ApplicationContext

Even better than having it with @Autowired is to let it be injected via constructor. Find some arguments pro constructor injection here

@Component
public class MyClass{
  private final ApplicationContext applicationContext;

  public MyClass(ApplicationContext applicationContext){
    this.applicationContext = applicationContext;
  }

  //here will be your methods using the applicationcontext
}

Execute a PHP script from another PHP script

On the command line:

> php yourfile.php

How to beautify JSON in Python?

Try underscore-cli:

cat myfile.json | underscore print --color

It's a pretty nifty tool that can elegantly do a lot of manipulation of structured data, execute js snippets, fill templates, etc. It's ridiculously well documented, polished, and ready for serious use. And I wrote it. :)

How do you reinstall an app's dependencies using npm?

Most of the time I use the following command to achieve a complete reinstall of all the node modules (be sure you are in the project folder).

rm -rf node_modules && npm install

You can also run npm cache clean after removing the node_modules folder to be sure there aren't any cached dependencies.

ASP.Net Download file to client browser

Just a slight addition to the above solution if you are having problem with downloaded file's name...

Response.AddHeader("Content-Disposition", "attachment; filename=\"" + file.Name + "\"");

This will return the exact file name even if it contains spaces or other characters.

How do I animate constraint changes?

Working and just tested solution for Swift 3 with Xcode 8.3.3:

self.view.layoutIfNeeded()
self.calendarViewHeight.constant = 56.0

UIView.animate(withDuration: 0.5, delay: 0.0, options: UIViewAnimationOptions.curveEaseIn, animations: {
        self.view.layoutIfNeeded()
    }, completion: nil)

Just keep in mind that self.calendarViewHeight is a constraint referred to a customView (CalendarView). I called the .layoutIfNeeded() on self.view and NOT on self.calendarView

Hope this help.

How to import JsonConvert in C# application?

If you are developing a .Net Core WebApi or WebSite you dont not need to install newtownsoft.json to perform json serialization/deserealization

Just make sure that your controller method returns a JsonResult and call return Json(<objectoToSerialize>); like this example

namespace WebApi.Controllers
{
    [Produces("application/json")]
    [Route("api/Accounts")]
    public class AccountsController : Controller
    {
        // GET: api/Transaction
        [HttpGet]
        public JsonResult Get()
        {
            List<Account> lstAccounts;

            lstAccounts = AccountsFacade.GetAll();

            return Json(lstAccounts);
        }
    }
}

If you are developing a .Net Framework WebApi or WebSite you need to use NuGet to download and install the newtonsoft json package

"Project" -> "Manage NuGet packages" -> "Search for "newtonsoft json". -> click "install".

namespace WebApi.Controllers
{
    [Produces("application/json")]
    [Route("api/Accounts")]
    public class AccountsController : Controller
    {
        // GET: api/Transaction
        [HttpGet]
        public JsonResult Get()
        {
            List<Account> lstAccounts;

            lstAccounts = AccountsFacade.GetAll();

            //This line is different !! 
            return new JsonConvert.SerializeObject(lstAccounts);
        }
    }
}

More details can be found here - https://docs.microsoft.com/en-us/aspnet/core/web-api/advanced/formatting?view=aspnetcore-2.1

What is the Swift equivalent of isEqualToString in Objective-C?

Use == operator instead of isEqual

Comparing Strings

Swift provides three ways to compare String values: string equality, prefix equality, and suffix equality.

String Equality

Two String values are considered equal if they contain exactly the same characters in the same order:

let quotation = "We're a lot alike, you and I."
let sameQuotation = "We're a lot alike, you and I."
if quotation == sameQuotation {
    println("These two strings are considered equal")
}
// prints "These two strings are considered equal"
.
.
.

For more read official documentation of Swift (search Comparing Strings).

Multi-dimensional arraylist or list in C#?

You can create a list of lists

   public class MultiDimList: List<List<string>> {  }

or a Dictionary of key-accessible Lists

   public class MultiDimDictList: Dictionary<string, List<int>>  { }
   MultiDimDictList myDicList = new MultiDimDictList ();
   myDicList.Add("ages", new List<int>()); 
   myDicList.Add("Salaries", new List<int>()); 
   myDicList.Add("AccountIds", new List<int>()); 

Generic versions, to implement suggestion in comment from @user420667

  public class MultiDimList<T>: List<List<T>> {  }

and for the dictionary,

   public class MultiDimDictList<K, T>: Dictionary<K, List<T>>  { }

  // to use it, in client code
   var myDicList = new MultiDimDictList<string, int> ();
   myDicList.Add("ages", new List<T>()); 
   myDicList["ages"].Add(23);
   myDicList["ages"].Add(32);
   myDicList["ages"].Add(18);

   myDicList.Add("salaries", new List<T>());
   myDicList["salaries"].Add(80000);
   myDicList["salaries"].Add(100000);

   myDicList.Add("accountIds", new List<T>()); 
   myDicList["accountIds"].Add(321123);
   myDicList["accountIds"].Add(342653);

or, even better, ...

   public class MultiDimDictList<K, T>: Dictionary<K, List<T>>  
   {
       public void Add(K key, T addObject)
       {
           if(!ContainsKey(key)) Add(key, new List<T>());
           if (!base[key].Contains(addObject)) base[key].Add(addObject);
       }           
   }


  // and to use it, in client code
    var myDicList = new MultiDimDictList<string, int> ();
    myDicList.Add("ages", 23);
    myDicList.Add("ages", 32);
    myDicList.Add("ages", 18);
    myDicList.Add("salaries", 80000);
    myDicList.Add("salaries", 110000);
    myDicList.Add("accountIds", 321123);
    myDicList.Add("accountIds", 342653);

EDIT: to include an Add() method for nested instance:

public class NestedMultiDimDictList<K, K2, T>: 
           MultiDimDictList<K, MultiDimDictList<K2, T>>: 
{
       public void Add(K key, K2 key2, T addObject)
       {
           if(!ContainsKey(key)) Add(key, 
                  new MultiDimDictList<K2, T>());
           if (!base[key].Contains(key2)) 
               base[key].Add(key2, addObject);
       }    
}

How to add Class in <li> using wp_nav_menu() in Wordpress?

<?php
    echo preg_replace( '#<li[^>]+>#', '<li class="col-sm-4">',
            wp_nav_menu(
                    array(
                        'menu' => $nav_menu, 
                        'container'  => false,
                        'container_class'   => false,
                        'menu_class'        => false,
                        'items_wrap'        => '%3$s',
                                            'depth'             => 1,
                                            'echo'              => false
                            )
                    )
            );
?>

add new row in gridview after binding C#, ASP.net

you can try the following code

protected void Button1_Click(object sender, EventArgs e)
   {
       DataTable dt = new DataTable();

       if (dt.Columns.Count == 0)
       {
           dt.Columns.Add("PayScale", typeof(string));
           dt.Columns.Add("IncrementAmt", typeof(string));
           dt.Columns.Add("Period", typeof(string));
       }

       DataRow NewRow = dt.NewRow();
       NewRow[0] = TextBox1.Text;
       NewRow[1] = TextBox2.Text;
       dt.Rows.Add(NewRow); 
       GridView1.DataSource = dt;
       GridViewl.DataBind();
   }

here payscale,incrementamt and period are database field name.

In a Bash script, how can I exit the entire script if a certain condition occurs?

A SysOps guy once taught me the Three-Fingered Claw technique:

yell() { echo "$0: $*" >&2; }
die() { yell "$*"; exit 111; }
try() { "$@" || die "cannot $*"; }

These functions are *NIX OS and shell flavor-robust. Put them at the beginning of your script (bash or otherwise), try() your statement and code on.

Explanation

(based on flying sheep comment).

  • yell: print the script name and all arguments to stderr:
    • $0 is the path to the script ;
    • $* are all arguments.
    • >&2 means > redirect stdout to & pipe 2. pipe 1 would be stdout itself.
  • die does the same as yell, but exits with a non-0 exit status, which means “fail”.
  • try uses the || (boolean OR), which only evaluates the right side if the left one failed.

How to make Apache serve index.php instead of index.html?

As others have noted, most likely you don't have .html set up to handle php code.

Having said that, if all you're doing is using index.html to include index.php, your question should probably be 'how do I use index.php as index document?

In which case, for Apache (httpd.conf), search for DirectoryIndex and replace the line with this (will only work if you have dir_module enabled, but that's default on most installs):

DirectoryIndex index.php

If you use other directory indexes, list them in order of preference i.e.

DirectoryIndex index.php index.phtml index.html index.htm

Space between Column's children in Flutter

Just use padding to wrap it like this:

Column(
  children: <Widget>[
  Padding(
    padding: EdgeInsets.all(8.0),
    child: Text('Hello World!'),
  ),
  Padding(
    padding: EdgeInsets.all(8.0),
    child: Text('Hello World2!'),
  )
]);

You can also use Container(padding...) or SizeBox(height: x.x). The last one is the most common but it will depents of how you want to manage the space of your widgets, I like to use padding if the space is part of the widget indeed and use sizebox for lists for example.

Using varchar(MAX) vs TEXT on SQL Server

If using MS Access (especially older versions like 2003) you are forced to use TEXT datatype on SQL Server as MS Access does not recognize nvarchar(MAX) as a Memo field in Access, whereas TEXT is recognized as a Memo-field.

How can I check if the array of objects have duplicate property values?

Use array.prototype.map and array.prototype.some:

var values = [
    { name: 'someName1' },
    { name: 'someName2' },
    { name: 'someName4' },
    { name: 'someName2' }
];

var valueArr = values.map(function(item){ return item.name });
var isDuplicate = valueArr.some(function(item, idx){ 
    return valueArr.indexOf(item) != idx 
});
console.log(isDuplicate);

JSFIDDLE.

Multiple Errors Installing Visual Studio 2015 Community Edition

None of the resolutions outlined in this question solved my issue. I posted a similar question and ended up having to open a support ticket with Microsoft to get it resolved. See my answer here if none of the other suggestions help: Error Installing Visual Studio 2015 Enterprise Update 1 with Team Explorer

Remove large .pack file created by git

As loganfsmyth already stated in his answer, you need to purge git history because the files continue to exist there even after deleting them from the repo. Official GitHub docs recommend BFG which I find easier to use than filter-branch:

Deleting files from history

Download BFG from their website. Make sure you have java installed, then create a mirror clone and purge history. Make sure to replace YOUR_FILE_NAME with the name of the file you'd like to delete:

git clone --mirror git://example.com/some-big-repo.git
java -jar bfg.jar --delete-files YOUR_FILE_NAME some-big-repo.git
cd some-big-repo.git
git reflog expire --expire=now --all && git gc --prune=now --aggressive
git push

Delete a folder

Same as above but use --delete-folders

java -jar bfg.jar --delete-folders YOUR_FOLDER_NAME some-big-repo.git

Other options

BFG also allows for even fancier options (see docs) like these:

Remove all files bigger than 100M from history:

java -jar bfg.jar --strip-blobs-bigger-than 100M some-big-repo.git

Important!

When running BFG, be careful that both YOUR_FILE_NAME and YOUR_FOLDER_NAME are indeed just file/folder names. They're not paths, so something like foo/bar.jpg will not work! Instead all files/folders with the specified name will be removed from repo history, no matter which path or branch they existed.

Execute the setInterval function without delay the first time

Here's a wrapper to pretty-fy it if you need it:

(function() {
    var originalSetInterval = window.setInterval;

    window.setInterval = function(fn, delay, runImmediately) {
        if(runImmediately) fn();
        return originalSetInterval(fn, delay);
    };
})();

Set the third argument of setInterval to true and it'll run for the first time immediately after calling setInterval:

setInterval(function() { console.log("hello world"); }, 5000, true);

Or omit the third argument and it will retain its original behaviour:

setInterval(function() { console.log("hello world"); }, 5000);

Some browsers support additional arguments for setInterval which this wrapper doesn't take into account; I think these are rarely used, but keep that in mind if you do need them.

Where can I download Eclipse Android bundle?

You don't actually need the bundle as the ADT can be used with just any latest Eclipse IDE.


1. Make sure you have JDK installed.

  1. Download latest eclipse.

  2. Download latest ADT plugin ADT-XX.X.X.zip. As of this answer the current version is ADT-23.0.7.zip (More versions at http://developer.android.com/tools/sdk/eclipse-adt.html)

  3. Open Eclipse and follow the following steps:

    • Open Help > Install New Software > Add > Archive
    • Navigate to where you downloaded your ADT plugin and select it.
    • Check Developer Tools, click Next, accept any licenses and Finish
  4. After restarting Eclipse, if you are not able to open a layout file go to step 4 but instead of selecting archive add https://dl-ssl.google.com/android/eclipse/ in the Location: textbox. Press Ok, update the ADT and restart Eclipse. Close and reopen the layout files and you'll be good to go.

  5. Run the Android SDK Manager to update its components.


EDIT: The ADT plugin has long since been deprecated. For more information visit this link:

https://developer.android.com/studio/tools/sdk/eclipse-adt.html

Check if input is number or letter javascript

A better(error-free) code would be like:

function isReallyNumber(data) {
    return typeof data === 'number' && !isNaN(data);
}

This will handle empty strings as well. Another reason, isNaN("12") equals to false but "12" is a string and not a number, so it should result to true. Lastly, a bonus link which might interest you.

How do I make the method return type generic?

Based on the same idea as Super Type Tokens, you could create a typed id to use instead of a string:

public abstract class TypedID<T extends Animal> {
  public final Type type;
  public final String id;

  protected TypedID(String id) {
    this.id = id;
    Type superclass = getClass().getGenericSuperclass();
    if (superclass instanceof Class) {
      throw new RuntimeException("Missing type parameter.");
    }
    this.type = ((ParameterizedType) superclass).getActualTypeArguments()[0];
  }
}

But I think this may defeat the purpose, since you now need to create new id objects for each string and hold on to them (or reconstruct them with the correct type information).

Mouse jerry = new Mouse();
TypedID<Dog> spike = new TypedID<Dog>("spike") {};
TypedID<Duck> quacker = new TypedID<Duck>("quacker") {};

jerry.addFriend(spike, new Dog());
jerry.addFriend(quacker, new Duck());

But you can now use the class in the way you originally wanted, without the casts.

jerry.callFriend(spike).bark();
jerry.callFriend(quacker).quack();

This is just hiding the type parameter inside the id, although it does mean you can retrieve the type from the identifier later if you wish.

You'd need to implement the comparison and hashing methods of TypedID too if you want to be able to compare two identical instances of an id.

node.js + mysql connection pooling

Using the standard mysql.createPool(), connections are lazily created by the pool. If you configure the pool to allow up to 100 connections, but only ever use 5 simultaneously, only 5 connections will be made. However if you configure it for 500 connections and use all 500 they will remain open for the durations of the process, even if they are idle!

This means if your MySQL Server max_connections is 510 your system will only have 10 mySQL connections available until your MySQL Server closes them (depends on what you have set your wait_timeout to) or your application closes! The only way to free them up is to manually close the connections via the pool instance or close the pool.

mysql-connection-pool-manager module was created to fix this issue and automatically scale the number of connections dependant on the load. Inactive connections are closed and idle connection pools are eventually closed if there has not been any activity.

    // Load modules
const PoolManager = require('mysql-connection-pool-manager');

// Options
const options = {
  ...example settings
}

// Initialising the instance
const mySQL = PoolManager(options);

// Accessing mySQL directly
var connection = mySQL.raw.createConnection({
  host     : 'localhost',
  user     : 'me',
  password : 'secret',
  database : 'my_db'
});

// Initialising connection
connection.connect();

// Performing query
connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
  if (error) throw error;
  console.log('The solution is: ', results[0].solution);
});

// Ending connection
connection.end();

Ref: https://www.npmjs.com/package/mysql-connection-pool-manager

Quick Way to Implement Dictionary in C

A hashtable is the traditional implementation of a simple "Dictionary". If you don't care about speed or size, just google for it. There are many freely available implementations.

here's the first one I saw -- at a glance, it looks ok to me. (it's pretty basic. If you really want it to hold an unlimited amount of data, then you'll need to add some logic to "realloc" the table memory as it grows.)

good luck!

How to make return key on iPhone make keyboard disappear?

You can try this UITextfield subclass which you can set a condition for the text to dynamically change the UIReturnKey:
https://github.com/codeinteractiveapps/OBReturnKeyTextField

Java: Static vs inner class

Let's look in the source of wisdom for such questions: Joshua Bloch's Effective Java:

Technically, there is no such thing as a static inner class. According to Effective Java, the correct terminology is a static nested class. A non-static nested class is indeed an inner class, along with anonymous classes and local classes.

And now to quote:

Each instance of a non-static nested class is implicitly associated with an enclosing instance of its containing class... It is possible to invoke methods on the enclosing instance.

A static nested class does not have access to the enclosing instance. It uses less space too.

How do I get a class instance of generic type T?

A standard approach/workaround/solution is to add a class object to the constructor(s), like:

 public class Foo<T> {

    private Class<T> type;
    public Foo(Class<T> type) {
      this.type = type;
    }

    public Class<T> getType() {
      return type;
    }

    public T newInstance() {
      return type.newInstance();
    }
 }

Ways to implement data versioning in MongoDB

If you are using mongoose, I have found the following plugin to be a useful implementation of the JSON Patch format

mongoose-patch-history

How to make Excel VBA variables available to multiple macros?

Create a "module" object and declare variables in there. Unlike class-objects that have to be instantiated each time, the module objects are always available. Therefore, a public variable, function, or property in a "module" will be available to all the other objects in the VBA project, macro, Excel formula, or even within a MS Access JET-SQL query def.

Could not find default endpoint element

In my case, I was referring to this service from a library project, not a startup Project. Once I copied <system.serviceModel> section to the configuration of the main startup project, The issue got resolved.

During running stage of any application, the configuration will be read from the startup/parent project instead of reading its own configurations mentioned in separate subprojects.

How to read files and stdout from a running Docker container

You can view the filesystem of the container at

/var/lib/docker/devicemapper/mnt/$CONTAINER_ID/rootfs/

and you can just

tail -f mylogfile.log

Oracle - How to create a readonly user

you can create user and grant privilege

create user read_only identified by read_only; grant create session,select any table to read_only;

How to convert string values from a dictionary, into int/float datatypes?

If that's your exact format, you can go through the list and modify the dictionaries.

for item in list_of_dicts:
    for key, value in item.iteritems():
        try:
            item[key] = int(value)
        except ValueError:
            item[key] = float(value)

If you've got something more general, then you'll have to do some kind of recursive update on the dictionary. Check if the element is a dictionary, if it is, use the recursive update. If it's able to be converted into a float or int, convert it and modify the value in the dictionary. There's no built-in function for this and it can be quite ugly (and non-pythonic since it usually requires calling isinstance).

makefile:4: *** missing separator. Stop

You should always write command after a Tab and not white space.

This applies to gcc line (line #4) in your case. You need to insert tab before gcc.

Also replace \rm -fr ll with rm -fr ll. Insert tabs before this command too.

How to group by month from Date field using sql

You can do this by using Year(), Month() Day() and datepart().

In you example this would be:

select  Closing_Date, Category,  COUNT(Status)TotalCount from  MyTable
where Closing_Date >= '2012-02-01' and Closing_Date <= '2012-12-31' 
and Defect_Status1 is not null 
group by Year(Closing_Date), Month(Closing_Date), Category

Convert array of strings to List<string>

From .Net 3.5 you can use LINQ extension method that (sometimes) makes code flow a bit better.

Usage looks like this:

using System.Linq; 

// ...

public void My()
{
    var myArray = new[] { "abc", "123", "zyx" };
    List<string> myList = myArray.ToList();
}

PS. There's also ToArray() method that works in other way.

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

Would something like this work:

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

Help with packages in java - import does not work

Just add classpath entry ( I mean your parent directory location) under System Variables and User Variables menu ... Follow : Right Click My Computer>Properties>Advanced>Environment Variables

C# - Create SQL Server table programmatically

For managing DataBase Objects in SQL Server i would suggest using Server Management Objects

jQuery return ajax result into outside variable

Using 'async': false to prevent asynchronous code is a bad practice,

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. https://xhr.spec.whatwg.org/

On the surface setting async to false fixes a lot of issues because, as the other answers show, you get your data into a variable. However, while waiting for the post data to return (which in some cases could take a few seconds because of database calls, slow connections, etc.) the rest of your Javascript functionality (like triggered events, Javascript handled buttons, JQuery transitions (like accordion, or autocomplete (JQuery UI)) will not be able to occur while the response is pending (which is really bad if the response never comes back as your site is now essentially frozen).

Try this instead,

var return_first;
function callback(response) {
  return_first = response;
  //use return_first variable here
}

$.ajax({
  'type': "POST",
  'global': false,
  'dataType': 'html',
  'url': "ajax.php?first",
  'data': { 'request': "", 'target': arrange_url, 'method': method_target },
  'success': function(data){
       callback(data);
  },
});

Get current rowIndex of table in jQuery

Since "$(this).parent().index();" and "$(this).parent('table').index();" don't work for me, I use this code instead:

$('td').click(function(){
   var row_index = $(this).closest("tr").index();
   var col_index = $(this).index();
});

Permission denied for relation

1st and important step is connect to your db:

psql -d yourDBName

2 step, grant privileges

GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO userName;

TreeMap sort by value

polygenelubricants answer is almost perfect. It has one important bug though. It will not handle map entries where the values are the same.

This code:...

Map<String, Integer> nonSortedMap = new HashMap<String, Integer>();
nonSortedMap.put("ape", 1);
nonSortedMap.put("pig", 3);
nonSortedMap.put("cow", 1);
nonSortedMap.put("frog", 2);

for (Entry<String, Integer> entry  : entriesSortedByValues(nonSortedMap)) {
    System.out.println(entry.getKey()+":"+entry.getValue());
}

Would output:

ape:1
frog:2
pig:3

Note how our cow dissapeared as it shared the value "1" with our ape :O!

This modification of the code solves that issue:

static <K,V extends Comparable<? super V>> SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map) {
        SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
            new Comparator<Map.Entry<K,V>>() {
                @Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
                    int res = e1.getValue().compareTo(e2.getValue());
                    return res != 0 ? res : 1; // Special fix to preserve items with equal values
                }
            }
        );
        sortedEntries.addAll(map.entrySet());
        return sortedEntries;
    }

How to get the version of ionic framework?

You can find the library version accessing the file package.json. Under dependencies, check the property ionic-angular. You can also check the Ionic CLI version typing ionic info in the terminal from your project's folder.

Override back button to act like home button

If you want to catch the Back Button have a look at this post on the Android Developer Blog. It covers the easier way to do this in Android 2.0 and the best way to do this for an application that runs on 1.x and 2.0.

However, if your Activity is Stopped it still may be killed depending on memory availability on the device. If you want a process to run with no UI you should create a Service. The documentation says the following about Services:

A service doesn't have a visual user interface, but rather runs in the background for an indefinite period of time. For example, a service might play background music as the user attends to other matters, or it might fetch data over the network or calculate something and provide the result to activities that need it.

These seems appropriate for your requirements.

How do function pointers in C work?

One of the big uses for function pointers in C is to call a function selected at run-time. For example, the C run-time library has two routines, qsort and bsearch, which take a pointer to a function that is called to compare two items being sorted; this allows you to sort or search, respectively, anything, based on any criteria you wish to use.

A very basic example, if there is one function called print(int x, int y) which in turn may require to call a function (either add() or sub(), which are of the same type) then what we will do, we will add one function pointer argument to the print() function as shown below:

#include <stdio.h>

int add()
{
   return (100+10);
}

int sub()
{
   return (100-10);
}

void print(int x, int y, int (*func)())
{
    printf("value is: %d\n", (x+y+(*func)()));
}

int main()
{
    int x=100, y=200;
    print(x,y,add);
    print(x,y,sub);

    return 0;
}

The output is:

value is: 410
value is: 390

Div not expanding even with content inside

There are two solutions to fix this:

  1. Use clear:both after the last floated tag. This works good.
  2. If you have fixed height for your div or clipping of content is fine, go with: overflow: hidden

Check last modified date of file in C#

You simply want the File.GetLastWriteTime static method.

Example:

var lastModified = System.IO.File.GetLastWriteTime("C:\foo.bar");

Console.WriteLine(lastModified.ToString("dd/MM/yy HH:mm:ss"));

Note however that in the rare case the last-modified time is not updated by the system when writing to the file (this can happen intentionally as an optimisation for high-frequency writing, e.g. logging, or as a bug), then this approach will fail, and you will instead need to subscribe to file write notifications from the system, constantly listening.

How can I pretty-print JSON using Go?

//You can do it with json.MarshalIndent(data, "", "  ")

package main

import(
  "fmt"
  "encoding/json" //Import package
)

//Create struct
type Users struct {
    ID   int
    NAME string
}

//Asign struct
var user []Users
func main() {
 //Append data to variable user
 user = append(user, Users{1, "Saturn Rings"})
 //Use json package the blank spaces are for the indent
 data, _ := json.MarshalIndent(user, "", "  ")
 //Print json formatted
 fmt.Println(string(data))
}

Convert char to int in C and C++

char is just a 1 byte integer. There is nothing magic with the char type! Just as you can assign a short to an int, or an int to a long, you can assign a char to an int.

Yes, the name of the primitive data type happens to be "char", which insinuates that it should only contain characters. But in reality, "char" is just a poor name choise to confuse everyone who tries to learn the language. A better name for it is int8_t, and you can use that name instead, if your compiler follows the latest C standard.

Though of course you should use the char type when doing string handling, because the index of the classic ASCII table fits in 1 byte. You could however do string handling with regular ints as well, although there is no practical reason in the real world why you would ever want to do that. For example, the following code will work perfectly:

  int str[] = {'h', 'e', 'l', 'l', 'o', '\0' };

  for(i=0; i<6; i++)
  {
    printf("%c", str[i]);
  }

You have to realize that characters and strings are just numbers, like everything else in the computer. When you write 'a' in the source code, it is pre-processed into the number 97, which is an integer constant.

So if you write an expression like

char ch = '5';
ch = ch - '0';

this is actually equivalent to

char ch = (int)53;
ch = ch - (int)48;

which is then going through the C language integer promotions

ch = (int)ch - (int)48;

and then truncated to a char to fit the result type

ch = (char)( (int)ch - (int)48 );

There's a lot of subtle things like this going on between the lines, where char is implicitly treated as an int.

pip install mysql-python fails with EnvironmentError: mysql_config not found

on MacOS Mojave, mysql_config is found at /usr/local/bin/ rather than /usr/local/mysql/bin as pointed above, so no need to add anything to path.

How to set image width to be 100% and height to be auto in react native?

use aspectRatio property in style

Aspect ratio control the size of the undefined dimension of a node. Aspect ratio is a non-standard property only available in react native and not CSS.

  • On a node with a set width/height aspect ratio control the size of the unset dimension
  • On a node with a set flex basis aspect ratio controls the size of the node in the cross axis if unset
  • On a node with a measure function aspect ratio works as though the measure function measures the flex basis
  • On a node with flex grow/shrink aspect ratio controls the size of the node in the cross axis if unset
  • Aspect ratio takes min/max dimensions into account

docs: https://reactnative.dev/docs/layout-props#aspectratio

try like this:

import {Image, Dimensions} from 'react-native';

var width = Dimensions.get('window').width; 

<Image
    source={{
        uri: '<IMAGE_URI>'
    }}
    style={{
        width: width * .2,  //its same to '20%' of device width
        aspectRatio: 1, // <-- this
        resizeMode: 'contain', //optional
    }}
/>

Declaration of Methods should be Compatible with Parent Methods in PHP

Just to expand on this error in the context of an interface, if you are type hinting your function parameters like so:

interface A

use Bar;

interface A
{
    public function foo(Bar $b);
}

Class B

class B implements A
{
    public function foo(Bar $b);
}

If you have forgotten to include the use statement on your implementing class (Class B), then you will also get this error even though the method parameters are identical.

Where does pip install its packages?

By default, on Linux, Pip installs packages to /usr/local/lib/python2.7/dist-packages.

Using virtualenv or --user during install will change this default location. If you use pip show make sure you are using the right user or else pip may not see the packages you are referencing.

What is Domain Driven Design?

I do not want to repeat others' answers, so, in short I explain some common misunderstanding

  • Practical resource: PATTERNS, PRINCIPLES, AND PRACTICES OF DOMAIN-DRIVEN DESIGN by Scott Millett
  • It is a methodology for complicated business systems. It takes all the technical matters out when communicating with business experts
  • It provides an extensive understanding of (simplified and distilled model of) business across the whole dev team.
  • it keeps business model in sync with code model by using ubiquitous language (the language understood by the whole dev team, business experts, business analysts, ...), which is used for communication within the dev team or dev with other teams
  • It has nothing to do with Project Management. Although it can be perfectly used in project management methods like Agile.
  • You should avoid using it all across your project

    DDD stresses the need to focus the most effort on the core subdomain. The core subdomain is the area of your product that will be the difference between it being a success and it being a failure. It’s the product’s unique selling point, the reason it is being built rather than bought.

    Basically, it is because it takes too much time and effort. So, it is suggested to break down the whole domain into subdomain and just apply it in those with high business value. (ex not in generic subdomain like email, ...)

  • It is not object oriented programming. It is mostly problem solving approach and (sometimes) you do not need to use OO patterns (such as Gang of Four) in your domain models. Simply because it can not be understood by Business Experts (they do not know much about Factory, Decorator, ...). There are even some patterns in DDD (such as The Transaction Script, Table Module) which are not 100% in line with OO concepts.

Module 'tensorflow' has no attribute 'contrib'

I used tensorflow 1.8 to train my model and there is no problem for now. Tensorflow 2.0 alpha is not suitable with object detection API

PHP - Check if two arrays are equal

if (array_diff($a,$b) == array_diff($b,$a)) {
  // Equals
}

if (array_diff($a,$b) != array_diff($b,$a)) {
  // Not Equals
}

From my pov it's better to use array_diff than array_intersect because with checks of this nature the differences returned commonly are less than the similarities, this way the bool conversion is less memory hungry.

Edit Note that this solution is for plain arrays and complements the == and === one posted above that is only valid for dictionaries.

OnClick in Excel VBA

In order to trap repeated clicks on the same cell, you need to move the focus to a different cell, so that each time you click, you are in fact moving the selection.

The code below will select the top left cell visible on the screen, when you click on any cell. Obviously, it has the flaw that it won't trap a click on the top left cell, but that can be managed (eg by selecting the top right cell if the activecell is the top left).

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  'put your code here to process the selection, then..
  ActiveWindow.VisibleRange.Cells(1, 1).Select
End Sub

Run bash command on jenkins pipeline

According to this document, you should be able to do it like so:

node {
    sh "#!/bin/bash \n" + 
       "echo \"Hello from \$SHELL\""
}

Is there a list of Pytz Timezones?

They appear to be populated by the tz database time zones found here.

enter image description here

When do I need to do "git pull", before or after "git add, git commit"?

I'd suggest pulling from the remote branch as often as possible in order to minimise large merges and possible conflicts.

Having said that, I would go with the first option:

git add foo.js
git commit foo.js -m "commit"
git pull
git push

Commit your changes before pulling so that your commits are merged with the remote changes during the pull. This may result in conflicts which you can begin to deal with knowing that your code is already committed should anything go wrong and you have to abort the merge for whatever reason.

I'm sure someone will disagree with me though, I don't think there's any correct way to do this merge flow, only what works best for people.

Check if a user has scrolled to the bottom

Try this for match condition if scroll to bottom end

if ($(this)[0].scrollHeight - $(this).scrollTop() == 
    $(this).outerHeight()) {

    //code for your custom logic

}

Remove all special characters with RegExp

I use RegexBuddy for debbuging my regexes it has almost all languages very usefull. Than copy/paste for the targeted language. Terrific tool and not very expensive.

So I copy/pasted your regex and your issue is that [,] are special characters in regex, so you need to escape them. So the regex should be : /!@#$^&%*()+=-[\x5B\x5D]\/{}|:<>?,./im

How do I change the text of a span element using JavaScript?

You may also use the querySelector() method, assuming the 'myspan' id is unique as the method returns the first element with the specified selector:

document.querySelector('#myspan').textContent = 'newtext';

developer.mozilla

Gradle Build Android Project "Could not resolve all dependencies" error

As Peter says, they won't be in Maven Central

from the Android SDK Manager download the 'Android Support Repository' and a Maven repo of the support libraries will be downloaded to your Android SDK directory (see 'extras' folder)

to deploy the libraries to your local .m2 repository you can use maven-android-sdk-deployer

2017 edit:

you can now reference the Google online M2 repo

repositories {
google()
jcenter()
}

Align the form to the center in Bootstrap 4

<div class="d-flex justify-content-center align-items-center container ">

    <div class="row ">


        <form action="">
            <div class="form-group">
                <label for="inputUserName" class="control-label">Enter UserName</label>
                <input type="email" class="form-control" id="inputUserName" aria-labelledby="emailnotification">
                <small id="emailnotification" class="form-text text-muted">Enter Valid Email Id</small>
            </div>
            <div class="form-group">
                <label for="inputPassword" class="control-label">Enter Password</label>
                <input type="password" class="form-control" id="inputPassword" aria-labelledby="passwordnotification">

            </div>
        </form>

    </div>

</div>

Setting ANDROID_HOME enviromental variable on Mac OS X

Could anybody post a working solution for doing this in the terminal?

ANDROID_HOME is usually a directory like .android. Its where things like the Debug Key will be stored.

export ANDROID_HOME=~/.android 

You can automate it for your login. Just add it to your .bash_profile (below is from my OS X 10.8.5 machine):

$ cat ~/.bash_profile
# MacPorts Installer addition on 2012-07-19 at 20:21:05
export PATH=/opt/local/bin:/opt/local/sbin:$PATH

# Android
export ANDROID_NDK_ROOT=/opt/android-ndk-r9
export ANDROID_SDK_ROOT=/opt/android-sdk
export JAVA_HOME=`/usr/libexec/java_home`
export ANDROID_HOME=~/.android

export PATH="$ANDROID_SDK_ROOT/tools/":"$ANDROID_SDK_ROOT/platform-tools/":"$PATH"

According to David Turner on the NDK Mailing List, both ANDROID_NDK_ROOT and ANDROID_SDK_ROOT need to be set because other tools depend on those values (see Recommended NDK Directory?).

After modifying ~/.bash_profile, then perform the following (or logoff and back on):

source ~/.bash_profile

How do you add a scroll bar to a div?

<head>
<style>
div.scroll
{
background-color:#00FFFF;
width:40%;
height:200PX;
FLOAT: left;
margin-left: 5%;
padding: 1%;
overflow:scroll;
}


</style>
</head>

<body>



<div class="scroll">You can use the overflow property when you want to have better       control of the layout. The default value is visible.better control of the layout. The default value is visible.better control of the layout. The default value is visible.better control of the layout. The default value is visible.better control of the layout. The default value is visible.better control of the layout. The default value is visible.better </div>


</body>
</html>

chai test array equality doesn't work as expected

You can use .deepEqual()

const { assert } = require('chai');

assert.deepEqual([0,0], [0,0]);

How to scroll to top of a div using jQuery?

Use the following function

window.scrollTo(xpos, ypos)

Here xpos is Required. The coordinate to scroll to, along the x-axis (horizontal), in pixels

ypos is also Required. The coordinate to scroll to, along the y-axis (vertical), in pixels

Converting between datetime and Pandas Timestamp objects

>>> pd.Timestamp('2014-01-23 00:00:00', tz=None).to_datetime()
datetime.datetime(2014, 1, 23, 0, 0)
>>> pd.Timestamp(datetime.date(2014, 3, 26))
Timestamp('2014-03-26 00:00:00')

Getter and Setter of Model object in Angular 4

The way you declare the date property as an input looks incorrect but its hard to say if it's the only problem without seeing all your code. Rather than using @Input('date') declare the date property like so: private _date: string;. Also, make sure you are instantiating the model with the new keyword. Lastly, access the property using regular dot notation.

Check your work against this example from https://www.typescriptlang.org/docs/handbook/classes.html :

let passcode = "secret passcode";

class Employee {
    private _fullName: string;

    get fullName(): string {
        return this._fullName;
    }

    set fullName(newName: string) {
        if (passcode && passcode == "secret passcode") {
            this._fullName = newName;
        }
        else {
            console.log("Error: Unauthorized update of employee!");
        }
    }
}

let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
    console.log(employee.fullName);
}

And here is a plunker demonstrating what it sounds like you're trying to do: https://plnkr.co/edit/OUoD5J1lfO6bIeME9N0F?p=preview

Why does Git say my master branch is "already up to date" even though it is not?

While none of these answers worked for me, I was able to fix the issue using the following command.

git fetch origin

This did a trick for me.

Override intranet compatibility mode IE8

Our system admin resolved this issue by unchecking the box globally for our organization. Users did not even need to log off.

enter image description here

"Port 4200 is already in use" when running the ng serve command

I had big troubles with this, and I was even trying with many others ports and nothing.

I did npm install [email protected] and it solved the problem. For some reason the typescript version was causing a conflict and using yarn or ng serve were not working.

hope this works for anyone else with the same issue.

Override default Spring-Boot application.properties settings in Junit Test

You can also create a application.properties file in src/test/resources where your JUnits are written.

Failed to add a service. Service metadata may not be accessible. Make sure your service is running and exposing metadata.`

In my case I was getting this error because the option (HttpActivation) was not enabled. Windows features dialog box showing HTTP Activation under WCF Services under .NET Framework 4.6 Advanced Services

Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax

If you are using ASP.NET Web API then you should just pass data: JSON.stringify(things).

And your controller should look something like this:

public class PassThingsController : ApiController
{
    public HttpResponseMessage Post(List<Thing> things)
    {
        // code
    }
}

Give all permissions to a user on a PostgreSQL database

GRANT USAGE ON SCHEMA schema_name TO user;

setTimeout in for-loop does not print consecutive values

Well, another working solution based on Cody's answer but a little more general can be something like this:

function timedAlert(msg, timing){
    setTimeout(function(){
        alert(msg);    
    }, timing);
}

function yourFunction(time, counter){
    for (var i = 1; i <= counter; i++) {
        var msg = i, timing = i * time * 1000; //this is in seconds
        timedAlert (msg, timing);
    };
}

yourFunction(timeInSeconds, counter); // well here are the values of your choice.

Random number in range [min - max] using PHP

<?php
  $min=1;
  $max=20;
  echo rand($min,$max);
?>

De-obfuscate Javascript code to make it readable again

I have tried both of online jsbeautifier(jsbeautifier, jsnice), these tools gave me beautiful js code,

but couldn't copy for very large js (must be bug, when i copy, copied buffer contains only one character '-').

I found that only working solution was prettyjs:

http://www.thaoh.net/prettyjs/

Eclipse comment/uncomment shortcut?

CTRL + 7

does comment/uncomment in the Java Editor.

OS X Terminal Colors

If you want to have your ls colorized you have to edit your ~/.bash_profile file and add the following line (if not already written) :

source .bashrc

Then you edit or create ~/.bashrc file and write an alias to the ls command :

alias ls="ls -G"

Now you have to type source .bashrc in a terminal if already launched, or simply open a new terminal.

If you want more options in your ls juste read the manual ( man ls ). Options are not exactly the same as in a GNU/Linux system.

Multiple line code example in Javadoc comment

In Visual Studio Code at least, you can force a Javadoc comment to respect line-breaks by wrapping it in triple-backticks, as seen below:

/** ```markdown
 * This content is rendered in (partial) markdown.
 * 
 * For example, *italic* and **bold** text works, but [links](https://www.google.com) do not.
 * Bonus: it keeps single line-breaks, as seen between this line and the previous.
 ``` */

java.util.Date format conversion yyyy-mm-dd to mm-dd-yyyy

Date is a container for the number of milliseconds since the Unix epoch ( 00:00:00 UTC on 1 January 1970).

It has no concept of format.

Java 8+

LocalDateTime ldt = LocalDateTime.now();
System.out.println(DateTimeFormatter.ofPattern("MM-dd-yyyy", Locale.ENGLISH).format(ldt));
System.out.println(DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH).format(ldt));
System.out.println(ldt);

Outputs...

05-11-2018
2018-05-11
2018-05-11T17:24:42.980

Java 7-

You should be making use of the ThreeTen Backport

Original Answer

For example...

Date myDate = new Date();
System.out.println(myDate);
System.out.println(new SimpleDateFormat("MM-dd-yyyy").format(myDate));
System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(myDate));
System.out.println(myDate);

Outputs...

Wed Aug 28 16:20:39 EST 2013
08-28-2013
2013-08-28
Wed Aug 28 16:20:39 EST 2013

None of the formatting has changed the underlying Date value. This is the purpose of the DateFormatters

Updated with additional example

Just in case the first example didn't make sense...

This example uses two formatters to format the same date. I then use these same formatters to parse the String values back to Dates. The resulting parse does not alter the way Date reports it's value.

Date#toString is just a dump of it's contents. You can't change this, but you can format the Date object any way you like

try {
    Date myDate = new Date();
    System.out.println(myDate);

    SimpleDateFormat mdyFormat = new SimpleDateFormat("MM-dd-yyyy");
    SimpleDateFormat dmyFormat = new SimpleDateFormat("yyyy-MM-dd");

    // Format the date to Strings
    String mdy = mdyFormat.format(myDate);
    String dmy = dmyFormat.format(myDate);

    // Results...
    System.out.println(mdy);
    System.out.println(dmy);
    // Parse the Strings back to dates
    // Note, the formats don't "stick" with the Date value
    System.out.println(mdyFormat.parse(mdy));
    System.out.println(dmyFormat.parse(dmy));
} catch (ParseException exp) {
    exp.printStackTrace();
}

Which outputs...

Wed Aug 28 16:24:54 EST 2013
08-28-2013
2013-08-28
Wed Aug 28 00:00:00 EST 2013
Wed Aug 28 00:00:00 EST 2013

Also, be careful of the format patterns. Take a closer look at SimpleDateFormat to make sure you're not using the wrong patterns ;)

Pass multiple values with onClick in HTML link

function ReAssign(valautionId, userName) {
   var valautionId 
   var userName 
 alert(valautionId);
 alert(userName);
  }

<a href=# onclick="return ReAssign('valuationId','user')">Re-Assign</a>

WPF global exception handler

I use the following code in my WPF apps to show a "Sorry for the inconvenience" dialog box whenever an unhandled exception occurs. It shows the exception message, and asks user whether they want to close the app or ignore the exception and continue (the latter case is convenient when a non-fatal exceptions occur and user can still normally continue to use the app).

In App.xaml add the Startup event handler:

<Application .... Startup="Application_Startup">

In App.xaml.cs code add Startup event handler function that will register the global application event handler:

using System.Windows.Threading;

private void Application_Startup(object sender, StartupEventArgs e)
{
    // Global exception handling  
    Application.Current.DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(AppDispatcherUnhandledException);    
}

void AppDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{    
    \#if DEBUG   // In debug mode do not custom-handle the exception, let Visual Studio handle it

    e.Handled = false;

    \#else

    ShowUnhandledException(e);    

    \#endif     
}

void ShowUnhandledException(DispatcherUnhandledExceptionEventArgs e)
{
    e.Handled = true;

    string errorMessage = string.Format("An application error occurred.\nPlease check whether your data is correct and repeat the action. If this error occurs again there seems to be a more serious malfunction in the application, and you better close it.\n\nError: {0}\n\nDo you want to continue?\n(if you click Yes you will continue with your work, if you click No the application will close)",

    e.Exception.Message + (e.Exception.InnerException != null ? "\n" + 
    e.Exception.InnerException.Message : null));

    if (MessageBox.Show(errorMessage, "Application Error", MessageBoxButton.YesNoCancel, MessageBoxImage.Error) == MessageBoxResult.No)   {
        if (MessageBox.Show("WARNING: The application will close. Any changes will not be saved!\nDo you really want to close it?", "Close the application!", MessageBoxButton.YesNoCancel, MessageBoxImage.Warning) == MessageBoxResult.Yes)
    {
        Application.Current.Shutdown();
    } 
}

Save matplotlib file to a directory

In addition to the answers already given, if you want to create a new directory, you could use this function:

def mkdir_p(mypath):
    '''Creates a directory. equivalent to using mkdir -p on the command line'''

    from errno import EEXIST
    from os import makedirs,path

    try:
        makedirs(mypath)
    except OSError as exc: # Python >2.5
        if exc.errno == EEXIST and path.isdir(mypath):
            pass
        else: raise

and then:

import matplotlib
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(100))

# Create new directory
output_dir = "some/new/directory"
mkdir_p(output_dir)

fig.savefig('{}/graph.png'.format(output_dir))

How to send email via Django?

I use Gmail as my SMTP server for Django. Much easier than dealing with postfix or whatever other server. I'm not in the business of managing email servers.

In settings.py:

EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'password'

NOTE: In 2016 Gmail is not allowing this anymore by default. You can either use an external service like Sendgrid, or you can follow this tutorial from Google to reduce security but allow this option: https://support.google.com/accounts/answer/6010255

Why I'm getting 'Non-static method should not be called statically' when invoking a method in a Eloquent model?

TL;DR. You can get around this by expressing your queries as MyModel::query()->find(10); instead of MyModel::find(10);.

To the best of my knowledge, starting PhpStorm 2017.2 code inspection fails for methods such as MyModel::where(), MyModel::find(), etc (check this thread). This could get quite annoying, when you try let's say to use PhpStorm's Git integration before committing your code, PhpStorm won't stop complaining about these static method call warnings.

One elegant way (IMOO) to get around this is to explicitly call ::query() wherever it makes sense to. This will let you benefit from a free auto-completion and a nice query formatting.

Examples

Snippet where inspection complains about static method calls

$myModel = MyModel::find(10); // static call complaint

// another poorly formatted query with code inspection complaints
$myFilteredModels = MyModel::where('is_beautiful', true)
    ->where('is_not_smart', false)
    ->get();

Well formatted code with no complaints

$myModel = MyModel::query()->find(10);

// a nicely formatted query with no complaints
$myFilteredModels = MyModel::query()
    ->where('is_beautiful', true)
    ->where('is_not_smart', false)
    ->get();

JSON serialization/deserialization in ASP.Net Core

.net core

using System.Text.Json;

To serialize

var jsonStr = JsonSerializer.Serialize(MyObject)

Deserialize

var weatherForecast = JsonSerializer.Deserialize<MyObject>(jsonStr);

For more information about excluding properties and nulls check out This Microsoft side

How to find files modified in last x minutes (find -mmin does not work as expected)

Manual of find:

   Numeric arguments can be specified as

   +n     for greater than n,

   -n     for less than n,

   n      for exactly n.

   -amin n
          File was last accessed n minutes ago.

   -anewer file
          File was last accessed more recently than file was modified.  If file is a symbolic link and the -H option or the -L option is in effect, the access time of the file it points  to  is  always
          used.

   -atime n
          File  was  last  accessed  n*24 hours ago.  When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to
          have been accessed at least two days ago.

   -cmin n
          File's status was last changed n minutes ago.

   -cnewer file
          File's status was last changed more recently than file was modified.  If file is a symbolic link and the -H option or the -L option is in effect, the status-change time of the file it  points
          to is always used.

   -ctime n
          File's status was last changed n*24 hours ago.  See the comments for -atime to understand how rounding affects the interpretation of file status change times.

Example:

find /dir -cmin -60 # creation time
find /dir -mmin -60 # modification time
find /dir -amin -60 # access time

How to get screen width without (minus) scrollbar?

The safest place to get the correct width and height without the scrollbars is from the HTML element. Try this:

var width = document.documentElement.clientWidth
var height = document.documentElement.clientHeight

Browser support is pretty decent, with IE 9 and up supporting this. For OLD IE, use one of the many fallbacks mentioned here.

Static variables in C++

Static variable in a header file:

say 'common.h' has

static int zzz;

This variable 'zzz' has internal linkage (This same variable can not be accessed in other translation units). Each translation unit which includes 'common.h' has it's own unique object of name 'zzz'.

Static variable in a class:

Static variable in a class is not a part of the subobject of the class. There is only one copy of a static data member shared by all the objects of the class.

$9.4.2/6 - "Static data members of a class in namespace scope have external linkage (3.5).A local class shall not have static data members."

So let's say 'myclass.h' has

struct myclass{
   static int zzz;        // this is only a declaration
};

and myclass.cpp has

#include "myclass.h"

int myclass::zzz = 0           // this is a definition, 
                               // should be done once and only once

and "hisclass.cpp" has

#include "myclass.h"

void f(){myclass::zzz = 2;}    // myclass::zzz is always the same in any 
                               // translation unit

and "ourclass.cpp" has

#include "myclass.h"
void g(){myclass::zzz = 2;}    // myclass::zzz is always the same in any 
                               // translation unit

So, class static members are not limited to only 2 translation units. They need to be defined only once in any one of the translation units.

Note: usage of 'static' to declare file scope variable is deprecated and unnamed namespace is a superior alternate

Django Rest Framework -- no module named rest_framework

In my case, my problem was different. I was creating in my bash_profile an alias like:

alias python=/usr/local/bin/python3

And even if I activate my environment, when I ran the command, the python interpreter accessed was from the system and not from my environment.

I just removed the alias from bash_profile and it worked fine.

How to set cookie value with AJAX request?

Basically, ajax request as well as synchronous request sends your document cookies automatically. So, you need to set your cookie to document, not to request. However, your request is cross-domain, and things became more complicated. Basing on this answer, additionally to set document cookie, you should allow its sending to cross-domain environment:

type: "GET",    
url: "http://example.com",
cache: false,
// NO setCookies option available, set cookie to document
//setCookies: "lkfh89asdhjahska7al446dfg5kgfbfgdhfdbfgcvbcbc dfskljvdfhpl",
crossDomain: true,
dataType: 'json',
xhrFields: {
    withCredentials: true
},
success: function (data) {
    alert(data);
});

SQL Error: ORA-00936: missing expression

In the above query when we are trying to combine two or more tables it is necessary to use joins and specify the alias name for description and date (that means, the table from which you are fetching the description and date values)

SELECT DISTINCT Description, Date as treatmentDate  
FROM doothey.Patient P  
INNER JOIN doothey.Account A ON P.PatientID = A.PatientID  
INNER JOIN doothey.AccountLine AL ON A.AccountNo = AL.AccountNo  
INNER JOIN doothey.Item I ON AL.ItemNo = I.ItemNo  
WHERE p.FamilyName = 'Stange' AND p.GivenName = 'Jessie';

Xcode 6 Storyboard the wrong size?

On your storyboard page, go to File Inspector and uncheck 'Use Size Classes'. This should shrink your view controller to regular IPhone size you were familiar with. Note that using 'size classes' will let you design your project across many devices. Once you uncheck this the Xcode will give you a warning dialogue as follows. This should be self-explainatory.

"Disabling size classes will limit this document to storing data for a single device family. The data for the size class best representing the targeted device will be retained, and all other data will be removed. In addition, segues will be converted to their non-adaptive equivalents."

What's the difference between Apache's Mesos and Google's Kubernetes

I like this short video here mesos learning material

with bare metal clusters, you would need to spawn stacks like HDFS, SPARK, MR etc... so if you launch tasks related to these using only bare metal cluster management, there will be a lot cold starting time.

with mesos, you can install these services on top of the bare metals and you can avoid the bring up time of those base services. This is something mesos does well. and can be utilised by kubernetes building on top of it.

'\r': command not found - .bashrc / .bash_profile

For those who don't have dos2unix installed (and don't want to install it):

Remove trailing \r character that causes this error:

sed -i 's/\r$//' filename


Explanation:

Option -i is for in-place editing, we delete the trailing \r directly in the input file. Thus be careful to type the pattern correctly.

Selectors in Objective-C?

Selectors are an efficient way to reference methods directly in compiled code - the compiler is what actually assigns the value to a SEL.

Other have already covered the second part of your q, the ':' at the end matches a different signature than what you're looking for (in this case that signature doesn't exist).

Html- how to disable <a href>?

I created a button...

This is where you've gone wrong. You haven't created a button, you've created an anchor element. If you had used a button element instead, you wouldn't have this problem:

<button type="button" data-toggle="modal" data-target="#myModal" data-role="disabled">
    Connect
</button>

If you are going to continue using an a element instead, at the very least you should give it a role attribute set to "button" and drop the href attribute altogether:

<a role="button" ...>

Once you've done that you can introduce a piece of JavaScript which calls event.preventDefault() - here with event being your click event.

Stashing only staged changes in git - is it possible?

With latest git you may use --patch option

git stash push --patch   # since 2.14.6

git stash save --patch   # for older git versions

And git will ask you for each change in your files to add or not into stash.
You just answer y or n

UPD
Alias for DOUBLE STASH:

git config --global alias.stash-staged '!bash -c "git stash --keep-index; git stash push -m "staged" --keep-index; git stash pop stash@{1}"'

Now you can stage your files and then run git stash-staged.
As result your staged files will be saved into stash.

If you do not want to keep staged files and want move them into stash. Then you can add another alias and run git move-staged:

git config --global alias.move-staged '!bash -c "git stash-staged;git commit -m "temp"; git stash; git reset --hard HEAD^; git stash pop"'

How to configure robots.txt to allow everything?

I understand that this is fairly old question and has some pretty good answers. But, here is my two cents for the sake of completeness.

As per the official documentation, there are four ways, you can allow complete access for robots to access your site.

Clean:

Specify a global matcher with a disallow segment as mentioned by @unor. So your /robots.txt looks like this.

User-agent: *
Disallow:

The hack:

Create a /robots.txt file with no content in it. Which will default to allow all for all type of Bots.

I don't care way:

Do not create a /robots.txt altogether. Which should yield the exact same results as the above two.

The ugly:

From the robots documentation for meta tags, You can use the following meta tag on all your pages on your site to let the Bots know that these pages are not supposed to be indexed.

<META NAME="ROBOTS" CONTENT="NOINDEX">

In order for this to be applied to your entire site, You will have to add this meta tag for all of your pages. And this tag should strictly be placed under your HEAD tag of the page. More about this meta tag here.

How to get image height and width using java?

Having struggled with ImageIO a lot in the past years, I think Andrew Taylor's solution is by far the best compromise (fast: not using ImageIO#read, and versatile). Thanks man!!

But I was a little frustrated to be compelled to use a local file (File/String), especially in cases where you want to check image sizes coming from, say, a multipart/form-data request where you usually retrieve InputPart/InputStream's. So I quickly made a variant that accepts File, InputStream and RandomAccessFile, based on the ability of ImageIO#createImageInputStream to do so.

Of course, such a method with Object input, may only remain private and you shall create as many polymorphic methods as needed, calling this one. You can also accept Path with Path#toFile() and URL with URL#openStream() prior to passing to this method:

  private static Dimension getImageDimensions(Object input) throws IOException {

    try (ImageInputStream stream = ImageIO.createImageInputStream(input)) { // accepts File, InputStream, RandomAccessFile
      if(stream != null) {
        IIORegistry iioRegistry = IIORegistry.getDefaultInstance();
        Iterator<ImageReaderSpi> iter = iioRegistry.getServiceProviders(ImageReaderSpi.class, true);
        while (iter.hasNext()) {
          ImageReaderSpi readerSpi = iter.next();
          if (readerSpi.canDecodeInput(stream)) {
            ImageReader reader = readerSpi.createReaderInstance();
            try {
              reader.setInput(stream);
              int width = reader.getWidth(reader.getMinIndex());
              int height = reader.getHeight(reader.getMinIndex());
              return new Dimension(width, height);
            } finally {
              reader.dispose();
            }
          }
        }
        throw new IllegalArgumentException("Can't find decoder for this image");
      } else {
        throw new IllegalArgumentException("Can't open stream for this image");
      }
    }
  }

The specified child already has a parent. You must call removeView() on the child's parent first (Android)

The code below solved it for me:

@Override
public void onDestroyView() {
    if (getView() != null) {
        ViewGroup parent = (ViewGroup) getView().getParent();
        parent.removeAllViews();
    }
    super.onDestroyView();
}

Note: The error was from my fragment class and by overriding the onDestroy method like this, I could solve it.

Is it possible to set transparency in CSS3 box-shadow?

I suppose rgba() would work here. After all, browser support for both box-shadow and rgba() is roughly the same.

/* 50% black box shadow */
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);

_x000D_
_x000D_
div {_x000D_
    width: 200px;_x000D_
    height: 50px;_x000D_
    line-height: 50px;_x000D_
    text-align: center;_x000D_
    color: white;_x000D_
    background-color: red;_x000D_
    margin: 10px;_x000D_
}_x000D_
_x000D_
div.a {_x000D_
  box-shadow: 10px 10px 10px #000;_x000D_
}_x000D_
_x000D_
div.b {_x000D_
  box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);_x000D_
}
_x000D_
<div class="a">100% black shadow</div>_x000D_
<div class="b">50% black shadow</div>
_x000D_
_x000D_
_x000D_

Requested registry access is not allowed

If you don't need admin privs for the entire app, or only for a few infrequent changes you can do the changes in a new process and launch it using:

Process.StartInfo.UseShellExecute = true;
Process.StartInfo.Verb = "runas";

which will run the process as admin to do whatever you need with the registry, but return to your app with the normal priviledges. This way it doesn't prompt the user with a UAC dialog every time it launches.

System.Data.SqlClient.SqlException: Invalid object name 'dbo.Projects'

If you are in that phase of development where you have an method inside your context class that creates testdata for you, don't call it in your constructor, it will try to create those test records while you don't have tables yet. Just sharing my mistake...

Is there a need for range(len(a))?

Very simple example:

def loadById(self, id):
    if id in range(len(self.itemList)):
        self.load(self.itemList[id])

I can't think of a solution that does not use the range-len composition quickly.

But probably instead this should be done with try .. except to stay pythonic i guess..

How to check if any flags of a flag combination are set?

To check if for example AB is set I can do this:

if((letter & Letters.AB) == Letters.AB)

Is there a simpler way to check if any of the flags of a combined flag constant are set than the following?

This checks that both A and B are set, and ignores whether any other flags are set.

if((letter & Letters.A) == Letters.A || (letter & Letters.B) == Letters.B)

This checks that either A or B is set, and ignores whether any other flags are set or not.

This can be simplified to:

if(letter & Letters.AB)

Here's the C for binary operations; it should be straightforward to apply this to C#:

enum {
     A = 1,
     B = 2,
     C = 4,
     AB = A | B,
     All = AB | C,
};

int flags = A|C;

bool anything_and_a = flags & A;

bool only_a = (flags == A);

bool a_and_or_c_and_anything_else = flags & (A|C);

bool both_ac_and_anything_else = (flags & (A|C)) == (A|C);

bool only_a_and_c = (flags == (A|C));

Incidentally, the naming of the variable in the question's example is the singular 'letter', which might imply that it represents only a single letter; the example code makes it clear that its a set of possible letters and that multiple values are allowed, so consider renaming the variable 'letters'.

How to convert string to integer in UNIX

The standard solution:

 expr $d1 - $d2

You can also do:

echo $(( d1 - d2 ))

but beware that this will treat 07 as an octal number! (so 07 is the same as 7, but 010 is different than 10).

Convert string to date then format the date

enter image description here

String myFormat= "yyyy-MM-dd";
String finalString = "";
try {
DateFormat formatter = new SimpleDateFormat("yyyy MMM dd");
Date date = (Date) formatter .parse("2015 Oct 09");
SimpleDateFormat newFormat = new SimpleDateFormat(myFormat);
finalString= newFormat .format(date );
newDate.setText(finalString);
} catch (Exception e) {

}

What is the best java image processing library/approach?

There's ImageJ, which boasts to be the

world's fastest pure Java image processing program

It can be used as a library in another application. It's architecture is not brilliant, but it does basic image processing tasks.

How to find the logs on android studio?

The path to the log files in Windows has been moved.

They appear to be under C:\Program Files\Android\Android Studio\caches\trunk-system\log\idea.log in Android Studio 4.1.1