Programs & Examples On #Definition

A generic tag for topics providing definitions.

What is an example of the Liskov Substitution Principle?

The Liskov Substitution Principle (LSP, ) is a concept in Object Oriented Programming that states:

Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it.

At its heart LSP is about interfaces and contracts as well as how to decide when to extend a class vs. use another strategy such as composition to achieve your goal.

The most effective way I have seen to illustrate this point was in Head First OOA&D. They present a scenario where you are a developer on a project to build a framework for strategy games.

They present a class that represents a board that looks like this:

Class Diagram

All of the methods take X and Y coordinates as parameters to locate the tile position in the two-dimensional array of Tiles. This will allow a game developer to manage units in the board during the course of the game.

The book goes on to change the requirements to say that the game frame work must also support 3D game boards to accommodate games that have flight. So a ThreeDBoard class is introduced that extends Board.

At first glance this seems like a good decision. Board provides both the Height and Width properties and ThreeDBoard provides the Z axis.

Where it breaks down is when you look at all the other members inherited from Board. The methods for AddUnit, GetTile, GetUnits and so on, all take both X and Y parameters in the Board class but the ThreeDBoard needs a Z parameter as well.

So you must implement those methods again with a Z parameter. The Z parameter has no context to the Board class and the inherited methods from the Board class lose their meaning. A unit of code attempting to use the ThreeDBoard class as its base class Board would be very out of luck.

Maybe we should find another approach. Instead of extending Board, ThreeDBoard should be composed of Board objects. One Board object per unit of the Z axis.

This allows us to use good object oriented principles like encapsulation and reuse and doesn’t violate LSP.

How to see the CREATE VIEW code for a view in PostgreSQL?

select definition from pg_views where viewname = 'my_view'

What exactly is RESTful programming?

I would say RESTful programming would be about creating systems (API) that follow the REST architectural style.

I found this fantastic, short, and easy to understand tutorial about REST by Dr. M. Elkstein and quoting the essential part that would answer your question for the most part:

Learn REST: A Tutorial

REST is an architecture style for designing networked applications. The idea is that, rather than using complex mechanisms such as CORBA, RPC or SOAP to connect between machines, simple HTTP is used to make calls between machines.

  • In many ways, the World Wide Web itself, based on HTTP, can be viewed as a REST-based architecture.

RESTful applications use HTTP requests to post data (create and/or update), read data (e.g., make queries), and delete data. Thus, REST uses HTTP for all four CRUD (Create/Read/Update/Delete) operations.

I don't think you should feel stupid for not hearing about REST outside Stack Overflow..., I would be in the same situation!; answers to this other SO question on Why is REST getting big now could ease some feelings.

What is the difference between a definition and a declaration?

Definition :

extern int a;      // Declaration 
int a;             // Definition
a = 10             // Initialization
int b = 10;        // Definition & Initialization

Definition associates the variable with a type and allocates memory, whereas declaration just specifies the type but doesn't allocate memory. Declaration is more useful when you want to refer the variable before definition.

*Don't confuse definition with initialization. Both are different, initialization gives value to the variable. See the above example.

Following are some examples of definition.

int a;
float b;
double c;

Now function declaration :

int fun(int a,int b); 

Note the semicolon at the end of function so it says it is only a declaration. Compiler knows that somewhere in the program that function will be defined with that prototype. Now if the compiler gets a function call something like this

int b=fun(x,y,z);

Compiler will throw an error saying that there is no such function. Because it doesn't has any prototype for that function.

Note the difference between two programs.

Program 1

#include <stdio.h>
void print(int a)
{
     printf("%d",a);
}
main()
{
    print(5);
}

In this, print function is declared and defined as well. Since function call is coming after the definition. Now see the next program.

Program 2

 #include <stdio.h>
 void print(int a); // In this case this is essential
 main()
 {
    print(5);
 }
 void print(int a)
 {
     printf("%d",a);
 }

It is essential because function call precedes definition so compiler must know whether there is any such function. So we declare the function which will inform the compiler.

Definition :

This part of defining a function is called Definition. It says what to do inside the function.

void print(int a)
{
    printf("%d",a);
}

What is the difference between a heuristic and an algorithm?

A heuristic is usually an optimization or a strategy that usually provides a good enough answer, but not always and rarely the best answer. For example, if you were to solve the traveling salesman problem with brute force, discarding a partial solution once its cost exceeds that of the current best solution is a heuristic: sometimes it helps, other times it doesn't, and it definitely doesn't improve the theoretical (big-oh notation) run time of the algorithm

ReferenceError: variable is not defined

Variables are available only in the scope you defined them. If you define a variable inside a function, you won't be able to access it outside of it.

Define variable with var outside the function (and of course before it) and then assign 10 to it inside function:

var value;
$(function() {
  value = "10";
});
console.log(value); // 10

Note that you shouldn't omit the first line in this code (var value;), because otherwise you are assigning value to undefined variable. This is bad coding practice and will not work in strict mode. Defining a variable (var variable;) and assigning value to a variable (variable = value;) are two different things. You can't assign value to variable that you haven't defined.

It might be irrelevant here, but $(function() {}) is a shortcut for $(document).ready(function() {}), which executes a function as soon as document is loaded. If you want to execute something immediately, you don't need it, otherwise beware that if you run it before DOM has loaded, value will be undefined until it has loaded, so console.log(value); placed right after $(function() {}) will return undefined. In other words, it would execute in following order:

var value;
console.log(value);
value = "10";

See also:

What is the difference between a schema and a table and a database?

Schemas contains Databases.

Databases are part of a Schema.

So, schemas > databases.

Schemas contains views, stored procedure(s), database(s), trigger(s) etc.

SOAP vs REST (differences)

Although SOAP and REST share similarities over the HTTP protocol, SOAP is a more rigid set of messaging patterns than REST. The rules in SOAP are relevant because we can’t achieve any degree of standardization without them. REST needs no processing as an architecture style and is inherently more versatile. In the spirit of information exchange, both SOAP and REST depend on well-established laws that everybody has decided to abide by. The choice of SOAP vs. REST is dependent on the programming language you are using the environment you are using and the specifications.

Add Auto-Increment ID to existing table?

This SQL request works for me :

ALTER TABLE users
CHANGE COLUMN `id` `id` INT(11) NOT NULL AUTO_INCREMENT ;

Explanation of BASE terminology

It could just be because ACID is one set of properties that substances show( in Chemistry) and BASE is a complement set of them.So it could be just to show the contrast between the two that the acronym was made up and then 'Basically Available Soft State Eventual Consistency' was decided as it's full-form.

Software Design vs. Software Architecture

In My opinion , Architecture is nothing but a vision ,gathering requirements and framing the building blocks in right way

where as design , to construct particular block there are 100 solutions may be available, but to meet exact requirement we need to choose the right method , so choosing right method or algorithm is nothing but design

What are unit tests, integration tests, smoke tests, and regression tests?

Everyone will have slightly different definitions, and there are often grey areas. However:

  • Unit test: does this one little bit (as isolated as possible) work?
  • Integration test: do these two (or more) components work together?
  • Smoke test: does this whole system (as close to being a production system as possible) hang together reasonably well? (i.e. are we reasonably confident it won't create a black hole?)
  • Regression test: have we inadvertently re-introduced any bugs we'd previously fixed?

What's the difference between faking, mocking, and stubbing?

the thing that you assert on it,is called a mock object and everything else that just helped the test run, is a stub.

What's the difference between unit, functional, acceptance, and integration tests?

I will explain you this with a practical example and no theory stuff:

A developer writes the code. No GUI is implemented yet. The testing at this level verifies that the functions work correctly and the data types are correct. This phase of testing is called Unit testing.

When a GUI is developed, and application is assigned to a tester, he verifies business requirements with a client and executes the different scenarios. This is called functional testing. Here we are mapping the client requirements with application flows.

Integration testing: let's say our application has two modules: HR and Finance. HR module was delivered and tested previously. Now Finance is developed and is available to test. The interdependent features are also available now, so in this phase, you will test communication points between the two and will verify they are working as requested in requirements.

Regression testing is another important phase, which is done after any new development or bug fixes. Its aim is to verify previously working functions.

What is a loop invariant?

Definition by How to Think About Algorithms, by Jeff Edmonds

A loop invariant is an assertion that is placed at the top of a loop and that must hold true every time the computation returns to the top of the loop.

What is boilerplate code?

Boilerplate definition is becoming more global in many other programming languages nowadays. It comes from OOP and hybrid languages that have become OOP and were before procedual have now the same goal to keep repeating the code you build with a model/template/class/object hence why they adapt this term. You make a template and the only things you do for each instance of a template are the parameters to individualize an object this part is what we call boilerplate. You simply re-use the code you made a template of, just with different parameters.

Synonyms
a blueprint is a boilerplate
a stencil is a boilerplate
a footer is a boilerplate
a design pattern for multiple use is a boilerplate
a signature of a mail is a boilerplate

What is 'Currying'?

A curried function is a function of several arguments rewritten such that it accepts the first argument and returns a function that accepts the second argument and so on. This allows functions of several arguments to have some of their initial arguments partially applied.

What are public, private and protected in object oriented programming?

They aren't really concepts but rather specific keywords that tend to occur (with slightly different semantics) in popular languages like C++ and Java.

Essentially, they are meant to allow a class to restrict access to members (fields or functions). The idea is that the less one type is allowed to access in another type, the less dependency can be created. This allows the accessed object to be changed more easily without affecting objects that refer to it.

Broadly speaking, public means everyone is allowed to access, private means that only members of the same class are allowed to access, and protected means that members of subclasses are also allowed. However, each language adds its own things to this. For example, C++ allows you to inherit non-publicly. In Java, there is also a default (package) access level, and there are rules about internal classes, etc.

What is a "thread" (really)?

Unfortunately, threads do exist. A thread is something tangible. You can kill one, and the others will still be running. You can spawn new threads.... although each thread is not it's own process, they are running separately inside the process. On multi-core machines, 2 threads could run at the same time.

http://en.wikipedia.org/wiki/Simultaneous_multithreading

http://www.intel.com/intelpress/samples/mcp_samplech01.pdf

Definition of "downstream" and "upstream"

In terms of source control, you're "downstream" when you copy (clone, checkout, etc) from a repository. Information flowed "downstream" to you.

When you make changes, you usually want to send them back "upstream" so they make it into that repository so that everyone pulling from the same source is working with all the same changes. This is mostly a social issue of how everyone can coordinate their work rather than a technical requirement of source control. You want to get your changes into the main project so you're not tracking divergent lines of development.

Sometimes you'll read about package or release managers (the people, not the tool) talking about submitting changes to "upstream". That usually means they had to adjust the original sources so they could create a package for their system. They don't want to keep making those changes, so if they send them "upstream" to the original source, they shouldn't have to deal with the same issue in the next release.

What is managed or unmanaged code in programming?

When you think of unmanaged, think machine-specific, machine-level code. Like x86 assembly language. Unmanaged (native) code is compiled and linked to run directly on the processor it was designed for, excluding all the OS stuff for the moment. It's not portable, but it is fast. Very simple, stripped down code.

Managed code is everything from Java to old Interpretive BASIC, or anything that runs under .NET. Managed code typically is compiled to an intermediate level P-Code or byte code set of instructions. These are not machine-specific instructions, although they look similar to assembly language. Managed code insulates the program from the machine it's running on, and creates a secure boundary in which all memory is allocated indirectly, and generally speaking, you don't have direct access to machine resources like ports, memory address space, the stack, etc. The idea is to run in a more secure environment.

To convert from a managed variable, say, to an unmanaged one, you have to get to the actual object itself. It's probably wrapped or boxed in some additional packaging. UNmanaged variables (like an 'int', say) - on a 32 bit machine - takes exactly 4 bytes. There is no overhead or additional packaging. The process of going from managed to unmanaged code - and back again - is called "marshaling". It allows your programs to cross the boundary.

Defining static const integer members in class definition

Not just int's. But you can't define the value in the class declaration. If you have:

class classname
{
    public:
       static int const N;
}

in the .h file then you must have:

int const classname::N = 10;

in the .cpp file.

What's the difference between "Solutions Architect" and "Applications Architect"?

No, an architect has a different job than a programmer. The architect is more concerned with nonfunctional ("ility") requirements. Like reliability, maintainability, security, and so on. (If you don't agree, consider this thought experiment: compare a CGI program written in C that does a complicated website, versus a Ruby on Rails implementation. They both have the same functional behavior; choosing an RoR architecture has what advantages.)

Generally, a "solution architect" is about the whole system -- hardware, software, and all -- which an "application architect" is working within a fixed platform, but the terms aren't that rigorous or well standardized.

What is an idempotent operation?

Just wanted to throw out a real use case that demonstrates idempotence. In JavaScript, say you are defining a bunch of model classes (as in MVC model). The way this is often implemented is functionally equivalent to something like this (basic example):

function model(name) {
  function Model() {
    this.name = name;
  }

  return Model;
}

You could then define new classes like this:

var User = model('user');
var Article = model('article');

But if you were to try to get the User class via model('user'), from somewhere else in the code, it would fail:

var User = model('user');
// ... then somewhere else in the code (in a different scope)
var User = model('user');

Those two User constructors would be different. That is,

model('user') !== model('user');

To make it idempotent, you would just add some sort of caching mechanism, like this:

var collection = {};

function model(name) {
  if (collection[name])
    return collection[name];

  function Model() {
    this.name = name;
  }

  collection[name] = Model;
  return Model;
}

By adding caching, every time you did model('user') it will be the same object, and so it's idempotent. So:

model('user') === model('user');

What is a web service endpoint?

Simply put, an endpoint is one end of a communication channel. When an API interacts with another system, the touch-points of this communication are considered endpoints. For APIs, an endpoint can include a URL of a server or service. Each endpoint is the location from which APIs can access the resources they need to carry out their function.

APIs work using ‘requests’ and ‘responses.’ When an API requests information from a web application or web server, it will receive a response. The place that APIs send requests and where the resource lives, is called an endpoint.

Reference: https://smartbear.com/learn/performance-monitoring/api-endpoints/

Java: int[] array vs int array[]

There is no difference between these two declarations, and both have the same performance.

What does "hard coded" mean?

There are two types of coding.

(1) hard-coding (2) soft-coding

Hard-coding. Assign values to program during writing source code and make executable file of program.Now, it is very difficult process to change or modify the program source code values. like in block-chain technology, genesis block is hard-code that cannot changed or modified.

Soft-coding: it is process of inserting values from external source into computer program. like insert values through keyboard, command line interface. Soft-coding considered as good programming practice because developers can easily modify programs.

What is a Y-combinator?

I think the best way to answer this is to pick a language, like JavaScript:

function factorial(num)
{
    // If the number is less than 0, reject it.
    if (num < 0) {
        return -1;
    }
    // If the number is 0, its factorial is 1.
    else if (num == 0) {
        return 1;
    }
    // Otherwise, call this recursive procedure again.
    else {
        return (num * factorial(num - 1));
    }
}

Now rewrite it so that it doesn't use the name of the function inside the function, but still calls it recursively.

The only place the function name factorial should be seen is at the call site.

Hint: you can't use names of functions, but you can use names of parameters.

Work the problem. Don't look it up. Once you solve it, you will understand what problem the y-combinator solves.

What is the definition of "interface" in object oriented programming

Interface is a contract you should comply to or given to, depending if you are implementer or a user.

C# Foreach statement does not contain public definition for GetEnumerator

In foreach loop instead of carBootSaleList use carBootSaleList.data.

You probably do not need answer anymore, but it could help someone.

Error with multiple definitions of function

The problem is that if you include fun.cpp in two places in your program, you will end up defining it twice, which isn't valid.

You don't want to include cpp files. You want to include header files.

The header file should just have the class definition. The corresponding cpp file, which you will compile separately, will have the function definition.

fun.hpp:

#include <iostream>

class classA {
    friend void funct();
public:
    classA(int a=1,int b=2):propa(a),propb(b){std::cout<<"constructor\n";}
private:
    int propa;
    int propb;
    void outfun(){
        std::cout<<"propa="<<propa<<endl<<"propb="<<propb<< std::endl;
    }
};

fun.cpp:

#include "fun.hpp"

using namespace std;

void funct(){
    cout<<"enter funct"<<endl;
    classA tmp(1,2);
    tmp.outfun();
    cout<<"exit funct"<<endl;
}

mainfile.cpp:

#include <iostream>
#include "fun.hpp"
using namespace std;

int main(int nargin,char* varargin[]) {
    cout<<"call funct"<<endl;
    funct();
    cout<<"exit main"<<endl;
    return 0;
}

Note that it is generally recommended to avoid using namespace std in header files.

"Multiple definition", "first defined here" errors

You should not include commands.c in your header file. In general, you should not include .c files. Rather, commands.c should include commands.h. As defined here, the C preprocessor is inserting the contents of commands.c into commands.h where the include is. You end up with two definitions of f123 in commands.h.

commands.h

#ifndef COMMANDS_H_
#define COMMANDS_H_

void f123();

#endif

commands.c

#include "commands.h"

void f123()
{
    /* code */
}

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

Quickest (drops and creates all tables including data):

./manage.py reset appname | ./manage.py dbshell

Caution:

  • Might not work on Windows correctly.
  • Might keep some old tables in the db

How do you overcome the svn 'out of date' error?

Are you sure you've checked out the head and not a lower revision? Also, have you done an update to make sure you've got the latest version?

There's a discussion about this on http://svn.haxx.se/users/archive-2007-01/0170.shtml.

Vector erase iterator

Because the method erase in vector return the next iterator of the passed iterator.

I will give example of how to remove element in vector when iterating.

void test_del_vector(){
    std::vector<int> vecInt{0, 1, 2, 3, 4, 5};

    //method 1
    for(auto it = vecInt.begin();it != vecInt.end();){
        if(*it % 2){// remove all the odds
            it = vecInt.erase(it); // note it will = next(it) after erase
        } else{
            ++it;
        }
    }

    // output all the remaining elements
    for(auto const& it:vecInt)std::cout<<it;
    std::cout<<std::endl;

    // recreate vecInt, and use method 2
    vecInt = {0, 1, 2, 3, 4, 5};
    //method 2
    for(auto it=std::begin(vecInt);it!=std::end(vecInt);){
        if (*it % 2){
            it = vecInt.erase(it);
        }else{
            ++it;
        }
    }

    // output all the remaining elements
    for(auto const& it:vecInt)std::cout<<it;
    std::cout<<std::endl;

    // recreate vecInt, and use method 3
    vecInt = {0, 1, 2, 3, 4, 5};
    //method 3
    vecInt.erase(std::remove_if(vecInt.begin(), vecInt.end(),
                 [](const int a){return a % 2;}),
                 vecInt.end());

    // output all the remaining elements
    for(auto const& it:vecInt)std::cout<<it;
    std::cout<<std::endl;

}

output aw below:

024
024
024

A more generate method:

template<class Container, class F>
void erase_where(Container& c, F&& f)
{
    c.erase(std::remove_if(c.begin(), c.end(),std::forward<F>(f)),
            c.end());
}

void test_del_vector(){
    std::vector<int> vecInt{0, 1, 2, 3, 4, 5};
    //method 4
    auto is_odd = [](int x){return x % 2;};
    erase_where(vecInt, is_odd);

    // output all the remaining elements
    for(auto const& it:vecInt)std::cout<<it;
    std::cout<<std::endl;    
}

How do I resolve `The following packages have unmet dependencies`

The command to have Ubuntu fix unmet dependencies and broken packages is

sudo apt-get install -f

from the man page:

-f, --fix-broken Fix; attempt to correct a system with broken dependencies in place. This option, when used with install/remove, can omit any packages to permit APT to deduce a likely solution. If packages are specified, these have to completely correct the problem. The option is sometimes necessary when running APT for the first time; APT itself does not allow broken package dependencies to exist on a system. It is possible that a system's dependency structure can be so corrupt as to require manual intervention (which usually means using dselect(1) or dpkg --remove to eliminate some of the offending packages)

Ubuntu will try to fix itself when you run the command. When it completes, you can test if it worked by running the command again, and you should receive output similar to:

Reading package lists... Done Building dependency tree Reading state information... Done 0 upgraded, 0 newly installed, 0 to remove and 2 not upgraded.

Jquery, checking if a value exists in array or not

Try jQuery.inArray()

Here is a jsfiddle link using the same code : http://jsfiddle.net/yrshaikh/SUKn2/

The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0

Example Code :

<html>
   <head>
      <style>
         div { color:blue; }
         span { color:red; }
  </style>
      <script src="http://code.jquery.com/jquery-latest.js"></script>
   </head>
   <body>    
      <div>"John" found at <span></span></div>
      <div>4 found at <span></span></div>
      <div>"Karl" not found, so <span></span></div>
      <div>
         "Pete" is in the array, but not at or after index 2, so <span></span>
      </div>
      <script>
         var arr = [ 4, "Pete", 8, "John" ];
         var $spans = $("span");
         $spans.eq(0).text(jQuery.inArray("John", arr));
         $spans.eq(1).text(jQuery.inArray(4, arr));
         $spans.eq(2).text(jQuery.inArray("Karl", arr));
         $spans.eq(3).text(jQuery.inArray("Pete", arr, 2));
      </script>  
   </body>
</html>

Output:

"John" found at 3
4 found at 0
"Karl" not found, so -1
"Pete" is in the array, but not at or after index 2, so -1

How to add a changed file to an older (not last) commit in Git

with git 1.7, there's a really easy way using git rebase:

stage your files:

git add $files

create a new commit and re-use commit message of your "broken" commit

git commit -c master~4

prepend fixup! in the subject line (or squash! if you want to edit commit (message)):

fixup! Factored out some common XPath Operations

use git rebase -i --autosquash to fixup your commit

Specifing width of a flexbox flex item: width or basis?

The bottom statement is equivalent to:

.half {
   flex-grow: 0;
   flex-shrink: 0;
   flex-basis: 50%;
}

Which, in this case, would be equivalent as the box is not allowed to flex and therefore retains the initial width set by flex-basis.

Flex-basis defines the default size of an element before the remaining space is distributed so if the element were allowed to flex (grow/shrink) it may not be 50% of the width of the page.

I've found that I regularly return to https://css-tricks.com/snippets/css/a-guide-to-flexbox/ for help regarding flexbox :)

How to display Woocommerce product price by ID number on a custom page?

In woocommerce,

Get regular price :

$price = get_post_meta( get_the_ID(), '_regular_price', true);
// $price will return regular price

Get sale price:

$sale = get_post_meta( get_the_ID(), '_sale_price', true);
// $sale will return sale price

jQuery - Disable Form Fields

$('input, select').attr('disabled', 'disabled');

What is the difference between a static and a non-static initialization code block

The static code block can be used to instantiate or initialize class variables (as opposed to object variables). So declaring "a" static means that is only one shared by all Test objects, and the static code block initializes "a" only once, when the Test class is first loaded, no matter how many Test objects are created.

How to dynamically insert a <script> tag via jQuery after page load?

A simpler way is:

$('head').append('<script type="text/javascript" src="your.js"></script>');

You can also use this form to load css.

How to load a UIView using a nib file created with Interface Builder

I made a category that I like:

UIView+NibInitializer.h

#import <UIKit/UIKit.h>

@interface UIView (NibInitializer)
- (instancetype)initWithNibNamed:(NSString *)nibNameOrNil;
@end

UIView+NibInitializer.m

#import "UIView+NibInitializer.h"

@implementation UIView (NibInitializer)

- (instancetype)initWithNibNamed:(NSString *)nibNameOrNil
{
    if (!nibNameOrNil) {
        nibNameOrNil = NSStringFromClass([self class]);
    }
    NSArray *viewsInNib = [[NSBundle mainBundle] loadNibNamed:nibNameOrNil
                                                        owner:self
                                                      options:nil];
    for (id view in viewsInNib) {
        if ([view isKindOfClass:[self class]]) {
            self = view;
            break;
        }
    }
    return self;
}

@end

Then, call like this:

MyCustomView *myCustomView = [[MyCustomView alloc] initWithNibNamed:nil];

Use a nib name if your nib is named something other than the name of your class.

To override it in your subclasses for additional behavior, it could look like this:

- (instancetype)initWithNibNamed:(NSString *)nibNameOrNil
{
    self = [super initWithNibNamed:nibNameOrNil];
    if (self) {
        self.layer.cornerRadius = CGRectGetHeight(self.bounds) / 2.0;
    }
    return self;
}

Registry key Error: Java version has value '1.8', but '1.7' is required

My short contribution, for sharing the same problem with Talend Open Studio 64 bit version.

  1. Launch ..\TOS_DI-Win32-20150702_1326-V6.0.0\TOS_DI-win-x86_64.exe manually (not link an startup Windows menu)
  2. and this registry error message appears

To resolve this, remove all java.exe, javaw.exe and javaws.exe files on c:\ProgramData\Oracle\Java\javapath\

and TOS start with 64 bits version correctly !

Get a list of all the files in a directory (recursive)

This is what I came up with for a gradle build script:

task doLast {
    ext.FindFile = { list, curPath ->
        def files = file(curPath).listFiles().sort()

        files.each {  File file ->

            if (file.isFile()) {
                list << file
            }
            else {
                list << file  // If you want the directories in the list

                list = FindFile( list, file.path) 
            }
        }
        return list
    }

    def list = []
    def theFile = FindFile(list, "${project.projectDir}")

    list.each {
        println it.path
    }
}

How do I configure IIS for URL Rewriting an AngularJS application in HTML5 mode?

I had a similar issue with Angular and IIS throwing a 404 status code on manual refresh and tried the most voted solution but that did not work for me. Also tried a bunch of other solutions having to deal with WebDAV and changing handlers and none worked.

Luckily I found this solution and it worked (took out parts I didn't need). So if none of the above works for you or even before trying them, try this and see if that fixes your angular deployment on iis issue.

Add the snippet to your webconfig in the root directory of your site. From my understanding, it removes the 404 status code from any inheritance (applicationhost.config, machine.config), then creates a 404 status code at the site level and redirects back to the home page as a custom 404 page.

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <httpErrors errorMode="Custom">
      <remove statusCode="404"/>
      <error statusCode="404" path="/index.html" responseMode="ExecuteURL"/>
    </httpErrors>
  </system.webServer>
</configuration>

"The system cannot find the file C:\ProgramData\Oracle\Java\javapath\java.exe"

I got same error while running JAVA command. To resolve this, I moved the java path as the first entry in the path, and it resolved the issue. Please have look at this screenshot for reference:

enter image description here

Datetime BETWEEN statement not working in SQL Server

Do you have times associated with your dates? BETWEEN is inclusive, but when you convert 2013-10-18 to a date it becomes 2013-10-18 00:00:000.00. Anything that is logged after the first second of the 18th will not shown using BETWEEN, unless you include a time value.

Try:

SELECT * FROM LOGS WHERE CHECK_IN BETWEEN CONVERT(datetime,'2013-10-17') AND CONVERT(datetime,'2013-10-18 23:59:59:999')

if you want to search the entire day of the 18th.

SQL DATETIME fields have milliseconds. So I added 999 to the field.

How to "test" NoneType in python?

It can also be done with isinstance as per Alex Hall's answer :

>>> NoneType = type(None)
>>> x = None
>>> type(x) == NoneType
True
>>> isinstance(x, NoneType)
True

isinstance is also intuitive but there is the complication that it requires the line

NoneType = type(None)

which isn't needed for types like int and float.

Downloading and unzipping a .zip file without writing to disk

I'd like to offer an updated Python 3 version of Vishal's excellent answer, which was using Python 2, along with some explanation of the adaptations / changes, which may have been already mentioned.

from io import BytesIO
from zipfile import ZipFile
import urllib.request
    
url = urllib.request.urlopen("http://www.unece.org/fileadmin/DAM/cefact/locode/loc162txt.zip")

with ZipFile(BytesIO(url.read())) as my_zip_file:
    for contained_file in my_zip_file.namelist():
        # with open(("unzipped_and_read_" + contained_file + ".file"), "wb") as output:
        for line in my_zip_file.open(contained_file).readlines():
            print(line)
            # output.write(line)

Necessary changes:

  • There's no StringIO module in Python 3 (it's been moved to io.StringIO). Instead, I use io.BytesIO]2, because we will be handling a bytestream -- Docs, also this thread.
  • urlopen:

Note:

  • In Python 3, the printed output lines will look like so: b'some text'. This is expected, as they aren't strings - remember, we're reading a bytestream. Have a look at Dan04's excellent answer.

A few minor changes I made:

  • I use with ... as instead of zipfile = ... according to the Docs.
  • The script now uses .namelist() to cycle through all the files in the zip and print their contents.
  • I moved the creation of the ZipFile object into the with statement, although I'm not sure if that's better.
  • I added (and commented out) an option to write the bytestream to file (per file in the zip), in response to NumenorForLife's comment; it adds "unzipped_and_read_" to the beginning of the filename and a ".file" extension (I prefer not to use ".txt" for files with bytestrings). The indenting of the code will, of course, need to be adjusted if you want to use it.
    • Need to be careful here -- because we have a byte string, we use binary mode, so "wb"; I have a feeling that writing binary opens a can of worms anyway...
  • I am using an example file, the UN/LOCODE text archive:

What I didn't do:

  • NumenorForLife asked about saving the zip to disk. I'm not sure what he meant by it -- downloading the zip file? That's a different task; see Oleh Prypin's excellent answer.

Here's a way:

import urllib.request
import shutil

with urllib.request.urlopen("http://www.unece.org/fileadmin/DAM/cefact/locode/2015-2_UNLOCODE_SecretariatNotes.pdf") as response, open("downloaded_file.pdf", 'w') as out_file:
    shutil.copyfileobj(response, out_file)

log4j configuration via JVM argument(s)?

The solution is using of the following JVM argument:

-Dlog4j.configuration={path to file}

If the file is NOT in the classpath (in WEB-INF/classes in case of Tomcat) but somewhere on you disk, use file:, like

-Dlog4j.configuration=file:C:\Users\me\log4j.xml

More information and examples here: http://logging.apache.org/log4j/1.2/manual.html

Python Save to file

You need to open the file again using open(), but this time passing 'w' to indicate that you want to write to the file. I would also recommend using with to ensure that the file will be closed when you are finished writing to it.

with open('Failed.txt', 'w') as f:
    for ip in [k for k, v in ips.iteritems() if v >=5]:
        f.write(ip)

Naturally you may want to include newlines or other formatting in your output, but the basics are as above.

The same issue with closing your file applies to the reading code. That should look like this:

ips = {}
with open('today','r') as myFile:
    for line in myFile:
        parts = line.split(' ')
        if parts[1] == 'Failure':
            if parts[0] in ips:
                ips[pars[0]] += 1
            else:
                ips[parts[0]] = 0

How does one parse XML files?

If you're using .NET 2.0, try XmlReader and its subclasses XmlTextReader, and XmlValidatingReader. They provide a fast, lightweight (memory usage, etc.), forward-only way to parse an XML file.

If you need XPath capabilities, try the XPathNavigator. If you need the entire document in memory try XmlDocument.

Count number of files within a directory in Linux?

this is one:

ls -l . | egrep -c '^-'

Note:

ls -1 | wc -l

Which means: ls: list files in dir

-1: (that's a ONE) only one entry per line. Change it to -1a if you want hidden files too

|: pipe output onto...

wc: "wordcount"

-l: count lines.

How to Enable ActiveX in Chrome?

anyone who says activex is less secure then NPAPI is crazy. They both allow the exact same access. Yes I've written both. The only reason people think activeX is insecure is because 10+ years ago IE had default settings that allowed a remote site to auto download the plugin.

How do you connect to multiple MySQL databases on a single webpage?

<?php
    // Sapan Mohanty
    // Skype:sapan.mohannty
    //***********************************
    $oldData = mysql_connect('localhost', 'DBUSER', 'DBPASS');
    echo mysql_error();
    $NewData = mysql_connect('localhost', 'DBUSER', 'DBPASS');
    echo mysql_error();
    mysql_select_db('OLDDBNAME', $oldData );
    mysql_select_db('NEWDBNAME', $NewData );
    $getAllTablesName    = "SELECT table_name FROM information_schema.tables WHERE table_type = 'base table'";
    $getAllTablesNameExe = mysql_query($getAllTablesName);
    //echo mysql_error();
    while ($dataTableName = mysql_fetch_object($getAllTablesNameExe)) {

        $oldDataCount       = mysql_query('select count(*) as noOfRecord from ' . $dataTableName->table_name, $oldData);
        $oldDataCountResult = mysql_fetch_object($oldDataCount);


        $newDataCount       = mysql_query('select count(*) as noOfRecord from ' . $dataTableName->table_name, $NewData);
        $newDataCountResult = mysql_fetch_object($newDataCount);

        if ( $oldDataCountResult->noOfRecord != $newDataCountResult->noOfRecord ) {
            echo "<br/><b>" . $dataTableName->table_name . "</b>";
            echo " | Old: " . $oldDataCountResult->noOfRecord;
            echo " | New: " . $newDataCountResult->noOfRecord;

            if ($oldDataCountResult->noOfRecord < $newDataCountResult->noOfRecord) {
                echo " | <font color='green'>*</font>";

            } else {
                echo " | <font color='red'>*</font>";
            }

            echo "<br/>----------------------------------------";

        }     

    }
    ?>

how to add picasso library in android studio

Add this to your dependencies in build.gradle:

enter image description here

dependencies {
 implementation 'com.squareup.picasso:picasso:2.71828'
  ...

The latest version can be found here

Make sure you are connected to the Internet. When you sync Gradle, all related files will be added to your project

Take a look at your libraries folder, the library you just added should be in there.

enter image description here

super() raises "TypeError: must be type, not classobj" for new-style class

You can also use class TextParser(HTMLParser, object):. This makes TextParser a new-style class, and super() can be used.

Plot a line graph, error in xy.coords(x, y, xlabel, ylabel, log) : 'x' and 'y' lengths differ

plot(t) is in this case the same as

plot(t[[1]], t[[2]])

As the error message says, x and y differ in length and that is because you plot a list with length 4 against 1:

> length(t)
[1] 4
> length(1)
[1] 1

In your second example you plot a list with elements named x and y, both vectors of length 2, so plot plots these two vectors.

Edit:

If you want to plot lines use

plot(t, type="l")

Targeting both 32bit and 64bit with Visual Studio in same solution/project

If you use Custom Actions written in .NET as part of your MSI installer then you have another problem.

The 'shim' that runs these custom actions is always 32bit then your custom action will run 32bit as well, despite what target you specify.

More info & some ninja moves to get around (basically change the MSI to use the 64 bit version of this shim)

Building an MSI in Visual Studio 2005/2008 to work on a SharePoint 64

64-bit Managed Custom Actions with Visual Studio

What is the proper way to check if a string is empty in Perl?

As already mentioned by several people, eq is the right operator here.

If you use warnings; in your script, you'll get warnings about this (and many other useful things); I'd recommend use strict; as well.

How do I correct this Illegal String Offset?

I get the same error in WP when I use php ver 7.1.6 - just take your php version back to 7.0.20 and the error will disappear.

How to run a command as a specific user in an init script?

I usually do it the way that you are doing it (i.e. sudo -u username command). But, there is also the 'djb' way to run a daemon with privileges of another user. See: http://thedjbway.b0llix.net/daemontools/uidgid.html

Apple Mach-O Linker Error when compiling for device

In my case, the cause of such Apple Mach-O Linker error was source code file (.m) inclusion to resource bundle target.

Verify that recently created .m file is not included in a bundle: select the file in project navigator, open file inspector and make sure that resource bundle checkbox is deselected in Target Membership section.

SQL Add foreign key to existing column

In the future.

ALTER TABLE Employees
ADD UserID int;

ALTER TABLE Employees
ADD CONSTRAINT FK_ActiveDirectories_UserID FOREIGN KEY (UserID)
    REFERENCES ActiveDirectories(id);

Transform char array into String

I have search it again and search this question in baidu. Then I find 2 ways:

1,

_x000D_
_x000D_
char ch[]={'a','b','c','d','e','f','g','\0'};_x000D_
string s=ch;_x000D_
cout<<s;
_x000D_
_x000D_
_x000D_

Be aware to that '\0' is necessary for char array ch.

2,

_x000D_
_x000D_
#include<iostream>_x000D_
#include<string>_x000D_
#include<strstream>_x000D_
using namespace std;_x000D_
_x000D_
int main()_x000D_
{_x000D_
 char ch[]={'a','b','g','e','d','\0'};_x000D_
 strstream s;_x000D_
 s<<ch;_x000D_
 string str1;_x000D_
 s>>str1;_x000D_
 cout<<str1<<endl;_x000D_
 return 0;_x000D_
}
_x000D_
_x000D_
_x000D_

In this way, you also need to add the '\0' at the end of char array.

Also, strstream.h file will be abandoned and be replaced by stringstream

How exactly do you configure httpOnlyCookies in ASP.NET?

If you're using ASP.NET 2.0 or greater, you can turn it on in the Web.config file. In the <system.web> section, add the following line:

<httpCookies httpOnlyCookies="true"/>

Property 'json' does not exist on type 'Object'

UPDATE: for rxjs > v5.5

As mentioned in some of the comments and other answers, by default the HttpClient deserializes the content of a response into an object. Some of its methods allow passing a generic type argument in order to duck-type the result. Thats why there is no json() method anymore.

import {throwError} from 'rxjs';
import {catchError, map} from 'rxjs/operators';

export interface Order {
  // Properties
}

interface ResponseOrders {
  results: Order[];
}

@Injectable()
export class FooService {
 ctor(private http: HttpClient){}

 fetch(startIndex: number, limit: number): Observable<Order[]> {
    let params = new HttpParams();
    params = params.set('startIndex',startIndex.toString()).set('limit',limit.toString());
    // base URL should not have ? in it at the en
    return this.http.get<ResponseOrders >(this.baseUrl,{
       params
    }).pipe(
       map(res => res.results || []),
       catchError(error => _throwError(error.message || error))
    );
} 

Notice that you could easily transform the returned Observable to a Promise by simply invoking toPromise().

ORIGINAL ANSWER:

In your case, you can

Assumming that your backend returns something like:

{results: [{},{}]}

in JSON format, where every {} is a serialized object, you would need the following:

// Somewhere in your src folder

export interface Order {
  // Properties
}

import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

import { Order } from 'somewhere_in_src';    

@Injectable()
export class FooService {
 ctor(private http: HttpClient){}

 fetch(startIndex: number, limit: number): Observable<Order[]> {
    let params = new HttpParams();
    params = params.set('startIndex',startIndex.toString()).set('limit',limit.toString());
    // base URL should not have ? in it at the en
    return this.http.get(this.baseUrl,{
       params
    })
    .map(res => res.results as Order[] || []); 
   // in case that the property results in the res POJO doesnt exist (res.results returns null) then return empty array ([])
  }
} 

I removed the catch section, as this could be archived through a HTTP interceptor. Check the docs. As example:

https://gist.github.com/jotatoledo/765c7f6d8a755613cafca97e83313b90

And to consume you just need to call it like:

// In some component for example
this.fooService.fetch(...).subscribe(data => ...); // data is Order[]

Remove values from select list based on condition

A few caveats not covered in most answers:

  • Check against multiple items (some should be deleted, some should remain)
  • Skip the first option (-Select-) on some option lists

A take on these:

const eligibleOptions = ['800000002', '800000001'];
let optionsList = document.querySelector("select#edit-salutation");
for (let i = 1; i<optionsList.length; i++) {
    if(eligibleOptions.indexOf(optionsList.options[i].value) === -1) {
        cbxSal.remove(i);
        i--;
    }
}

Inconsistent accessibility: property type is less accessible

Your class Delivery has no access modifier, which means it defaults to internal. If you then try to expose a property of that type as public, it won't work. Your type (class) needs to have the same, or higher access as your property.

More about access modifiers: http://msdn.microsoft.com/en-us/library/ms173121.aspx

How do I count unique items in field in Access query?

Access-Engine does not support

SELECT count(DISTINCT....) FROM ...

You have to do it like this:

SELECT count(*) 
FROM
(SELECT DISTINCT Name FROM table1)

Its a little workaround... you're counting a DISTINCT selection.

JAVA_HOME does not point to the JDK

Experienced this issue when trying to run the android emulator with Meteor 1.0 on elementary OS Luna (based on Ubuntu 12.04 LTS sources).

openjdk-6-jdk was installed, as well as the jre. In the end, not expecting any success, I tried:

sudo apt-get remove openjdk-6-*

this resulted in fully expected errors, so I followed up with

sudo apt-get install openjdk-6-jdk

and things worked. Go figure.

How to redirect DNS to different ports

Since I had troubles understanding this post here is a simple explanation for people like me. It is useful if:

  • You DO NOT need Load Balacing.
  • You DO NOT want to use nginx to do port forwarding.
  • You DO want to do PORT FORWARDING according to specific subdomains using SRV record.

Then here is what you need to do:

SRV records:

_minecraft._tcp.1.12          IN SRV    1 100 25567 1.12.<your-domain-name.com>.
_minecraft._tcp.1.13          IN SRV    1 100 25566 1.13.<your-domain-name.com>.

(I did not need a srv record for 1.14 since my 1.14 minecraft server was already on the 25565 port which is the default port of minecraft.)

And the A records:

1.12                          IN A      <your server IP>
1.13                          IN A      <your server IP>
1.14                          IN A      <your server IP>

Insert and set value with max()+1 problems

We declare a variable 'a'

SET **@a** = (SELECT MAX( customer_id ) FROM customers) +1;

INSERT INTO customers
  ( customer_id, firstname, surname )
VALUES 
  (**@a**, 'jim', 'sock')

How do I combine two lists into a dictionary in Python?

I found myself needing to create a dictionary of three lists (latitude, longitude, and a value), with the following doing the trick:

> lat = [45.3,56.2,23.4,60.4]
> lon = [134.6,128.7,111.9,75.8]
> val = [3,6,2,5]
> dict(zip(zip(lat,lon),val))
{(56.2, 128.7): 6, (60.4, 75.8): 5, (23.4, 111.9): 2, (45.3, 134.6): 3}

or similar to the above examples:

> list1 = [1,2,3,4]
> list2 = [1,2,3,4]
> list3 = ['a','b','c','d']
> dict(zip(zip(list1,list2),list3))
{(3, 3): 'c', (4, 4): 'd', (1, 1): 'a', (2, 2): 'b'}

Note: Dictionaries are "orderless", but if you would like to view it as "sorted", refer to THIS question if you'd like to sort by key, or THIS question if you'd like to sort by value.

jQuery issue in Internet Explorer 8

Some people stumbling on this post might get this issue with jquery and IE8 because they're using >= jQuery v2. Use this code:

<!--[if lt IE 9]>
    <script src="jquery-1.9.0.js"></script>
<![endif]-->
<!--[if gte IE 9]><!-->
    <script src="jquery-2.0.0.js"></script>
<!--<![endif]-->

How to add 'libs' folder in Android Studio?

libs and Assets folder in Android Studio:

Create libs folder inside app folder and Asset folder inside main in the project directory by exploring project directory.

Now come back to Android Studio and switch the combo box from Android to Project. enjoy...

SyntaxError: Cannot use import statement outside a module

Tried with all the methods but nothing worked

I got one reference from git hub.

To use type script imports with nodejs, i installed below packages.

1. npm i typescript

2. npm i ts-node

Won't require type: module in package.json

E:g

{
  "name": "my-app",
  "version": "0.0.1",
  "description": "",
  "scripts": {
   
  },
  "dependencies": {
    "knex": "^0.16.3",
    "pg": "^7.9.0",
    "ts-node": "^8.1.0",
    "typescript": "^3.3.4000"
  }
}

JavaScript getElementByID() not working

You need to put the JavaScript at the end of the body tag.

It doesn't find it because it's not in the DOM yet!

You can also wrap it in the onload event handler like this:

window.onload = function() {
var refButton = document.getElementById( 'btnButton' );
refButton.onclick = function() {
   alert( 'I am clicked!' );
}
}

JSON to string variable dump

Yes, JSON.stringify, can be found here, it's included in Firefox 3.5.4 and above.

A JSON stringifier goes in the opposite direction, converting JavaScript data structures into JSON text. JSON does not support cyclic data structures, so be careful to not give cyclical structures to the JSON stringifier. https://web.archive.org/web/20100611210643/http://www.json.org/js.html

var myJSONText = JSON.stringify(myObject, replacer);

Cannot perform runtime binding on a null reference, But it is NOT a null reference

My solution to this error was that a copy and paste from another project that had a reference to @Model.Id. This particular page didn't have a model but the error line was so far off from the actual error I about never found it!

Call Python function from MATLAB

This seems to be a suitable method to "tunnel" functions from Python to MATLAB:

http://code.google.com/p/python-matlab-wormholes/

The big advantage is that you can handle ndarrays with it, which is not possible by the standard output of programs, as suggested before. (Please correct me, if you think this is wrong - it would save me a lot of trouble :-) )

Advantage of switch over if-else statement

Use switch, it is what it's for and what programmers expect.

I would put the redundant case labels in though - just to make people feel comfortable, I was trying to remember when / what the rules are for leaving them out.
You don't want the next programmer working on it to have to do any unnecessary thinking about language details (it might be you in a few months time!)

grep output to show only matching file

-l (that's a lower-case L).

Not Able To Debug App In Android Studio

I solved this issue after doing the following steps:

Go to Tools==>android==>Disable ADB integration and enable it again.

After that, unplug USB from device and plug in again.

Finally press shift + F9

How do I revert an SVN commit?

While the suggestions given already may work for some people, it does not work for my case. When performing the merge, users at rev 1443 who update to rev 1445, still sync all files changed in 1444 even though they are equal to 1443 from the merge. I needed end users to not see the update at all.

If you want to completely hide the commit it is possible by creating a new branch at correct revision and then swapping the branches. The only thing is you need to remove and re add all locks.

copy -r 1443 file:///<your_branch> file:///<your_branch_at_correct_rev>
svn move file:///<your_branch> file:///<backup_branch>
svn move file:///<your_branch_at_correct_rev> file:///<your_branch>

This worked for me, perhaps it will be helpful to someone else out there =)

Declaring a python function with an array parameters and passing an array argument to the function call?

I guess I'm unclear about what the OP was really asking for... Do you want to pass the whole array/list and operate on it inside the function? Or do you want the same thing done on every value/item in the array/list. If the latter is what you wish I have found a method which works well.

I'm more familiar with programming languages such as Fortran and C, in which you can define elemental functions which operate on each element inside an array. I finally tracked down the python equivalent to this and thought I would repost the solution here. The key is to 'vectorize' the function. Here is an example:

def myfunc(a,b):
    if (a>b): return a
    else: return b
vecfunc = np.vectorize(myfunc)
result=vecfunc([[1,2,3],[5,6,9]],[7,4,5])
print(result)

Output:

[[7 4 5]
 [7 6 9]]

How to draw rounded rectangle in Android UI?

You could just define a new xml background in the drawables folder

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="enter_your_desired_color_here" />
<corners android:radius="enter_your_desired_radius_the_corners" />
</shape>  

After this just include it in your TextView or EditText by defining it in the background.

<TextView
 android:id="@+id/textView"
 android:layout_width="0dp"
 android:layout_height="80dp"
 android:background="YOUR_FILE_HERE"
 Android:layout_weight="1"
 android:gravity="center"
 android:text="TEXT_HERE"
 android:textSize="40sp" />

javax.persistence.PersistenceException: No Persistence provider for EntityManager named customerManager

I was also facing the same issue when I was trying to get JPA entity manager configured in Tomcat 8. First I has an issue with the SystemException class not being found and hence the entityManagerFactory was not being created. I removed the hibernate entity manager dependency and then my entityManagerFactory was not able to lookup for the persistence provider. After going thru a lot of research and time got to know that hibernate entity manager is must to lookup for some configuration. Then put back the entity manager jar and then added JTA Api as a dependency and it worked fine.

Calculate average in java

It seems old thread, but Java has evolved since then & introduced Streams & Lambdas in Java 8. So might help everyone who want to do it using Java 8 features.

  • In your case, you want to convert args which is String[] into double or int. You can do this using Arrays.stream(<arr>). Once you have stream of String array elements, you can use mapToDouble(s -> Double.parseDouble(s)) which will convert stream of Strings into stream of doubles.
  • Then you can use Stream.collect(supplier, accumulator, combiner) to calculate average if you want to control incremental calculation yourselves. Here is some good example.
  • If you don't want to incrementally do average, you can directly use Java's Collectors.averagingDouble() which directly calculates and returns average. some examples here.

How to call a function, PostgreSQL

The function call still should be a valid SQL statement:

SELECT "saveUser"(3, 'asd','asd','asd','asd','asd');

WPF: Setting the Width (and Height) as a Percentage Value

For anybody who is getting an error like : '2*' string cannot be converted to Length.

<Grid >
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="2*" /><!--This will make any control in this column of grid take 2/5 of total width-->
        <ColumnDefinition Width="3*" /><!--This will make any control in this column of grid take 3/5 of total width-->
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition MinHeight="30" />
    </Grid.RowDefinitions>

    <TextBlock Grid.Column="0" Grid.Row="0">Your text block a:</TextBlock>
    <TextBlock Grid.Column="1" Grid.Row="0">Your text block b:</TextBlock>
</Grid>

Proper MIME media type for PDF files

The standard MIME type is application/pdf. The assignment is defined in RFC 3778, The application/pdf Media Type, referenced from the MIME Media Types registry.

MIME types are controlled by a standards body, The Internet Assigned Numbers Authority (IANA). This is the same organization that manages the root name servers and the IP address space.

The use of x-pdf predates the standardization of the MIME type for PDF. MIME types in the x- namespace are considered experimental, just as those in the vnd. namespace are considered vendor-specific. x-pdf might be used for compatibility with old software.

How to automate browsing using python?

You may have a look at these slides from the last italian pycon (pdf): The author listed most of the library for doing scraping and autoted browsing in python. so you may have a look at it.

I like very much twill (which has already been suggested), which has been developed by one of the authors of nose and it is specifically aimed at testing web sites.

Read next word in java

Using Scanners, you will end up spawning a lot of objects for every line. You will generate a decent amount of garbage for the GC with large files. Also, it is nearly three times slower than using split().

On the other hand, If you split by space (line.split(" ")), the code will fail if you try to read a file with a different whitespace delimiter. If split() expects you to write a regular expression, and it does matching anyway, use split("\\s") instead, that matches a "bit" more whitespace than just a space character.

P.S.: Sorry, I don't have right to comment on already given answers.

Unix epoch time to Java Date object

Epoch is the number of seconds since Jan 1, 1970..

So:

String epochString = "1081157732";
long epoch = Long.parseLong( epochString );
Date expiry = new Date( epoch * 1000 );

For more information: http://www.epochconverter.com/

How to Solve Max Connection Pool Error

Here's what u can also try....

run your application....while it is still running launch your command prompt

while your application is running type netstat -n on the command prompt. You should see a list of TCP/IP connections. Check if your list is not very long. Ideally you should have less than 5 connections in the list. Check the status of the connections.
If you have too many connections with a TIME_WAIT status it means the connection has been closed and is waiting for the OS to release the resources. If you are running on Windows, the default ephemeral port rang is between 1024 and 5000 and the default time it takes Windows to release the resource from TIME_WAIT status is 4 minutes. So if your application used more then 3976 connections in less then 4 minutes, you will get the exception you got.

Suggestions to fix it:

  1. Add a connection pool to your connection string.

If you continue to receive the same error message (which is highly unlikely) you can then try the following: (Please don't do it if you are not familiar with the Windows registry)

  1. Run regedit from your run command. In the registry editor look for this registry key: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters:

Modify the settings so they read:

MaxUserPort = dword:00004e20 (10,000 decimal) TcpTimedWaitDelay = dword:0000001e (30 decimal)

This will increase the number of ports to 10,000 and reduce the time to release freed tcp/ip connections.

Only use suggestion 2 if 1 fails.

Thank you.

Http Post With Body

You can use HttpClient and HttpPost to build and send the request.

HttpClient client= new DefaultHttpClient();
HttpPost request = new HttpPost("www.example.com");

List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("paramName", "paramValue"));

request.setEntity(new UrlEncodedFormEntity(pairs ));
HttpResponse resp = client.execute(request);

How to force a web browser NOT to cache images

Simple fix: Attach a random query string to the image:

<img src="foo.cgi?random=323527528432525.24234" alt="">

What the HTTP RFC says:

Cache-Control: no-cache

But that doesn't work that well :)

How to parse a string into a nullable int

Try this:

public static int? ParseNullableInt(this string value)
{
    int intValue;
    if (int.TryParse(value, out intValue))
        return intValue;
    return null;
}

What does the regex \S mean in JavaScript?

\s matches whitespace (spaces, tabs and new lines). \S is negated \s.

pandas: to_numeric for multiple columns

df[cols] = pd.to_numeric(df[cols].stack(), errors='coerce').unstack()

insert datetime value in sql database with c#

This is an older question with a proper answer (please use parameterized queries) which I'd like to extend with some timezone discussion. For my current project I was interested in how do the datetime columns handle timezones and this question is the one I found.

Turns out, they do not, at all.

datetime column stores the given DateTime as is, without any conversion. It does not matter if the given datetime is UTC or local.

You can see for yourself:

using (var connection = new SqlConnection(connectionString))
{
    connection.Open();
    using (var command = connection.CreateCommand())
    {
        command.CommandText = "SELECT * FROM (VALUES (@a, @b, @c)) example(a, b, c);";

        var local = DateTime.Now;
        var utc = local.ToUniversalTime();

        command.Parameters.AddWithValue("@a", utc);
        command.Parameters.AddWithValue("@b", local);
        command.Parameters.AddWithValue("@c", utc.ToLocalTime());

        using (var reader = command.ExecuteReader())
        {
            reader.Read();

            var localRendered = local.ToString("o");

            Console.WriteLine($"a = {utc.ToString("o").PadRight(localRendered.Length, ' ')} read = {reader.GetDateTime(0):o}, {reader.GetDateTime(0).Kind}");
            Console.WriteLine($"b = {local:o} read = {reader.GetDateTime(1):o}, {reader.GetDateTime(1).Kind}");
            Console.WriteLine($"{"".PadRight(localRendered.Length + 4, ' ')} read = {reader.GetDateTime(2):o}, {reader.GetDateTime(2).Kind}");
        }
    }
}

What this will print will of course depend on your time zone but most importantly the read values will all have Kind = Unspecified. The first and second output line will be different by your timezone offset. Second and third will be the same. Using the "o" format string (roundtrip) will not show any timezone specifiers for the read values.

Example output from GMT+02:00:

a = 2018-11-20T10:17:56.8710881Z      read = 2018-11-20T10:17:56.8700000, Unspecified
b = 2018-11-20T12:17:56.8710881+02:00 read = 2018-11-20T12:17:56.8700000, Unspecified
                                      read = 2018-11-20T12:17:56.8700000, Unspecified

Also note of how the data gets truncated (or rounded) to what seems like 10ms.

What is a Subclass

A subclass is something that extends the functionality of your existing class. I.e.

Superclass - describes the catagory of objects:

public abstract class Fruit {

    public abstract Color color;

}

Subclass1 - describes attributes of the individual Fruit objects:

public class Apple extends Fruit {

    Color color = red;

}

Subclass2 - describes attributes of the individual Fruit objects:

public class Banana extends Fruit {

    Color color = yellow;

}

The 'abstract' keyword in the superclass means that the class will only define the mandatory information that each subclass must have i.e. A piece of fruit must have a color so it is defines in the super class and all subclasses must 'inherit' that attribute and define the value that describes the specific object.

Does that make sense?

Horizontal list items

A much better way is to use inline-block, because you don't need to use clear:both at the end of your list anymore.

Try this:

<ul>
    <li>
        <a href="#">some item</a>
    </li>
    <li>
        <a href="#">another item</a>
    </li>
</ul>

CSS:

ul > li{
    display:inline-block;
}

Have a look at it here : http://jsfiddle.net/shahverdy/4N6Ap/

How can I repeat a character in Bash?

No easy way. But for example:

seq -s= 100|tr -d '[:digit:]'

Or maybe a standard-conforming way:

printf %100s |tr " " "="

There's also a tput rep, but as for my terminals at hand (xterm and linux) they don't seem to support it:)

tsc is not recognized as internal or external command

In the VSCode file tasks.json, the "command": "tsc" will try to find the tsc windows command script in some folder that it deems to be your modules folder.

If you know where the command npm install -g typescript or npm install typescript is saving to, I would recommend replacing:

"command": "tsc"

with

"command": "D:\\Projects\\TS\\Tutorial\\node_modules\\.bin\\tsc"

where D:\\...\\bin is the folder that contains my tsc windows executable

Will determine where my vscode is natively pointing to right now to find the tsc and fix it I guess.

The service cannot accept control messages at this time

I forgot I had mine attached to Visual Studio debugger. Be sure to disconnect from there, and then wait a moment. Otherwise killing the process viewing the PID from the Worker Processes functionality of IIS manager will work too.

How to indent HTML tags in Notepad++

In Notepad++ v7.8.9 you can use the Tab key to increase the indention level, and use Shift + Tab to decrease the indentation level.

What in layman's terms is a Recursive Function using PHP

It work a simple example recursive (Y)

<?php 


function factorial($y,$x) { 

    if ($y < $x) { 
        echo $y; 
    } else { 
        echo $x; 
        factorial($y,$x+1);
    } 
}

$y=10;

$x=0;
factorial($y,$x);

 ?>

How to create batch file in Windows using "start" with a path and command with spaces

Actually, his example won't work (although at first I thought that it would, too). Based on the help for the Start command, the first parameter is the name of the newly created Command Prompt window, and the second and third should be the path to the application and its parameters, respectively. If you add another "" before path to the app, it should work (at least it did for me). Use something like this:

start "" "c:\path with spaces\app.exe" param1 "param with spaces"

You can change the first argument to be whatever you want the title of the new command prompt to be. If it's a Windows app that is created, then the command prompt won't be displayed, and the title won't matter.

How to force the browser to reload cached CSS and JavaScript files

My method to do this is simply to have the link element into a server-side include:

<!--#include virtual="/includes/css-element.txt"-->

where the contents of css-element.txt is

<link rel="stylesheet" href="mycss.css"/>

so the day you want to link to my-new-css.css or whatever, you just change the include.

Is it possible to hide/encode/encrypt php source code and let others have the system?

Yes, you can definitely hide/encode/encrypt the php source code and 'others' can install it on their machine. You could use the below tools to achieve the same.

But these 'others' can also decode/decrypt the source code using other tools and services found online. So you cannot 100% protect your code, what you can do is, make it tougher for someone to reverse engineer your code.

Most of these tools above support Encoding and Obfuscating.

  • Encoding will hide your code by encrypting it.
  • Obfuscating will make your code difficult to understand.

You can choose to use both (Encoding and Obfuscating) or either one, depending on your needs.

Calculating a directory's size using Python?

This walks all sub-directories; summing file sizes:

import os

def get_size(start_path = '.'):
    total_size = 0
    for dirpath, dirnames, filenames in os.walk(start_path):
        for f in filenames:
            fp = os.path.join(dirpath, f)
            # skip if it is symbolic link
            if not os.path.islink(fp):
                total_size += os.path.getsize(fp)

    return total_size

print(get_size(), 'bytes')

And a oneliner for fun using os.listdir (Does not include sub-directories):

import os
sum(os.path.getsize(f) for f in os.listdir('.') if os.path.isfile(f))

Reference:

Updated To use os.path.getsize, this is clearer than using the os.stat().st_size method.

Thanks to ghostdog74 for pointing this out!

os.stat - st_size Gives the size in bytes. Can also be used to get file size and other file related information.

import os

nbytes = sum(d.stat().st_size for d in os.scandir('.') if d.is_file())

Update 2018

If you use Python 3.4 or previous then you may consider using the more efficient walk method provided by the third-party scandir package. In Python 3.5 and later, this package has been incorporated into the standard library and os.walk has received the corresponding increase in performance.

Update 2019

Recently I've been using pathlib more and more, here's a pathlib solution:

from pathlib import Path

root_directory = Path('.')
sum(f.stat().st_size for f in root_directory.glob('**/*') if f.is_file())

How to get Last record from Sqlite?

I wanted to maintain my table while pulling in one row that gives me the last value in a particular column in the table. I essentially was looking to replace the LAST() function in excel and this worked.

, (Select column_name FROM report WHERE rowid = (select last_insert_rowid() from report))

How to use ArrayList's get() method

To put it nice and simply, get(int index) returns the element at the specified index.

So say we had an ArrayList of Strings:

List<String> names = new ArrayList<String>();
names.add("Arthur Dent");
names.add("Marvin");
names.add("Trillian");
names.add("Ford Prefect");

Which can be visualised as: A visual representation of the array list Where 0, 1, 2, and 3 denote the indexes of the ArrayList.

Say we wanted to retrieve one of the names we would do the following: String name = names.get(1); Which returns the name at the index of 1.

Getting the element at index 1 So if we were to print out the name System.out.println(name); the output would be Marvin - Although he might not be too happy with us disturbing him.

How to install mod_ssl for Apache httpd?

I used:

sudo yum install mod24_ssl

and it worked in my Amazon Linux AMI.

Angular.js: set element height on page load

I came across your post as I was looking for a solution to the same problem for myself. I put together the following solution using a directive based on a number of posts. You can try it here (try resizing the browser window): http://jsfiddle.net/zbjLh/2/

View:

<div ng-app="miniapp" ng-controller="AppController" ng-style="style()" resize>
    window.height: {{windowHeight}} <br />
    window.width: {{windowWidth}} <br />
</div>

Controller:

var app = angular.module('miniapp', []);

function AppController($scope) {
    /* Logic goes here */
}

app.directive('resize', function ($window) {
    return function (scope, element) {
        var w = angular.element($window);
        scope.getWindowDimensions = function () {
            return { 'h': w.height(), 'w': w.width() };
        };
        scope.$watch(scope.getWindowDimensions, function (newValue, oldValue) {
            scope.windowHeight = newValue.h;
            scope.windowWidth = newValue.w;

            scope.style = function () {
                return { 
                    'height': (newValue.h - 100) + 'px',
                    'width': (newValue.w - 100) + 'px' 
                };
            };

        }, true);

        w.bind('resize', function () {
            scope.$apply();
        });
    }
})

FYI I originally had it working in a controller (http://jsfiddle.net/zbjLh/), but from subsequent reading found that this is uncool from Angular's perspective, so I have now converted it to use a directive.

Importantly, note the true flag at the end of the 'watch' function, for comparing the getWindowDimensions return object's equality (remove or change to false if not using an object).

Convert AM/PM time to 24 hours format?

You can use like this:

string date = "";

date = DateTime.ParseExact("01:00 PM" , "h:mm tt", CultureInfo.InvariantCulture).ToString("HH:mm");

h: 12 hours

mm: mins

tt: PM/AM

HH:24 hours

How do I log errors and warnings into a file?

See

  • error_log — Send an error message somewhere

Example

error_log("You messed up!", 3, "/var/tmp/my-errors.log");

You can customize error handling with your own error handlers to call this function for you whenever an error or warning or whatever you need to log occurs. For additional information, please refer to the Chapter Error Handling in the PHP Manual

Hidden Features of Java

You can access final local variables and parameters in initialization blocks and methods of local classes. Consider this:

    final String foo = "42";
    new Thread() {
        public void run() {
             dowhatever(foo);
        }
    }.start();

A bit like a closure, isn't it?

Save attachments to a folder and rename them

See ReceivedTime Property

http://msdn.microsoft.com/en-us/library/office/aa171873(v=office.11).aspx

You added another \ to the end of C:\Temp\ in the SaveAs File line. Could be a problem. Do a test first before adding a path separator.

dateFormat = Format(itm.ReceivedTime, "yyyy-mm-dd H-mm")  
saveFolder = "C:\Temp"

You have not set objAtt so there is no need for "Set objAtt = Nothing". If there was it would be just before End Sub not in the loop.


Public Sub saveAttachtoDisk (itm As Outlook.MailItem) 
    Dim objAtt As Outlook.Attachment 
    Dim saveFolder As String Dim dateFormat
    dateFormat = Format(itm.ReceivedTime, "yyyy-mm-dd H-mm")  saveFolder = "C:\Temp"
    For Each objAtt In itm.Attachments
        objAtt.SaveAsFile saveFolder & "\" & dateFormat & objAtt.DisplayName
    Next
End Sub

Re: It worked the first day I started tinkering but after that it stopped saving files.

This is usually due to Security settings. It is a "trap" set for first time users to allow macros then take it away. http://www.slipstick.com/outlook-developer/how-to-use-outlooks-vba-editor/

Can we locate a user via user's phone number in Android?

I checked play.google.com/store/apps/details?id=and.p2l&hl=en They are not locating the user's current location at all. So based on the number itself they are judging the location of the user. Like if the number starts from 240 ( in US) they they are saying location is Maryland but the person can be in California. So i don't think they are getting the user's location through LocationListner of Java at all.

concatenate variables

set ROOT=c:\programs 
set SRC_ROOT=%ROOT%\System\Source

Change Git repository directory location.

Simply copy the entire working directory contents (including the hidden .git directory). This will move the entire working directory to the new directory and will not affect the remote repository on GitHub.

If you are using GitHub for Windows, you may move the repository using the method as above. However, when you click on the repository in the application it will be unable to find it. To resolve this simply click on the blue circle with the !, select Find It and then browse to the new directory.

Use a loop to plot n charts Python

Use a dictionary!!

You can also use dictionaries that allows you to have more control over the plots:

import matplotlib.pyplot as plt
#   plot 0     plot 1    plot 2   plot 3
x=[[1,2,3,4],[1,4,3,4],[1,2,3,4],[9,8,7,4]]
y=[[3,2,3,4],[3,6,3,4],[6,7,8,9],[3,2,2,4]]

plots = zip(x,y)
def loop_plot(plots):
    figs={}
    axs={}
    for idx,plot in enumerate(plots):
        figs[idx]=plt.figure()
        axs[idx]=figs[idx].add_subplot(111)
        axs[idx].plot(plot[0],plot[1])
return figs, axs

figs, axs = loop_plot(plots)

Now you can select the plot that you want to modify easily:

axs[0].set_title("Now I can control it!")

Of course, is up to you to decide what to do with the plots. You can either save them to disk figs[idx].savefig("plot_%s.png" %idx) or show them plt.show(). Use the argument block=False only if you want to pop up all the plots together (this could be quite messy if you have a lot of plots). You can do this inside the loop_plot function or in a separate loop using the dictionaries that the function provided.

How to process each output line in a loop?

For those looking for a one-liner:

grep xyz abc.txt | while read -r line; do echo "Processing $line"; done

Django - how to create a file and save it to a model's FileField?

You want to have a look at FileField and FieldFile in the Django docs, and especially FieldFile.save().

Basically, a field declared as a FileField, when accessed, gives you an instance of class FieldFile, which gives you several methods to interact with the underlying file. So, what you need to do is:

self.license_file.save(new_name, new_contents)

where new_name is the filename you wish assigned and new_contents is the content of the file. Note that new_contents must be an instance of either django.core.files.File or django.core.files.base.ContentFile (see given links to manual for the details).

The two choices boil down to:

from django.core.files.base import ContentFile, File

# Using File
with open('/path/to/file') as f:
    self.license_file.save(new_name, File(f))

# Using ContentFile
self.license_file.save(new_name, ContentFile('A string with the file content'))

KERNELBASE.dll Exception 0xe0434352 offset 0x000000000000a49d

0xe0434352 is the SEH code for a CLR exception. If you don't understand what that means, stop and read A Crash Course on the Depths of Win32™ Structured Exception Handling. So your process is not handling a CLR exception. Don't shoot the messenger, KERNELBASE.DLL is just the unfortunate victim. The perpetrator is MyApp.exe.

There should be a minidump of the crash in DrWatson folders with a full stack, it will contain everything you need to root cause the issue.

I suggest you wire up, in your myapp.exe code, AppDomain.UnhandledException and Application.ThreadException, as appropriate.

how do I create an infinite loop in JavaScript

By omitting all parts of the head, the loop can also become infinite:

for (;;) {}

get all characters to right of last dash

You can get the position of the last - with str.LastIndexOf('-'). So the next step is obvious:

var result = str.Substring(str.LastIndexOf('-') + 1);

Correction:

As Brian states below, using this on a string with no dashes will result in the same string being returned.

MySQL: ALTER TABLE if column not exists

I used this approach (Without using stored procedure):

SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'tbl_name' AND COLUMN_NAME = 'column_name'

If it didnt return any rows then the column doesn't exists then alter the table:

ALTER TABLE tbl_name ADD COLUMN column_name TINYINT(1) NOT NULL DEFAULT 1

Hope this helps.

How to pass parameters in $ajax POST?

For send parameters in url in POST method You can simply append it to url like this:

$.ajax({
    type: 'POST',
    url: 'superman?' + jQuery.param({ f1: "hello1", f2 : "hello2"}),
    // ...
}); 

Add tooltip to font awesome icon

The simplest solution I have found is to wrap your Font Awesome Icon in an <a></a> tag:

   <Tooltip title="Node.js" >
     <a>
        <FontAwesomeIcon icon={faNode} size="2x" />
     </a>
   </Tooltip>

How to grep for two words existing on the same line?

Why do you pass -c? That will just show the number of matches. Similarly, there is no reason to use -r. I suggest you read man grep.

To grep for 2 words existing on the same line, simply do:

grep "word1" FILE | grep "word2"

grep "word1" FILE will print all lines that have word1 in them from FILE, and then grep "word2" will print the lines that have word2 in them. Hence, if you combine these using a pipe, it will show lines containing both word1 and word2.

If you just want a count of how many lines had the 2 words on the same line, do:

grep "word1" FILE | grep -c "word2"

Also, to address your question why does it get stuck : in grep -c "word1", you did not specify a file. Therefore, grep expects input from stdin, which is why it seems to hang. You can press Ctrl+D to send an EOF (end-of-file) so that it quits.

Calling a Javascript Function from Console

This is an older thread, but I just searched and found it. I am new to using Web Developer Tools: primarily Firefox Developer Tools (Firefox v.51), but also Chrome DevTools (Chrome v.56)].

I wasn't able to run functions from the Developer Tools console, but I then found this

https://developer.mozilla.org/en-US/docs/Tools/Scratchpad

and I was able to add code to the Scratchpad, highlight and run a function, outputted to console per the attched screenshot.

I also added the Chrome "Scratch JS" extension: it looks like it provides the same functionality as the Scratchpad in Firefox Developer Tools (screenshot below).

https://chrome.google.com/webstore/detail/scratch-js/alploljligeomonipppgaahpkenfnfkn

Image 1 (Firefox): http://imgur.com/a/ofkOp

enter image description here

Image 2 (Chrome): http://imgur.com/a/dLnRX

enter image description here

Can we instantiate an abstract class?

No, we can't create the object of abstract class, but create the reference variable of the abstract class. The reference variable is used to refer to the objects of derived classes (Sub classes of Abstract class)

Here is the example that illustrates this concept

abstract class Figure { 

    double dim1; 

    double dim2; 

    Figure(double a, double b) { 

        dim1 = a; 

        dim2 = b; 

    } 

    // area is now an abstract method 

    abstract double area(); 

    }


    class Rectangle extends Figure { 
        Rectangle(double a, double b) { 
        super(a, b); 
    } 
    // override area for rectangle 
    double area() { 
        System.out.println("Inside Area for Rectangle."); 
        return dim1 * dim2; 
    } 
}

class Triangle extends Figure { 
    Triangle(double a, double b) { 
        super(a, b); 
    } 
    // override area for right triangle 
    double area() { 
        System.out.println("Inside Area for Triangle."); 
        return dim1 * dim2 / 2; 
    } 
}

class AbstractAreas { 
    public static void main(String args[]) { 
        // Figure f = new Figure(10, 10); // illegal now 
        Rectangle r = new Rectangle(9, 5); 
        Triangle t = new Triangle(10, 8); 
        Figure figref; // this is OK, no object is created 
        figref = r; 
        System.out.println("Area is " + figref.area()); 
        figref = t; 
        System.out.println("Area is " + figref.area()); 
    } 
}

Here we see that we cannot create the object of type Figure but we can create a reference variable of type Figure. Here we created a reference variable of type Figure and Figure Class reference variable is used to refer to the objects of Class Rectangle and Triangle.

Setting the target version of Java in ant javac

To find the version of the java in the classfiles I used:

javap -verbose <classname>

which announces the version at the start as

minor version: 0
major version: 49

which corresponds to Java 1.5

How can I open a URL in Android's web browser from my application?

Try this:

Uri uri = Uri.parse("https://www.google.com");
startActivity(new Intent(Intent.ACTION_VIEW, uri));

or if you want then web browser open in your activity then do like this:

WebView webView = (WebView) findViewById(R.id.webView1);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
webView.loadUrl(URL);

and if you want to use zoom control in your browser then you can use:

settings.setSupportZoom(true);
settings.setBuiltInZoomControls(true);

How do I kill this tomcat process in Terminal?

In tomcat/bin/catalina.sh

add the following line after just after the comment section ends:

CATALINA_PID=someFile.txt

then, to kill a running instance of Tomcat, you can use:

kill -9 `cat someFile.txt`

SyntaxError: import declarations may only appear at top level of a module

I got this on Firefox (FF58). I fixed this with:

  1. It is still experimental on Firefox (from v54): You have to set to true the variable dom.moduleScripts.enabled in about:config

Source: Import page on mozilla (See Browser compatibility)

  1. Add type="module" to your script tag where you import the js file

<script type="module" src="appthatimports.js"></script>

  1. Import files have to be prefixed (./, /, ../ or http:// before)

import * from "./mylib.js"

For more examples, this blog post is good.

Why is this rsync connection unexpectedly closed on Windows?

The trick for me was I had ssh conflict.

I have Git installed on my Windows path, which includes ssh. cwrsync also installs ssh.

The trick is to have make a batch file to set the correct paths:

rsync.bat

@echo off
SETLOCAL
SET CWRSYNCHOME=c:\commands\cwrsync
SET HOME=c:\Users\Petah\
SET CWOLDPATH=%PATH%
SET PATH=%CWRSYNCHOME%\bin;%PATH%
%~dp0\cwrsync\bin\rsync.exe %*

On Windows you can type where ssh to check if this is an issue. You will get something like this:

where ssh
C:\Program Files (x86)\Git\bin\ssh.exe
C:\Program Files\cwRsync\ssh.exe

ReactJS SyntheticEvent stopPropagation() only works with React events?

I ran into this problem yesterday, so I created a React-friendly solution.

Check out react-native-listener. It's working very well so far. Feedback appreciated.

Output array to CSV in Ruby

I've got this down to just one line.

rows = [['a1', 'a2', 'a3'],['b1', 'b2', 'b3', 'b4'], ['c1', 'c2', 'c3'], ... ]
csv_str = rows.inject([]) { |csv, row|  csv << CSV.generate_line(row) }.join("")
#=> "a1,a2,a3\nb1,b2,b3\nc1,c2,c3\n" 

Do all of the above and save to a csv, in one line.

File.open("ss.csv", "w") {|f| f.write(rows.inject([]) { |csv, row|  csv << CSV.generate_line(row) }.join(""))}

NOTE:

To convert an active record database to csv would be something like this I think

CSV.open(fn, 'w') do |csv|
  csv << Model.column_names
  Model.where(query).each do |m|
    csv << m.attributes.values
  end
end

Hmm @tamouse, that gist is somewhat confusing to me without reading the csv source, but generically, assuming each hash in your array has the same number of k/v pairs & that the keys are always the same, in the same order (i.e. if your data is structured), this should do the deed:

rowid = 0
CSV.open(fn, 'w') do |csv|
  hsh_ary.each do |hsh|
    rowid += 1
    if rowid == 1
      csv << hsh.keys# adding header row (column labels)
    else
      csv << hsh.values
    end# of if/else inside hsh
  end# of hsh's (rows)
end# of csv open

If your data isn't structured this obviously won't work

Better way to represent array in java properties file

Didn't exactly get your intent. Do check Apache Commons configuration library http://commons.apache.org/configuration/

You can have multiple values against a key as in key=value1,value2 and you can read this into an array as configuration.getAsStringArray("key")

Maintain/Save/Restore scroll position when returning to a ListView

use this below code :

int index,top;

@Override
protected void onPause() {
    super.onPause();
    index = mList.getFirstVisiblePosition();

    View v = challengeList.getChildAt(0);
    top = (v == null) ? 0 : (v.getTop() - mList.getPaddingTop());
}

and whenever your refresh your data use this below code :

adapter.notifyDataSetChanged();
mList.setSelectionFromTop(index, top);

Manually Set Value for FormBuilder Control

If you are using form control then the simplest way to do this:

this.FormName.get('ControlName').setValue(value);

Bootstrap carousel multiple frames at once

The most popular answer is right but I think the code is uselessly complicated. With the same css, this jquery code is easier to understand I believe:

$('#myCarousel').carousel({
  interval: 10000
})

$('.carousel .item').each(function() {
  var item = $(this);
  item.siblings().each(function(index) {
    if (index < 4) {
      $(this).children(':first-child').clone().appendTo(item);
    }
  });
});

What are your favorite extension methods for C#? (codeplex.com/extensionoverflow)

Hate this kind of code?

CloneableClass cc1 = new CloneableClass ();
CloneableClass cc2 = null;
CloneableClass cc3 = null;

cc3 = (CloneableClass) cc1.Clone (); // this is ok
cc3 = cc2.Clone (); // this throws null ref exception
// code to handle both cases
cc3 = cc1 != null ? (CloneableClass) cc1.Clone () : null;

It's a bit clunky, so I replace it with this extension, which I call CloneOrNull -

public static T CloneOrNull<T> (this T self) where T : class, ICloneable
{
    if (self == null) return null;
    return (T) self.Clone ();
}

Usage is like:

CloneableClass cc1 = new CloneableClass ();
CloneableClass cc2 = null;
CloneableClass cc3 = null;

cc3 = cc1.CloneOrNull (); // clone of cc1
cc3 = cc2.CloneOrNull (); // null
// look mom, no casts!

Please feel free to use this anywhere!

AsyncTask Android example

private class AsyncTaskDemo extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Loading...");
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    @Override
    protected Void doInBackground(Void... arg0) {

        // Do code here

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    @Override
    protected void onCancelled() {

        super.onCancelled();
        progressDialog.dismiss();
        Toast toast = Toast.makeText(
                          getActivity(),
                          "An error is occurred due to some problem",
                          Toast.LENGTH_LONG);
        toast.setGravity(Gravity.TOP, 25, 400);
        toast.show();
    }

}

How do I convert a single character into it's hex ascii value in python

To use the hex encoding in Python 3, use

>>> import codecs
>>> codecs.encode(b"c", "hex")
b'63'

In legacy Python, there are several other ways of doing this:

>>> hex(ord("c"))
'0x63'
>>> format(ord("c"), "x")
'63'
>>> "c".encode("hex")
'63'

Add class to <html> with Javascript?

You should append class not overwrite it

var headCSS = document.getElementsByTagName("html")[0].getAttribute("class") || "";
document.getElementsByTagName("html")[0].setAttribute("class",headCSS +"foo");

I would still recommend using jQuery to avoid browser incompatibilities

Private Variables and Methods in Python

Double underscore. That mangles the name. The variable can still be accessed, but it's generally a bad idea to do so.

Use single underscores for semi-private (tells python developers "only change this if you absolutely must") and doubles for fully private.

how can get index & count in vuejs

Why its printing 0,1,2...?

Because those are indexes of the items in array, and index always starts from 0 to array.length-1.

To print the item count instead of index, use index+1. Like this:

<li v-for="(catalog, index) in catalogs">this index : {{index + 1}}</li>

And to show the total count use array.length, Like this:

<p>Total Count: {{ catalogs.length }}</p>

As per DOC:

v-for also supports an optional second argument (not first) for the index of the current item.

What are the specific differences between .msi and setup.exe file?

.msi files are windows installer files without the windows installer runtime, setup.exe can be any executable programm (probably one that installs stuff on your computer)

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

np.fromfile() has a sep= keyword argument:

Separator between items if file is a text file. Empty (“”) separator means the file should be treated as binary. Spaces (” ”) in the separator match zero or more whitespace characters. A separator consisting only of spaces must match at least one whitespace.

The default value of sep="" means that np.fromfile() tries to read it as a binary file rather than a space-separated text file, so you get nonsense values back. If you use np.fromfile('markers.txt', sep=" ") you will get the result you are looking for.

However, as others have pointed out, np.loadtxt() is the preferred way to convert text files to numpy arrays, and unless the file needs to be human-readable it is usually better to use binary formats instead (e.g. np.load()/np.save()).

Required request body content is missing: org.springframework.web.method.HandlerMethod$HandlerMethodParameter

I made some minor modification to you code and tested it with a spring project that I have and it works, The logic will only work with POST if I use GET it throws an error with invalid request. Also in your ajax call I commented out commit(true), the browser debugger flagged and error that it is not defined. Just modify the url to fit your Spring project architecture.

 $.ajax({ 
                    url: "/addDepartment", 
                    method: 'POST', 
                    dataType: 'json', 
                    data: "{\"message\":\"abc\",\"success\":true}",
                    contentType: 'application/json',
                    mimeType: 'application/json',
                    success: function(data) { 
                        alert(data.success + " " + data.message);
                        //commit(true);
                    },
                    error:function(data,status,er) { 
                        alert("error: "+data+" status: "+status+" er:"+er);
                    }
                });



@RequestMapping(value="/addDepartment", method=RequestMethod.POST)
  public AjaxResponse addDepartment(@RequestBody final AjaxResponse  departmentDTO)
  {
    System.out.println("addDepartment: >>>>>>> "+departmentDTO);
    AjaxResponse response=new AjaxResponse();
    response.setSuccess(departmentDTO.isSuccess());
    response.setMessage(departmentDTO.getMessage());
    return response;
  }

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

You're passing the array into the function by copy. Only objects are passed by reference in PHP, and an array is not an object. Here's what you do (note the &)

function foo(&$arr) { # note the &
  $arr[3] = $arr[0]+$arr[1]+$arr[2];
}
$waffles = array(1,2,3);
foo($waffles);
echo $waffles[3]; # prints 6

That aside, I'm not sure why you would do that particular operation like that. Why not just return the sum instead of assigning it to a new array element?

Group by month and year in MySQL

You must do something like this

SELECT onDay, id, 
sum(pxLow)/count(*),sum(pxLow),count(`*`),
CONCAT(YEAR(onDay),"-",MONTH(onDay)) as sdate 
FROM ... where stockParent_id =16120 group by sdate order by onDay

Excel: Search for a list of strings within a particular string using array formulas?

This will return the matching word or an error if no match is found. For this example I used the following.

List of words to search for: G1:G7
Cell to search in: A1

=INDEX(G1:G7,MAX(IF(ISERROR(FIND(G1:G7,A1)),-1,1)*(ROW(G1:G7)-ROW(G1)+1)))

Enter as an array formula by pressing Ctrl+Shift+Enter.

This formula works by first looking through the list of words to find matches, then recording the position of the word in the list as a positive value if it is found or as a negative value if it is not found. The largest value from this array is the position of the found word in the list. If no word is found, a negative value is passed into the INDEX() function, throwing an error.

To return the row number of a matching word, you can use the following:

=MAX(IF(ISERROR(FIND(G1:G7,A1)),-1,1)*ROW(G1:G7))

This also must be entered as an array formula by pressing Ctrl+Shift+Enter. It will return -1 if no match is found.

Change background of LinearLayout in Android

u just used attribute

  • android:background="#ColorCode" for colors

    if your image save in drawable folder then used :-

  • android:background="@drawable/ImageName" for image setting

android.content.res.Resources$NotFoundException: String resource ID Fatal Exception in Main

Move

Random pp = new Random();
int a1 = pp.nextInt(10);
TextView tv = (TextView)findViewById(R.id.tv);
tv.setText(a1);

To inside onCreate(), and change tv.setText(a1); to tv.setText(String.valueOf(a1)); :

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  Random pp = new Random();
  int a1 = pp.nextInt(10);

  TextView tv = (TextView)findViewById(R.id.tv);
  tv.setText(String.valueOf(a1));

}   

First issue: findViewById() was called before onCreate(), which would throw an NPE.

Second issue: Passing an int directly to a TextView calls the overloaded method that looks for a String resource (from R.string). Therefore, we want to use String.valueOf() to force the String overloaded method.

Query for array elements inside JSON type

Create a table with column as type json

CREATE TABLE friends ( id serial primary key, data jsonb);

Now let's insert json data

INSERT INTO friends(data) VALUES ('{"name": "Arya", "work": ["Improvements", "Office"], "available": true}');
INSERT INTO friends(data) VALUES ('{"name": "Tim Cook", "work": ["Cook", "ceo", "Play"], "uses": ["baseball", "laptop"], "available": false}');

Now let's make some queries to fetch data

select data->'name' from friends;
select data->'name' as name, data->'work' as work from friends;

You might have noticed that the results comes with inverted comma( " ) and brackets ([ ])

    name    |            work            
------------+----------------------------
 "Arya"     | ["Improvements", "Office"]
 "Tim Cook" | ["Cook", "ceo", "Play"]
(2 rows)

Now to retrieve only the values just use ->>

select data->>'name' as name, data->'work'->>0 as work from friends;
select data->>'name' as name, data->'work'->>0 as work from friends where data->>'name'='Arya';

Parse JSON response using jQuery

Give this a try:

success: function(json) {
   console.log(JSON.stringify(json.topics));
   $.each(json.topics, function(idx, topic){
     $("#nav").html('<a href="' + topic.link_src + '">' + topic.link_text + "</a>");
   });
},

master branch and 'origin/master' have diverged, how to 'undiverge' branches'?

I found myself in this situation when I tried to rebase a branch that was tracking a remote branch, and I was trying to rebase it on master. In this scenario if you try to rebase, you'll most likely find your branch diverged and it can create a mess that isn't for git nubees!

Let's say you are on branch my_remote_tracking_branch, which was branched from master

$ git status

# On branch my_remote_tracking_branch

nothing to commit (working directory clean)

And now you are trying to rebase from master as:

git rebase master

STOP NOW and save yourself some trouble! Instead, use merge as:

git merge master

Yes, you'll end up with extra commits on your branch. But unless you are up for "un-diverging" branches, this will be a much smoother workflow than rebasing. See this blog for a much more detailed explanation.

On the other hand, if your branch is only a local branch (i.e. not yet pushed to any remote) you should definitely do a rebase (and your branch will not diverge in this case).

Now if you are reading this because you already are in a "diverged" scenario due to such rebase, you can get back to the last commit from origin (i.e. in an un-diverged state) by using:

git reset --hard origin/my_remote_tracking_branch

PHPExcel how to set cell value dynamically

I don't have much experience working with php but from a logic standpoint this is what I would do.

  1. Loop through your result set from MySQL
  2. In Excel you should already know what A,B,C should be because those are the columns and you know how many columns you are returning.
  3. The row number can just be incremented with each time through the loop.

Below is some pseudocode illustrating this technique:

    for (int i = 0; i < MySQLResults.count; i++){
         $objPHPExcel->getActiveSheet()->setCellValue('A' . (string)(i + 1), MySQLResults[i].name); 
        // Add 1 to i because Excel Rows start at 1, not 0, so row will always be one off
         $objPHPExcel->getActiveSheet()->setCellValue('B' . (string)(i + 1), MySQLResults[i].number);
         $objPHPExcel->getActiveSheet()->setCellValue('C' . (string)(i + 1), MySQLResults[i].email);
    }

How large should my recv buffer be when calling recv in the socket library

For streaming protocols such as TCP, you can pretty much set your buffer to any size. That said, common values that are powers of 2 such as 4096 or 8192 are recommended.

If there is more data then what your buffer, it will simply be saved in the kernel for your next call to recv.

Yes, you can keep growing your buffer. You can do a recv into the middle of the buffer starting at offset idx, you would do:

recv(socket, recv_buffer + idx, recv_buffer_size - idx, 0);

Is there a <meta> tag to turn off caching in all browsers?

It doesn't work in IE5, but that's not a big issue.

However, cacheing headers are unreliable in meta elements; for one, any web proxies between the site and the user will completely ignore them. You should always use a real HTTP header for headers such as Cache-Control and Pragma.

Android TabLayout Android Design

Add this to the module build.gradle:

implementation 'com.android.support.constraint:constraint-layout:1.1.3'

implementation 'com.android.support:design:28.0.0'

Mix Razor and Javascript code

Use <text>:

<script type="text/javascript">

   var data = [];

   @foreach (var r in Model.rows)
   {
      <text>
            data.push([ @r.UnixTime * 1000, @r.Value ]);
      </text>
   }
</script>

- java.lang.NullPointerException - setText on null object reference

The problem is the tv.setText(text). The variable tv is probably null and you call the setText method on that null, which you can't. My guess that the problem is on the findViewById method, but it's not here, so I can't tell more, without the code.

How to use Google App Engine with my own naked domain (not subdomain)?

For App Engine in 2019, googles has made it easier to set up a custom domain.

  1. Google App Engine -> Settings -> Custom Domains

  2. Verify your domain

  3. Select Your Domain Name Registra

Reminder: Use TXT Record with the value Google provides without a existing CNAME record, otherwise TXT Record will be override

  1. Follow the steps on the page, which includes the configuration of your subdomain, CNAME Record, A Record, AAAA Record, and you'll be good to go.

Rounding Bigdecimal values with 2 Decimal Places

You can call setScale(newScale, roundingMode) method three times with changing the newScale value from 4 to 3 to 2 like

First case

    BigDecimal a = new BigDecimal("10.12345");

    a = a.setScale(4, BigDecimal.ROUND_HALF_UP); 
    System.out.println("" + a); //10.1235
    a = a.setScale(3, BigDecimal.ROUND_HALF_UP); 
    System.out.println("" + a); //10.124
    a = a.setScale(2, BigDecimal.ROUND_HALF_UP);
    System.out.println("" + a); //10.12

Second case

    BigDecimal a = new BigDecimal("10.12556");

    a = a.setScale(4, BigDecimal.ROUND_HALF_UP); 
    System.out.println("" + a); //10.1256
    a = a.setScale(3, BigDecimal.ROUND_HALF_UP); 
    System.out.println("" + a); //10.126
    a = a.setScale(2, BigDecimal.ROUND_HALF_UP);
    System.out.println("" + a); //10.13

ClassNotFoundException com.mysql.jdbc.Driver

If you are using NetBeans follow the following steps:

  1. Right click on 'Libraries' and select 'Add Library..'
  2. Scroll down the list of 'Global Libraries' and select 'MySQL JDBC Driver' and click on 'Add Library'.

The OutputPath property is not set for this project

In my case the built address of my app was set to another computer that was turned off so i turned it on and restart VS and problem solved.

Difference between acceptance test and functional test?

They are the same thing.

Acceptance testing is performed on the completed system in as identical as possible to the real production/deployement environment before the system is deployed or delivered.

You can do acceptance testing in an automated manner, or manually.

Sleep function in ORACLE

If Java is installed on your 11G then you can do it in a java class and call it from your PL/SQL, but I am not sure that it does not require also a specific grant to call java.

Query EC2 tags from within instance

Using the AWS 'user data' and 'meta data' APIs its possible to write a script which wraps puppet to start a puppet run with a custom cert name.

First start an aws instance with custom user data: 'role:webserver'

#!/bin/bash

# Find the name from the user data passed in on instance creation
USER=$(curl -s "http://169.254.169.254/latest/user-data")
IFS=':' read -ra UDATA <<< "$USER"

# Find the instance ID from the meta data api
ID=$(curl -s "http://169.254.169.254/latest/meta-data/instance-id")
CERTNAME=${UDATA[1]}.$ID.aws

echo "Running Puppet for certname: " $CERTNAME
puppet agent -t --certname=$CERTNAME 

This calls puppet with a certname like 'webserver.i-hfg453.aws' you can then create a node manifest called 'webserver' and puppets 'fuzzy node matching' will mean it is used to provision all webservers.

This example assumes you build on a base image with puppet installed etc.

Benefits:

1) You don't have to pass round your credentials

2) You can be as granular as you like with the role configs.

Java System.out.print formatting

Something likes this

public void testPrintOut() {
    int val1 = 8;
    String val2 = "$951.23";
    String val3 = "$215.92";
    String val4 = "$198,301.22";
    System.out.println(String.format("%03d %7s %7s %11s", val1, val2, val3, val4));

    val1 = 9;
    val2 = "$950.19";
    val3 = "$216.95";
    val4 = "$198,084.26";
    System.out.println(String.format("%03d %7s %7s %11s", val1, val2, val3, val4));
}

What is the official "preferred" way to install pip and virtualenv systemwide?

The former method is fine. The only problem I can see is that you might end up with an old version of setuptools (if the apt repository hasn't been kept up-to-date..

Error: Cannot match any routes. URL Segment: - Angular 2

please modify your router.module.ts as:

const routes: Routes = [
{
    path: '',
    redirectTo: 'one',
    pathMatch: 'full'
},
{
    path: 'two',
    component: ClassTwo, children: [
        {
            path: 'three',
            component: ClassThree,
            outlet: 'nameThree',
        },
        {
            path: 'four',
            component: ClassFour,
            outlet: 'nameFour'
        },
        {
           path: '',
           redirectTo: 'two',
           pathMatch: 'full'
        }
    ]
},];

and in your component1.html

<h3>In One</h3>

<nav>
    <a routerLink="/two" class="dash-item">...Go to Two...</a>
    <a routerLink="/two/three" class="dash-item">... Go to THREE...</a>
    <a routerLink="/two/four" class="dash-item">...Go to FOUR...</a>
</nav>

<router-outlet></router-outlet>                   // Successfully loaded component2.html
<router-outlet name="nameThree" ></router-outlet> // Error: Cannot match any routes. URL Segment: 'three'
<router-outlet name="nameFour" ></router-outlet>  // Error: Cannot match any routes. URL Segment: 'three'

Truncating long strings with CSS: feasible yet?

If you're OK with a JavaScript solution, there's a jQuery plug-in to do this in a cross-browser fashion - see http://azgtech.wordpress.com/2009/07/26/text-overflow-ellipsis-for-firefox-via-jquery/

Check if Cookie Exists

public static class CookieHelper
{
    /// <summary>
    /// Checks whether a cookie exists.
    /// </summary>
    /// <param name="cookieCollection">A CookieCollection, such as Response.Cookies.</param>
    /// <param name="name">The cookie name to delete.</param>
    /// <returns>A bool indicating whether a cookie exists.</returns>
    public static bool Exists(this HttpCookieCollection cookieCollection, string name)
    {
        if (cookieCollection == null)
        {
            throw new ArgumentNullException("cookieCollection");
        }

        return cookieCollection[name] != null;
    }
}

Usage:

Request.Cookies.Exists("MyCookie")

How do I get the color from a hexadecimal color code using .NET?

If you don't want to use the ColorTranslator, you can do it in easily:

string colorcode = "#FFFFFF00";
int argb = Int32.Parse(colorcode.Replace("#", ""), NumberStyles.HexNumber);
Color clr = Color.FromArgb(argb);

The colorcode is just the hexadecimal representation of the ARGB value.

EDIT

If you need to use 4 values instead of a single integer, you can use this (combining several comments):

string colorcode = "#FFFFFF00";    
colorcode = colorcode.TrimStart('#');

Color col; // from System.Drawing or System.Windows.Media
if (colorcode.Length == 6)
    col = Color.FromArgb(255, // hardcoded opaque
                int.Parse(colorcode.Substring(0,2), NumberStyles.HexNumber),
                int.Parse(colorcode.Substring(2,2), NumberStyles.HexNumber),
                int.Parse(colorcode.Substring(4,2), NumberStyles.HexNumber));
else // assuming length of 8
    col = Color.FromArgb(
                int.Parse(colorcode.Substring(0, 2), NumberStyles.HexNumber),
                int.Parse(colorcode.Substring(2, 2), NumberStyles.HexNumber),
                int.Parse(colorcode.Substring(4, 2), NumberStyles.HexNumber),
                int.Parse(colorcode.Substring(6, 2), NumberStyles.HexNumber));

Note 1: NumberStyles is in System.Globalization.
Note 2: please provide your own error checking (colorcode should be a hexadecimal value of either 6 or 8 characters)

How do I send a file in Android from a mobile device to server using http?

the most effective method is to use org.apache.http.entity.mime.MultipartEntity;

see this code from the link using org.apache.http.entity.mime.MultipartEntity;

public class SimplePostRequestTest3 {

  /**
   * @param args
   */
  public static void main(String[] args) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://localhost:8080/HTTP_TEST_APP/index.jsp");

    try {
      FileBody bin = new FileBody(new File("C:/ABC.txt"));
      StringBody comment = new StringBody("BETHECODER HttpClient Tutorials");

      MultipartEntity reqEntity = new MultipartEntity();
      reqEntity.addPart("fileup0", bin);
      reqEntity.addPart("fileup1", comment);

      reqEntity.addPart("ONE", new StringBody("11111111"));
      reqEntity.addPart("TWO", new StringBody("222222222"));
      httppost.setEntity(reqEntity);

      System.out.println("Requesting : " + httppost.getRequestLine());
      ResponseHandler<String> responseHandler = new BasicResponseHandler();
      String responseBody = httpclient.execute(httppost, responseHandler);

      System.out.println("responseBody : " + responseBody);

    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      httpclient.getConnectionManager().shutdown();
    }
  }

}

Added:

Example Link

Image scaling causes poor quality in firefox/internet explorer but not chrome

This is possible! At least now that css transforms have good support:

You need to use a CSS transform to scale the image - the trick is not just to use a scale(), but also to apply a very small rotation. This triggers IE to use a smoother interpolation of the image:

img {
    /* double desired size */
    width: 56px; 
    height: 56px;

    /* margins to reduce layout size to match the transformed size */ 
    margin: -14px -14px -14px -14px; 

    /* transform to scale with smooth interpolation: */
    transform: scale(0.5) rotate(0.1deg);
}

How to make the checkbox unchecked by default always

Well I guess you can use checked="false". That is the html way to leave a checkbox unchecked. You can refer to http://www.w3schools.com/jsref/dom_obj_checkbox.asp.

Deleting rows with MySQL LEFT JOIN

Try this:

DELETE `deadline`
FROM `deadline`
INNER JOIN `job` ON `deadline`.`job_id` = `job`.`id`
WHERE `job`.`id` = 123

Why isn't .ico file defined when setting window's icon?

So it looks like root.iconbitmap() only supports a fixed directory.
sys.argv[0] returns the directory that the file was read from so a simple code would work to create a fixed directory.

import sys
def get_dir(src):
    dir = sys.argv[0]
    dir = dir.split('/')
    dir.pop(-1)
    dir = '/'.join(dir)
    dir = dir+'/'+src
    return dir

This is the output

>>> get_dir('test.txt')
'C:/Users/Josua/Desktop/test.txt'

EDIT:
The only issue is that this method dosn't work on linux

josua@raspberrypi:~ $ python
Python 2.7.9 (default, Sep 17 2016, 20:26:04) [GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.argv[0]
''
>>>

Counting number of lines, words, and characters in a text file

import java.io.*;
class wordcount
{
    public static int words=0;
    public static int lines=0;
    public static int chars=0;
    public static void wc(InputStreamReader isr)throws IOException
    {
        int c=0;
        boolean lastwhite=true;
        while((c=isr.read())!=-1)
        {
            chars++;
            if(c=='\n')
                lines++;
            if(c=='\t' || c==' ' || c=='\n')
                ++words;
            if(chars!=0)
                ++chars;
        }   
       }
    public static void main(String[] args)
    {
        FileReader fr;
        try
        {
            if(args.length==0)
            {
                wc(new InputStreamReader(System.in));
            }
            else
            {
                for(int i=0;i<args.length;i++)
                {
                    fr=new FileReader(args[i]);
                    wc(fr);
                }
            }

        }
        catch(IOException ie)
        {
            return;
        }
        System.out.println(lines+" "+words+" "+chars);
    }
}

Xcode is not currently available from the Software Update server

I deleted the command tools directory given by xcode-select -p due to npm gyp error.

xcode-select failed to install the files with the not available error.

I ran the Xcode application and the command tools installed as part of the startup.

npm worked.

However this didn't fully fix the tools. I had to use xcode-select to switch the path to the Developer directory within the Xcode application directory.

sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer  

MacOS catalina.

How to assert two list contain the same elements in Python?

Given

l1 = [a,b]
l2 = [b,a]

In Python >= 3.0

assertCountEqual(l1, l2) # True

In Python >= 2.7, the above function was named:

assertItemsEqual(l1, l2) # True

In Python < 2.7

import unittest2
assertItemsEqual(l1, l2) # True

Via six module (Any Python version)

import unittest
import six
class MyTest(unittest.TestCase):
    def test(self):
        six.assertCountEqual(self, self.l1, self.l2) # True

How to add fonts to create-react-app based projects?

You can use the Web API FontFace constructor (also Typescript) without need of CSS:

export async function loadFont(fontFamily: string, url: string): Promise<void> {
    const font = new FontFace(fontFamily, `local(${fontFamily}), url(${url})`);
    // wait for font to be loaded
    await font.load();
    // add font to document
    document.fonts.add(font);
    // enable font with CSS class
    document.body.classList.add("fonts-loaded");
}
import ComicSans from "./assets/fonts/ComicSans.ttf";

loadFont("Comic Sans ", ComicSans).catch((e) => {
    console.log(e);
});

Declare a file font.ts with your modules (TS only):

declare module "*.ttf";
declare module "*.woff";
declare module "*.woff2";

If TS cannot find FontFace type as its still officially WIP, add this declaration to your project. It will work in your browser, except for IE.

Python urllib2 Basic Auth Problem

Here's what I'm using to deal with a similar problem I encountered while trying to access MailChimp's API. This does the same thing, just formatted nicer.

import urllib2
import base64

chimpConfig = {
    "headers" : {
    "Content-Type": "application/json",
    "Authorization": "Basic " + base64.encodestring("hayden:MYSECRETAPIKEY").replace('\n', '')
    },
    "url": 'https://us12.api.mailchimp.com/3.0/'}

#perform authentication
datas = None
request = urllib2.Request(chimpConfig["url"], datas, chimpConfig["headers"])
result = urllib2.urlopen(request)

INSTALL_FAILED_UPDATE_INCOMPATIBLE when I try to install compiled .apk on device

I don't see anyone mentioning my case so let me add it - it happens when you build the app in one mode (e.g. Dev) and then try to override it with a different mode (e.g. Production).

The solution is the same as for the other cases - delete the app on the device/simulator and run again.

Java ArrayList of Doubles

double[] arr = new double[] {1.38, 2.56, 4.3};

ArrayList<Double> list = DoubleStream.of( arr ).boxed().collect(
    Collectors.toCollection( new Supplier<ArrayList<Double>>() {
      public ArrayList<Double> get() {
        return( new ArrayList<Double>() );
      }
    } ) );

How to convert an integer to a character array using C

'sprintf' will work fine, if your first argument is a pointer to a character (a pointer to a character is an array in 'c'), you'll have to make sure you have enough space for all the digits and a terminating '\0'. For example, If an integer uses 32 bits, it has up to 10 decimal digits. So your code should look like:

int i;
char s[11]; 
...
sprintf(s,"%ld", i);

How to change the size of the font of a JLabel to take the maximum size

Source Code for Label - How to change Color and Font (in Netbeans)

jLabel1.setFont(new Font("Serif", Font.BOLD, 12));


jLabel1.setForeground(Color.GREEN);

LINQ - Full Outer Join

Performs a in-memory streaming enumeration over both inputs and invokes the selector for each row. If there is no correlation at the current iteration, one of the selector arguments will be null.

Example:

   var result = left.FullOuterJoin(
         right, 
         x=>left.Key, 
         x=>right.Key, 
         (l,r) => new { LeftKey = l?.Key, RightKey=r?.Key });
  • Requires an IComparer for the correlation type, uses the Comparer.Default if not provided.

  • Requires that 'OrderBy' is applied to the input enumerables

    /// <summary>
    /// Performs a full outer join on two <see cref="IEnumerable{T}" />.
    /// </summary>
    /// <typeparam name="TLeft"></typeparam>
    /// <typeparam name="TValue"></typeparam>
    /// <typeparam name="TRight"></typeparam>
    /// <typeparam name="TResult"></typeparam>
    /// <param name="left"></param>
    /// <param name="right"></param>
    /// <param name="leftKeySelector"></param>
    /// <param name="rightKeySelector"></param>
    /// <param name="selector">Expression defining result type</param>
    /// <param name="keyComparer">A comparer if there is no default for the type</param>
    /// <returns></returns>
    [System.Diagnostics.DebuggerStepThrough]
    public static IEnumerable<TResult> FullOuterJoin<TLeft, TRight, TValue, TResult>(
        this IEnumerable<TLeft> left,
        IEnumerable<TRight> right,
        Func<TLeft, TValue> leftKeySelector,
        Func<TRight, TValue> rightKeySelector,
        Func<TLeft, TRight, TResult> selector,
        IComparer<TValue> keyComparer = null)
        where TLeft: class
        where TRight: class
        where TValue : IComparable
    {
    
        keyComparer = keyComparer ?? Comparer<TValue>.Default;
    
        using (var enumLeft = left.OrderBy(leftKeySelector).GetEnumerator())
        using (var enumRight = right.OrderBy(rightKeySelector).GetEnumerator())
        {
    
            var hasLeft = enumLeft.MoveNext();
            var hasRight = enumRight.MoveNext();
            while (hasLeft || hasRight)
            {
    
                var currentLeft = enumLeft.Current;
                var valueLeft = hasLeft ? leftKeySelector(currentLeft) : default(TValue);
    
                var currentRight = enumRight.Current;
                var valueRight = hasRight ? rightKeySelector(currentRight) : default(TValue);
    
                int compare =
                    !hasLeft ? 1
                    : !hasRight ? -1
                    : keyComparer.Compare(valueLeft, valueRight);
    
                switch (compare)
                {
                    case 0:
                        // The selector matches. An inner join is achieved
                        yield return selector(currentLeft, currentRight);
                        hasLeft = enumLeft.MoveNext();
                        hasRight = enumRight.MoveNext();
                        break;
                    case -1:
                        yield return selector(currentLeft, default(TRight));
                        hasLeft = enumLeft.MoveNext();
                        break;
                    case 1:
                        yield return selector(default(TLeft), currentRight);
                        hasRight = enumRight.MoveNext();
                        break;
                }
            }
    
        }
    
    }
    

How do you use $sce.trustAsHtml(string) to replicate ng-bind-html-unsafe in Angular 1.2+

That should be:

<div ng-bind-html="trustedHtml"></div>

plus in your controller:

$scope.html = '<ul><li>render me please</li></ul>';
$scope.trustedHtml = $sce.trustAsHtml($scope.html);

instead of old syntax, where you could reference $scope.html variable directly:

<div ng-bind-html-unsafe="html"></div>

As several commenters pointed out, $sce has to be injected in the controller, otherwise you will get $sce undefined error.

 var myApp = angular.module('myApp',[]);

 myApp.controller('MyController', ['$sce', function($sce) {
    // ... [your code]
 }]);

Set a default parameter value for a JavaScript function

As an update...with ECMAScript 6 you can FINALLY set default values in function parameter declarations like so:

function f (x, y = 7, z = 42) {
  return x + y + z
}

f(1) === 50

As referenced by - http://es6-features.org/#DefaultParameterValues

Incrementing a date in JavaScript

Three options for you:

1. Using just JavaScript's Date object (no libraries):

My previous answer for #1 was wrong (it added 24 hours, failing to account for transitions to and from daylight saving time; Clever Human pointed out that it would fail with November 7, 2010 in the Eastern timezone). Instead, Jigar's answer is the correct way to do this without a library:

var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);

This works even for the last day of a month (or year), because the JavaScript date object is smart about rollover:

_x000D_
_x000D_
var lastDayOf2015 = new Date(2015, 11, 31);_x000D_
snippet.log("Last day of 2015: " + lastDayOf2015.toISOString());_x000D_
var nextDay = new Date(+lastDayOf2015);_x000D_
var dateValue = nextDay.getDate() + 1;_x000D_
snippet.log("Setting the 'date' part to " + dateValue);_x000D_
nextDay.setDate(dateValue);_x000D_
snippet.log("Resulting date: " + nextDay.toISOString());
_x000D_
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->_x000D_
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
_x000D_
_x000D_
_x000D_

(This answer is currently accepted, so I can't delete it. Before it was accepted I suggested to the OP they accept Jigar's, but perhaps they accepted this one for items #2 or #3 on the list.)

2. Using MomentJS:

var today = moment();
var tomorrow = moment(today).add(1, 'days');

(Beware that add modifies the instance you call it on, rather than returning a new instance, so today.add(1, 'days') would modify today. That's why we start with a cloning op on var tomorrow = ....)

3. Using DateJS, but it hasn't been updated in a long time:

var today = new Date(); // Or Date.today()
var tomorrow = today.add(1).day();

Copy struct to struct in C

copy structure in c you just need to assign the values as follow:

struct RTCclk RTCclk1;
struct RTCclk RTCclkBuffert;

RTCclk1.second=3;
RTCclk1.minute=4;
RTCclk1.hour=5;

RTCclkBuffert=RTCclk1;

now RTCclkBuffert.hour will have value 5,

RTCclkBuffert.minute will have value 4

RTCclkBuffert.second will have value 3

How to stop/cancel 'git log' command in terminal?

You can hit the key q (for quit) and it should take you to the prompt.

Please see this link.

How can I delete Docker's images?

I have found a solution with Powershell script that will do it for me.

The script at first stop all containers than remove all containers and then remove images that are named by the user.

Look here http://www.devcode4.com/article/powershell-remove-docker-containers-and-images

How can I draw vertical text with CSS cross-browser?

If CSS writing-mode: sideways-lr is what you prefer, and you happen to run into chromium/chrome based browser. You may try

{
  writing-mode: vertical-rl; 
  transform: rotate(180deg);
}

so all modern browsers support it now.

reference: https://bugs.chromium.org/p/chromium/issues/detail?id=680331#c4

How to install/start Postman native v4.10.3 on Ubuntu 16.04 LTS 64-bit?

open terminal and type command

sudo snap install postman

hit enter button if it asks for password enter and proceed it will install postman

If above solution doesn't work for you then you should install snap first to install it

sudo apt update
sudo apt install snapd

when snap is installed successfully then u can use its packages and follow my solution for postman

How to add and remove classes in Javascript without jQuery

Add & Remove Classes (tested on IE8+)

Add trim() to IE (taken from: .trim() in JavaScript not working in IE)

if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, ''); 
  }
}

Add and Remove Classes:

function addClass(element,className) {
  var currentClassName = element.getAttribute("class");
  if (typeof currentClassName!== "undefined" && currentClassName) {
    element.setAttribute("class",currentClassName + " "+ className);
  }
  else {
    element.setAttribute("class",className); 
  }
}
function removeClass(element,className) {
  var currentClassName = element.getAttribute("class");
  if (typeof currentClassName!== "undefined" && currentClassName) {

    var class2RemoveIndex = currentClassName.indexOf(className);
    if (class2RemoveIndex != -1) {
        var class2Remove = currentClassName.substr(class2RemoveIndex, className.length);
        var updatedClassName = currentClassName.replace(class2Remove,"").trim();
        element.setAttribute("class",updatedClassName);
    }
  }
  else {
    element.removeAttribute("class");   
  } 
}

Usage:

var targetElement = document.getElementById("myElement");

addClass(targetElement,"someClass");

removeClass(targetElement,"someClass");

A working JSFIDDLE: http://jsfiddle.net/fixit/bac2vuzh/1/

Show Image View from file path?

       public static Bitmap decodeFile(String path) {
    Bitmap b = null;
    File f = new File(path);
    // Decode image size
    BitmapFactory.Options o = new BitmapFactory.Options();
    o.inJustDecodeBounds = true;

    FileInputStream fis = null;
    try {
        fis = new FileInputStream(f);
        BitmapFactory.decodeStream(fis, null, o);
        fis.close();

        int IMAGE_MAX_SIZE = 1024; // maximum dimension limit
        int scale = 1;
        if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
            scale = (int) Math.pow(2, (int) Math.round(Math.log(IMAGE_MAX_SIZE / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
        }

        // Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;

        fis = new FileInputStream(f);
        b = BitmapFactory.decodeStream(fis, null, o2);
        fis.close();

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return b;
}

public static Bitmap showBitmapFromFile(String file_path)
{
    try {
        File imgFile = new  File(file_path);
        if(imgFile.exists()){

            Bitmap pic_Bitmap = decodeFile(file_path);
            return pic_Bitmap;

        }
    } catch (Exception e) {
        MyLog.e("Exception showBitmapFromFile");
        return null;
    }
    return null;
}   

if you are using image loading in List view then use Aquery concept .

https://github.com/AshishPsaini/AqueryExample

     AQuery  aq= new AQuery((Activity) activity, convertView);
            //load image from file, down sample to target width of 250 pixels .gi 
    File file=new File("//pic/path/here/aaaa.jpg");
    if(aq!=null)
    aq.id(holder.pic_imageview).image(file, 250);

How do I get JSON data from RESTful service using Python?

I would give the requests library a try for this. Essentially just a much easier to use wrapper around the standard library modules (i.e. urllib2, httplib2, etc.) you would use for the same thing. For example, to fetch json data from a url that requires basic authentication would look like this:

import requests

response = requests.get('http://thedataishere.com',
                         auth=('user', 'password'))
data = response.json()

For kerberos authentication the requests project has the reqests-kerberos library which provides a kerberos authentication class that you can use with requests:

import requests
from requests_kerberos import HTTPKerberosAuth

response = requests.get('http://thedataishere.com',
                         auth=HTTPKerberosAuth())
data = response.json()

Is there a php echo/print equivalent in javascript

this is an another way:

<html>
<head>
    <title>Echo</title>
    <style type="text/css">
    #result{
        border: 1px solid #000000;
        min-height: 250px;
        max-height: 100%;
        padding: 5px;
        font-family: sans-serif;
        font-size: 12px;
    }
    </style>
    <script type="text/javascript" lang="ja">
    function start(){
        function echo(text){
            lastResultAreaText = document.getElementById('result').innerHTML;
            resultArea = document.getElementById('result');
            if(lastResultAreaText==""){
                resultArea.innerHTML=text;
            }
            else{
                resultArea.innerHTML=lastResultAreaText+"</br>"+text;
            }
        }

        echo("Hello World!");
        }
    </script>
</head>
<body onload="start()">
<pre id="result"></pre> 
</body>

Using PHP variables inside HTML tags?

You can do it a number of ways, depending on the type of quotes you use:

  • echo "<a href='http://www.whatever.com/$param'>Click here</a>";
  • echo "<a href='http://www.whatever.com/{$param}'>Click here</a>";
  • echo '<a href="http://www.whatever.com/' . $param . '">Click here</a>';
  • echo "<a href=\"http://www.whatever.com/$param\">Click here</a>";

Double quotes allow for variables in the middle of the string, where as single quotes are string literals and, as such, interpret everything as a string of characters -- nothing more -- not even \n will be expanded to mean the new line character, it will just be the characters \ and n in sequence.

You need to be careful about your use of whichever type of quoting you decide. You can't use double quotes inside a double quoted string (as in your example) as you'll be ending the string early, which isn't what you want. You can escape the inner double quotes, however, by adding a backslash.

On a separate note, you might need to be careful about XSS attacks when printing unsafe variables (populated by the user) out to the browser.

Copying sets Java

The copy constructor given by @Stephen C is the way to go when you have a Set you created (or when you know where it comes from). When it comes from a Map.entrySet(), it will depend on the Map implementation you're using:

findbugs says

The entrySet() method is allowed to return a view of the underlying Map in which a single Entry object is reused and returned during the iteration. As of Java 1.6, both IdentityHashMap and EnumMap did so. When iterating through such a Map, the Entry value is only valid until you advance to the next iteration. If, for example, you try to pass such an entrySet to an addAll method, things will go badly wrong.

As addAll() is called by the copy constructor, you might find yourself with a Set of only one Entry: the last one.

Not all Map implementations do that though, so if you know your implementation is safe in that regard, the copy constructor definitely is the way to go. Otherwise, you'd have to create new Entry objects yourself:

Set<K,V> copy = new HashSet<K,V>(map.size());
for (Entry<K,V> e : map.entrySet())
    copy.add(new java.util.AbstractMap.SimpleEntry<K,V>(e));

Edit: Unlike tests I performed on Java 7 and Java 6u45 (thanks to Stephen C), the findbugs comment does not seem appropriate anymore. It might have been the case on earlier versions of Java 6 (before u45) but I don't have any to test.

How to un-commit last un-pushed git commit without losing the changes

For the case: "This has not been pushed, only committed." - if you use IntelliJ (or another JetBrains IDE) and you haven't pushed changes yet you can do next.

  1. Go to Version control window (Alt + 9/Command + 9) - "Log" tab.
  2. Right-click on a commit before your last one.
  3. Reset current branch to here
  4. pick Soft (!!!)
  5. push the Reset button in the bottom of the dialog window.

Done.

This will "uncommit" your changes and return your git status to the point before your last local commit. You will not lose any changes you made.

Serialize form data to JSON

You can do this:

_x000D_
_x000D_
function onSubmit( form ){_x000D_
  var data = JSON.stringify( $(form).serializeArray() ); //  <-----------_x000D_
_x000D_
  console.log( data );_x000D_
  return false; //don't submit_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<form onsubmit='return onSubmit(this)'>_x000D_
  <input name='user' placeholder='user'><br>_x000D_
  <input name='password' type='password' placeholder='password'><br>_x000D_
  <button type='submit'>Try</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

see this: http://www.json.org/js.html

iFrame src change event detection?

You may want to use the onLoad event, as in the following example:

<iframe src="http://www.google.com/" onLoad="alert('Test');"></iframe>

The alert will pop-up whenever the location within the iframe changes. It works in all modern browsers, but may not work in some very older browsers like IE5 and early Opera. (Source)

If the iframe is showing a page within the same domain of the parent, you would be able to access the location with contentWindow.location, as in the following example:

<iframe src="/test.html" onLoad="alert(this.contentWindow.location);"></iframe>

How do I get git to default to ssh and not https for new repositories

SSH File

~/.ssh/config file
Host *
    StrictHostKeyChecking no
    UserKnownHostsFile=/dev/null
    LogLevel QUIET
    ConnectTimeout=10
Host github.com
        User git
        AddKeystoAgent yes
        UseKeychain yes
        Identityfile ~/github_rsa

Edit reponame/.git/config

[remote "origin"]
        url = [email protected]:username/repo.git

Parameter binding on left joins with array in Laravel Query Builder

You don't have to bind parameters if you use query builder or eloquent ORM. However, if you use DB::raw(), ensure that you binding the parameters.

Try the following:

$array = array(1,2,3);       $query = DB::table('offers');             $query->select('id', 'business_id', 'address_id', 'title', 'details', 'value', 'total_available', 'start_date', 'end_date', 'terms', 'type', 'coupon_code', 'is_barcode_available', 'is_exclusive', 'userinformations_id', 'is_used');             $query->leftJoin('user_offer_collection', function ($join) use ($array)             {                 $join->on('user_offer_collection.offers_id', '=', 'offers.id')                       ->whereIn('user_offer_collection.user_id', $array);             });       $query->get(); 

Java balanced expressions check {[()]}

Please try this.

    import java.util.Stack;

    public class PatternMatcher {
        static String[] patterns = { "{([])}", "{}[]()", "(}{}]]", "{()", "{}" };
        static String openItems = "{([";

        boolean isOpen(String sy) {
            return openItems.contains(sy);
        }

        String getOpenSymbol(String byCloseSymbol) {
            switch (byCloseSymbol) {
            case "}":
                return "{";
            case "]":
                return "[";
            case ")":
                return "(";

            default:
                return null;
            }
        }

        boolean isValid(String pattern) {

            if(pattern == null) {
                return false;
            }

            Stack<String> stack = new Stack<String>();
            char[] symbols = pattern.toCharArray();

            if (symbols.length == 0 || symbols.length % 2 != 0) {
                return false;
            }

            for (char c : symbols) {
                String symbol = Character.toString(c);
                if (isOpen(symbol)) {
                    stack.push(symbol);
                } else {
                    String openSymbol = getOpenSymbol(symbol);
                    if (stack.isEmpty() 
                            || openSymbol == null 
                            || !openSymbol.equals(stack.pop())) {
                        return false;
                    }
                }
            }
            return stack.isEmpty();
        }

        public static void main(String[] args) {
            PatternMatcher patternMatcher = new PatternMatcher();

            for (String pattern : patterns) {
                boolean valid = patternMatcher.isValid(pattern);
                System.out.println(pattern + "\t" + valid);
            }
        }

    }

Regex match everything after question mark?

\?(.*)

You want the content of the first capture group.

Position a CSS background image x pixels from the right?

Works for all real browsers (and for IE9+):

background-position: right 10px top 10px;

I use it to RTL WordPress themes. See example: temporary website or the real website will be up soon. Look at the icons at the big DIVs right corners.

jQuery if Element has an ID?

You can do this:

if ($(".parent a[Id]").length > 0) {

    /* then do something here */

}

Preventing SQL injection in Node.js

The library has a section in the readme about escaping. It's Javascript-native, so I do not suggest switching to node-mysql-native. The documentation states these guidelines for escaping:

Edit: node-mysql-native is also a pure-Javascript solution.

  • Numbers are left untouched
  • Booleans are converted to true / false strings
  • Date objects are converted to YYYY-mm-dd HH:ii:ss strings
  • Buffers are converted to hex strings, e.g. X'0fa5'
  • Strings are safely escaped
  • Arrays are turned into list, e.g. ['a', 'b'] turns into 'a', 'b'
  • Nested arrays are turned into grouped lists (for bulk inserts), e.g. [['a', 'b'], ['c', 'd']] turns into ('a', 'b'), ('c', 'd')
  • Objects are turned into key = 'val' pairs. Nested objects are cast to strings.
  • undefined / null are converted to NULL
  • NaN / Infinity are left as-is. MySQL does not support these, and trying to insert them as values will trigger MySQL errors until they implement support.

This allows for you to do things like so:

var userId = 5;
var query = connection.query('SELECT * FROM users WHERE id = ?', [userId], function(err, results) {
  //query.sql returns SELECT * FROM users WHERE id = '5'
});

As well as this:

var post  = {id: 1, title: 'Hello MySQL'};
var query = connection.query('INSERT INTO posts SET ?', post, function(err, result) {
  //query.sql returns INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL'
});

Aside from those functions, you can also use the escape functions:

connection.escape(query);
mysql.escape(query);

To escape query identifiers:

mysql.escapeId(identifier);

And as a response to your comment on prepared statements:

From a usability perspective, the module is great, but it has not yet implemented something akin to PHP's Prepared Statements.

The prepared statements are on the todo list for this connector, but this module at least allows you to specify custom formats that can be very similar to prepared statements. Here's an example from the readme:

connection.config.queryFormat = function (query, values) {
  if (!values) return query;
  return query.replace(/\:(\w+)/g, function (txt, key) {
    if (values.hasOwnProperty(key)) {
      return this.escape(values[key]);
    }
    return txt;
  }.bind(this));
};

This changes the query format of the connection so you can use queries like this:

connection.query("UPDATE posts SET title = :title", { title: "Hello MySQL" });
//equivalent to
connection.query("UPDATE posts SET title = " + mysql.escape("Hello MySQL");

Can an int be null in Java?

The code won't even compile. Only an fullworthy Object can be null, like Integer. Here's a basic example to show when you can test for null:

Integer data = check(Node root);

if ( data == null ) {
 // do something
} else {
 // do something
}

On the other hand, if check() is declared to return int, it can never be null and the whole if-else block is then superfluous.

int data = check(Node root);

// do something

Autoboxing problems doesn't apply here as well when check() is declared to return int. If it had returned Integer, then you may risk NullPointerException when assigning it to an int instead of Integer. Assigning it as an Integer and using the if-else block would then indeed have been mandatory.

To learn more about autoboxing, check this Sun guide.

Get absolute path to workspace directory in Jenkins Pipeline plugin

Since version 2.5 of the Pipeline Nodes and Processes Plugin (a component of the Pipeline plugin, installed by default), the WORKSPACE environment variable is available again. This version was released on 2016-09-23, so it should be available on all up-to-date Jenkins instances.

Example

node('label'){
    // now you are on slave labeled with 'label'
    def workspace = WORKSPACE
    // ${workspace} will now contain an absolute path to job workspace on slave

    workspace = env.WORKSPACE
    // ${workspace} will still contain an absolute path to job workspace on slave

    // When using a GString at least later Jenkins versions could only handle the env.WORKSPACE variant:
    echo "Current workspace is ${env.WORKSPACE}"

    // the current Jenkins instances will support the short syntax, too:
    echo "Current workspace is $WORKSPACE"

}

How to do a simple file search in cmd

dir /b/s *.txt  

searches for all txt file in the directory tree. Before using it just change the directory to root using

cd/

you can also export the list to a text file using

dir /b/s *.exe >> filelist.txt

and search within using

type filelist.txt | find /n "filename"

EDIT 1: Although this dir command works since the old dos days but Win7 added something new called Where

where /r c:\Windows *.exe *.dll

will search for exe & dll in the drive c:\Windows as suggested by @SPottuit you can also copy the output to the clipboard with

where /r c:\Windows *.exe |clip

just wait for the prompt to return and don't copy anything until then.

EDIT 2: If you are searching recursively and the output is big you can always use more to enable paging, it will show -- More -- at the bottom and will scroll to the next page once you press SPACE or moves line by line on pressing ENTER

where /r c:\Windows *.exe |more

For more help try

where/?

What is the different between RESTful and RESTless

REST stands for REpresentational State Transfer and goes a little something like this:

We have a bunch of uniquely addressable 'entities' that we want made available via a web application. Those entities each have some identifier and can be accessed in various formats. REST defines a bunch of stuff about what GET, POST, etc mean for these purposes.

the basic idea with REST is that you can attach a bunch of 'renderers' to different entities so that they can be available in different formats easily using the same HTTP verbs and url formats.

For more clarification on what RESTful means and how it is used google rails. Rails is a RESTful framework so there's loads of good information available in its docs and associated blog posts. Worth a read even if you arent keen to use the framework. For example: http://www.sitepoint.com/restful-rails-part-i/

RESTless means not restful. If you have a web app that does not adhere to RESTful principles then it is not RESTful

What is the best way to compare 2 folder trees on windows?

Like the OP, I was looking for a Windows folder diff tool, in particular one that could handle very large trees (100s of Gigabytes of data). Thanks Lieven Keersmaekers for the pointer to BeyondCompare, which I found to be VERY fast (roughly 10-100 times faster) than my previous old school tool windiff.

BTW, BeyondCompare does have a command line mode in addition to the GUI.

"Unable to get the VLookup property of the WorksheetFunction Class" error

I was having the same problem. It seems that passing Me.ComboBox1.Value as an argument for the Vlookup function is causing the issue. What I did was assign this value to a double and then put it into the Vlookup function.

Dim x As Double
x = Me.ComboBox1.Value
Me.TextBox1.Value = Application.WorksheetFunction.VLookup(x, Worksheets("Sheet3").Range("Names"), 2, False) 

Or, for a shorter method, you can just convert the type within the Vlookup function using Cdbl(<Value>).

So it would end up being

Me.TextBox1.Value = Application.WorksheetFunction.VLookup(Cdbl(Me.ComboBox1.Value), Worksheets("Sheet3").Range("Names"), 2, False) 

Strange as it may sound, it works for me.

Hope this helps.

How to receive JSON as an MVC 5 action method parameter

You are sending a array of string

var usersRoles = [];
jQuery("#dualSelectRoles2 option").each(function () {
    usersRoles.push(jQuery(this).val());
});   

So change model type accordingly

 public ActionResult AddUser(List<string> model)
 {
 }