Programs & Examples On #Game physics

Game Physics is about implementation, creation, optimization and any other thing related to physics in games. Physics controls the interaction of every physical object in a game, where any 2d or 3d model interacts with any other 2d or 3d model of an object in a game. Physics is used to give realistic effects of this interaction.

How to prevent colliders from passing through each other?

I have a pinball prototype that also gave me much trouble in the same areas. These are all the steps I've taken to almost (but not yet entirely) solve these problems:

For fast moving objects:

  • Set the rigidbody's Interpolate to 'Interpolate' (this does not affect the actual physics simulation, but updates the rendering of the object properly - use this only on important objects from a rendering point of view, like the player, or a pinball, but not for projectiles)

  • Set Collision Detection to Continuous Dynamic

  • Attach the script DontGoThroughThings (https://www.auto.tuwien.ac.at/wordpress/?p=260) to your object. This script cleverly uses the Raycasting solution I posted in my other answer to pull back offending objects to before the collision points.

In Edit -> Project Settings -> Physics:

  • Set Min Penetration for Penalty to a very low value. I've set mine to 0.001

  • Set Solver Iteration Count to a higher value. I've set mine to 50, but you can probably do ok with much less.

All that is going to have a penalty in performace, but that's unavoidable. The defaults values are soft on performance but are not really intented for proper simulation of small and fast-moving objects.

How to count items in JSON data

import json

json_data = json.dumps({
  "result":[
    {
      "run":[
        {
          "action":"stop"
        },
        {
          "action":"start"
        },
        {
          "action":"start"
        }
      ],
      "find": "true"
    }
  ]
})

item_dict = json.loads(json_data)
print len(item_dict['result'][0]['run'])

Convert it in dict.

How to stop EditText from gaining focus at Activity startup in Android

add below line in Manifest file where you have mentioned your activity

android:windowSoftInputMode="stateAlwaysHidden"

Check if an HTML input element is empty or has no value entered by user

The getElementById method returns an Element object that you can use to interact with the element. If the element is not found, null is returned. In case of an input element, the value property of the object contains the string in the value attribute.

By using the fact that the && operator short circuits, and that both null and the empty string are considered "falsey" in a boolean context, we can combine the checks for element existence and presence of value data as follows:

var myInput = document.getElementById("customx");
if (myInput && myInput.value) {
  alert("My input has a value!");
}

boolean in an if statement

In general, it is cleaner and simpler to omit the === true.

However, in Javascript, those statements are different.

if (booleanValue) will execute if booleanValue is truthy – anything other than 0, false, '', NaN, null, and undefined.

if (booleanValue === true) will only execute if booleanValue is precisely equal to true.

How to access to a child method from the parent in vue.js

To communicate a child component with another child component I've made a method in parent which calls a method in a child with:

this.$refs.childMethod()

And from the another child I've called the root method:

this.$root.theRootMethod()

It worked for me.

Spring Boot Multiple Datasource

once you start work with jpa and some driver is in your class path spring boot right away puts it inside as your data source (e.g h2 ) for using the defult data source therefore u will need only to define

spring.datasource.url= jdbc:mysql://localhost:3306/
spring.datasource.username=test
spring.datasource.password=test

if we go one step farther and u want to use two I would reccomend to use two data sources such as explained here : Spring Boot Configure and Use Two DataSources

Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed

1- Never use Response.Write.

2- I put the code below after create (not in Page_Load) a LinkButton (dynamically) and solved my problem:

ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
scriptManager.RegisterPostBackControl(lblbtndoc1);

How to match all occurrences of a regex

Using scan should do the trick:

string.scan(/regex/)

How to access host port from docker container

For all platforms

Docker v 20.10 and above (since December 14th 2020)

On Linux, add --add-host=host.docker.internal:host-gateway to your Docker command to enable this feature. (See below for Docker Compose configuration.)

Use your internal IP address or connect to the special DNS name host.docker.internal which will resolve to the internal IP address used by the host.

To enable this in Docker Compose on Linux, add the following lines to the container definition:

extra_hosts:
- "host.docker.internal:host-gateway"

For macOS and Windows

Docker v 18.03 and above (since March 21st 2018)

Use your internal IP address or connect to the special DNS name host.docker.internal which will resolve to the internal IP address used by the host.

Linux support pending https://github.com/docker/for-linux/issues/264

MacOS with earlier versions of Docker

Docker for Mac v 17.12 to v 18.02

Same as above but use docker.for.mac.host.internal instead.

Docker for Mac v 17.06 to v 17.11

Same as above but use docker.for.mac.localhost instead.

Docker for Mac 17.05 and below

To access host machine from the docker container you must attach an IP alias to your network interface. You can bind whichever IP you want, just make sure you're not using it to anything else.

sudo ifconfig lo0 alias 123.123.123.123/24

Then make sure that you server is listening to the IP mentioned above or 0.0.0.0. If it's listening on localhost 127.0.0.1 it will not accept the connection.

Then just point your docker container to this IP and you can access the host machine!

To test you can run something like curl -X GET 123.123.123.123:3000 inside the container.

The alias will reset on every reboot so create a start-up script if necessary.

Solution and more documentation here: https://docs.docker.com/docker-for-mac/networking/#use-cases-and-workarounds

try/catch with InputMismatchException creates infinite loop

@Limp, your answer is right, just use .nextLine() while reading the input. Sample code:

    do {
        try {
            System.out.println("Enter first num: ");
            n1 = Integer.parseInt(input.nextLine());
            System.out.println("Enter second num: ");
            n2 = Integer.parseInt(input.nextLine());
            nQuotient = n1 / n2;
            bError = false;
        } catch (Exception e) {
            System.out.println("Error!");
        }
    } while (bError);

    System.out.printf("%d/%d = %d", n1, n2, nQuotient);

Read the description of why this problem was caused in the link below. Look for the answer I posted for the detail in this thread. Java Homework user input issue

Ok, I will briefly describe it. When you read input using nextInt(), you just read the number part but the ENDLINE character was still on the stream. That was the main cause. Now look at the code above, all I did is read the whole line and parse it , it still throws the exception and work the way you were expecting it to work. Rest of your code works fine.

What is it exactly a BLOB in a DBMS context

A BLOB is a Binary Large OBject. It is used to store large quantities of binary data in a database.

You can use it to store any kind of binary data that you want, includes images, video, or any other kind of binary data that you wish to store.

Different DBMSes treat BLOBs in different ways; you should read the documentation of the databases you are interested in to see how (and if) they handle BLOBs.

How does the Spring @ResponseBody annotation work?

@RequestBody annotation binds the HTTPRequest body to the domain object. Spring automatically deserializes incoming HTTP Request to object using HttpMessageConverters. HttpMessageConverter converts body of request to resolve the method argument depending on the content type of the request. Many examples how to use converters https://upcodein.com/search/jc/mg/ResponseBody/page/0

Docker error : no space left on device

If it's just a test installation of Docker (ie not production) and you don't care about doing a nuclear clean, you can:

clean all containers: docker ps -a | sed '1 d' | awk '{print $1}' | xargs -L1 docker rm

clean all images: docker images -a | sed '1 d' | awk '{print $3}' | xargs -L1 docker rmi -f

Again, I use this in my ec2 instances when developing Docker, not in any serious QA or Production path. The great thing is that if you have your Dockerfile(s), it's easy to rebuild and or docker pull.

Get AVG ignoring Null or Zero values

this should work, haven't tried though. this will exclude zero. NULL is excluded by default

AVG (CASE WHEN SecurityW <> 0 THEN SecurityW ELSE NULL END)

git cherry-pick says "...38c74d is a merge but no -m option was given"

Simplification of @Daira Hopwood method good for picking one single commit. Need no temporary branches.

In the case of the author:

  • Z is wanted commit (fd9f578)
  • Y is commit before it
  • X current working branch

then do:

git checkout Z   # move HEAD to wanted commit
git reset Y      # have Z as changes in working tree
git stash        # save Z in stash
git checkout X   # return to working branch
git stash pop    # apply Z to current branch
git commit -a    # do commit

Find duplicate records in MongoDB

You can find the list of duplicate names using the following aggregate pipeline:

  • Group all the records having similar name.
  • Match those groups having records greater than 1.
  • Then group again to project all the duplicate names as an array.

The Code:

db.collection.aggregate([
{$group:{"_id":"$name","name":{$first:"$name"},"count":{$sum:1}}},
{$match:{"count":{$gt:1}}},
{$project:{"name":1,"_id":0}},
{$group:{"_id":null,"duplicateNames":{$push:"$name"}}},
{$project:{"_id":0,"duplicateNames":1}}
])

o/p:

{ "duplicateNames" : [ "ksqn291", "ksqn29123213Test" ] }

How to center a subview of UIView

func callAlertView() {

    UIView.animate(withDuration: 0, animations: {
        let H = self.view.frame.height * 0.4
        let W = self.view.frame.width * 0.9
        let X = self.view.bounds.midX - (W/2)
        let Y = self.view.bounds.midY - (H/2)
        self.alertView.frame = CGRect(x:X, y: Y, width: W, height: H)
        self.alertView.layer.borderWidth = 1
        self.alertView.layer.borderColor = UIColor.red.cgColor
        self.alertView.layer.cornerRadius = 16
        self.alertView.layer.masksToBounds = true
        self.view.addSubview(self.alertView)

    })


}// calculation works adjust H and W according to your requirement

How to search a list of tuples in Python

[k for k,v in l if v =='delicia']

here l is the list of tuples-[(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")]

And instead of converting it to a dict, we are using llist comprehension.

*Key* in Key,Value in list, where value = **delicia**

Difference between number and integer datatype in oracle dictionary views

This is what I got from oracle documentation, but it is for oracle 10g release 2:

When you define a NUMBER variable, you can specify its precision (p) and scale (s) so that it is sufficiently, but not unnecessarily, large. Precision is the number of significant digits. Scale can be positive or negative. Positive scale identifies the number of digits to the right of the decimal point; negative scale identifies the number of digits to the left of the decimal point that can be rounded up or down.

The NUMBER data type is supported by Oracle Database standard libraries and operates the same way as it does in SQL. It is used for dimensions and surrogates when a text or INTEGER data type is not appropriate. It is typically assigned to variables that are not used for calculations (like forecasts and aggregations), and it is used for variables that must match the rounding behavior of the database or require a high degree of precision. When deciding whether to assign the NUMBER data type to a variable, keep the following facts in mind in order to maximize performance:

  • Analytic workspace calculations on NUMBER variables is slower than other numerical data types because NUMBER values are calculated in software (for accuracy) rather than in hardware (for speed).
  • When data is fetched from an analytic workspace to a relational column that has the NUMBER data type, performance is best when the data already has the NUMBER data type in the analytic workspace because a conversion step is not required.

CodeIgniter Select Query

echo $this->db->select('title, content, date')->get_compiled_select();

Why doesn't TFS get latest get the latest?

It could happen when you use TFS from two different machines with the same account, if so you should compare to see changed files and check out them then get latest then undo pending changes to remove checkout

Nginx no-www to www and www to no-www

Redirect non-www to www

For Single Domain :

server {
        server_name example.com;
        return 301 $scheme://www.example.com$request_uri;
}

For All Domains :

server {
        server_name "~^(?!www\.).*" ;
        return 301 $scheme://www.$host$request_uri;
}

Redirect www to non-www For Single Domain:

server {
        server_name www.example.com;
        return 301 $scheme://example.com$request_uri;
}

For All Domains :

server {
         server_name "~^www\.(.*)$" ;
         return 301 $scheme://$1$request_uri ;
}

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

The easy solution is to create a payload class that has the str1 and the str2 as attributes:

@Getter
@Setter
public class ObjHolder{

String str1;
String str2;

}

And after you can pass

@RequestMapping(value = "/Test", method = RequestMethod.POST)
@ResponseBody
public boolean getTest(@RequestBody ObjHolder Str) {}

and the body of your request is:

{
    "str1": "test one",
    "str2": "two test"
}

Getting mouse position in c#

Initialize the current cursor. Use it to get the position of X and Y

this.Cursor = new Cursor(Cursor.Current.Handle);
int posX = Cursor.Position.X;
int posY = Cursor.Position.Y;

How do I get bit-by-bit data from an integer value in C?

Here's one way to do it—there are many others:

bool b[4];
int v = 7;  // number to dissect

for (int j = 0;  j < 4;  ++j)
   b [j] =  0 != (v & (1 << j));

It is hard to understand why use of a loop is not desired, but it is easy enough to unroll the loop:

bool b[4];
int v = 7;  // number to dissect

b [0] =  0 != (v & (1 << 0));
b [1] =  0 != (v & (1 << 1));
b [2] =  0 != (v & (1 << 2));
b [3] =  0 != (v & (1 << 3));

Or evaluating constant expressions in the last four statements:

b [0] =  0 != (v & 1);
b [1] =  0 != (v & 2);
b [2] =  0 != (v & 4);
b [3] =  0 != (v & 8);

How to mount a host directory in a Docker container

Jul 2015 update - boot2docker now supports direct mounting. You can use -v /var/logs/on/host:/var/logs/in/container directly from your Mac prompt, without double mounting

hidden field in php

Can I use a field of the type ... and retrieve it after the GET / POST method ...

Yes (haven't you tried?)

Are there any other ways of using hidden fields in PHP?

You mean other ways of retrieving the value? No.
Of course you can use hidden fields for what ever you want.


Btw. input fiels have no end tag. So write either just <input ...> or as self-closing tag <input .../>.

What's the difference between window.location and document.location in JavaScript?

Despite of most people recommend here, that is how Google Analytics's dynamic protocol snipped looked like for ages (before they moved from ga.js to analytics.js recently):

ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';

More info: https://developers.google.com/analytics/devguides/collection/gajs/

In new version they used '//' so browser can automatically add protocol:

'//www.google-analytics.com/analytics.js'

So if Google prefers document.location to window.location when they need protocol in JS, I guess they have some reasons for that.

OVERALL: I personally believe that document.location and window.location are the same, but if giant with biggest stats about usage of browsers like Google using document.location, I recommend to follow them.

How to embed a PDF viewer in a page?

I would really opt for FlowPaper, especially their new Elements mode that can be found here : https://flowpaper.com/demo/

It flattens the PDFs significantly at the same time as keeping text sharp which means that it will load much faster on mobile devices

Java : Comparable vs Comparator

When your class implements Comparable, the compareTo method of the class is defining the "natural" ordering of that object. That method is contractually obligated (though not demanded) to be in line with other methods on that object, such as a 0 should always be returned for objects when the .equals() comparisons return true.

A Comparator is its own definition of how to compare two objects, and can be used to compare objects in a way that might not align with the natural ordering.

For example, Strings are generally compared alphabetically. Thus the "a".compareTo("b") would use alphabetical comparisons. If you wanted to compare Strings on length, you would need to write a custom comparator.

In short, there isn't much difference. They are both ends to similar means. In general implement comparable for natural order, (natural order definition is obviously open to interpretation), and write a comparator for other sorting or comparison needs.

How to inherit constructors?

Don't forget that you can also redirect constructors to other constructors at the same level of inheritance:

public Bar(int i, int j) : this(i) { ... }
                            ^^^^^

mkdir's "-p" option

The man pages is the best source of information you can find... and is at your fingertips: man mkdir yields this about -p switch:

-p, --parents
    no error if existing, make parent directories as needed

Use case example: Assume I want to create directories hello/goodbye but none exist:

$mkdir hello/goodbye
mkdir:cannot create directory 'hello/goodbye': No such file or directory
$mkdir -p hello/goodbye
$

-p created both, hello and goodbye

This means that the command will create all the directories necessaries to fulfill your request, not returning any error in case that directory exists.

About rlidwka, Google has a very good memory for acronyms :). My search returned this for example: http://www.cs.cmu.edu/~help/afs/afs_acls.html

 Directory permissions

l (lookup)
    Allows one to list the contents of a directory. It does not allow the reading of files. 
i (insert)
    Allows one to create new files in a directory or copy new files to a directory. 
d (delete)
    Allows one to remove files and sub-directories from a directory. 
a (administer)
    Allows one to change a directory's ACL. The owner of a directory can always change the ACL of a directory that s/he owns, along with the ACLs of any subdirectories in that directory. 

File permissions

r (read)
    Allows one to read the contents of file in the directory. 
w (write)
    Allows one to modify the contents of files in a directory and use chmod on them. 
k (lock)
    Allows programs to lock files in a directory. 

Hence rlidwka means: All permissions on.

It's worth mentioning, as @KeithThompson pointed out in the comments, that not all Unix systems support ACL. So probably the rlidwka concept doesn't apply here.

How to Install Font Awesome in Laravel Mix

Try in your webpack.mix.js to add the '*'

.copy('node_modules/font-awesome/fonts/*', 'public/fonts')

Math constant PI value in C

The closest thing C does to "computing p" in a way that's directly visible to applications is acos(-1) or similar. This is almost always done with polynomial/rational approximations for the function being computed (either in C, or by the FPU microcode).

However, an interesting issue is that computing the trigonometric functions (sin, cos, and tan) requires reduction of their argument modulo 2p. Since 2p is not a diadic rational (and not even rational), it cannot be represented in any floating point type, and thus using any approximation of the value will result in catastrophic error accumulation for large arguments (e.g. if x is 1e12, and 2*M_PI differs from 2p by e, then fmod(x,2*M_PI) differs from the correct value of 2p by up to 1e12*e/p times the correct value of x mod 2p. That is to say, it's completely meaningless.

A correct implementation of C's standard math library simply has a gigantic very-high-precision representation of p hard coded in its source to deal with the issue of correct argument reduction (and uses some fancy tricks to make it not-quite-so-gigantic). This is how most/all C versions of the sin/cos/tan functions work. However, certain implementations (like glibc) are known to use assembly implementations on some cpus (like x86) and don't perform correct argument reduction, leading to completely nonsensical outputs. (Incidentally, the incorrect asm usually runs about the same speed as the correct C code for small arguments.)

How to force Eclipse to ask for default workspace?

I first tried the -clean option, but that didn't solve the problem.

Then I added the -data option with the correct path to the workspace.

That solved the problem for me.

C++ terminate called without an active exception

When a thread object goes out of scope and it is in joinable state, the program is terminated. The Standard Committee had two other options for the destructor of a joinable thread. It could quietly join -- but join might never return if the thread is stuck. Or it could detach the thread (a detached thread is not joinable). However, detached threads are very tricky, since they might survive till the end of the program and mess up the release of resources. So if you don't want to terminate your program, make sure you join (or detach) every thread.

Save range to variable

In your own answer, you effectively do this:

Dim SrcRange As Range ' you should always declare things explicitly
Set SrcRange = Sheets("Src").Range("A2:A9")
SrcRange.Copy Destination:=Sheets("Dest").Range("A2")

You're not really "extracting" the range to a variable, you're setting a reference to the range.

In many situations, this can be more efficient as well as more flexible:

Dim Src As Variant
Src= Sheets("Src").Range("A2:A9").Value 'Read range to array
'Here you can add code to manipulate your Src array
'...
Sheets("Dest").Range("A2:A9").Value = Src 'Write array back to another range

How do I format date value as yyyy-mm-dd using SSIS expression builder?

Correct expression is

"source " + (DT_STR,4,1252)DATEPART( "yyyy" , getdate() ) + "-" +
RIGHT("0" + (DT_STR,4,1252)DATEPART( "mm" , getdate() ), 2) + "-" +
RIGHT("0" + (DT_STR,4,1252)DATEPART( "dd" , getdate() ), 2) +".CSV"

From ND to 1D arrays

In [14]: b = np.reshape(a, (np.product(a.shape),))

In [15]: b
Out[15]: array([1, 2, 3, 4, 5, 6])

or, simply:

In [16]: a.flatten()
Out[16]: array([1, 2, 3, 4, 5, 6])

C# Copy a file to another location with a different name

If you want to use only FileInfo class try this

             string oldPath = @"C:\MyFolder\Myfile.xyz";
             string newpath = @"C:\NewFolder\";
             string newFileName = "new file name";
             FileInfo f1 = new FileInfo(oldPath);
           if(f1.Exists)
             {
                if(!Directory.Exists(newpath))
                {
                    Directory.CreateDirectory(newpath); 
                }
                 f1.CopyTo(string.Format("{0}{1}{2}", newpath, newFileName, f1.Extension));
             }

How to remove spaces from a string using JavaScript?

easy way

   someString.replace(' ', '');

Show a leading zero if a number is less than 10

Try this

function pad (str, max) {
  return str.length < max ? pad("0" + str, max) : str;
}

alert(pad("5", 2));

Example

http://jsfiddle.net/

Or

var number = 5;
var i;
if (number < 10) {
    alert("0"+number);
}

Example

http://jsfiddle.net/

What does the error "JSX element type '...' does not have any construct or call signatures" mean?

You can use

function renderGreeting(props: {Elem: React.Component<any, any>}) {
    return <span>Hello, {props.Elem}!</span>;
}

However, does the following work?

function renderGreeting(Elem: React.ComponentType) {
    const propsToPass = {one: 1, two: 2};

    return <span>Hello, <Elem {...propsToPass} />!</span>;
}

val() doesn't trigger change() in jQuery

From https://api.jquery.com/change/:

The change event is sent to an element when its value changes. This event is limited to <input> elements, <textarea> boxes and <select> elements. For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus.

Unsupported method: BaseConfig.getApplicationIdSuffix()

If this ()Unsupported method: BaseConfig.getApplicationIdSuffix Android Project is old and you have updated Android Studio, what I did was simply CLOSE PROJECT and ran it again. It solved the issue for me. Did not add any dependencies or whatever as described by other answers.

When to use IList and when to use List

I would agree with Lee's advice for taking parameters, but not returning.

If you specify your methods to return an interface that means you are free to change the exact implementation later on without the consuming method ever knowing. I thought I'd never need to change from a List<T> but had to later change to use a custom list library for the extra functionality it provided. Because I'd only returned an IList<T> none of the people that used the library had to change their code.

Of course that only need apply to methods that are externally visible (i.e. public methods). I personally use interfaces even in internal code, but as you are able to change all the code yourself if you make breaking changes it's not strictly necessary.

How do I get length of list of lists in Java?

count of the contained lists in the outmost list

int count = data.size();

lambda to get the count of the contained inner lists

int count = data.stream().collect( summingInt(l -> l.size()) );

How to change MySQL data directory?

This solution works in Windows 7 using Workbench. You will need Administrator privileges to do this. It creates a junction (like a shortcut) to wherever you really want to store your data

Open Workbench and select INSTANCE - Startup / Shutdown Stop the server

Install Junction Master from https://bitsum.com/junctionmaster.php

Navigate to C:\ProgramData\MySQL\MySQL Server 5.6

Right click on Data and select "MOVE and then LINK folder to ..." Accept the warning Point destination to "Your new data directory here without the quotes" Click MOVE AND LINK

Now go to "Your new data directory here without the quotes"

Right click on Data Go to the security tab Click Edit Click Add Type NETWORK SERVICE then Check Names Click OK Click the Allow Full Control checkbox and then OK

Go back to Workbench and Start the server

This method worked for me using MySQL Workbench 6.2 on Windows 7 Enterprise.

iOS 7 - Status bar overlaps the view

This is the default behaviour for UIViewController on iOS 7. The view will be full-screen which means the status bar will cover the top of your view.

If you have a UIViewController within a UINavigationController and the navigationBar is visible, you can have the following code in your viewDidLoad or have a background image for navigationBar do the trick.

self.edgesForExtendedLayout = UIRectEdgeNone;

If you have navigationBar hidden, then you have to adjust all the UIView elements by shifting 20 points. I dont't see any other solution. Use auto layout will help a little bit.

Here is the sample code for detecting the iOS version, if you want to backward compatibility.

NSUInteger DeviceSystemMajorVersion() {
    static NSUInteger _deviceSystemMajorVersion = -1;
    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{
        NSString *systemVersion = [UIDevice currentDevice].systemVersion;
        _deviceSystemMajorVersion = [[systemVersion componentsSeparatedByString:@"."][0] intValue];
    });

   return _deviceSystemMajorVersion;
}

How to compile without warnings being treated as errors?

If you are compiling linux kernel. For example, if you want to disable the warning that is "unused-but-set-variable" been treated as error. You can add a statement:

KBUILD_CFLAGS += $(call cc-option,-Wno-error=unused-but-set-variable,)

in your Makefile

How to change UINavigationBar background color from the AppDelegate

Swift:

self.navigationController?.navigationBar.barTintColor = UIColor.red
self.navigationController?.navigationBar.isTranslucent = false

Running Python code in Vim

Plugin: jupyter-vim

So you can send lines (<leader>E), visual selection (<leader>e) to a running jupyter-client (the replacement of ipython)

enter image description here

I prefer to separate editor and interpreter (each one in its shell). Imagine you send a bad input reading command ...

Adding a directory to PATH in Ubuntu

Actually I would advocate .profile if you need it to work from scripts, and in particular, scripts run by /bin/sh instead of Bash. If this is just for your own private interactive use, .bashrc is fine, though.

How to generate a Makefile with source in sub-directories using just one makefile

This does the trick:

CC        := g++
LD        := g++

MODULES   := widgets test ui
SRC_DIR   := $(addprefix src/,$(MODULES))
BUILD_DIR := $(addprefix build/,$(MODULES))

SRC       := $(foreach sdir,$(SRC_DIR),$(wildcard $(sdir)/*.cpp))
OBJ       := $(patsubst src/%.cpp,build/%.o,$(SRC))
INCLUDES  := $(addprefix -I,$(SRC_DIR))

vpath %.cpp $(SRC_DIR)

define make-goal
$1/%.o: %.cpp
    $(CC) $(INCLUDES) -c $$< -o $$@
endef

.PHONY: all checkdirs clean

all: checkdirs build/test.exe

build/test.exe: $(OBJ)
    $(LD) $^ -o $@


checkdirs: $(BUILD_DIR)

$(BUILD_DIR):
    @mkdir -p $@

clean:
    @rm -rf $(BUILD_DIR)

$(foreach bdir,$(BUILD_DIR),$(eval $(call make-goal,$(bdir))))

This Makefile assumes you have your include files in the source directories. Also it checks if the build directories exist, and creates them if they do not exist.

The last line is the most important. It creates the implicit rules for each build using the function make-goal, and it is not necessary write them one by one

You can also add automatic dependency generation, using Tromey's way

How to get Git to clone into current directory

I used this to clone a repo to the current directory, which wasn't empty. Not necessarily clean living, but it was in a disposable docker container:

git clone https://github.com/myself/myRepo.git temp
cp -r temp/* .
rm -rf temp

Here, I used cp -r instead of mv, since that copies hidden files and directories. Then dispose of the temporary directory with rm -rf

SoapUI "failed to load url" error when loading WSDL

Close and reopen soapui. Probably is a bug of the application

Call an overridden method from super class in typescript

If you want a super class to call a function from a subclass, the cleanest way is to define an abstract pattern, in this manner you explicitly know the method exists somewhere and must be overridden by a subclass.

This is as an example, normally you do not call a sub method within the constructor as the sub instance is not initialized yet… (reason why you have an "undefined" in your question's example)

abstract class A {
    // The abstract method the subclass will have to call
    protected abstract doStuff():void;

    constructor(){
     alert("Super class A constructed, calling now 'doStuff'")
     this.doStuff();
    }
}

class B extends A{

    // Define here the abstract method
    protected doStuff()
    {
        alert("Submethod called");
    }
}

var b = new B();

Test it Here

And if like @Max you really want to avoid implementing the abstract method everywhere, just get rid of it. I don't recommend this approach because you might forget you are overriding the method.

abstract class A {
    constructor() {
        alert("Super class A constructed, calling now 'doStuff'")
        this.doStuff();
    }

    // The fallback method the subclass will call if not overridden
    protected doStuff(): void {
        alert("Default doStuff");
    };
}

class B extends A {
    // Override doStuff()
    protected doStuff() {
        alert("Submethod called");
    }
}

class C extends A {
    // No doStuff() overriding, fallback on A.doStuff()
}

var b = new B();
var c = new C();

Try it Here

How can I redirect a php page to another php page?

<?php  
header('Location: http://www.google.com'); //Send browser to http://www.google.com
?>  

Adding close button in div to close the box

it's easy with the id of the div container : (I didn't put the close button inside the <a> because that's does work properly on all browser.

<div id="myDiv">
<button class="close" onclick="document.getElementById('myDiv').style.display='none'" >Close</button>
<a class="fragment" href="http://google.com">
    <div>
    <img src ="http://placehold.it/116x116" alt="some description"/> 
    <h3>the title will go here</h3>
        <h4> www.myurlwill.com </h4>
    <p class="text">
        this is a short description yada yada peanuts etc this is a short description yada yada peanuts etc this is a short description yada yada peanuts etc this is a short description yada yada peanuts etcthis is a short description yada yada peanuts etc 
    </p>
</div>
</a>
</div>

How do I get the path of the current executed file in Python?

Simply add the following:

from sys import *
path_to_current_file = sys.argv[0]
print(path_to_current_file)

Or:

from sys import *
print(sys.argv[0])

How to get the HTML for a DOM element in javascript

var el = document.getElementById('foo');
el.parentNode.innerHTML;

Dynamic LINQ OrderBy on IEnumerable<T> / IQueryable<T>

Thanks to Maarten (Query a collection using PropertyInfo object in LINQ) I got this solution:

myList.OrderByDescending(x => myPropertyInfo.GetValue(x, null)).ToList();

In my case I was working on a "ColumnHeaderMouseClick" (WindowsForm) so just found the specific Column pressed and its correspondent PropertyInfo:

foreach (PropertyInfo column in (new Process()).GetType().GetProperties())
{
    if (column.Name == dgvProcessList.Columns[e.ColumnIndex].Name)
    {}
}

OR

PropertyInfo column = (new Process()).GetType().GetProperties().Where(x => x.Name == dgvProcessList.Columns[e.ColumnIndex].Name).First();

(be sure to have your column Names matching the object Properties)

Cheers

Python/Django: log to console under runserver, log to file under Apache

You can do this pretty easily with tagalog (https://github.com/dorkitude/tagalog)

For instance, while the standard python module writes to a file object opened in append mode, the App Engine module (https://github.com/dorkitude/tagalog/blob/master/tagalog_appengine.py) overrides this behavior and instead uses logging.INFO.

To get this behavior in an App Engine project, one could simply do:

import tagalog.tagalog_appengine as tagalog
tagalog.log('whatever message', ['whatever','tags'])

You could extend the module yourself and overwrite the log function without much difficulty.

Is the 'as' keyword required in Oracle to define an alias?

(Tested on Oracle 11g)

About AS:

  • When used on result column, AS is optional.
  • When used on table name, AS shouldn't be added, otherwise it's an error.

About double quote:

  • It's optional & valid for both result column & table name.

e.g

-- 'AS' is optional for result column
select (1+1) as result from dual;
select (1+1) result from dual;


-- 'AS' shouldn't be used for table name
select 'hi' from dual d;


-- Adding double quotes for alias name is optional, but valid for both result column & table name,
select (1+1) as "result" from dual;
select (1+1) "result" from dual;

select 'hi' from dual "d";

Visual Studio 2012 Web Publish doesn't copy files

For what it's worth, I eventually gave up on fighting with Web Deploy to get it to do what I wanted (copy deployable files and nothing else), so I scripted it in PowerShell and am really happy with the result. It's much faster than anything I tried through MSBuild/Web Publish, presumably because those methods were still doing things I didn't need.

Here's the gist (literally):

function copy-deployable-web-files($proj_path, $deploy_dir) {
  # copy files where Build Action = "Content" 
  $proj_dir = split-path -parent $proj_path
  [xml]$xml = get-content $proj_path
  $xml.Project.ItemGroup | % { $_.Content } | % { $_.Include } | ? { $_ } | % {
    $from = "$proj_dir\$_"
    $to = split-path -parent "$deploy_dir\$_"
    if (!(test-path $to)) { md $to }
    cp $from $to
  }

  # copy everything in bin
  cp "$proj_dir\bin" $deploy_dir -recurse
}

In my case I'm calling this in a CI environment (TeamCity), but it could easily be hooked into a post-build event as well.

How can I control the width of a label tag?

You can definitely try this way

.col-form-label{
  display: inline-block;
  width:200px;}

How to show PIL images on the screen?

I tested this and it works fine for me:

from PIL import Image
im = Image.open('image.jpg')
im.show()

How to really read text file from classpath in Java

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile

{
    /**
     * * feel free to make any modification I have have been here so I feel you
     * * * @param args * @throws InterruptedException
     */

    public static void main(String[] args) throws InterruptedException {
        // thread pool of 10
        File dir = new File(".");
        // read file from same directory as source //
        if (dir.isDirectory()) {
            File[] files = dir.listFiles();
            for (File file : files) {
                // if you wanna read file name with txt files
                if (file.getName().contains("txt")) {
                    System.out.println(file.getName());
                }

                // if you want to open text file and read each line then
                if (file.getName().contains("txt")) {
                    try {
                        // FileReader reads text files in the default encoding.
                        FileReader fileReader = new FileReader(
                                file.getAbsolutePath());
                        // Always wrap FileReader in BufferedReader.
                        BufferedReader bufferedReader = new BufferedReader(
                                fileReader);
                        String line;
                        // get file details and get info you need.
                        while ((line = bufferedReader.readLine()) != null) {
                            System.out.println(line);
                            // here you can say...
                            // System.out.println(line.substring(0, 10)); this
                            // prints from 0 to 10 indext
                        }
                    } catch (FileNotFoundException ex) {
                        System.out.println("Unable to open file '"
                                + file.getName() + "'");
                    } catch (IOException ex) {
                        System.out.println("Error reading file '"
                                + file.getName() + "'");
                        // Or we could just do this:
                        ex.printStackTrace();
                    }
                }
            }
        }

    }

}

Regex for parsing directory and filename

Most languages have path parsing functions that will give you this already. If you have the ability, I'd recommend using what comes to you for free out-of-the-box.

Assuming / is the path delimiter...

^(.*/)([^/]*)$

The first group will be whatever the directory/path info is, the second will be the filename. For example:

  • /foo/bar/baz.log: "/foo/bar/" is the path, "baz.log" is the file
  • foo/bar.log: "foo/" is the path, "bar.log" is the file
  • /foo/bar: "/foo/" is the path, "bar" is the file
  • /foo/bar/: "/foo/bar/" is the path and there is no file.

How to fill color in a cell in VBA?

Non VBA Solution:

Use Conditional Formatting rule with formula: =ISNA(A1) (to highlight cells with all errors - not only #N/A, use =ISERROR(A1))

enter image description here

VBA Solution:

Your code loops through 50 mln cells. To reduce number of cells, I use .SpecialCells(xlCellTypeFormulas, 16) and .SpecialCells(xlCellTypeConstants, 16)to return only cells with errors (note, I'm using If cell.Text = "#N/A" Then)

Sub ColorCells()
    Dim Data As Range, Data2 As Range, cell As Range
    Dim currentsheet As Worksheet

    Set currentsheet = ActiveWorkbook.Sheets("Comparison")

    With currentsheet.Range("A2:AW" & Rows.Count)
        .Interior.Color = xlNone
        On Error Resume Next
        'select only cells with errors
        Set Data = .SpecialCells(xlCellTypeFormulas, 16)
        Set Data2 = .SpecialCells(xlCellTypeConstants, 16)
        On Error GoTo 0
    End With

    If Not Data2 Is Nothing Then
        If Not Data Is Nothing Then
            Set Data = Union(Data, Data2)
        Else
            Set Data = Data2
        End If
    End If

    If Not Data Is Nothing Then
        For Each cell In Data
            If cell.Text = "#N/A" Then
               cell.Interior.ColorIndex = 4
            End If
        Next
    End If
End Sub

Note, to highlight cells witn any error (not only "#N/A"), replace following code

If Not Data Is Nothing Then
   For Each cell In Data
       If cell.Text = "#N/A" Then
          cell.Interior.ColorIndex = 3
       End If
   Next
End If

with

If Not Data Is Nothing Then Data.Interior.ColorIndex = 3

UPD: (how to add CF rule through VBA)

Sub test()
    With ActiveWorkbook.Sheets("Comparison").Range("A2:AW" & Rows.Count).FormatConditions
        .Delete
        .Add Type:=xlExpression, Formula1:="=ISNA(A1)"
        .Item(1).Interior.ColorIndex = 3
    End With
End Sub

Oracle: Call stored procedure inside the package

To those that are incline to use GUI:

Click Right mouse button on procecdure name then select Test

enter image description here

Then in new window you will see script generated just add the parameters and click on Start Debugger or F9

enter image description here

Hope this saves you some time.

SQL query to find record with ID not in another table

There are basically 3 approaches to that: not exists, not in and left join / is null.

LEFT JOIN with IS NULL

SELECT  l.*
FROM    t_left l
LEFT JOIN
        t_right r
ON      r.value = l.value
WHERE   r.value IS NULL

NOT IN

SELECT  l.*
FROM    t_left l
WHERE   l.value NOT IN
        (
        SELECT  value
        FROM    t_right r
        )

NOT EXISTS

SELECT  l.*
FROM    t_left l
WHERE   NOT EXISTS
        (
        SELECT  NULL
        FROM    t_right r
        WHERE   r.value = l.value
        )

Which one is better? The answer to this question might be better to be broken down to major specific RDBMS vendors. Generally speaking, one should avoid using select ... where ... in (select...) when the magnitude of number of records in the sub-query is unknown. Some vendors might limit the size. Oracle, for example, has a limit of 1,000. Best thing to do is to try all three and show the execution plan.

Specifically form PostgreSQL, execution plan of NOT EXISTS and LEFT JOIN / IS NULL are the same. I personally prefer the NOT EXISTS option because it shows better the intent. After all the semantic is that you want to find records in A that its pk do not exist in B.

Old but still gold, specific to PostgreSQL though: https://explainextended.com/2009/09/16/not-in-vs-not-exists-vs-left-join-is-null-postgresql/

How to get a .csv file into R?

You need read.csv("C:/somedirectory/some/file.csv") and in general it doesn't hurt to actually look at the help page including its example section at the bottom.

width:auto for <input> fields

It may not be exactly what you want, but my workaround is to apply the autowidth styling to a wrapper div - then set your input to 100%.

how to use List<WebElement> webdriver

List<WebElement> myElements = driver.findElements(By.xpath("some/path//a"));
        System.out.println("Size of List: "+myElements.size());
        for(WebElement e : myElements) 
        {        
            System.out.print("Text within the Anchor tab"+e.getText()+"\t");
            System.out.println("Anchor: "+e.getAttribute("href"));
        }

//NOTE: "//a" will give you all the anchors there on after the point your XPATH has reached.

Inline for loop

q  = [1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5]
vm = [-1, -1, -1, -1,1,2,3,1]

p = []
for v in vm:
    if v in q:
        p.append(q.index(v))
    else:
        p.append(99999)

print p
p = [q.index(v) if v in q else 99999 for v in vm]
print p

Output:

[99999, 99999, 99999, 99999, 0, 1, 2, 0]
[99999, 99999, 99999, 99999, 0, 1, 2, 0]

Instead of using append() in the list comprehension you can reference the p as direct output, and use q.index(v) and 99999 in the LC.

Not sure if this is intentional but note that q.index(v) will find just the first occurrence of v, even tho you have several in q. If you want to get the index of all v in q, consider using a enumerator and a list of already visited indexes

Something in those lines(pseudo-code):

visited = []
for i, v in enumerator(vm):
   if i not in visited:
       p.append(q.index(v))
   else:
       p.append(q.index(v,max(visited))) # this line should only check for v in q after the index of max(visited)
   visited.append(i)

Best practices for API versioning?

This is a good and a tricky question. The topic of URI design is at the same time the most prominent part of a REST API and, therefore, a potentially long-term commitment towards the users of that API.

Since evolution of an application and, to a lesser extent, its API is a fact of life and that it's even similar to the evolution of a seemingly complex product like a programming language, the URI design should have less natural constraints and it should be preserved over time. The longer the application's and API's lifespan, the greater the commitment to the users of the application and API.

On the other hand, another fact of life is that it is hard to foresee all the resources and their aspects that would be consumed through the API. Luckily, it is not necessary to design the entire API which will be used until Apocalypse. It is sufficient to correctly define all the resource end-points and the addressing scheme of every resource and resource instance.

Over time you may need to add new resources and new attributes to each particular resource, but the method that API users follow to access a particular resources should not change once a resource addressing scheme becomes public and therefore final.

This method applies to HTTP verb semantics (e.g. PUT should always update/replace) and HTTP status codes that are supported in earlier API versions (they should continue to work so that API clients that have worked without human intervention should be able to continue to work like that).

Furthermore, since embedding of API version into the URI would disrupt the concept of hypermedia as the engine of application state (stated in Roy T. Fieldings PhD dissertation) by having a resource address/URI that would change over time, I would conclude that API versions should not be kept in resource URIs for a long time meaning that resource URIs that API users can depend on should be permalinks.

Sure, it is possible to embed API version in base URI but only for reasonable and restricted uses like debugging a API client that works with the the new API version. Such versioned APIs should be time-limited and available to limited groups of API users (like during closed betas) only. Otherwise, you commit yourself where you shouldn't.

A couple of thoughts regarding maintenance of API versions that have expiration date on them. All programming platforms/languages commonly used to implement web services (Java, .NET, PHP, Perl, Rails, etc.) allow easy binding of web service end-point(s) to a base URI. This way it's easy to gather and keep a collection of files/classes/methods separate across different API versions.

From the API users POV, it's also easier to work with and bind to a particular API version when it's this obvious but only for limited time, i.e. during development.

From the API maintainer's POV, it's easier to maintain different API versions in parallel by using source control systems that predominantly work on files as the smallest unit of (source code) versioning.

However, with API versions clearly visible in URI there's a caveat: one might also object this approach since API history becomes visible/aparent in the URI design and therefore is prone to changes over time which goes against the guidelines of REST. I agree!

The way to go around this reasonable objection, is to implement the latest API version under versionless API base URI. In this case, API client developers can choose to either:

  • develop against the latest one (committing themselves to maintain the application protecting it from eventual API changes that might break their badly designed API client).

  • bind to a specific version of the API (which becomes apparent) but only for a limited time

For example, if API v3.0 is the latest API version, the following two should be aliases (i.e. behave identically to all API requests):

http://shonzilla/api/customers/1234
http://shonzilla/api/v3.0/customers/1234
http://shonzilla/api/v3/customers/1234

In addition, API clients that still try to point to the old API should be informed to use the latest previous API version, if the API version they're using is obsolete or not supported anymore. So accessing any of the obsolete URIs like these:

http://shonzilla/api/v2.2/customers/1234
http://shonzilla/api/v2.0/customers/1234
http://shonzilla/api/v2/customers/1234
http://shonzilla/api/v1.1/customers/1234
http://shonzilla/api/v1/customers/1234

should return any of the 30x HTTP status codes that indicate redirection that are used in conjunction with Location HTTP header that redirects to the appropriate version of resource URI which remain to be this one:

http://shonzilla/api/customers/1234

There are at least two redirection HTTP status codes that are appropriate for API versioning scenarios:

  • 301 Moved permanently indicating that the resource with a requested URI is moved permanently to another URI (which should be a resource instance permalink that does not contain API version info). This status code can be used to indicate an obsolete/unsupported API version, informing API client that a versioned resource URI been replaced by a resource permalink.

  • 302 Found indicating that the requested resource temporarily is located at another location, while requested URI may still supported. This status code may be useful when the version-less URIs are temporarily unavailable and that a request should be repeated using the redirection address (e.g. pointing to the URI with APi version embedded) and we want to tell clients to keep using it (i.e. the permalinks).

  • other scenarios can be found in Redirection 3xx chapter of HTTP 1.1 specification

How to have a default option in Angular.js select box

Try this:

HTML

<select 
    ng-model="selectedOption" 
    ng-options="option.name for option in options">
</select>

Javascript

function Ctrl($scope) {
    $scope.options = [
        {
          name: 'Something Cool',
          value: 'something-cool-value'
        }, 
        {
          name: 'Something Else',
          value: 'something-else-value'
        }
    ];

    $scope.selectedOption = $scope.options[0];
}

Plunker here.

If you really want to set the value that will be bound to the model, then change the ng-options attribute to

ng-options="option.value as option.name for option in options"

and the Javascript to

...
$scope.selectedOption = $scope.options[0].value;

Another Plunker here considering the above.

MySQL show current connection info

There are MYSQL functions you can use. Like this one that resolves the user:

SELECT USER();

This will return something like root@localhost so you get the host and the user.

To get the current database run this statement:

SELECT DATABASE();

Other useful functions can be found here: http://dev.mysql.com/doc/refman/5.0/en/information-functions.html

Closing Twitter Bootstrap Modal From Angular Controller

You can do it with a simple jquery code.

$('#Mymodal').modal('hide');

replacing NA's with 0's in R dataframe

Here are two quickie approaches I know of:

In base

AQ1 <- airquality
AQ1[is.na(AQ1 <- airquality)] <- 0
AQ1

Not in base

library(qdap)
NAer(airquality)

PS P.S. Does my command above create a new dataframe called AQ1?

Look at AQ1 and see

Remove substring from the string

If you are using rails or at less activesupport you got String#remove and String#remove! method

def remove!(*patterns)
  patterns.each do |pattern|
    gsub! pattern, ""
  end

  self
end

source: http://api.rubyonrails.org/classes/String.html#method-i-remove

How eliminate the tab space in the column in SQL Server 2008

See it might be worked -------

UPDATE table_name SET column_name=replace(column_name, ' ', '') //Remove white space

UPDATE table_name SET column_name=replace(column_name, '\n', '') //Remove newline

UPDATE table_name SET column_name=replace(column_name, '\t', '') //Remove all tab

Thanks Subroto

UIViewController viewDidLoad vs. viewWillAppear: What is the proper division of labor?

It's important to note that using viewDidLoad for positioning is a bit risky and should be avoided since the bounds are not set. this may cause unexpected results (I had a variety of issues...)

This post describes quite well the different methods and what happens in each of them.

currently for one-time init and positioning I'm thinking of using viewDidAppear with a flag, if anyone has any other recommendation please let me know.

Decompile an APK, modify it and then recompile it

This is a way:

  1. Using apktool to decode:

     $ apktool d -f {apkfile} -o {output folder}
    
  2. Next, using JADX (at github.com/skylot/jadx)

     $ jadx -d {output folder} {apkfile}
    

2 tools extract and decompiler to same output folder.

Easy way: Using Online APK Decompiler

Zipping a file in bash fails

Run dos2unix or similar utility on it to remove the carriage returns (^M).

This message indicates that your file has dos-style lineendings:

-bash: /backup/backup.sh: /bin/bash^M: bad interpreter: No such file or directory 

Utilities like dos2unix will fix it:

 dos2unix <backup.bash >improved-backup.sh 

Or, if no such utility is installed, you can accomplish the same thing with translate:

tr -d "\015\032" <backup.bash >improved-backup.sh 

As for how those characters got there in the first place, @MadPhysicist had some good comments.

How to select multiple files with <input type="file">?

<form action="" method="post" enctype="multipart/form-data">
<input type="file" multiple name="img[]"/>
<input type="submit">
</form>
<?php
print_r($_FILES['img']['name']);
?>

on change event for file input element

Use the files filelist of the element instead of val()

$("input[type=file]").on('change',function(){
    alert(this.files[0].name);
});

How can I wrap text in a label using WPF?

The Label control doesn't directly support text wrapping in WPF. You should use a TextBlock instead. (Of course, you can place the TextBlock inside of a Label control, if you wish.)

Sample code:

<TextBlock TextWrapping="WrapWithOverflow">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec adipiscing
    nulla quis libero egestas lobortis. Duis blandit imperdiet ornare. Nulla
    ac arcu ut purus placerat congue. Integer pretium fermentum gravida.
</TextBlock>

How do I center content in a div using CSS?

By using transform: works like a charm!

<div class="parent">
    <span>center content using transform</span>
    </div>

    //CSS
    .parent {
        position: relative;
        height: 200px;
        border: 1px solid;
    }
    .parent span {
        position: absolute;
        top: 50%;
        left: 50%;
        -webkit-transform: translate(-50%, -50%);
        transform: translate(-50%, -50%);
    }

How can I create numbered map markers in Google Maps V3?

Unfortunately it's not very easy. You could create your own custom marker based on the OverlayView class (an example) and put your own HTML in it, including a counter. This will leave you with a very basic marker, that you can't drag around or add shadows easily, but it is very customisable.

Alternatively, you could add a label to the default marker. This will be less customisable but should work. It also keeps all the useful things the standard marker does.

You can read more about the overlays in Google's article Fun with MVC Objects.

Edit: if you don't want to create a JavaScript class, you could use Google's Chart API. For example:

Numbered marker:

http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=7|FF0000|000000

Text marker:

http://chart.apis.google.com/chart?chst=d_map_spin&chld=1|0|FF0000|12|_|foo

This is the quick and easy route, but it's less customisable, and requires a new image to be downloaded by the client for each marker.

How to remove border from specific PrimeFaces p:panelGrid?

I placed the panelgrid inside datatable, and hence my working solution is

.ui-datatable-scrollable-body .myStyleClass tbody td{border:none;}

for

<h:panelGrid  styleClass="myStyleClass" >...</h:panelGrid>

C++ Calling a function from another class

What you should do, is put CallFunction into *.cpp file, where you include B.h.

After edit, files will look like:

B.h:

#pragma once //or other specific to compiler...
using namespace std;

class A 
{
public:
    void CallFunction ();
};

class B: public A
{
public:
    virtual void bFunction()
        {
            //stuff done here
        }
};

B.cpp

#include "B.h"
void A::CallFunction(){
//use B object here...
}

Referencing to your explanation, that you have tried to change B b; into pointer- it would be okay, if you wouldn't use it in that same place. You can use pointer of undefined class(but declared), because ALL pointers have fixed byte size(4), so compiler doesn't have problems with that. But it knows nothing about the object they are pointing to(simply: knows the size/boundary, not the content).

So as long as you are using the knowledge, that all pointers are same size, you can use them anywhere. But if you want to use the object, they are pointing to, the class of this object must be already defined and known by compiler.

And last clarification: objects may differ in size, unlike pointers. Pointer is a number/index, which indicates the place in RAM, where something is stored(for example index: 0xf6a7b1).

What does AngularJS do better than jQuery?

Data-Binding

You go around making your webpage, and keep on putting {{data bindings}} whenever you feel you would have dynamic data. Angular will then provide you a $scope handler, which you can populate (statically or through calls to the web server).

This is a good understanding of data-binding. I think you've got that down.

DOM Manipulation

For simple DOM manipulation, which doesnot involve data manipulation (eg: color changes on mousehover, hiding/showing elements on click), jQuery or old-school js is sufficient and cleaner. This assumes that the model in angular's mvc is anything that reflects data on the page, and hence, css properties like color, display/hide, etc changes dont affect the model.

I can see your point here about "simple" DOM manipulation being cleaner, but only rarely and it would have to be really "simple". I think DOM manipulation is one the areas, just like data-binding, where Angular really shines. Understanding this will also help you see how Angular considers its views.

I'll start by comparing the Angular way with a vanilla js approach to DOM manipulation. Traditionally, we think of HTML as not "doing" anything and write it as such. So, inline js, like "onclick", etc are bad practice because they put the "doing" in the context of HTML, which doesn't "do". Angular flips that concept on its head. As you're writing your view, you think of HTML as being able to "do" lots of things. This capability is abstracted away in angular directives, but if they already exist or you have written them, you don't have to consider "how" it is done, you just use the power made available to you in this "augmented" HTML that angular allows you to use. This also means that ALL of your view logic is truly contained in the view, not in your javascript files. Again, the reasoning is that the directives written in your javascript files could be considered to be increasing the capability of HTML, so you let the DOM worry about manipulating itself (so to speak). I'll demonstrate with a simple example.

This is the markup we want to use. I gave it an intuitive name.

<div rotate-on-click="45"></div>

First, I'd just like to comment that if we've given our HTML this functionality via a custom Angular Directive, we're already done. That's a breath of fresh air. More on that in a moment.

Implementation with jQuery

live demo here (click).

function rotate(deg, elem) {
  $(elem).css({
    webkitTransform: 'rotate('+deg+'deg)', 
    mozTransform: 'rotate('+deg+'deg)', 
    msTransform: 'rotate('+deg+'deg)', 
    oTransform: 'rotate('+deg+'deg)', 
    transform: 'rotate('+deg+'deg)'    
  });
}

function addRotateOnClick($elems) {
  $elems.each(function(i, elem) {
    var deg = 0;
    $(elem).click(function() {
      deg+= parseInt($(this).attr('rotate-on-click'), 10);
      rotate(deg, this);
    });
  });
}

addRotateOnClick($('[rotate-on-click]'));

Implementation with Angular

live demo here (click).

app.directive('rotateOnClick', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      var deg = 0;
      element.bind('click', function() {
        deg+= parseInt(attrs.rotateOnClick, 10);
        element.css({
          webkitTransform: 'rotate('+deg+'deg)', 
          mozTransform: 'rotate('+deg+'deg)', 
          msTransform: 'rotate('+deg+'deg)', 
          oTransform: 'rotate('+deg+'deg)', 
          transform: 'rotate('+deg+'deg)'    
        });
      });
    }
  };
});

Pretty light, VERY clean and that's just a simple manipulation! In my opinion, the angular approach wins in all regards, especially how the functionality is abstracted away and the dom manipulation is declared in the DOM. The functionality is hooked onto the element via an html attribute, so there is no need to query the DOM via a selector, and we've got two nice closures - one closure for the directive factory where variables are shared across all usages of the directive, and one closure for each usage of the directive in the link function (or compile function).

Two-way data binding and directives for DOM manipulation are only the start of what makes Angular awesome. Angular promotes all code being modular, reusable, and easily testable and also includes a single-page app routing system. It is important to note that jQuery is a library of commonly needed convenience/cross-browser methods, but Angular is a full featured framework for creating single page apps. The angular script actually includes its own "lite" version of jQuery so that some of the most essential methods are available. Therefore, you could argue that using Angular IS using jQuery (lightly), but Angular provides much more "magic" to help you in the process of creating apps.

This is a great post for more related information: How do I “think in AngularJS” if I have a jQuery background?

General differences.

The above points are aimed at the OP's specific concerns. I'll also give an overview of the other important differences. I suggest doing additional reading about each topic as well.

Angular and jQuery can't reasonably be compared.

Angular is a framework, jQuery is a library. Frameworks have their place and libraries have their place. However, there is no question that a good framework has more power in writing an application than a library. That's exactly the point of a framework. You're welcome to write your code in plain JS, or you can add in a library of common functions, or you can add a framework to drastically reduce the code you need to accomplish most things. Therefore, a more appropriate question is:

Why use a framework?

Good frameworks can help architect your code so that it is modular (therefore reusable), DRY, readable, performant and secure. jQuery is not a framework, so it doesn't help in these regards. We've all seen the typical walls of jQuery spaghetti code. This isn't jQuery's fault - it's the fault of developers that don't know how to architect code. However, if the devs did know how to architect code, they would end up writing some kind of minimal "framework" to provide the foundation (achitecture, etc) I discussed a moment ago, or they would add something in. For example, you might add RequireJS to act as part of your framework for writing good code.

Here are some things that modern frameworks are providing:

  • Templating
  • Data-binding
  • routing (single page app)
  • clean, modular, reusable architecture
  • security
  • additional functions/features for convenience

Before I further discuss Angular, I'd like to point out that Angular isn't the only one of its kind. Durandal, for example, is a framework built on top of jQuery, Knockout, and RequireJS. Again, jQuery cannot, by itself, provide what Knockout, RequireJS, and the whole framework built on top them can. It's just not comparable.

If you need to destroy a planet and you have a Death Star, use the Death star.

Angular (revisited).

Building on my previous points about what frameworks provide, I'd like to commend the way that Angular provides them and try to clarify why this is matter of factually superior to jQuery alone.

DOM reference.

In my above example, it is just absolutely unavoidable that jQuery has to hook onto the DOM in order to provide functionality. That means that the view (html) is concerned about functionality (because it is labeled with some kind of identifier - like "image slider") and JavaScript is concerned about providing that functionality. Angular eliminates that concept via abstraction. Properly written code with Angular means that the view is able to declare its own behavior. If I want to display a clock:

<clock></clock>

Done.

Yes, we need to go to JavaScript to make that mean something, but we're doing this in the opposite way of the jQuery approach. Our Angular directive (which is in it's own little world) has "augumented" the html and the html hooks the functionality into itself.

MVW Architecure / Modules / Dependency Injection

Angular gives you a straightforward way to structure your code. View things belong in the view (html), augmented view functionality belongs in directives, other logic (like ajax calls) and functions belong in services, and the connection of services and logic to the view belongs in controllers. There are some other angular components as well that help deal with configuration and modification of services, etc. Any functionality you create is automatically available anywhere you need it via the Injector subsystem which takes care of Dependency Injection throughout the application. When writing an application (module), I break it up into other reusable modules, each with their own reusable components, and then include them in the bigger project. Once you solve a problem with Angular, you've automatically solved it in a way that is useful and structured for reuse in the future and easily included in the next project. A HUGE bonus to all of this is that your code will be much easier to test.

It isn't easy to make things "work" in Angular.

THANK GOODNESS. The aforementioned jQuery spaghetti code resulted from a dev that made something "work" and then moved on. You can write bad Angular code, but it's much more difficult to do so, because Angular will fight you about it. This means that you have to take advantage (at least somewhat) to the clean architecture it provides. In other words, it's harder to write bad code with Angular, but more convenient to write clean code.

Angular is far from perfect. The web development world is always growing and changing and there are new and better ways being put forth to solve problems. Facebook's React and Flux, for example, have some great advantages over Angular, but come with their own drawbacks. Nothing's perfect, but Angular has been and is still awesome for now. Just as jQuery once helped the web world move forward, so has Angular, and so will many to come.

IIS sc-win32-status codes

Here's the list of all Win32 error codes. You can use this page to lookup the error code mentioned in IIS logs:
http://msdn.microsoft.com/en-us/library/ms681381.aspx

You can also use command line utility net to find information about a Win32 error code. The syntax would be:
net helpmsg Win32_Status_Code

Inserting data into a MySQL table using VB.NET

Dim connString as String ="server=localhost;userid=root;password=123456;database=uni_park_db"
Dim conn as MySqlConnection(connString)
Dim cmd as MysqlCommand
Dim dt as New DataTable
Dim ireturn as Boolean

Private Sub Insert_Car()

Dim sql as String = "insert into members_car (car_id, member_id, model, color, chassis_id, plate_number, code) values (@car_id,@member_id,@model,@color,@chassis_id,@plate_number,@code)"

Dim cmd = new MySqlCommand(sql, conn)

    cmd.Paramaters.AddwithValue("@car_id", txtCar.Text)
    cmd.Paramaters.AddwithValue("@member_id", txtMember.Text)
    cmd.Paramaters.AddwithValue("@model", txtModel.Text)
    cmd.Paramaters.AddwithValue("@color", txtColor.Text)
    cmd.Paramaters.AddwithValue("@chassis_id", txtChassis.Text)
    cmd.Paramaters.AddwithValue("@plate_number", txtPlateNo.Text)
    cmd.Paramaters.AddwithValue("@code", txtCode.Text)

    Try
        conn.Open()
        If cmd.ExecuteNonQuery() > 0 Then
            ireturn = True
        End If  
        conn.Close()


    Catch ex as Exception
        ireturn = False
        conn.Close()
    End Try

Return ireturn

End Sub

Div Background Image Z-Index Issue

Set your header and footer position to "absolute" and that should do the trick. Hope it helps and good luck with your project!

Manually Set Value for FormBuilder Control

Updated: 19/03/2017

this.form.controls['dept'].setValue(selected.id);

OLD:

For now we are forced to do a type cast:

(<Control>this.form.controls['dept']).updateValue(selected.id)

Not very elegant I agree. Hope this gets improved in future versions.

Is it possible to style a mouseover on an image map using CSS?

CSS Only:

Thinking about it on my way to the supermarket, you could of course also skip the entire image map idea, and make use of :hover on the elements on top of the image (changed the divs to a-blocks). Which makes things hell of a lot simpler, no jQuery needed...

Short explanation:

  • Image is in the bottom
  • 2 x a with display:block and absolute positioning + opacity:0
  • Set opacity to 0.2 on hover

Example:

_x000D_
_x000D_
.area {_x000D_
    background:#fff;_x000D_
    display:block;_x000D_
    height:475px;_x000D_
    opacity:0;_x000D_
    position:absolute;_x000D_
    width:320px;_x000D_
}_x000D_
#area2 {_x000D_
    left:320px;_x000D_
}_x000D_
#area1:hover, #area2:hover {_x000D_
    opacity:0.2;_x000D_
}
_x000D_
<a id="area1" class="area" href="#"></a>_x000D_
<a id="area2" class="area" href="#"></a>_x000D_
<img src="http://upload.wikimedia.org/wikipedia/commons/thumb/2/20/Saimiri_sciureus-1_Luc_Viatour.jpg/640px-Saimiri_sciureus-1_Luc_Viatour.jpg" width="640" height="475" />
_x000D_
_x000D_
_x000D_

Original Answer using jQuery

I just created something similar with jQuery, I don't think it can be done with CSS only.

Short explanation:

  • Image is in the bottom
  • Divs with rollover (image or color) with absolute positioning + display:none
  • Transparent gif with the actual #map is on top (absolute position) (to prevent call to mouseout when the rollovers appear)
  • jQuery is used to show/hide the divs

_x000D_
_x000D_
    $(document).ready(function() {_x000D_
        if($('#location-map')) {_x000D_
            $('#location-map area').each(function() {_x000D_
                var id = $(this).attr('id');_x000D_
                $(this).mouseover(function() {_x000D_
                    $('#overlay'+id).show();_x000D_
                    _x000D_
                });_x000D_
                _x000D_
                $(this).mouseout(function() {_x000D_
                    var id = $(this).attr('id');_x000D_
                    $('#overlay'+id).hide();_x000D_
                });_x000D_
            _x000D_
            });_x000D_
        }_x000D_
    });
_x000D_
body,html {_x000D_
    margin:0;_x000D_
}_x000D_
#emptygif {_x000D_
    position:absolute;_x000D_
    z-index:200;_x000D_
}_x000D_
#overlayr1 {_x000D_
    position:absolute;_x000D_
    background:#fff;_x000D_
    opacity:0.2;_x000D_
    width:300px;_x000D_
    height:160px;_x000D_
    z-index:100;_x000D_
    display:none;_x000D_
}_x000D_
#overlayr2 {_x000D_
    position:absolute;_x000D_
    background:#fff;_x000D_
    opacity:0.2;_x000D_
    width:300px;_x000D_
    height:160px;_x000D_
    top:160px;_x000D_
    z-index:100;_x000D_
    display:none;_x000D_
}
_x000D_
<img src="http://www.tfo.be/jobs/axa/premiumplus/img/empty.gif" width="300" height="350" border="0" usemap="#location-map" id="emptygif" />_x000D_
<div id="overlayr1">&nbsp;</div>_x000D_
<div id="overlayr2">&nbsp;</div>_x000D_
<img src="http://2.bp.blogspot.com/_nP6ESfPiKIw/SlOGugKqaoI/AAAAAAAAACs/6jnPl85TYDg/s1600-R/monkey300.jpg" width="300" height="350" border="0" />_x000D_
<map name="location-map" id="location-map">_x000D_
  <area shape="rect" coords="0,0,300,160" href="#" id="r1" />_x000D_
  <area shape="rect" coords="0,161,300,350" href="#" id="r2"/>_x000D_
</map>
_x000D_
_x000D_
_x000D_

Hope it helps..

How can I initialize an ArrayList with all zeroes in Java?

// apparently this is broken. Whoops for me!
java.util.Collections.fill(list,new Integer(0));

// this is better
Integer[] data = new Integer[60];
Arrays.fill(data,new Integer(0));
List<Integer> list = Arrays.asList(data);

How to create a MySQL hierarchical recursive query?

Try these:

Table definition:

DROP TABLE IF EXISTS category;
CREATE TABLE category (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(20),
    parent_id INT,
    CONSTRAINT fk_category_parent FOREIGN KEY (parent_id)
    REFERENCES category (id)
) engine=innodb;

Experimental rows:

INSERT INTO category VALUES
(19, 'category1', NULL),
(20, 'category2', 19),
(21, 'category3', 20),
(22, 'category4', 21),
(23, 'categoryA', 19),
(24, 'categoryB', 23),
(25, 'categoryC', 23),
(26, 'categoryD', 24);

Recursive Stored procedure:

DROP PROCEDURE IF EXISTS getpath;
DELIMITER $$
CREATE PROCEDURE getpath(IN cat_id INT, OUT path TEXT)
BEGIN
    DECLARE catname VARCHAR(20);
    DECLARE temppath TEXT;
    DECLARE tempparent INT;
    SET max_sp_recursion_depth = 255;
    SELECT name, parent_id FROM category WHERE id=cat_id INTO catname, tempparent;
    IF tempparent IS NULL
    THEN
        SET path = catname;
    ELSE
        CALL getpath(tempparent, temppath);
        SET path = CONCAT(temppath, '/', catname);
    END IF;
END$$
DELIMITER ;

Wrapper function for the stored procedure:

DROP FUNCTION IF EXISTS getpath;
DELIMITER $$
CREATE FUNCTION getpath(cat_id INT) RETURNS TEXT DETERMINISTIC
BEGIN
    DECLARE res TEXT;
    CALL getpath(cat_id, res);
    RETURN res;
END$$
DELIMITER ;

Select example:

SELECT id, name, getpath(id) AS path FROM category;

Output:

+----+-----------+-----------------------------------------+
| id | name      | path                                    |
+----+-----------+-----------------------------------------+
| 19 | category1 | category1                               |
| 20 | category2 | category1/category2                     |
| 21 | category3 | category1/category2/category3           |
| 22 | category4 | category1/category2/category3/category4 |
| 23 | categoryA | category1/categoryA                     |
| 24 | categoryB | category1/categoryA/categoryB           |
| 25 | categoryC | category1/categoryA/categoryC           |
| 26 | categoryD | category1/categoryA/categoryB/categoryD |
+----+-----------+-----------------------------------------+

Filtering rows with certain path:

SELECT id, name, getpath(id) AS path FROM category HAVING path LIKE 'category1/category2%';

Output:

+----+-----------+-----------------------------------------+
| id | name      | path                                    |
+----+-----------+-----------------------------------------+
| 20 | category2 | category1/category2                     |
| 21 | category3 | category1/category2/category3           |
| 22 | category4 | category1/category2/category3/category4 |
+----+-----------+-----------------------------------------+

Multiple lines of input in <input type="text" />

If you need textarea with auto height, Use follows with pure javascript,

_x000D_
_x000D_
function auto_height(elem) {  /* javascript */_x000D_
    elem.style.height = "1px";_x000D_
    elem.style.height = (elem.scrollHeight)+"px";_x000D_
}
_x000D_
.auto_height { /* CSS */_x000D_
  width: 100%;_x000D_
}
_x000D_
<textarea rows="1" class="auto_height" oninput="auto_height(this)"></textarea>
_x000D_
_x000D_
_x000D_

Concatenating Column Values into a Comma-Separated List

Another solution within a query :

select 
    Id, 
    STUFF(
        (select (', "' + od.ProductName + '"')
        from OrderDetails od (nolock)
        where od.Order_Id = o.Id
        order by od.ProductName
        FOR XML PATH('')), 1, 2, ''
    ) ProductNames
from Orders o (nolock)
where o.Customer_Id = 525188
order by o.Id desc

(EDIT: thanks @user007 for the STUFF declaration)

HTML / CSS table with GRIDLINES

<table border="1"></table>

should do the trick.

Python Selenium accessing HTML source

With Selenium2Library you can use get_source()

import Selenium2Library
s = Selenium2Library.Selenium2Library()
s.open_browser("localhost:7080", "firefox")
source = s.get_source()

Eclipse won't compile/run java file

  • Make a project to put the files in.
    • File -> New -> Java Project
    • Make note of where that project was created (where your "workspace" is)
  • Move your java files into the src folder which is immediately inside the project's folder.
    • Find the project INSIDE Eclipse's Package Explorer (Window -> Show View -> Package Explorer)
    • Double-click on the project, then double-click on the 'src' folder, and finally double-click on one of the java files inside the 'src' folder (they should look familiar!)
  • Now you can run the files as expected.

Note the hollow 'J' in the image. That indicates that the file is not part of a project.

Hollow J means it is not part of a project

Shell script "for" loop syntax

Try the arithmetic-expression version of for:

max=10
for (( i=2; i <= $max; ++i ))
do
    echo "$i"
done

This is available in most versions of bash, and should be Bourne shell (sh) compatible also.

What is android:weightSum in android, and how does it work?

Per documentation, android:weightSum defines the maximum weight sum, and is calculated as the sum of the layout_weight of all the children if not specified explicitly.

Let's consider an example with a LinearLayout with horizontal orientation and 3 ImageViews inside it. Now we want these ImageViews always to take equal space. To acheive this, you can set the layout_weight of each ImageView to 1 and the weightSum will be calculated to be equal to 3 as shown in the comment.

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    <!-- android:weightSum="3" -->
    android:orientation="horizontal"
    android:layout_gravity="center">

   <ImageView
       android:layout_height="wrap_content"       
       android:layout_weight="1"
       android:layout_width="0dp"/>
  .....

weightSum is useful for having the layout rendered correctly for any device, which will not happen if you set width and height directly.

Blur the edges of an image or background image with CSS

I'm not entirely sure what visual end result you're after, but here's an easy way to blur an image's edge: place a div with the image inside another div with the blurred image.

Working example here: http://jsfiddle.net/ZY5hn/1/

Screenshot

HTML:

<div class="placeholder">
     <!-- blurred background image for blurred edge -->
     <div class="bg-image-blur"></div>
     <!-- same image, no blur -->
     <div class="bg-image"></div>
     <!-- content -->
     <div class="content">Blurred Image Edges</div>
</div>

CSS:

.placeholder {
    margin-right: auto;
    margin-left:auto;
    margin-top: 20px;
    width: 200px;
    height: 200px;
    position: relative;
    /* this is the only relevant part for the example */
}
/* both DIVs have the same image */
 .bg-image-blur, .bg-image {
    background-image: url('http://lorempixel.com/200/200/city/9');
    position:absolute;
    top:0;
    left:0;
    width: 100%;
    height:100%;
}
/* blur the background, to make blurred edges that overflow the unblurred image that is on top */
 .bg-image-blur {
    -webkit-filter: blur(20px);
    -moz-filter: blur(20px);
    -o-filter: blur(20px);
    -ms-filter: blur(20px);
    filter: blur(20px);
}
/* I added this DIV in case you need to place content inside */
 .content {
    position: absolute;
    top:0;
    left:0;
    width: 100%;
    height: 100%;
    color: #fff;
    text-shadow: 0 0 3px #000;
    text-align: center;
    font-size: 30px;
}

Notice the blurred effect is using the image, so it changes with the image color.

I hope this helps.

How to filter Pandas dataframe using 'in' and 'not in' like in SQL

You can use pd.Series.isin.

For "IN" use: something.isin(somewhere)

Or for "NOT IN": ~something.isin(somewhere)

As a worked example:

import pandas as pd

>>> df
  country
0        US
1        UK
2   Germany
3     China
>>> countries_to_keep
['UK', 'China']
>>> df.country.isin(countries_to_keep)
0    False
1     True
2    False
3     True
Name: country, dtype: bool
>>> df[df.country.isin(countries_to_keep)]
  country
1        UK
3     China
>>> df[~df.country.isin(countries_to_keep)]
  country
0        US
2   Germany

Forcing anti-aliasing using css: Is this a myth?

Seems like the most exhaustive solution can be found at http://www.elfboy.com/blog/text-shadow_anti-aliasing/. Works in Firefox and Chrome, although Firefox is not quite as effective as Chrome.

Find a file by name in Visual Studio Code

When you have opened a folder in a workspace you can do Ctrl+P (Cmd+P on Mac) and start typing the filename, or extension to filter the list of filenames

if you have:

  • plugin.ts
  • page.css
  • plugger.ts

You can type css and press enter and it will open the page.css. If you type .ts the list is filtered and contains two items.

How to create an empty array in PHP with predefined size?

PHP Arrays don't need to be declared with a size.

An array in PHP is actually an ordered map

You also shouldn't get a warning/notice using code like the example you have shown. The common Notice people get is "Undefined offset" when reading from an array.

A way to counter this is to check with isset or array_key_exists, or to use a function such as:

function isset_or($array, $key, $default = NULL) {
    return isset($array[$key]) ? $array[$key] : $default;
}

So that you can avoid the repeated code.

Note: isset returns false if the element in the array is NULL, but has a performance gain over array_key_exists.

If you want to specify an array with a size for performance reasons, look at:

SplFixedArray in the Standard PHP Library.

How to get first and last day of previous month (with timestamp) in SQL Server

SELECT CONVERT(DATE,DATEADD(MM, DATEDIFF(MM, 0, GETDATE())-1, 0)) AS FirstDayOfPrevMonth
SELECT CONVERT(DATE,DATEADD(MS, -3, DATEADD(MM, DATEDIFF(MM, 0, GETDATE()) , 0))) AS LastDayOfPrevMonth

Is it possible to set async:false to $.getJSON call

You need to make the call using $.ajax() to it synchronously, like this:

$.ajax({
  url: myUrl,
  dataType: 'json',
  async: false,
  data: myData,
  success: function(data) {
    //stuff
    //...
  }
});

This would match currently using $.getJSON() like this:

$.getJSON(myUrl, myData, function(data) { 
  //stuff
  //...
});

How to return a PNG image from Jersey REST service method to the browser

I'm not convinced its a good idea to return image data in a REST service. It ties up your application server's memory and IO bandwidth. Much better to delegate that task to a proper web server that is optimized for this kind of transfer. You can accomplish this by sending a redirect to the image resource (as a HTTP 302 response with the URI of the image). This assumes of course that your images are arranged as web content.

Having said that, if you decide you really need to transfer image data from a web service you can do so with the following (pseudo) code:

@Path("/whatever")
@Produces("image/png")
public Response getFullImage(...) {

    BufferedImage image = ...;

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(image, "png", baos);
    byte[] imageData = baos.toByteArray();

    // uncomment line below to send non-streamed
    // return Response.ok(imageData).build();

    // uncomment line below to send streamed
    // return Response.ok(new ByteArrayInputStream(imageData)).build();
}

Add in exception handling, etc etc.

Python "expected an indented block"

This one is wrong at least:

            for x in range(x, 1, 1):
        elif option == 0:

How to close a window using jQuery

You can only use the window.close function when you have opened the window using window.open(), so I use the following function:

function close_window(url){
    var newWindow = window.open('', '_self', ''); //open the current window
    window.close(url);
 }

How to get jQuery dropdown value onchange event

Add try this code .. Its working grt.......

_x000D_
_x000D_
<body>_x000D_
<?php_x000D_
 if (isset($_POST['nav'])) {_x000D_
   header("Location: $_POST[nav]");_x000D_
 }_x000D_
?>_x000D_
<form id="page-changer" action="" method="post">_x000D_
    <select name="nav">_x000D_
        <option value="">Go to page...</option>_x000D_
        <option value="http://css-tricks.com/">CSS-Tricks</option>_x000D_
        <option value="http://digwp.com/">Digging Into WordPress</option>_x000D_
        <option value="http://quotesondesign.com/">Quotes on Design</option>_x000D_
    </select>_x000D_
    <input type="submit" value="Go" id="submit" />_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
<html>_x000D_
<head>_x000D_
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>_x000D_
<script>_x000D_
$(function() {_x000D_
_x000D_
    $("#submit").hide();_x000D_
_x000D_
    $("#page-changer select").change(function() {_x000D_
        window.location = $("#page-changer select option:selected").val();_x000D_
    })_x000D_
_x000D_
});_x000D_
</script>_x000D_
</head>
_x000D_
_x000D_
_x000D_

C++ Array of pointers: delete or delete []?

delete[] monsters;

Is incorrect because monsters isn't a pointer to a dynamically allocated array, it is an array of pointers. As a class member it will be destroyed automatically when the class instance is destroyed.

Your other implementation is the correct one as the pointers in the array do point to dynamically allocated Monster objects.

Note that with your current memory allocation strategy you probably want to declare your own copy constructor and copy-assignment operator so that unintentional copying doesn't cause double deletes. (If you you want to prevent copying you could declare them as private and not actually implement them.)

Declare Variable for a Query String

I will point out that in the article linked in the top rated answer The Curse and Blessings of Dynamic SQL the author states that the answer is not to use dynamic SQL. Scroll almost to the end to see this.

From the article: "The correct method is to unpack the list into a table with a user-defined function or a stored procedure."

Of course, once the list is in a table you can use a join. I could not comment directly on the top rated answer, so I just added this comment.

List Git commits not pushed to the origin yet

git log origin/master..master

or, more generally:

git log <since>..<until>

You can use this with grep to check for a specific, known commit:

git log <since>..<until> | grep <commit-hash>

Or you can also use git-rev-list to search for a specific commit:

git rev-list origin/master | grep <commit-hash>

How to find current transaction level?

just run DBCC useroptions and you'll get something like this:

Set Option                  Value
--------------------------- --------------
textsize                    2147483647
language                    us_english
dateformat                  mdy
datefirst                   7
lock_timeout                -1
quoted_identifier           SET
arithabort                  SET
ansi_null_dflt_on           SET
ansi_warnings               SET
ansi_padding                SET
ansi_nulls                  SET
concat_null_yields_null     SET
isolation level             read committed

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required?

Below is my code.I also had the same error but the problem was that i gave my password wrong.The below code will work perfectly..try it

            MailMessage mail = new MailMessage();
            SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");              
            mail.From = new MailAddress("[email protected]");
            mail.To.Add("[email protected]");
            mail.To.Add("[email protected]");
            mail.Subject = "Password Recovery ";
            mail.Body += " <html>";
            mail.Body += "<body>";
            mail.Body += "<table>";

            mail.Body += "<tr>";
            mail.Body += "<td>User Name : </td><td> HAi </td>";
            mail.Body += "</tr>";

            mail.Body += "<tr>";
            mail.Body += "<td>Password : </td><td>aaaaaaaaaa</td>";
            mail.Body += "</tr>";

            mail.Body += "</table>";
            mail.Body += "</body>";
            mail.Body += "</html>";

            mail.IsBodyHtml = true;
            SmtpServer.Port = 587;
            SmtpServer.Credentials = new System.Net.NetworkCredential("sendfrommailaddress.com", "password");
            SmtpServer.EnableSsl = true;

            SmtpServer.Send(mail);

You can reffer it in Sending mail

Put spacing between divs in a horizontal row?

Another idea: Compensate for your margin on the opposite side of the div.

For the side with the spacing you are looking to achieve as an example: 10px, and for the opposing side, compensate with a -10px. It works for me. This likely won't work in all scenarios, but depending on your layout and spacing of other elements, it might work great.

Insert HTML with React Variable Statements (JSX)

By using '' you are making it to string. Use without inverted commas it will work fine.

How to include PHP files that require an absolute path?

@Flubba, does this allow me to have folders inside my include directory? flat include directories give me nightmares. as the whole objects directory should be in the inc directory.

Oh yes, absolutely. So for example, we use a single layer of subfolders, generally:

require_once('library/string.class.php')

You need to be careful with relying on the include path too much in really high traffic sites, because php has to hunt through the current directory and then all the directories on the include path in order to see if your file is there and this can slow things up if you're getting hammered.

So for example if you're doing MVC, you'd put the path to your application directoy in the include path and then specify refer to things in the form

'model/user.class'
'controllers/front.php'

or whatever.

But generally speaking, it just lets you work with really short paths in your PHP that will work from anywhere and it's a lot easier to read than all that realpath document root malarkey.

The benefit of those script-based alternatives others have suggested is they work anywhere, even on shared boxes; setting the include path requires a little more thought and effort but as I mentioned lets you start using __autoload which just the coolest.

How do I serialize a C# anonymous type to a JSON string?

For those checking this around the year 2020:

Microsoft's System.Text.Json namespace is the new king in town. In terms of performance, it is the best as far as I can tell:

var model = new Model
{
    Name = "Test Name",
    Age = 5
};

string json = JsonSerializer.Serialize(model);

As some others have mentioned, NewtonSoft.Json is a very nice library as well.

Android overlay a view ontop of everything?

I have just made a solution for it. I made a library for this to do that in a reusable way that's why you don't need to recode in your XML. Here is documentation on how to use it in Java and Kotlin. First, initialize it from an activity from where you want to show the overlay-

AppWaterMarkBuilder.doConfigure()
                .setAppCompatActivity(MainActivity.this)
                .setWatermarkProperty(R.layout.layout_water_mark)
                .showWatermarkAfterConfig();

Then you can hide and show it from anywhere in your app -

  /* For hiding the watermark*/
  AppWaterMarkBuilder.hideWatermark() 

  /* For showing the watermark*/
  AppWaterMarkBuilder.showWatermark() 

Gif preview -

preview

Why is Spring's ApplicationContext.getBean considered bad?

Reasons to prefer Service Locator over Inversion of Control (IoC) are:

  1. Service Locator is much, much easier for other people to following in your code. IoC is 'magic' but maintenance programmers must understand your convoluted Spring configurations and all the myriad of locations to figure out how you wired your objects.

  2. IoC is terrible for debugging configuration problems. In certain classes of applications the application will not start when misconfigured and you may not get a chance to step through what is going on with a debugger.

  3. IoC is primarily XML based (Annotations improve things but there is still a lot of XML out there). That means developers can't work on your program unless they know all the magic tags defined by Spring. It is not good enough to know Java anymore. This hinders less experience programmers (ie. it is actually poor design to use a more complicated solution when a simpler solution, such as Service Locator, will fulfill the same requirements). Plus, support for diagnosing XML problems is far weaker than support for Java problems.

  4. Dependency injection is more suited to larger programs. Most of the time the additional complexity is not worth it.

  5. Often Spring is used in case you "might want to change the implementation later". There are other ways of achieving this without the complexity of Spring IoC.

  6. For web applications (Java EE WARs) the Spring context is effectively bound at compile time (unless you want operators to grub around the context in the exploded war). You can make Spring use property files, but with servlets property files will need to be at a pre-determined location, which means you can't deploy multiple servlets of the same time on the same box. You can use Spring with JNDI to change properties at servlet startup time, but if you are using JNDI for administrator-modifiable parameters the need for Spring itself lessens (since JNDI is effectively a Service Locator).

  7. With Spring you can lose program Control if Spring is dispatching to your methods. This is convenient and works for many types of applications, but not all. You may need to control program flow when you need to create tasks (threads etc) during initialization or need modifiable resources that Spring didn't know about when the content was bound to your WAR.

Spring is very good for transaction management and has some advantages. It is just that IoC can be over-engineering in many situations and introduce unwarranted complexity for maintainers. Do not automatically use IoC without thinking of ways of not using it first.

how to implement a long click listener on a listview

    listView.setOnLongClickListener(new View.OnLongClickListener() {
    @Override
    public boolean onLongClick(View view) {
        return false;
    }
});

Definitely does the trick.

Random integer in VB.NET

If you are using Joseph's answer which is a great answer, and you run these back to back like this:

dim i = GetRandom(1, 1715)
dim o = GetRandom(1, 1715)

Then the result could come back the same over and over because it processes the call so quickly. This may not have been an issue in '08, but since the processors are much faster today, the function doesn't allow the system clock enough time to change prior to making the second call.

Since the System.Random() function is based on the system clock, we need to allow enough time for it to change prior to the next call. One way of accomplishing this is to pause the current thread for 1 millisecond. See example below:

Public Function GetRandom(ByVal min as Integer, ByVal max as Integer) as Integer
    Static staticRandomGenerator As New System.Random
    max += 1
    Return staticRandomGenerator.Next(If(min > max, max, min), If(min > max, min, max))
End Function

Converting integer to digit list

n = int(raw_input("n= "))

def int_to_list(n):
    l = []
    while n != 0:
        l = [n % 10] + l
        n = n // 10
    return l

print int_to_list(n)

How to check if an element of a list is a list (in Python)?

Expression you are looking for may be:

...
return any( isinstance(e, list) for e in my_list )

Testing:

>>> my_list = [1,2]
>>> any( isinstance(e, list) for e in my_list )
False
>>> my_list = [1,2, [3,4,5]]
>>> any( isinstance(e, list) for e in my_list )
True
>>> 

jQuery - Add ID instead of Class

Try this:

$('element').attr('id', 'value');

So it becomes;

$(function() {
    $('span .breadcrumb').each(function(){
        $('#nav').attr('id', $(this).text());
        $('#container').attr('id', $(this).text());
        $('.stretch_footer').attr('id', $(this).text())
        $('#footer').attr('id', $(this).text());
    });
});

So you are changing/overwriting the id of three elements and adding an id to one element. You can modify as per you needs...

You seem to not be depending on "@angular/core". This is an error

from terminal

 > cd myProjectPath
 myProjectPath > npm install

What is console.log in jQuery?

It has nothing to do with jQuery, it's just a handy js method built into modern browsers.

Think of it as a handy alternative to debugging via window.alert()

Lost httpd.conf file located apache

Get the path of running Apache

$ ps -ef | grep apache
apache   12846 14590  0 Oct20 ?        00:00:00 /usr/sbin/apache2

Append -V argument to the path

$ /usr/sbin/apache2 -V | grep SERVER_CONFIG_FILE
-D SERVER_CONFIG_FILE="/etc/apache2/apache2.conf"

Reference:
http://commanigy.com/blog/2011/6/8/finding-apache-configuration-file-httpd-conf-location

Datatable select with multiple conditions

Do you have to use DataTable.Select()? I prefer to write a linq query for this kind of thing.

var dValue=  from row in myDataTable.AsEnumerable()
             where row.Field<int>("A") == 1 
                   && row.Field<int>("B") == 2 
                   && row.Field<int>("C") == 3
             select row.Field<string>("D");

How do I compare a value to a backslash?

When you only need to check for equality, you can also simply use the in operator to do a membership test in a sequence of accepted elements:

if message.value[0] in ('/', '\\'):
    do_stuff()

How to fit a smooth curve to my data in R?

the qplot() function in the ggplot2 package is very simple to use and provides an elegant solution that includes confidence bands. For instance,

qplot(x,y, geom='smooth', span =0.5)

produces enter image description here

How to customize a Spinner in Android

Try this

i was facing lot of issues when i was trying other solution...... After lot of R&D now i got solution

  1. create custom_spinner.xml in layout folder and paste this code

     <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorGray">
    <TextView
    android:id="@+id/tv_spinnervalue"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textColor="@color/colorWhite"
    android:gravity="center"
    android:layout_alignParentLeft="true"
    android:textSize="@dimen/_18dp"
    android:layout_marginTop="@dimen/_3dp"/>
    <ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:background="@drawable/men_icon"/>
    </RelativeLayout>
    
  2. in your activity

    Spinner spinner =(Spinner)view.findViewById(R.id.sp_colorpalates);
    String[] years = {"1996","1997","1998","1998"};
    spinner.setAdapter(new SpinnerAdapter(this, R.layout.custom_spinner, years));
    
  3. create a new class of adapter

    public class SpinnerAdapter extends ArrayAdapter<String> {
    private String[] objects;
    
    public SpinnerAdapter(Context context, int textViewResourceId, String[] objects) {
        super(context, textViewResourceId, objects);
        this.objects=objects;
    }
    
    @Override
    public View getDropDownView(int position, View convertView, @NonNull ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }
    
    @NonNull
    @Override
    public View getView(int position, View convertView, @NonNull ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }
    
    private View getCustomView(final int position, View convertView, ViewGroup parent) {
        View row = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_spinner, parent, false);
        final TextView label=(TextView)row.findViewById(R.id.tv_spinnervalue);
        label.setText(objects[position]);
        return row;
    }
    }
    

How to Delete node_modules - Deep Nested Folder in Windows

I think this was not mentioned before. but the best way to delete unwanted node_modules is to install an utility called npmkill.

Installation:

From your terminal:

npm i -g npkill

And to use it:

From your terminal:

npkill

You will then be presented with a list of projects, and by hitting space bar you can delete their node_modules.

Convert an array to string

You probably want something like this overload of String.Join:

String.Join<T> Method (String, IEnumerable<T>)

Docs:

http://msdn.microsoft.com/en-us/library/dd992421.aspx

In your example, you'd use

String.Join("", Client);

Login credentials not working with Gmail SMTP

I beleive I'm little late here. But I think this would help for the new peeps! If you're using smtp.gmail.com , then you have to do the following:

  1. Turn on the less secure apps

  2. You'll get the security mail in your gmail inbox, Click Yes,it's me in that.

  3. Now run your code again.

How to set JAVA_HOME environment variable on Mac OS X 10.9?

Literally all you have to do is:

echo export "JAVA_HOME=\$(/usr/libexec/java_home)" >> ~/.bash_profile

and restart your shell.

If you have multiple JDK versions installed and you want it to be a specific one, you can use the -v flag to java_home like so:

echo export "JAVA_HOME=\$(/usr/libexec/java_home -v 1.7)" >> ~/.bash_profile

Bigger Glyphicons

You can just give the glyphicon a font-size to your liking:

span.glyphicon-link {
    font-size: 1.2em;
}

No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?

I tried most of the answers without success. What worked for me was (after following https://stackoverflow.com/a/21279068/2408893):

  • right click on project -> Properties
  • select Java Build Path
  • select the JRE System Library
  • click edit
  • In execution environment select a jdk

enter image description here

  • click Finish
  • build and run

Running Python on Windows for Node.js dependencies

One and/or multiple of those should help:

  1. Add C:\Python27\ to your PATH variable (considering you have Python installed in this directory)
    How to set PATH env variable: http://www.computerhope.com/issues/ch000549.htm
    Restart your console and/or Windows after setting variable.

  2. In the same section as above ("Environment Variables"), add new variable with name PYTHON and value C:\Python27\python.exe
    Restart your console and/or Windows after setting variable.

  3. Open Windows command line (cmd) in Admin mode.
    Change directory to your Python installation path: cd C:\Python27
    Make symlink needed for some installations: mklink python2.7.exe python.exe

Please note that you should have Python 2.x, NOT 3.x, to run node-gyp based installations!

The text below says about Unix, but Windows version also requires Python 2.x:

You can install with npm:

$ npm install -g node-gyp
You will also need to install:

On Unix:
python (v2.7 recommended, v3.x.x is not supported)
make
A proper C/C++ compiler toolchain, like GCC

This article may also help: https://github.com/nodejs/node-gyp#installation

Create excel ranges using column numbers in vba?

Function fncToLetters(vintCol As Integer) As String

        Dim mstrDigits As String

    ' Convert a positive number n to its digit representation in base 26.
    mstrDigits = ""
    Do While vintCol > 0
        mstrDigits = Chr(((vintCol - 1) Mod 26) + 65) & mstrDigits
        vintCol = Int((vintCol - 1) / 26)
    Loop

    fncToLetters = mstrDigits

End Function

Get only specific attributes with from Laravel Collection

I have now come up with an own solution to this:

1. Created a general function to extract specific attributes from arrays

The function below extract only specific attributes from an associative array, or an array of associative arrays (the last is what you get when doing $collection->toArray() in Laravel).

It can be used like this:

$data = array_extract( $collection->toArray(), ['id','url'] );

I am using the following functions:

function array_is_assoc( $array )
{
        return is_array( $array ) && array_diff_key( $array, array_keys(array_keys($array)) );
}



function array_extract( $array, $attributes )
{
    $data = [];

    if ( array_is_assoc( $array ) )
    {
        foreach ( $attributes as $attribute )
        {
            $data[ $attribute ] = $array[ $attribute ];
        }
    }
    else
    {
        foreach ( $array as $key => $values )
        {
            $data[ $key ] = [];

            foreach ( $attributes as $attribute )
            {
                $data[ $key ][ $attribute ] = $values[ $attribute ];
            }
        }   
    }

    return $data;   
}

This solution does not focus on performance implications on looping through the collections in large datasets.

2. Implement the above via a custom collection i Laravel

Since I would like to be able to simply do $collection->extract('id','url'); on any collection object, I have implemented a custom collection class.

First I created a general Model, which extends the Eloquent model, but uses a different collection class. All you models need to extend this custom model, and not the Eloquent Model then.

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model as EloquentModel;
use Lib\Collection;
class Model extends EloquentModel
{
    public function newCollection(array $models = [])
    {
        return new Collection( $models );
    }    
}
?>

Secondly I created the following custom collection class:

<?php
namespace Lib;
use Illuminate\Support\Collection as EloquentCollection;
class Collection extends EloquentCollection
{
    public function extract()
    {
        $attributes = func_get_args();
        return array_extract( $this->toArray(), $attributes );
    }
}   
?>

Lastly, all models should then extend your custom model instead, like such:

<?php
namespace App\Models;
class Article extends Model
{
...

Now the functions from no. 1 above are neatly used by the collection to make the $collection->extract() method available.

There is no argument given that corresponds to the required formal parameter - .NET Error

You have a constructor which takes 2 parameters. You should write something like:

new ErrorEventArg(errorMsv, lastQuery)

It's less code and easier to read.

EDIT

Or, in order for your way to work, you can try writing a default constructor for ErrorEventArg which would have no parameters, like this:

public ErrorEventArg() {}

How to pattern match using regular expression in Scala?

First we should know that regular expression can separately be used. Here is an example:

import scala.util.matching.Regex
val pattern = "Scala".r // <=> val pattern = new Regex("Scala")
val str = "Scala is very cool"
val result = pattern findFirstIn str
result match {
  case Some(v) => println(v)
  case _ =>
} // output: Scala

Second we should notice that combining regular expression with pattern matching would be very powerful. Here is a simple example.

val date = """(\d\d\d\d)-(\d\d)-(\d\d)""".r
"2014-11-20" match {
  case date(year, month, day) => "hello"
} // output: hello

In fact, regular expression itself is already very powerful; the only thing we need to do is to make it more powerful by Scala. Here are more examples in Scala Document: http://www.scala-lang.org/files/archive/api/current/index.html#scala.util.matching.Regex

How Do I Replace/Change The Heading Text Inside <h3></h3>, Using jquery?

Something like:

$(".head h3").html("Public offers");

How do I replace a character in a string in Java?

Try this code.You can replace any character with another given character. Here I tried to replace the letter 'a' with "-" character for the give string "abcdeaa"

OutPut -->_bcdef__

    public class Replace {

    public static void replaceChar(String str,String target){
        String result = str.replaceAll(target, "_");
        System.out.println(result);
    }

    public static void main(String[] args) {
        replaceChar("abcdefaa","a");
    }

}

FirstOrDefault: Default value other than null

You can also do this

    Band[] objects = { new Band { Name = "Iron Maiden" } };
    first = objects.Where(o => o.Name == "Slayer")
        .DefaultIfEmpty(new Band { Name = "Black Sabbath" })
        .FirstOrDefault();   // returns "Black Sabbath" 

This uses only linq - yipee!

What is the "assert" function?

There are three main reasons for using the assert() function over the normal if else and printf

  1. assert() function is mainly used in the debugging phase, it is tedious to write if else with a printf statement everytime you want to test a condition which might not even make its way in the final code.

  2. In large software deployments , assert comes very handy where you can make the compiler ignore the assert statements using the NDEBUG macro defined before linking the header file for assert() function.

  3. assert() comes handy when you are designing a function or some code and want to get an idea as to what limits the code will and not work and finally include an if else for evaluating it basically playing with assumptions.

ERROR Error: StaticInjectorError(AppModule)[UserformService -> HttpClient]:

There are two possible reasons 1. If you are using HttpClient in your service you need to import HttpClientModule in your module file and mention it in the imports array.

import { HttpClientModule } from '@angular/common/http';
  1. If you are using normal Http in your services you need to import HttpModule in your module file and mention it in the imports array.

    import { HttpModule } from '@angular/http'

By default, this is not available in the angular then you need to install @angular/http

If you wish you can use both HttpClientModule and HttpModule in your project.

System.currentTimeMillis vs System.nanoTime

If you're just looking for extremely precise measurements of elapsed time, use System.nanoTime(). System.currentTimeMillis() will give you the most accurate possible elapsed time in milliseconds since the epoch, but System.nanoTime() gives you a nanosecond-precise time, relative to some arbitrary point.

From the Java Documentation:

public static long nanoTime()

Returns the current value of the most precise available system timer, in nanoseconds.

This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time. The value returned represents nanoseconds since some fixed but arbitrary origin time (perhaps in the future, so values may be negative). This method provides nanosecond precision, but not necessarily nanosecond accuracy. No guarantees are made about how frequently values change. Differences in successive calls that span greater than approximately 292 years (263 nanoseconds) will not accurately compute elapsed time due to numerical overflow.

For example, to measure how long some code takes to execute:

long startTime = System.nanoTime();    
// ... the code being measured ...    
long estimatedTime = System.nanoTime() - startTime;

See also: JavaDoc System.nanoTime() and JavaDoc System.currentTimeMillis() for more info.

Jquery get input array field

var data = $("input[name='page_title[]']")
  .map(function () {
    return $(this).val();
  })
  .get();

How can I define a composite primary key in SQL?

Just for clarification: a table can have at most one primary key. A primary key consists of one or more columns (from that table). If a primary key consists of two or more columns it is called a composite primary key. It is defined as follows:

CREATE TABLE voting (
  QuestionID NUMERIC,
  MemberID NUMERIC,
  PRIMARY KEY (QuestionID, MemberID)
);

The pair (QuestionID,MemberID) must then be unique for the table and neither value can be NULL. If you do a query like this:

SELECT * FROM voting WHERE QuestionID = 7

it will use the primary key's index. If however you do this:

SELECT * FROM voting WHERE MemberID = 7

it won't because to use a composite index requires using all the keys from the "left". If an index is on fields (A,B,C) and your criteria is on B and C then that index is of no use to you for that query. So choose from (QuestionID,MemberID) and (MemberID,QuestionID) whichever is most appropriate for how you will use the table.

If necessary, add an index on the other:

CREATE UNIQUE INDEX idx1 ON voting (MemberID, QuestionID);

Converting milliseconds to a date (jQuery/JavaScript)

/Date(1383066000000)/

function convertDate(data) {
    var getdate = parseInt(data.replace("/Date(", "").replace(")/", ""));
    var ConvDate= new Date(getdate);
    return ConvDate.getDate() + "/" + ConvDate.getMonth() + "/" + ConvDate.getFullYear();
}

iPhone UIView Animation Best Practice

In the UIView docs, have a read about this function for ios4+

+ (void)transitionFromView:(UIView *)fromView toView:(UIView *)toView duration:(NSTimeInterval)duration options:(UIViewAnimationOptions)options completion:(void (^)(BOOL finished))completion

Visual C++ executable and missing MSVCR100d.dll

This problem explained in MSDN Library and as I understand installing Microsoft's Redistributable Package can help.

But sometimes the following solution can be used (as developer's side solution):

In your Visual Studio, open Project properties -> Configuration properties -> C/C++ -> Code generation and change option Runtime Library to /MT instead of /MD

Hadoop/Hive : Loading data from .csv on a local machine

There is another way of enabling this,

  1. use hadoop hdfs -copyFromLocal to copy the .csv data file from your local computer to somewhere in HDFS, say '/path/filename'

  2. enter Hive console, run the following script to load from the file to make it as a Hive table. Note that '\054' is the ascii code of 'comma' in octal number, representing fields delimiter.


CREATE EXTERNAL TABLE table name (foo INT, bar STRING)
 COMMENT 'from csv file'
 ROW FORMAT DELIMITED FIELDS TERMINATED BY '\054'
 STORED AS TEXTFILE
 LOCATION '/path/filename';

Determine if Android app is being used for the first time

My version for kotlin looks like the following:

PreferenceManager.getDefaultSharedPreferences(this).apply {
        // Check if we need to display our OnboardingSupportFragment
        if (!getBoolean("wasAppStartedPreviously", false)) {
            // The user hasn't seen the OnboardingSupportFragment yet, so show it
            startActivity(Intent(this@SplashScreenActivity, AppIntroActivity::class.java))
        } else {
            startActivity(Intent(this@SplashScreenActivity, MainActivity::class.java))
        }
    }

How I can get and use the header file <graphics.h> in my C++ program?

<graphics.h> is not a standard header. Most commonly it refers to the header for Borland's BGI API for DOS and is antiquated at best.

However it is nicely simple; there is a Win32 implementation of the BGI interface called WinBGIm. It is implemented using Win32 GDI calls - the lowest level Windows graphics interface. As it is provided as source code, it is perhaps a simple way of understanding how GDI works.

WinBGIm however is by no means cross-platform. If all you want are simple graphics primitives, most of the higher level GUI libraries such as wxWidgets and Qt support that too. There are simpler libraries suggested in the possible duplicate answers mentioned in the comments.

Android SDK folder taking a lot of disk space. Do we need to keep all of the System Images?

I had 20.8 GB in the C:\Users\ggo\AppData\Local\Android\Sdk\system-images folder (6 android images: - android-10 - android-15 - android-21 - android-23 - android-25 - android-26 ).

I have compressed the C:\Users\ggo\AppData\Local\Android\Sdk\system-images folder.

Now it takes only 4.65 GB.

C:\Users\ggo\AppData\Local\Android\Sdk\system-images

I did not encountered any problem up to now...

Compression seems to vary from 2/3 to 6, sometimes much more:

android-10

android-23

android-25

android-26

SyntaxError: Unexpected token function - Async Await Nodejs

Node.JS does not fully support ES6 currently, so you can either use asyncawait module or transpile it using Bable.

install

npm install --save asyncawait

helloz.js

var async = require('asyncawait/async');
var await = require('asyncawait/await');

(async (function testingAsyncAwait() {
    await (console.log("Print me!"));
}))();

ScriptManager.RegisterStartupScript code not working - why?

You must put the updatepanel id in the first argument if the control causing the script is inside the updatepanel else use the keyword 'this' instead of update panel here is the code

ScriptManager.RegisterStartupScript(UpdatePanel3, this.GetType(), UpdatePanel3.UniqueID, "showError();", true);

DB2 Query to retrieve all table names for a given schema

For Db2 for Linux, Unix and Windows (i.e. Db2 LUW) or for Db2 Warehouse use the SYSCAT.TABLES catalog view. E.g.

SELECT TABSCHEMA, TABNAME FROM SYSCAT.TABLES WHERE TABSCHEMA LIKE '%CUR%' AND TYPE = 'T'

Which is a SQL statement that will return all standard tables in all schema that contains the substring CUR. From a Db2 command line you could also use a CLP command e.g. db2 list tables for all | grep CUR to similar effect

This page describes the columns in SYSCAT.TABLES including the different values for the TYPE column.

A = Alias
G = Created temporary table
H = Hierarchy table
L = Detached table
N = Nickname
S = Materialized query table
T = Table (untyped)
U = Typed table
V = View (untyped)
W = Typed view

Other commonly used catalog views incude

SYSCAT.COLUMNS      Lists the columns in each table, view and nickname
SYSCAT.VIEWS        Full SQL text for view and materialized query tables
SYSCAT.KEYCOLUSE    Column that are in PK, FK or Uniuqe constraints

In Db2 LUW it is considered bad practice to use the SYSIBM catalog tables (which the SYSCAT catalog views select thier data from). They are less consistent as far as column names go, are not quite as easy to use, are not documented and are more likely to change between versions.

This page has a list of all the catalog views Road map to the catalog views


For Db2 for z/OS, use SYSIBM.TABLES which is described here. E.g.

SELECT CREATOR, NAME FROM SYSIBM.SYSTABLES WHERE OWNER LIKE '%CUR%' AND TYPE = 'T'

For Db2 for i (i.e. iSeries aka AS/400) use QSYS2.SYSTABLES which is described here

SELECT TABLE_OWNER, TABLE_NAME FROM QSYS2.SYSTABLES WHERE TABLE_SCHEMA LIKE '%CUR%' AND TABLE_TYPE = 'T'

For DB2 Server for VSE and VM use SYSTEM.SYSCATALOG which is described here DB2 Server for VSE and VM SQL Reference

SELECT CREATOR, TNAME FROM SYSTEM.SYSCATALOG WHERE TABLETYPE = 'R'

How to call same method for a list of objects?

maybe map, but since you don't want to make a list, you can write your own...

def call_for_all(f, seq):
    for i in seq:
        f(i)

then you can do:

call_for_all(lamda x: x.start(), all)
call_for_all(lamda x: x.stop(), all)

by the way, all is a built in function, don't overwrite it ;-)

Elasticsearch error: cluster_block_exception [FORBIDDEN/12/index read-only / allow delete (api)], flood stage disk watermark exceeded

This happens when Elasticsearch thinks the disk is running low on space so it puts itself into read-only mode.

By default Elasticsearch's decision is based on the percentage of disk space that's free, so on big disks this can happen even if you have many gigabytes of free space.

The flood stage watermark is 95% by default, so on a 1TB drive you need at least 50GB of free space or Elasticsearch will put itself into read-only mode.

For docs about the flood stage watermark see https://www.elastic.co/guide/en/elasticsearch/reference/6.2/disk-allocator.html.

The right solution depends on the context - for example a production environment vs a development environment.

Solution 1: free up disk space

Freeing up enough disk space so that more than 5% of the disk is free will solve this problem. Elasticsearch won't automatically take itself out of read-only mode once enough disk is free though, you'll have to do something like this to unlock the indices:

$ curl -XPUT -H "Content-Type: application/json" https://[YOUR_ELASTICSEARCH_ENDPOINT]:9200/_all/_settings -d '{"index.blocks.read_only_allow_delete": null}'

Solution 2: change the flood stage watermark setting

Change the "cluster.routing.allocation.disk.watermark.flood_stage" setting to something else. It can either be set to a lower percentage or to an absolute value. Here's an example of how to change the setting from the docs:

PUT _cluster/settings
{
  "transient": {
    "cluster.routing.allocation.disk.watermark.low": "100gb",
    "cluster.routing.allocation.disk.watermark.high": "50gb",
    "cluster.routing.allocation.disk.watermark.flood_stage": "10gb",
    "cluster.info.update.interval": "1m"
  }
}

Again, after doing this you'll have to use the curl command above to unlock the indices, but after that they should not go into read-only mode again.

Display a loading bar before the entire page is loaded

HTML

<div class="preload">
<img src="http://i.imgur.com/KUJoe.gif">
</div>

<div class="content">
I would like to display a loading bar before the entire page is loaded. 
</div>

JAVASCRIPT

$(function() {
    $(".preload").fadeOut(2000, function() {
        $(".content").fadeIn(1000);        
    });
});?

CSS

.content {display:none;}
.preload { 
    width:100px;
    height: 100px;
    position: fixed;
    top: 50%;
    left: 50%;
}
?

DEMO

How to generate gcc debug symbol outside the build target?

NOTE: Programs compiled with high-optimization levels (-O3, -O4) cannot generate many debugging symbols for optimized variables, in-lined functions and unrolled loops, regardless of the symbols being embedded (-g) or extracted (objcopy) into a '.debug' file.

Alternate approaches are

  1. Embed the versioning (VCS, git, svn) data into the program, for compiler optimized executables (-O3, -O4).
  2. Build a 2nd non-optimized version of the executable.

The first option provides a means to rebuild the production code with full debugging and symbols at a later date. Being able to re-build the original production code with no optimizations is a tremendous help for debugging. (NOTE: This assumes testing was done with the optimized version of the program).

Your build system can create a .c file loaded with the compile date, commit, and other VCS details. Here is a 'make + git' example:

program: program.o version.o 

program.o: program.cpp program.h 

build_version.o: build_version.c    

build_version.c: 
    @echo "const char *build1=\"VCS: Commit: $(shell git log -1 --pretty=%H)\";" > "$@"
    @echo "const char *build2=\"VCS: Date: $(shell git log -1 --pretty=%cd)\";" >> "$@"
    @echo "const char *build3=\"VCS: Author: $(shell git log -1 --pretty="%an %ae")\";" >> "$@"
    @echo "const char *build4=\"VCS: Branch: $(shell git symbolic-ref HEAD)\";" >> "$@"
    # TODO: Add compiler options and other build details

.TEMPORARY: build_version.c

After the program is compiled you can locate the original 'commit' for your code by using the command: strings -a my_program | grep VCS

VCS: PROGRAM_NAME=my_program
VCS: Commit=190aa9cace3b12e2b58b692f068d4f5cf22b0145
VCS: BRANCH=refs/heads/PRJ123_feature_desc
VCS: AUTHOR=Joe Developer  [email protected]
VCS: COMMIT_DATE=2013-12-19

All that is left is to check-out the original code, re-compile without optimizations, and start debugging.

Join/Where with LINQ and Lambda

I've done something like this;

var certificationClass = _db.INDIVIDUALLICENSEs
    .Join(_db.INDLICENSECLAsses,
        IL => IL.LICENSE_CLASS,
        ILC => ILC.NAME,
        (IL, ILC) => new { INDIVIDUALLICENSE = IL, INDLICENSECLAsse = ILC })
    .Where(o => 
        o.INDIVIDUALLICENSE.GLOBALENTITYID == "ABC" &&
        o.INDIVIDUALLICENSE.LICENSE_TYPE == "ABC")
    .Select(t => new
        {
            value = t.PSP_INDLICENSECLAsse.ID,
            name = t.PSP_INDIVIDUALLICENSE.LICENSE_CLASS,                
        })
    .OrderBy(x => x.name);

creating charts with angularjs

I've seen some nice AngularJS charting solutions that make use of Highcharts. There's a highcharts-ng directive on GitHub to make AngularJS integration easier, and some examples on JSFiddle to give you a quick taste of what's possible.

You set up the chart on the JS side like this:

$scope.chart = {
    options: {
        chart: {
            type: 'bar'
        }
    },
    series: [{
        data: [10, 15, 12, 8, 7]
    }],
    title: {
        text: 'Hello'
    },
    loading: false
}

And then refer to it in the HTML like this:

<highchart id="chart1" config="chart"></highchart>

Usage/licensing warning: Highcharts is available for free under the Creative Commons license for non-commercial use. If you're looking for charting options in a for-profit/commercial scenario, you'll need to buy the product or look elsewhere.

Use images instead of radio buttons

Just using a class to only hide some...based on https://stackoverflow.com/a/17541916/1815624

_x000D_
_x000D_
/* HIDE RADIO */_x000D_
.hiddenradio [type=radio] { _x000D_
  position: absolute;_x000D_
  opacity: 0;_x000D_
  width: 0;_x000D_
  height: 0;_x000D_
}_x000D_
_x000D_
/* IMAGE STYLES */_x000D_
.hiddenradio [type=radio] + img {_x000D_
  cursor: pointer;_x000D_
}_x000D_
_x000D_
/* CHECKED STYLES */_x000D_
.hiddenradio [type=radio]:checked + img {_x000D_
  outline: 2px solid #f00;_x000D_
}
_x000D_
<div class="hiddenradio">_x000D_
<label>_x000D_
  <input type="radio" name="test" value="small" checked>_x000D_
  <img src="http://placehold.it/40x60/0bf/fff&text=A">_x000D_
</label>_x000D_
_x000D_
<label>_x000D_
  <input type="radio" name="test" value="big">_x000D_
  <img src="http://placehold.it/40x60/b0f/fff&text=B">_x000D_
</label>_x000D_
</div>_x000D_
_x000D_
<div class="">_x000D_
<label>_x000D_
  <input type="radio" name="test" value="small" checked>_x000D_
  <img src="http://placehold.it/40x60/0bf/fff&text=A">_x000D_
</label>_x000D_
_x000D_
<label>_x000D_
  <input type="radio" name="test" value="big">_x000D_
  <img src="http://placehold.it/40x60/b0f/fff&text=B">_x000D_
</label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to get a list of current open windows/process with Java?

Finally, with Java 9+ it is possible with ProcessHandle:

public static void main(String[] args) {
    ProcessHandle.allProcesses()
            .forEach(process -> System.out.println(processDetails(process)));
}

private static String processDetails(ProcessHandle process) {
    return String.format("%8d %8s %10s %26s %-40s",
            process.pid(),
            text(process.parent().map(ProcessHandle::pid)),
            text(process.info().user()),
            text(process.info().startInstant()),
            text(process.info().commandLine()));
}

private static String text(Optional<?> optional) {
    return optional.map(Object::toString).orElse("-");
}

Output:

    1        -       root   2017-11-19T18:01:13.100Z /sbin/init
  ...
  639     1325   www-data   2018-12-04T06:35:58.680Z /usr/sbin/apache2 -k start
  ...
23082    11054    huguesm   2018-12-04T10:24:22.100Z /.../java ProcessListDemo

Sorting Values of Set

You're using the default comparator to sort a Set<String>. In this case, that means lexicographic order. Lexicographically, "12" comes before "15", comes before "5".

Either use a Set<Integer>:

Set<Integer> set=new HashSet<Integer>();
set.add(12);
set.add(15);
set.add(5);

Or use a different comparator:

Collections.sort(list, new Comparator<String>() {
    public int compare(String a, String b) {
        return Integer.parseInt(a) - Integer.parseInt(b);
    }
});

Remove insignificant trailing zeros from a number?

How about just multiplying by one like this?

var x = 1.234000*1; // becomes 1.234

var y = 1.234001*1; // stays as 1.234001

What is "pass-through authentication" in IIS 7?

Normally, IIS would use the process identity (the user account it is running the worker process as) to access protected resources like file system or network.

With passthrough authentication, IIS will attempt to use the actual identity of the user when accessing protected resources.

If the user is not authenticated, IIS will use the application pool identity instead. If pool identity is set to NetworkService or LocalSystem, the actual Windows account used is the computer account.

The IIS warning you see is not an error, it's just a warning. The actual check will be performed at execution time, and if it fails, it'll show up in the log.

Checking for NULL pointer in C/C++

Frankly, I don't see why it matters. Either one is quite clear and anyone moderately experienced with C or C++ should understand both. One comment, though:

If you plan to recognize the error and not continue executing the function (i.e., you are going to throw an exception or return an error code immediately), you should make it a guard clause:

int f(void* p)
{
    if (!p) { return -1; }

    // p is not null
    return 0;
}

This way, you avoid "arrow code."

Time part of a DateTime Field in SQL

This will return the time-Only

For SQL Server:

SELECT convert(varchar(8), getdate(), 108)

Explanation:

getDate() is giving current date and time.
108 is formatting/giving us the required portion i.e time in this case.
varchar(8) gives us the number of characters from that portion.
Like:
If you wrote varchar(7) there, it will give you 00:00:0
If you wrote varchar(6) there, it will give you 00:00:
If you wrote varchar(15) there, it will still give you 00:00:00 because it is giving output of just time portion. SQLFiddle Demo

For MySQL:

SELECT DATE_FORMAT(NOW(), '%H:%i:%s')

SQLFiddle Demo

How to use multiprocessing pool.map with multiple arguments?

Another way is to pass a list of lists to a one-argument routine:

import os
from multiprocessing import Pool

def task(args):
    print "PID =", os.getpid(), ", arg1 =", args[0], ", arg2 =", args[1]

pool = Pool()

pool.map(task, [
        [1,2],
        [3,4],
        [5,6],
        [7,8]
    ])

One can than construct a list lists of arguments with one's favorite method.

Calculate the mean by group

Adding alternative base R approach, which remains fast under various cases.

rowsummean <- function(df) {
  rowsum(df$speed, df$dive) / tabulate(df$dive)
}

Borrowing the benchmarks from @Ari:

10 rows, 2 groups

res1

10 million rows, 10 groups

res2

10 million rows, 1000 groups

res3

Remove last commit from remote git repository

Be careful that this will create an "alternate reality" for people who have already fetch/pulled/cloned from the remote repository. But in fact, it's quite simple:

git reset HEAD^ # remove commit locally
git push origin +HEAD # force-push the new HEAD commit

If you want to still have it in your local repository and only remove it from the remote, then you can use:

git push origin +HEAD^:<name of your branch, most likely 'master'>

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

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

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

It's not necessary to modify the Dockerfile.

Xcode process launch failed: Security

I have the same issue. I click ok in xcode and when launching the app on my iPhone I'm asked if I want to trust this application. Doing it, the app runs and further build-and-run from xcode went without any issue until deleting the app from the iPhone and reinstalling it. Then goto first line ;-)

ios simulator: how to close an app

You can use this command to quit an app in iOS Simulator

xcrun simctl terminate booted com.apple.mobilesafari

You will need to know the bundle id of the app you have installed in the simulator. You can refer to this link

Read XLSX file in Java

Might be a little late, but the beta POI now supports xlsx.

Convert a List<T> into an ObservableCollection<T>

ObservableCollection < T > has a constructor overload which takes IEnumerable < T >

Example for a List of int:

ObservableCollection<int> myCollection = new ObservableCollection<int>(myList);

One more example for a List of ObjectA:

ObservableCollection<ObjectA> myCollection = new ObservableCollection<ObjectA>(myList as List<ObjectA>);

How do I get today's date in C# in mm/dd/yyyy format?

DateTime.Now.Date.ToShortDateString()

I think this is what you are looking for

JQuery Validate Dropdown list

$(document).ready(function(){
$("#HoursEntry").change(function(){
var HoursEntry = $(#HoursEntry option:selected).val();
if(HoursEntry == "")
{
$("#HoursEntry").html("Please select");
return false;
}
});
});

How to compile C++ under Ubuntu Linux?

Update your apt-get:

$ sudo apt-get update
$ sudo apt-get install g++

Run your program.cpp:

$ g++ program.cpp
$ ./a.out

What is the use of printStackTrace() method in Java?

It's a method on Exception instances that prints the stack trace of the instance to System.err.

It's a very simple, but very useful tool for diagnosing an exceptions. It tells you what happened and where in the code this happened.

Here's an example of how it might be used in practice:

try {
    // ...
} catch (SomeException e) { 
    e.printStackTrace();
}

How to file split at a line number

file_name=test.log

# set first K lines:
K=1000

# line count (N): 
N=$(wc -l < $file_name)

# length of the bottom file:
L=$(( $N - $K ))

# create the top of file: 
head -n $K $file_name > top_$file_name

# create bottom of file: 
tail -n $L $file_name > bottom_$file_name

Also, on second thought, split will work in your case, since the first split is larger than the second. Split puts the balance of the input into the last split, so

split -l 300000 file_name

will output xaa with 300k lines and xab with 100k lines, for an input with 400k lines.

Adding HTML entities using CSS content

Use the hex code for a non-breaking space. Something like this:

.breadcrumbs a:before {
    content: '>\00a0';
}

Clearing Magento Log Data

No need to do this yourself, the Magento system has a built-in for cleaning up log information. If you go to

System > Configuration > Advanced > System > Log Cleaning

You can configure your store to automatically clean up these logs.