Programs & Examples On #Wedge

How to make a page redirect using JavaScript?

You can call a JavaScript function and use window.location = 'url';:

http://www.pageresource.com/jscript/jredir.htm

NumPy array is not JSON serializable

You could also use default argument for example:

def myconverter(o):
    if isinstance(o, np.float32):
        return float(o)

json.dump(data, default=myconverter)

How can I find the number of years between two dates?

If you don't want to calculate it using java's Calendar you can use Androids Time class It is supposed to be faster but I didn't notice much difference when i switched.

I could not find any pre-defined functions to determine time between 2 dates for an age in Android. There are some nice helper functions to get formatted time between dates in the DateUtils but that's probably not what you want.

I need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array

  1. What exactly doesn't work?
  2. Why are you using a 2d array?
  3. If you must use a 2d array:

    int numOfPairs = 10;  String[][] array = new String[numOfPairs][2]; for(int i = 0; i < array.length; i++){     for(int j = 0; j < array[i].length; j++){         array[i] = new String[2];         array[i][0] = "original word";         array[i][1] = "rearranged word";     }    } 

Does this give you a hint?

Search a whole table in mySQL for a string

If you are just looking for some text and don't need a result set for programming purposes, you could install HeidiSQL for free (I'm using v9.2.0.4947).

Right click any database or table and select "Find text on server".

All the matches are shown in a separate tab for each table - very nice.

Frighteningly useful and saved me hours. Forget messing about with lengthy queries!!

How to run function in AngularJS controller on document ready?

Angular has several timepoints to start executing functions. If you seek for something like jQuery's

$(document).ready();

You may find this analog in angular to be very useful:

$scope.$watch('$viewContentLoaded', function(){
    //do something
});

This one is helpful when you want to manipulate the DOM elements. It will start executing only after all te elements are loaded.

UPD: What is said above works when you want to change css properties. However, sometimes it doesn't work when you want to measure the element properties, such as width, height, etc. In this case you may want to try this:

$scope.$watch('$viewContentLoaded', 
    function() { 
        $timeout(function() {
            //do something
        },0);    
});

How to set the title of UIButton as left alignment?

There is a small error in the code of @DyingCactus. Here is the correct solution to add an UILabel to an UIButton to align the button text to better control the button 'title':

NSString *myLabelText = @"Hello World";
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];

// position in the parent view and set the size of the button
myButton.frame = CGRectMake(myX, myY, myWidth, myHeight); 

CGRect myButtonRect = myButton.bounds;
UILabel *myLabel = [[UILabel alloc] initWithFrame: myButtonRect];   
myLabel.text = myLabelText;
myLabel.backgroundColor = [UIColor clearColor];
myLabel.textColor = [UIColor redColor]; 
myLabel.font = [UIFont fontWithName:@"Helvetica Neue" size:14.0];   
myLabel.textAlignment = UITextAlignmentLeft;

[myButton addSubview:myLabel];
[myLabel release];

Hope this helps....

Al

How to link to a <div> on another page?

You can add hash info in next page url to move browser at specific position(any html element), after page is loaded.

This is can done in this way:

add hash in the url of next_page : example.com#hashkey

$( document ).ready(function() {

  ##get hash code at next page
  var hashcode = window.location.hash;

  ## move page to any specific position of next page(let that is div with id "hashcode")
  $('html,body').animate({scrollTop: $('div#'+hascode).offset().top},'slow');

});

Change grid interval and specify tick labels in Matplotlib

A subtle alternative to MaxNoe's answer where you aren't explicitly setting the ticks but instead setting the cadence.

import matplotlib.pyplot as plt
from matplotlib.ticker import (AutoMinorLocator, MultipleLocator)

fig, ax = plt.subplots(figsize=(10, 8))

# Set axis ranges; by default this will put major ticks every 25.
ax.set_xlim(0, 200)
ax.set_ylim(0, 200)

# Change major ticks to show every 20.
ax.xaxis.set_major_locator(MultipleLocator(20))
ax.yaxis.set_major_locator(MultipleLocator(20))

# Change minor ticks to show every 5. (20/4 = 5)
ax.xaxis.set_minor_locator(AutoMinorLocator(4))
ax.yaxis.set_minor_locator(AutoMinorLocator(4))

# Turn grid on for both major and minor ticks and style minor slightly
# differently.
ax.grid(which='major', color='#CCCCCC', linestyle='--')
ax.grid(which='minor', color='#CCCCCC', linestyle=':')

Matplotlib Custom Grid

Spring Boot Program cannot find main class

I also got this error, was not having any clue. I could see the class and jars in Target folder. I later installed Maven 3.5, switched my local repo from C drive to other drive through conf/settings.xml of Maven. It worked perfectly fine after that. I think having local repo in C drive was main issue. Even though repo was having full access.

Abort a git cherry-pick?

For me, the only way to reset the failed cherry-pick-attempt was

git reset --hard HEAD

PHP Accessing Parent Class Variable

Just echo it since it's inherited

echo $this->bb;

React Native Error: ENOSPC: System limit for number of file watchers reached

You can fix it, that increasing the amount of inotify watchers.

If you are not interested in the technical details and only want to get Listen to work:

  • If you are running Debian, RedHat, or another similar Linux distribution, run the following in a terminal:

    $ echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p

  • If you are running ArchLinux, run the following command instead

    $ echo fs.inotify.max_user_watches=524288 | sudo tee /etc/sysctl.d/40-max-user-watches.conf && sudo sysctl --system

Then paste it in your terminal and press on enter to run it.


The Technical Details

Listen uses inotify by default on Linux to monitor directories for changes. It's not uncommon to encounter a system limit on the number of files you can monitor. For example, Ubuntu Lucid's (64bit) inotify limit is set to 8192.

You can get your current inotify file watch limit by executing:

$ cat /proc/sys/fs/inotify/max_user_watches

When this limit is not enough to monitor all files inside a directory, the limit must be increased for Listen to work properly.

You can set a new limit temporary with:

$ sudo sysctl fs.inotify.max_user_watches=524288
$ sudo sysctl -p

If you like to make your limit permanent, use:

$ echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf
$ sudo sysctl -p

You may also need to pay attention to the values of max_queued_events and max_user_instances if listen keeps on complaining.

Why is ZoneOffset.UTC != ZoneId.of("UTC")?

The answer comes from the javadoc of ZoneId (emphasis mine) ...

A ZoneId is used to identify the rules used to convert between an Instant and a LocalDateTime. There are two distinct types of ID:

  • Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-times
  • Geographical regions - an area where a specific set of rules for finding the offset from UTC/Greenwich apply

Most fixed offsets are represented by ZoneOffset. Calling normalized() on any ZoneId will ensure that a fixed offset ID will be represented as a ZoneOffset.

... and from the javadoc of ZoneId#of (emphasis mine):

This method parses the ID producing a ZoneId or ZoneOffset. A ZoneOffset is returned if the ID is 'Z', or starts with '+' or '-'.

The argument id is specified as "UTC", therefore it will return a ZoneId with an offset, which also presented in the string form:

System.out.println(now.withZoneSameInstant(ZoneOffset.UTC));
System.out.println(now.withZoneSameInstant(ZoneId.of("UTC")));

Outputs:

2017-03-10T08:06:28.045Z
2017-03-10T08:06:28.045Z[UTC]

As you use the equals method for comparison, you check for object equivalence. Because of the described difference, the result of the evaluation is false.

When the normalized() method is used as proposed in the documentation, the comparison using equals will return true, as normalized() will return the corresponding ZoneOffset:

Normalizes the time-zone ID, returning a ZoneOffset where possible.

now.withZoneSameInstant(ZoneOffset.UTC)
    .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())); // true

As the documentation states, if you use "Z" or "+0" as input id, of will return the ZoneOffset directly and there is no need to call normalized():

now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("Z"))); //true
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("+0"))); //true

To check if they store the same date time, you can use the isEqual method instead:

now.withZoneSameInstant(ZoneOffset.UTC)
    .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))); // true

Sample

System.out.println("equals - ZoneId.of(\"UTC\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC"))));
System.out.println("equals - ZoneId.of(\"UTC\").normalized(): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())));
System.out.println("equals - ZoneId.of(\"Z\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("Z"))));
System.out.println("equals - ZoneId.of(\"+0\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("+0"))));
System.out.println("isEqual - ZoneId.of(\"UTC\"): "+ nowZoneOffset
        .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))));

Output:

equals - ZoneId.of("UTC"): false
equals - ZoneId.of("UTC").normalized(): true
equals - ZoneId.of("Z"): true
equals - ZoneId.of("+0"): true
isEqual - ZoneId.of("UTC"): true

Choosing a jQuery datagrid plugin?

A good plugin that I have used before is DataTables.

Why is division in Ruby returning an integer instead of decimal value?

It’s doing integer division. You can make one of the numbers a Float by adding .0:

9.0 / 5  #=> 1.8
9 / 5.0  #=> 1.8

MySQL - Select the last inserted row easiest way

You can use ORDER BY ID DESC, but it's WAY faster if you go that way:

SELECT * FROM bugs WHERE ID = (SELECT MAX(ID) FROM bugs WHERE user = 'me')

In case that you have a huge table, it could make a significant difference.

EDIT

You can even set a variable in case you need it more than once (or if you think it is easier to read).

SELECT @bug_id := MAX(ID) FROM bugs WHERE user = 'me';
SELECT * FROM bugs WHERE ID = @bug_id;

Can someone explain Microsoft Unity?

Unity is an IoC. The point of IoC is to abstract the wiring of dependencies between types outside of the types themselves. This has a couple of advantages. First of all, it is done centrally which means you don't have to change a lot of code when dependencies change (which may be the case for unit tests).

Furthermore, if the wiring is done using configuration data instead of code, you can actually rewire the dependencies after deployment and thus change the behavior of the application without changing the code.

"The breakpoint will not currently be hit. The source code is different from the original version." What does this mean?

For me, none of the items solved the issue. I just added a new line of code inside that function, something like:

int a=0;

by adding that, I guess I triggered visual studio to add this function to the original version

glm rotate usage in Opengl

I noticed that you can also get errors if you don't specify the angles correctly, even when using glm::rotate(Model, angle_in_degrees, glm::vec3(x, y, z)) you still might run into problems. The fix I found for this was specifying the type as glm::rotate(Model, (glm::mediump_float)90, glm::vec3(x, y, z)) instead of just saying glm::rotate(Model, 90, glm::vec3(x, y, z))

Or just write the second argument, the angle in radians (previously in degrees), as a float with no cast needed such as in:

glm::mat4 rotationMatrix = glm::rotate(glm::mat4(1.0f), 3.14f, glm::vec3(1.0));

You can add glm::radians() if you want to keep using degrees. And add the includes:

#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"

How to Remove the last char of String in C#?

If you are using string datatype, below code works:

string str = str.Remove(str.Length - 1);

But when you have StringBuilder, you have to specify second parameter length as well.

SB

That is,

string newStr = sb.Remove(sb.Length - 1, 1).ToString();

To avoid below error:

SB2

Store mysql query output into a shell variable

myvariable=$(mysql database -u $user -p$password | SELECT A, B, C FROM table_a)

without the blank space after -p. Its trivial, but without don't work.

Node.js global proxy setting

Unfortunately, it seems that proxy information must be set on each call to http.request. Node does not include a mechanism for global proxy settings.

The global-tunnel-ng module on NPM appears to handle this, however:

var globalTunnel = require('global-tunnel-ng');

globalTunnel.initialize({
  host: '10.0.0.10',
  port: 8080,
  proxyAuth: 'userId:password', // optional authentication
  sockets: 50 // optional pool size for each http and https
});

After the global settings are establish with a call to initialize, both http.request and the request library will use the proxy information.

The module can also use the http_proxy environment variable:

process.env.http_proxy = 'http://proxy.example.com:3129';
globalTunnel.initialize();

Calling a function on bootstrap modal open

Bootstrap modal exposes events. Listen for the the shown event like this

$('#my-modal').on('shown', function(){
  // code here
});

How do I get a list of all subdomains of a domain?

The hint (using axfr) only works if the NS you're querying (ns1.foo.bar in your example) is configured to allow AXFR requests from the IP you're using; this is unlikely, unless your IP is configured as a secondary for the domain in question.

Basically, there's no easy way to do it if you're not allowed to use axfr. This is intentional, so the only way around it would be via brute force (i.e. dig a.some_domain.com, dig b.some_domain.com, ...), which I can't recommend, as it could be viewed as a denial of service attack.

How to list all users in a Linux group?

Here's a very simple awk script that takes into account all common pitfalls listed in the other answers:

getent passwd | awk -F: -v group_name="wheel" '
  BEGIN {
    "getent group " group_name | getline groupline;
    if (!groupline) exit 1;
    split(groupline, groupdef, ":");
    guid = groupdef[3];
    split(groupdef[4], users, ",");
    for (k in users) print users[k]
  }
  $4 == guid {print $1}'

I'm using this with my ldap-enabled setup, runs on anything with standards-compliant getent & awk, including solaris 8+ and hpux.

Select multiple columns by labels in pandas

Just pick the columns you want directly....

df[['A','E','I','C']]

What does the shrink-to-fit viewport meta attribute do?

It is Safari specific, at least at time of writing, being introduced in Safari 9.0. From the "What's new in Safari?" documentation for Safari 9.0:

Viewport Changes

Viewport meta tags using "width=device-width" cause the page to scale down to fit content that overflows the viewport bounds. You can override this behavior by adding "shrink-to-fit=no" to your meta tag as shown below. The added value will prevent the page from scaling to fit the viewport.

<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">

In short, adding this to the viewport meta tag restores pre-Safari 9.0 behaviour.

Example

Here's a worked visual example which shows the difference upon loading the page in the two configurations.

The red section is the width of the viewport and the blue section is positioned outside the initial viewport (eg left: 100vw). Note how in the first example the page is zoomed to fit when shrink-to-fit=no is omitted (thus showing the out-of-viewport content) and the blue content remains off screen in the latter example.

The code for this example can be found at https://codepen.io/davidjb/pen/ENGqpv.

Without shrink-to-fit specified

Without shrink-to-fit=no

With shrink-to-fit=no

With shrink-to-fit=no

How do I check for equality using Spark Dataframe without SQL Query?

To get the negation, do this ...

df.filter(not( ..expression.. ))

eg

df.filter(not($"state" === "TX"))

CSS background-image - What is the correct usage?

Have a look at the respective sitepoint reference pages for background-image and URIs

  1. It does not have to be in quotes but can use them if you like. (I think IE5/Mac does not support single quotes).
  2. Both relative and absolute is possible; a relative path is relative to the path of the css file.

Dots in URL causes 404 with ASP.NET mvc and IIS

Add URL Rewrite rule to Web.config archive. You need to have the URL Rewrite module already installed in IIS. Use the following rewrite rule as inspiration for your own.

<?xml version="1.0" encoding="utf-8"?>
<configuration>

<system.webServer>
  <rewrite>
    <rules>
      <rule name="Add trailing slash for some URLs" stopProcessing="true">
        <match url="^(.*(\.).+[^\/])$" />
          <conditions>
              <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
              <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
          </conditions>
          <action type="Redirect" url="{R:1}/" />
      </rule>
    </rules>
    </rewrite>
</system.webServer>

</configuration> 

Way to ng-repeat defined number of times instead of repeating over array?

There are many ways to do this. I was really bothered at having the logic in my controller so I created a simple directive to solve the problem of repeating an element n-times.

Installation:

The directive can be installed using bower install angular-repeat-n

Example:

<span ng-repeat-n="4">{{$index}}</span

produces: 1234

It also works using a scope variable:

<span ng-repeat-n="repeatNum"></span>

Source:

Github

Waiting for another flutter command to release the startup lock

1. Stop all running dart instances

If you're using Android Studio save your work and close it. And open your terminal to kill running dart instances.

Linux:

killall -9 dart

Windows:

taskkill /F /IM dart.exe

2. Remove lockfile

You can find lockfile inside flutter installation directory.

<flutter folder>/bin/cache/lockfile

Cannot resolve method 'getSupportFragmentManager ( )' inside Fragment

getSupportFragmentManager() is not part of Fragment, so you cannot get it here that way. You can get it from parent Activity (so in onAttach() the earliest) using normal

activity.getSupportFragmentManager();

or you can try getChildFragmentManager(), which is in scope of Fragment, but requires API17+

What is the most efficient way to loop through dataframes with pandas?

For sure, the fastest way to iterate over a dataframe is to access the underlying numpy ndarray either via df.values (as you do) or by accessing each column separately df.column_name.values. Since you want to have access to the index too, you can use df.index.values for that.

index = df.index.values
column_of_interest1 = df.column_name1.values
...
column_of_interestk = df.column_namek.values

for i in range(df.shape[0]):
   index_value = index[i]
   ...
   column_value_k = column_of_interest_k[i]

Not pythonic? Sure. But fast.

If you want to squeeze more juice out of the loop you will want to look into cython. Cython will let you gain huge speedups (think 10x-100x). For maximum performance check memory views for cython.

Language Books/Tutorials for popular languages

One site I keep coming back to is http://www.javapractices.com. It covers most of the techniques that are discussed in the Effective Java book. Also another good site to check up coding examples (from basic to advanced) is http://www.java2s.com

Excel tab sheet names vs. Visual Basic sheet names

Actually "Sheet1" object / code name can be changed. In VBA, click on Sheet1 in Excel Objects list. In the properties window, you can change Sheet1 to say rng.

Then you can reference rng as a global object without having to create a variable first. So debug.print rng.name works just fine. No more Worksheets("rng").name.

Unlike the tab, the object name has same restrictions as other variables (i.e. no spaces).

Groovy executing shell commands

// a wrapper closure around executing a string                                  
// can take either a string or a list of strings (for arguments with spaces)    
// prints all output, complains and halts on error                              
def runCommand = { strList ->
  assert ( strList instanceof String ||
           ( strList instanceof List && strList.each{ it instanceof String } ) \
)
  def proc = strList.execute()
  proc.in.eachLine { line -> println line }
  proc.out.close()
  proc.waitFor()

  print "[INFO] ( "
  if(strList instanceof List) {
    strList.each { print "${it} " }
  } else {
    print strList
  }
  println " )"

  if (proc.exitValue()) {
    println "gave the following error: "
    println "[ERROR] ${proc.getErrorStream()}"
  }
  assert !proc.exitValue()
}

How to format current time using a yyyyMMddHHmmss format?

Time package in Golang has some methods that might be worth looking.

func (Time) Format

func (t Time) Format(layout string) string Format returns a textual representation of the time value formatted according to layout, which defines the format by showing how the reference time,

Mon Jan 2 15:04:05 -0700 MST 2006 would be displayed if it were the value; it serves as an example of the desired output. The same display rules will then be applied to the time value. Predefined layouts ANSIC, UnixDate, RFC3339 and others describe standard and convenient representations of the reference time. For more information about the formats and the definition of the reference time, see the documentation for ANSIC and the other constants defined by this package.

Source (http://golang.org/pkg/time/#Time.Format)

I also found an example of defining the layout (http://golang.org/src/pkg/time/example_test.go)

func ExampleTime_Format() {
        // layout shows by example how the reference time should be represented.
        const layout = "Jan 2, 2006 at 3:04pm (MST)"
        t := time.Date(2009, time.November, 10, 15, 0, 0, 0, time.Local)
        fmt.Println(t.Format(layout))
        fmt.Println(t.UTC().Format(layout))
        // Output:
    // Nov 10, 2009 at 3:00pm (PST)
        // Nov 10, 2009 at 11:00pm (UTC)
    }

Get the closest number out of an array

Works with unsorted arrays

While there were some good solutions posted here, JavaScript is a flexible language that gives us tools to solve a problem in many different ways. It all comes down to your style, of course. If your code is more functional, you'll find the reduce variation suitable, i.e.:

  arr.reduce(function (prev, curr) {
    return (Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev);
  });

However, some might find that hard to read, depending on their coding style. Therefore I propose a new way of solving the problem:

  var findClosest = function (x, arr) {
    var indexArr = arr.map(function(k) { return Math.abs(k - x) })
    var min = Math.min.apply(Math, indexArr)
    return arr[indexArr.indexOf(min)]
  }

  findClosest(80, [2, 42, 82, 122, 162, 202, 242, 282, 322, 362]) // Outputs 82

Contrary to other approaches finding the minimum value using Math.min.apply, this one doesn't require the input array arr to be sorted. We don't need to care about the indexes or sort it beforehand.

I'll explain the code line by line for clarity:

  1. arr.map(function(k) { return Math.abs(k - x) }) Creates a new array, essentially storing the absolute values of the given numbers (number in arr) minus the input number (x). We'll look for the smallest number next (which is also the closest to the input number)
  2. Math.min.apply(Math, indexArr) This is a legit way of finding the smallest number in the array we've just created before (nothing more to it)
  3. arr[indexArr.indexOf(min)] This is perhaps the most interesting part. We have found our smallest number, but we're not sure if we should add or subtract the initial number (x). That's because we used Math.abs() to find the difference. However, array.map creates (logically) a map of the input array, keeping the indexes in the same place. Therefore, to find out the closest number we just return the index of the found minimum in the given array indexArr.indexOf(min).

I've created a bin demonstrating it.

How does Trello access the user's clipboard?

I actually built a Chrome extension that does exactly this, and for all web pages. The source code is on GitHub.

I find three bugs with Trello's approach, which I know because I've faced them myself :)

The copy doesn't work in these scenarios:

  1. If you already have Ctrl pressed and then hover a link and hit C, the copy doesn't work.
  2. If your cursor is in some other text field in the page, the copy doesn't work.
  3. If your cursor is in the address bar, the copy doesn't work.

I solved #1 by always having a hidden span, rather than creating one when user hits Ctrl/Cmd.

I solved #2 by temporarily clearing the zero-length selection, saving the caret position, doing the copy and restoring the caret position.

I haven't found a fix for #3 yet :) (For information, check the open issue in my GitHub project).

static linking only some libraries

You could also use ld option -Bdynamic

gcc <objectfiles> -static -lstatic1 -lstatic2 -Wl,-Bdynamic -ldynamic1 -ldynamic2

All libraries after it (including system ones linked by gcc automatically) will be linked dynamically.

Find UNC path of a network drive?

The answer is a simple PowerShell one-liner:

Get-WmiObject Win32_NetworkConnection | ft "RemoteName","LocalName" -A

If you only want to pull the UNC for one particular drive, add a where statement:

Get-WmiObject Win32_NetworkConnection | where -Property 'LocalName' -eq 'Z:'  | ft "RemoteName","LocalName" -A

How to decode HTML entities using jQuery?

Suppose you have below String.

Our Deluxe cabins are warm, cozy &amp; comfortable

var str = $("p").text(); // get the text from <p> tag
$('p').html(str).text();  // Now,decode html entities in your variable i.e 

str and assign back to

tag.

that's it.

The input is not a valid Base-64 string as it contains a non-base 64 character

We can remove unnecessary string input in front of the value.

string convert = hdnImage.Replace("data:image/png;base64,", String.Empty);

byte[] image64 = Convert.FromBase64String(convert);

How can I call a WordPress shortcode within a template?

Try this:

<?php 
/*
Template Name: [contact us]

*/
get_header();
echo do_shortcode('[CONTACT-US-FORM]'); 
?>

How to know if other threads have finished?

Many things have been changed in last 6 years on multi-threading front.

Instead of using join() and lock API, you can use

1.ExecutorService invokeAll() API

Executes the given tasks, returning a list of Futures holding their status and results when all complete.

2.CountDownLatch

A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.

A CountDownLatch is initialized with a given count. The await methods block until the current count reaches zero due to invocations of the countDown() method, after which all waiting threads are released and any subsequent invocations of await return immediately. This is a one-shot phenomenon -- the count cannot be reset. If you need a version that resets the count, consider using a CyclicBarrier.

3.ForkJoinPool or newWorkStealingPool() in Executors is other way

4.Iterate through all Future tasks from submit on ExecutorService and check the status with blocking call get() on Future object

Have a look at related SE questions:

How to wait for a thread that spawns it's own thread?

Executors: How to synchronously wait until all tasks have finished if tasks are created recursively?

What's the difference between echo, print, and print_r in PHP?

echo

Not having return type

print

Have return type

print_r()

Outputs as formatted,

Complete list of reasons why a css file might not be working

I had the same problem, chinese characters were appearing in firefox when uploaded to web server, but not on localhost. I copied the contents of the css file to a new text file. All working now. Must have been a unicode/encoding error of some sort.

Change project name on Android Studio

You can change the name that is shown in the title bar in the file ".idea/.name".

Best way to check if MySQL results returned in PHP?

What is more logical then testing the TYPE of the result variable before processing? It is either of type 'boolean' or 'resource'. When you use a boolean for parameter with mysqli_num_rows, a warning will be generated because the function expects a resource.

$result = mysqli_query($dbs, $sql);

if(gettype($result)=='boolean'){ // test for boolean
    if($result){  // returned TRUE, e.g. in case of a DELETE sql  
        echo "SQL succeeded"; 
    } else { // returned FALSE
        echo "Error: " . mysqli_error($dbs);
    } 
} else { // must be a resource
    if(mysqli_num_rows($result)){

       // process the data    

    }
    mysqli_free_result($result);  
 }

Flutter plugin not installed error;. When running flutter doctor

For those who still have this error even if they have tried the solutions mentioned before, try this it works on windows 10/ macOS and linux (run in the command line):

  1. flutter channel dev
  2. flutter upgrade
  3. flutter config --android-studio-dir="C:\Program Files\Android\Android Studio"

jQuery.active function

This is a variable jQuery uses internally, but had no reason to hide, so it's there to use. Just a heads up, it becomes jquery.ajax.active next release. There's no documentation because it's exposed but not in the official API, lots of things are like this actually, like jQuery.cache (where all of jQuery.data() goes).

I'm guessing here by actual usage in the library, it seems to be there exclusively to support $.ajaxStart() and $.ajaxStop() (which I'll explain further), but they only care if it's 0 or not when a request starts or stops. But, since there's no reason to hide it, it's exposed to you can see the actual number of simultaneous AJAX requests currently going on.


When jQuery starts an AJAX request, this happens:

if ( s.global && ! jQuery.active++ ) {
  jQuery.event.trigger( "ajaxStart" );
}

This is what causes the $.ajaxStart() event to fire, the number of connections just went from 0 to 1 (jQuery.active++ isn't 0 after this one, and !0 == true), this means the first of the current simultaneous requests started. The same thing happens at the other end. When an AJAX request stops (because of a beforeSend abort via return false or an ajax call complete function runs):

if ( s.global && ! --jQuery.active ) {
  jQuery.event.trigger( "ajaxStop" );
}

This is what causes the $.ajaxStop() event to fire, the number of requests went down to 0, meaning the last simultaneous AJAX call finished. The other global AJAX handlers fire in there along the way as well.

How to find and restore a deleted file in a Git repository

If you’re insane, use git-bisect. Here's what to do:

git bisect start
git bisect bad
git bisect good <some commit where you know the file existed>

Now it's time to run the automated test. The shell command '[ -e foo.bar ]' will return 0 if foo.bar exists, and 1 otherwise. The "run" command of git-bisect will use binary search to automatically find the first commit where the test fails. It starts halfway through the range given (from good to bad) and cuts it in half based on the result of the specified test.

git bisect run '[ -e foo.bar ]'

Now you're at the commit which deleted it. From here, you can jump back to the future and use git-revert to undo the change,

git bisect reset
git revert <the offending commit>

or you could go back one commit and manually inspect the damage:

git checkout HEAD^
cp foo.bar /tmp
git bisect reset
cp /tmp/foo.bar .

Running Groovy script from the command line

It will work on Linux kernel 2.6.28 (confirmed on 4.9.x). It won't work on FreeBSD and other Unix flavors.

Your /usr/local/bin/groovy is a shell script wrapping the Java runtime running Groovy.

See the Interpreter Scripts section of EXECVE(2) and EXECVE(2).

jQuery: how to trigger anchor link's click event

You cannot open in a new tab programmatically, it's a browser functionality. You can open a link in an external window . Have a look here

TypeScript: Interfaces vs Types

When it comes to compilation speed, composed interfaces perform better than type intersections:

[...] interfaces create a single flat object type that detects property conflicts. This is in contrast with intersection types, where every constituent is checked before checking against the effective type. Type relationships between interfaces are also cached, as opposed to intersection types.

Source: https://github.com/microsoft/TypeScript/wiki/Performance#preferring-interfaces-over-intersections

Automated way to convert XML files to SQL database?

If there is XML file with 2 different tables then will:

LOAD XML LOCAL INFILE 'table1.xml' INTO TABLE table1 
LOAD XML LOCAL INFILE 'table1.xml' INTO TABLE table2

work

How to add text to JFrame?

The easiest way to add a text to a JFrame:

JFrame window = new JFrame("JFrame with text"); 
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLayout(new BorderLayout());
window.add(new JLabel("Hello World"), BorderLayout.CENTER);
window.pack();
window.setVisible(true);
window.setLocationRelativeTo(null);

Easiest way to ignore blank lines when reading a file in Python

You can use not:

for line in lines:
    if not line:
        continue

How can I submit a form using JavaScript?

It works perfectly in my case.

document.getElementById("form1").submit();

Also, you can use it in a function as below:

function formSubmit()
{
    document.getElementById("form1").submit();
}

In PHP how can you clear a WSDL cache?

Edit your php.ini file, search for soap.wsdl_cache_enabled and set the value to 0

[soap]
; Enables or disables WSDL caching feature.
; http://php.net/soap.wsdl-cache-enabled
soap.wsdl_cache_enabled=0

How do I apply a style to all children of an element

Instead of the * selector you can use the :not(selector) with the > selector and set something that definitely wont be a child.

Edit: I thought it would be faster but it turns out I was wrong. Disregard.

Example:

.container > :not(marquee){
        color:red;
    }


<div class="container">
    <p></p>
    <span></span>
<div>

PHP date yesterday

strtotime(), as in date("F j, Y", strtotime("yesterday"));

python NameError: name 'file' is not defined

To solve this error, it is enough to add from google.colab import files in your code!

How to get the Android Emulator's IP address?

Use this method you will be getting 100% correct ip address for your android emulator

To get the ip address of yoor emulator

Go to adb shell and type this command

adb shell
ifconfig eth0

enter image description here

After running this command I am getting

IP : 10.0.2.15

Mask : 255.255.255.0

Which works for me . I am also working for an networking application.

How to get WordPress post featured image URL

I had searched a lot and found nothing, until I got this:

<?php echo get_the_post_thumbnail_url( null, 'full' ); ?>

Which simply give you the full image URL without the entire <img> tag.

Hope that can help you.

MySQL JDBC Driver 5.1.33 - Time Zone Issue

It worked for me just by adding serverTimeZone=UTC on application.properties.
spring.datasource.url=jdbc:mysql://localhost/db?serverTimezone=UTC

Laravel 5 Failed opening required bootstrap/../vendor/autoload.php

Run composer install in your root project folder (or php composer.phar install).

Scroll Position of div with "overflow: auto"

You need to use the scrollTop property.

document.getElementById('box').scrollTop

Where are my postgres *.conf files?

On Mac OS X:

sudo find / -name postgresql.conf 

You can find other conf files by the following command:

sudo find / -name pg\*.conf

Note: See usage using man:

man find

Do I need a content-type header for HTTP GET requests?

The problem with not passing over the content-type on a GET message is that sure the content-type is irrelevant because the server side determines the content anyway. The problem that I have encountered is that there are now a lot of places that set up their webservices to be smart enough to pick up the content-type that you pass and return the response in the 'type' that you request. Eg. we are currently messaging with a place that defaults to JSON, however, they have set their webservice up so that if you pass a content-type of xml they will then return xml rather than their JSON default. Which I think going forward is a great idea

Why declare unicode by string in python?

As others have said, # coding: specifies the encoding the source file is saved in. Here are some examples to illustrate this:

A file saved on disk as cp437 (my console encoding), but no encoding declared

b = 'über'
u = u'über'
print b,repr(b)
print u,repr(u)

Output:

  File "C:\ex.py", line 1
SyntaxError: Non-ASCII character '\x81' in file C:\ex.py on line 1, but no
encoding declared; see http://www.python.org/peps/pep-0263.html for details

Output of file with # coding: cp437 added:

über '\x81ber'
über u'\xfcber'

At first, Python didn't know the encoding and complained about the non-ASCII character. Once it knew the encoding, the byte string got the bytes that were actually on disk. For the Unicode string, Python read \x81, knew that in cp437 that was a ü, and decoded it into the Unicode codepoint for ü which is U+00FC. When the byte string was printed, Python sent the hex value 81 to the console directly. When the Unicode string was printed, Python correctly detected my console encoding as cp437 and translated Unicode ü to the cp437 value for ü.

Here's what happens with a file declared and saved in UTF-8:

++ber '\xc3\xbcber'
über u'\xfcber'

In UTF-8, ü is encoded as the hex bytes C3 BC, so the byte string contains those bytes, but the Unicode string is identical to the first example. Python read the two bytes and decoded it correctly. Python printed the byte string incorrectly, because it sent the two UTF-8 bytes representing ü directly to my cp437 console.

Here the file is declared cp437, but saved in UTF-8:

++ber '\xc3\xbcber'
++ber u'\u251c\u255dber'

The byte string still got the bytes on disk (UTF-8 hex bytes C3 BC), but interpreted them as two cp437 characters instead of a single UTF-8-encoded character. Those two characters where translated to Unicode code points, and everything prints incorrectly.

Why is using the JavaScript eval function a bad idea?

I know this discussion is old, but I really like this approach by Google and wanted to share that feeling with others ;)

The other thing is that the better You get the more You try to understand and finally You just don't believe that something is good or bad just because someone said so :) This is a very inspirational video that helped me to think more by myself :) GOOD PRACTICES are good, but don't use them mindelessly :)

How can I use "." as the delimiter with String.split() in java

You might be interested in the StringTokenizer class. However, the java docs advise that you use the .split method as StringTokenizer is a legacy class.

How to set Bullet colors in UL/LI html lists via CSS without using any images or span tags

The easiest thing you can do is wrap the contents of the <li> in a <span> or equivalent then you can set the color independently.

Alternatively, you could make an image with the bullet color you want and set it with the list-style-image property.

How to force a script reload and re-execute?

Have you tried removing it from the DOM, then inserting it back again?

I just did, that doesn't work. However, creating a new script tag and copying the contents of the existing script tag, then adding it, works well.

See my example http://jsfiddle.net/mendesjuan/LPFYB/

var scriptTag = document.createElement('script');
scriptTag.innerText = "document.body.innerHTML += 'Here again ---<BR>';";
var head = document.getElementsByTagName('head')[0];
head.appendChild(scriptTag);

setInterval(function() {
    head.removeChild(scriptTag);
    var newScriptTag = document.createElement('script');
    newScriptTag.innerText = scriptTag.innerText;
    head.appendChild(newScriptTag);
    scriptTag = newScriptTag;    
}, 1000);

This won't work if you expect the script to change every time, which I believe is your case. You should follow Kelly's suggestion, just remove the old script tag (just to keep the DOM slim, it won't affect the outcome) and reinsert a new script tag with the same src, plus a cachebuster.

Hosting a Maven repository on github

The best solution I've been able to find consists of these steps:

  1. Create a branch called mvn-repo to host your maven artifacts.
  2. Use the github site-maven-plugin to push your artifacts to github.
  3. Configure maven to use your remote mvn-repo as a maven repository.

There are several benefits to using this approach:

  • Maven artifacts are kept separate from your source in a separate branch called mvn-repo, much like github pages are kept in a separate branch called gh-pages (if you use github pages)
  • Unlike some other proposed solutions, it doesn't conflict with your gh-pages if you're using them.
  • Ties in naturally with the deploy target so there are no new maven commands to learn. Just use mvn deploy as you normally would

The typical way you deploy artifacts to a remote maven repo is to use mvn deploy, so let's patch into that mechanism for this solution.

First, tell maven to deploy artifacts to a temporary staging location inside your target directory. Add this to your pom.xml:

<distributionManagement>
    <repository>
        <id>internal.repo</id>
        <name>Temporary Staging Repository</name>
        <url>file://${project.build.directory}/mvn-repo</url>
    </repository>
</distributionManagement>

<plugins>
    <plugin>
        <artifactId>maven-deploy-plugin</artifactId>
        <version>2.8.1</version>
        <configuration>
            <altDeploymentRepository>internal.repo::default::file://${project.build.directory}/mvn-repo</altDeploymentRepository>
        </configuration>
    </plugin>
</plugins>

Now try running mvn clean deploy. You'll see that it deployed your maven repository to target/mvn-repo. The next step is to get it to upload that directory to GitHub.

Add your authentication information to ~/.m2/settings.xml so that the github site-maven-plugin can push to GitHub:

<!-- NOTE: MAKE SURE THAT settings.xml IS NOT WORLD READABLE! -->
<settings>
  <servers>
    <server>
      <id>github</id>
      <username>YOUR-USERNAME</username>
      <password>YOUR-PASSWORD</password>
    </server>
  </servers>
</settings>

(As noted, please make sure to chmod 700 settings.xml to ensure no one can read your password in the file. If someone knows how to make site-maven-plugin prompt for a password instead of requiring it in a config file, let me know.)

Then tell the GitHub site-maven-plugin about the new server you just configured by adding the following to your pom:

<properties>
    <!-- github server corresponds to entry in ~/.m2/settings.xml -->
    <github.global.server>github</github.global.server>
</properties>

Finally, configure the site-maven-plugin to upload from your temporary staging repo to your mvn-repo branch on Github:

<build>
    <plugins>
        <plugin>
            <groupId>com.github.github</groupId>
            <artifactId>site-maven-plugin</artifactId>
            <version>0.11</version>
            <configuration>
                <message>Maven artifacts for ${project.version}</message>  <!-- git commit message -->
                <noJekyll>true</noJekyll>                                  <!-- disable webpage processing -->
                <outputDirectory>${project.build.directory}/mvn-repo</outputDirectory> <!-- matches distribution management repository url above -->
                <branch>refs/heads/mvn-repo</branch>                       <!-- remote branch name -->
                <includes><include>**/*</include></includes>
                <repositoryName>YOUR-REPOSITORY-NAME</repositoryName>      <!-- github repo name -->
                <repositoryOwner>YOUR-GITHUB-USERNAME</repositoryOwner>    <!-- github username  -->
            </configuration>
            <executions>
              <!-- run site-maven-plugin's 'site' target as part of the build's normal 'deploy' phase -->
              <execution>
                <goals>
                  <goal>site</goal>
                </goals>
                <phase>deploy</phase>
              </execution>
            </executions>
        </plugin>
    </plugins>
</build>

The mvn-repo branch does not need to exist, it will be created for you.

Now run mvn clean deploy again. You should see maven-deploy-plugin "upload" the files to your local staging repository in the target directory, then site-maven-plugin committing those files and pushing them to the server.

[INFO] Scanning for projects...
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building DaoCore 1.3-SNAPSHOT
[INFO] ------------------------------------------------------------------------
...
[INFO] --- maven-deploy-plugin:2.5:deploy (default-deploy) @ greendao ---
Uploaded: file:///Users/mike/Projects/greendao-emmby/DaoCore/target/mvn-repo/com/greendao-orm/greendao/1.3-SNAPSHOT/greendao-1.3-20121223.182256-3.jar (77 KB at 2936.9 KB/sec)
Uploaded: file:///Users/mike/Projects/greendao-emmby/DaoCore/target/mvn-repo/com/greendao-orm/greendao/1.3-SNAPSHOT/greendao-1.3-20121223.182256-3.pom (3 KB at 1402.3 KB/sec)
Uploaded: file:///Users/mike/Projects/greendao-emmby/DaoCore/target/mvn-repo/com/greendao-orm/greendao/1.3-SNAPSHOT/maven-metadata.xml (768 B at 150.0 KB/sec)
Uploaded: file:///Users/mike/Projects/greendao-emmby/DaoCore/target/mvn-repo/com/greendao-orm/greendao/maven-metadata.xml (282 B at 91.8 KB/sec)
[INFO] 
[INFO] --- site-maven-plugin:0.7:site (default) @ greendao ---
[INFO] Creating 24 blobs
[INFO] Creating tree with 25 blob entries
[INFO] Creating commit with SHA-1: 0b8444e487a8acf9caabe7ec18a4e9cff4964809
[INFO] Updating reference refs/heads/mvn-repo from ab7afb9a228bf33d9e04db39d178f96a7a225593 to 0b8444e487a8acf9caabe7ec18a4e9cff4964809
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 8.595s
[INFO] Finished at: Sun Dec 23 11:23:03 MST 2012
[INFO] Final Memory: 9M/81M
[INFO] ------------------------------------------------------------------------

Visit github.com in your browser, select the mvn-repo branch, and verify that all your binaries are now there.

enter image description here

Congratulations!

You can now deploy your maven artifacts to a poor man's public repo simply by running mvn clean deploy.

There's one more step you'll want to take, which is to configure any poms that depend on your pom to know where your repository is. Add the following snippet to any project's pom that depends on your project:

<repositories>
    <repository>
        <id>YOUR-PROJECT-NAME-mvn-repo</id>
        <url>https://github.com/YOUR-USERNAME/YOUR-PROJECT-NAME/raw/mvn-repo/</url>
        <snapshots>
            <enabled>true</enabled>
            <updatePolicy>always</updatePolicy>
        </snapshots>
    </repository>
</repositories>

Now any project that requires your jar files will automatically download them from your github maven repository.

Edit: to avoid the problem mentioned in the comments ('Error creating commit: Invalid request. For 'properties/name', nil is not a string.'), make sure you state a name in your profile on github.

I can't access http://localhost/phpmyadmin/

sudo apt-get -y --reinstall install phpmyadmin;
sudo service apache2 restart;

Hope this helps.

How to get the currently logged in user's user id in Django?

FOR WITHIN TEMPLATES

This is how I usually get current logged in user and their id in my templates.

<p>Your Username is : {{user}} </p>
<p>Your User Id is  : {{user.id}} </p>

Can anyone explain what JSONP is, in layman terms?

Say you had some URL that gave you JSON data like:

{'field': 'value'}

...and you had a similar URL except it used JSONP, to which you passed the callback function name 'myCallback' (usually done by giving it a query parameter called 'callback', e.g. http://example.com/dataSource?callback=myCallback). Then it would return:

myCallback({'field':'value'})

...which is not just an object, but is actually code that can be executed. So if you define a function elsewhere in your page called myFunction and execute this script, it will be called with the data from the URL.

The cool thing about this is: you can create a script tag and use your URL (complete with callback parameter) as the src attribute, and the browser will run it. That means you can get around the 'same-origin' security policy (because browsers allow you to run script tags from sources other than the domain of the page).

This is what jQuery does when you make an ajax request (using .ajax with 'jsonp' as the value for the dataType property). E.g.

$.ajax({
  url: 'http://example.com/datasource',
  dataType: 'jsonp',
  success: function(data) {
    // your code to handle data here
  }
});

Here, jQuery takes care of the callback function name and query parameter - making the API identical to other ajax calls. But unlike other types of ajax requests, as mentioned, you're not restricted to getting data from the same origin as your page.

Usages of doThrow() doAnswer() doNothing() and doReturn() in mockito

doThrow : Basically used when you want to throw an exception when a method is being called within a mock object.

public void validateEntity(final Object object){}
Mockito.doThrow(IllegalArgumentException.class)
.when(validationService).validateEntity(Matchers.any(AnyObjectClass.class));

doReturn : Used when you want to send back a return value when a method is executed.

public Socket getCosmosSocket() throws IOException {}
Mockito.doReturn(cosmosSocket).when(cosmosServiceImpl).getCosmosSocket();

doAnswer: Sometimes you need to do some actions with the arguments that are passed to the method, for example, add some values, make some calculations or even modify them doAnswer gives you the Answer interface that being executed in the moment that method is called, this interface allows you to interact with the parameters via the InvocationOnMock argument. Also, the return value of answer method will be the return value of the mocked method.

public ReturnValueObject quickChange(Object1 object);
Mockito.doAnswer(new Answer<ReturnValueObject>() {

        @Override
        public ReturnValueObject answer(final InvocationOnMock invocation) throws Throwable {

            final Object1 originalArgument = (invocation.getArguments())[0];
            final ReturnValueObject returnedValue = new ReturnValueObject();
            returnedValue.setCost(new Cost());

            return returnedValue ;
        }
}).when(priceChangeRequestService).quickCharge(Matchers.any(Object1.class));

doNothing: Is the easiest of the list, basically it tells Mockito to do nothing when a method in a mock object is called. Sometimes used in void return methods or method that does not have side effects, or are not related to the unit testing you are doing.

public void updateRequestActionAndApproval(final List<Object1> cmItems);

Mockito.doNothing().when(pagLogService).updateRequestActionAndApproval(
                Matchers.any(Object1.class));

JavaScript closures vs. anonymous functions

According to the closure definition:

A "closure" is an expression (typically a function) that can have free variables together with an environment that binds those variables (that "closes" the expression).

You are using closure if you define a function which use a variable which is defined outside of the function. (we call the variable a free variable).
They all use closure(even in the 1st example).

Is there a Google Keep API?

I have been waiting to see if Google would open a Keep API. When I discovered Google Tasks, and saw that it had an Android app, web app, and API, I converted over to Tasks. This may not directly answer your question, but it is my solution to the Keep API problem.

Tasks doesn't have a reminder alarm exactly like Keep. I can live without that if I also connect with the Calendar API.

https://developers.google.com/google-apps/tasks/

npm ERR! registry error parsing json - While trying to install Cordova for Ionic Framework in Windows 8

In my case artifactory was down. npm install command is throwing below error.

npm ERR! registry error parsing json

Regex to check with starts with http://, https:// or ftp://

If you wanna do it in case-insensitive way, this is better:

System.out.println(test.matches("^(?i)(https?|ftp)://.*$")); 

When is del useful in Python?

Just another thinking.

When debugging http applications in framework like Django, the call stack full of useless and messed up variables previously used, especially when it's a very long list, could be very painful for developers. so, at this point, namespace controlling could be useful.

Setting the selected value on a Django forms.ChoiceField

To be sure I need to see how you're rendering the form. The initial value is only used in a unbound form, if it's bound and a value for that field is not included nothing will be selected.

android asynctask sending callbacks to ui

I felt the below approach is very easy.

I have declared an interface for callback

public interface AsyncResponse {
    void processFinish(Object output);
}

Then created asynchronous Task for responding all type of parallel requests

 public class MyAsyncTask extends AsyncTask<Object, Object, Object> {

    public AsyncResponse delegate = null;//Call back interface

    public MyAsyncTask(AsyncResponse asyncResponse) {
        delegate = asyncResponse;//Assigning call back interfacethrough constructor
    }

    @Override
    protected Object doInBackground(Object... params) {

    //My Background tasks are written here

      return {resutl Object}

    }

    @Override
    protected void onPostExecute(Object result) {
        delegate.processFinish(result);
    }

}

Then Called the asynchronous task when clicking a button in activity Class.

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {

        Button mbtnPress = (Button) findViewById(R.id.btnPress);

        mbtnPress.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                MyAsyncTask asyncTask =new MyAsyncTask(new AsyncResponse() {

                    @Override
                    public void processFinish(Object output) {
                        Log.d("Response From Asynchronous task:", (String) output);          
                        mbtnPress.setText((String) output);
                    }
                });
                asyncTask.execute(new Object[] { "Youe request to aynchronous task class is giving here.." });

            }
        });
    }
}

Thanks

What is the "Temporary ASP.NET Files" folder for?

Thats where asp.net puts dynamically compiled assemblies.

Rails 3 check if attribute changed

For rails 5.1+ callbacks

As of Ruby on Rails 5.1, the attribute_changed? and attribute_was ActiveRecord methods will be deprecated

Use saved_change_to_attribute? instead of attribute_changed?

@user.saved_change_to_street1? # => true/false

More examples here

How can I check if a date is the same day as datetime.today()?

If you want to just compare dates,

yourdatetime.date() < datetime.today().date()

Or, obviously,

yourdatetime.date() == datetime.today().date()

If you want to check that they're the same date.

The documentation is usually helpful. It is also usually the first google result for python thing_i_have_a_question_about. Unless your question is about a function/module named "snake".

Basically, the datetime module has three types for storing a point in time:

  • date for year, month, day of month
  • time for hours, minutes, seconds, microseconds, time zone info
  • datetime combines date and time. It has the methods date() and time() to get the corresponding date and time objects, and there's a handy combine function to combine date and time into a datetime.

jQuery count child elements

$('#selected ul').children().length;

or even better

 $('#selected li').length;

Reading in a JSON File Using Swift

Based on Abhishek's answer, for iOS 8 this would be:

let masterDataUrl: NSURL = NSBundle.mainBundle().URLForResource("masterdata", withExtension: "json")!
let jsonData: NSData = NSData(contentsOfURL: masterDataUrl)!
let jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: nil) as! NSDictionary
var persons : NSArray = jsonResult["person"] as! NSArray

In Subversion can I be a user other than my login name?

I believe you can set the SVN_USER environment variable to change your SVN username.

Python Matplotlib figure title overlaps axes label when using twiny

Forget using plt.title and place the text directly with plt.text. An over-exaggerated example is given below:

import pylab as plt

fig = plt.figure(figsize=(5,10))

figure_title = "Normal title"
ax1  = plt.subplot(1,2,1)

plt.title(figure_title, fontsize = 20)
plt.plot([1,2,3],[1,4,9])

figure_title = "Raised title"
ax2  = plt.subplot(1,2,2)

plt.text(0.5, 1.08, figure_title,
         horizontalalignment='center',
         fontsize=20,
         transform = ax2.transAxes)
plt.plot([1,2,3],[1,4,9])

plt.show()

enter image description here

Is there a Subversion command to reset the working copy?

To revert tracked files

svn revert . -R

To clean untracked files

svn status | rm -rf $(awk '/^?/{$1 = ""; print $0}')

The -rf may/should look scary at first, but once understood it will not be for these reasons:

  1. Only wholly-untracked directories will match the pattern passed to rm
  2. The -rf is required, else these directories will not be removed

To revert then clean (the OP question)

svn revert . -R && svn status | rm -rf $(awk '/^?/{$1 = ""; print $0}')

For consistent ease of use

Add permanent alias to your .bash_aliases

alias svn.HardReset='read -p "destroy all local changes?[y/N]" && [[ $REPLY =~ ^[yY] ]] && svn revert . -R && rm -rf $(awk -f <(echo "/^?/{print \$2}") <(svn status) ;)'

Displaying the Error Messages in Laravel after being Redirected from controller

Laravel 4

When the validation fails return back with the validation errors.

if($validator->fails()) {
    return Redirect::back()->withErrors($validator);
}

You can catch the error on your view using

@if($errors->any())
    {{ implode('', $errors->all('<div>:message</div>')) }}
@endif

UPDATE

To display error under each field you can do like this.

<input type="text" name="firstname">
@if($errors->has('firstname'))
    <div class="error">{{ $errors->first('firstname') }}</div>
@endif

For better display style with css.

You can refer to the docs here.

UPDATE 2

To display all errors at once

@if($errors->any())
    {!! implode('', $errors->all('<div>:message</div>')) !!}
@endif

To display error under each field.

@error('firstname')
    <div class="error">{{ $message }}</div>
@enderror

How do I read configuration settings from Symfony2 config.yml?

While the solution of moving the contact_email to parameters.yml is easy, as proposed in other answers, that can easily clutter your parameters file if you deal with many bundles or if you deal with nested blocks of configuration.

  • First, I'll answer strictly the question.
  • Later, I'll give an approach for getting those configs from services without ever passing via a common space as parameters.

FIRST APPROACH: Separated config block, getting it as a parameter

With an extension (more on extensions here) you can keep this easily "separated" into different blocks in the config.yml and then inject that as a parameter gettable from the controller.

Inside your Extension class inside the DependencyInjection directory write this:

class MyNiceProjectExtension extends Extension
{
    public function load( array $configs, ContainerBuilder $container )
    {
        // The next 2 lines are pretty common to all Extension templates.
        $configuration = new Configuration();
        $processedConfig = $this->processConfiguration( $configuration, $configs );

        // This is the KEY TO YOUR ANSWER
        $container->setParameter( 'my_nice_project.contact_email', $processedConfig[ 'contact_email' ] );

        // Other stuff like loading services.yml
    }

Then in your config.yml, config_dev.yml and so you can set

my_nice_project:
    contact_email: [email protected]

To be able to process that config.yml inside your MyNiceBundleExtension you'll also need a Configuration class in the same namespace:

class Configuration implements ConfigurationInterface
{
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root( 'my_nice_project' );

        $rootNode->children()->scalarNode( 'contact_email' )->end();

        return $treeBuilder;
    }
}

Then you can get the config from your controller, as you desired in your original question, but keeping the parameters.yml clean, and setting it in the config.yml in separated sections:

$recipient = $this->container->getParameter( 'my_nice_project.contact_email' );

SECOND APPROACH: Separated config block, injecting the config into a service

For readers looking for something similar but for getting the config from a service, there is even a nicer way that never clutters the "paramaters" common space and does even not need the container to be passed to the service (passing the whole container is practice to avoid).

This trick above still "injects" into the parameters space your config.

Nevertheless, after loading your definition of the service, you could add a method-call like for example setConfig() that injects that block only to the service.

For example, in the Extension class:

class MyNiceProjectExtension extends Extension
{
    public function load( array $configs, ContainerBuilder $container )
    {
        $configuration = new Configuration();
        $processedConfig = $this->processConfiguration( $configuration, $configs );

        // Do not add a paramater now, just continue reading the services.
        $loader = new YamlFileLoader( $container, new FileLocator( __DIR__ . '/../Resources/config' ) );
        $loader->load( 'services.yml' );

        // Once the services definition are read, get your service and add a method call to setConfig()
        $sillyServiceDefintion = $container->getDefinition( 'my.niceproject.sillymanager' );
        $sillyServiceDefintion->addMethodCall( 'setConfig', array( $processedConfig[ 'contact_email' ] ) );
    }
}

Then in your services.yml you define your service as usual, without any absolute change:

services:
    my.niceproject.sillymanager:
        class: My\NiceProjectBundle\Model\SillyManager
        arguments: []

And then in your SillyManager class, just add the method:

class SillyManager
{
    private $contact_email;

    public function setConfig( $newConfigContactEmail )
    {
        $this->contact_email = $newConfigContactEmail;
    }
}

Note that this also works for arrays instead of scalar values! Imagine that you configure a rabbit queue and need host, user and password:

my_nice_project:
    amqp:
        host: 192.168.33.55
        user: guest
        password: guest

Of course you need to change your Tree, but then you can do:

$sillyServiceDefintion->addMethodCall( 'setConfig', array( $processedConfig[ 'amqp' ] ) );

and then in the service do:

class SillyManager
{
    private $host;
    private $user;
    private $password;

    public function setConfig( $config )
    {
        $this->host = $config[ 'host' ];
        $this->user = $config[ 'user' ];
        $this->password = $config[ 'password' ];
    }
}

Hope this helps!

Error - replacement has [x] rows, data has [y]

You could use cut

 df$valueBin <- cut(df$value, c(-Inf, 250, 500, 1000, 2000, Inf), 
    labels=c('<=250', '250-500', '500-1,000', '1,000-2,000', '>2,000'))

data

 set.seed(24)
 df <- data.frame(value= sample(0:2500, 100, replace=TRUE))

What is the difference between tinyint, smallint, mediumint, bigint and int in MySQL?

Data type Range Storage

bigint  -2^63 (-9,223,372,036,854,775,808) to 2^63-1 (9,223,372,036,854,775,807)    8 Bytes
int -2^31 (-2,147,483,648) to 2^31-1 (2,147,483,647)    4 Bytes
smallint    -2^15 (-32,768) to 2^15-1 (32,767)  2 Bytes
tinyint 0 to 255    1 Byte

Example

The following example creates a table using the bigint, int, smallint, and tinyint data types. Values are inserted into each column and returned in the SELECT statement.

CREATE TABLE dbo.MyTable
(
  MyBigIntColumn bigint
 ,MyIntColumn  int
 ,MySmallIntColumn smallint
 ,MyTinyIntColumn tinyint
);

GO

INSERT INTO dbo.MyTable VALUES (9223372036854775807, 214483647,32767,255);
 GO
SELECT MyBigIntColumn, MyIntColumn, MySmallIntColumn, MyTinyIntColumn
FROM dbo.MyTable;

PHPExcel How to apply styles and set cell width and cell height to cell generated dynamically

You can use

$objWorksheet->getActiveSheet()->getRowDimension('1')->setRowHeight(40);
$objWorksheet->getActiveSheet()->getColumnDimension('A')->setWidth(100);

or define auto-size:

$objWorksheet->getRowDimension('1')->setRowHeight(-1);

How to populate HTML dropdown list with values from database

Below code is nice.. It was given by somebody else named aaronbd in this forum

<?php

$conn = new mysqli('localhost', 'username', 'password', 'database') 
or die ('Cannot connect to db');

    $result = $conn->query("select id, name from table");

    echo "<html>";
    echo "<body>";
    echo "<select name='id'>";

    while ($row = $result->fetch_assoc()) {

                  unset($id, $name);
                  $id = $row['id'];
                  $name = $row['name']; 
                  echo '<option value="'.$id.'">'.$name.'</option>';

}

    echo "</select>";
    echo "</body>";
    echo "</html>";
?> 

How do I do multiple CASE WHEN conditions using SQL Server 2008?

There are two formats of case expression. You can do CASE with many WHEN as;

CASE  WHEN Col1 = 1 OR Col3 = 1  THEN 1 
      WHEN Col1 = 2 THEN 2
      ...
      ELSE 0 END as Qty

Or a Simple CASE expression

CASE Col1 WHEN 1 THEN 11 WHEN 2 THEN 21 ELSE 13 END

Or CASE within CASE as;

CASE  WHEN Col1 < 2 THEN  
                    CASE Col2 WHEN 'X' THEN 10 ELSE 11 END
      WHEN Col1 = 2 THEN 2
      ...
      ELSE 0 END as Qty

How to decrypt hash stored by bcrypt

You're HASHING, not ENCRYPTING!

What's the difference?

The difference is that hashing is a one way function, where encryption is a two-way function.

So, how do you ascertain that the password is right?

Therefore, when a user submits a password, you don't decrypt your stored hash, instead you perform the same bcrypt operation on the user input and compare the hashes. If they're identical, you accept the authentication.

Should you hash or encrypt passwords?

What you're doing now -- hashing the passwords -- is correct. If you were to simply encrypt passwords, a breach of security of your application could allow a malicious user to trivially learn all user passwords. If you hash (or better, salt and hash) passwords, the user needs to crack passwords (which is computationally expensive on bcrypt) to gain that knowledge.

As your users probably use their passwords in more than one place, this will help to protect them.

Cross compile Go on OSX?

Thanks to kind and patient help from golang-nuts, recipe is the following:

1) One needs to compile Go compiler for different target platforms and architectures. This is done from src folder in go installation. In my case Go installation is located in /usr/local/go thus to compile a compiler you need to issue make utility. Before doing this you need to know some caveats.

There is an issue about CGO library when cross compiling so it is needed to disable CGO library.

Compiling is done by changing location to source dir, since compiling has to be done in that folder

cd /usr/local/go/src

then compile the Go compiler:

sudo GOOS=windows GOARCH=386 CGO_ENABLED=0 ./make.bash --no-clean

You need to repeat this step for each OS and Architecture you wish to cross compile by changing the GOOS and GOARCH parameters.

If you are working in user mode as I do, sudo is needed because Go compiler is in the system dir. Otherwise you need to be logged in as super user. On Mac you may need to enable/configure SU access (it is not available by default), but if you have managed to install Go you possibly already have root access.

2) Once you have all cross compilers built, you can happily cross compile your application by using the following settings for example:

GOOS=windows GOARCH=386 go build -o appname.exe appname.go

GOOS=linux GOARCH=386 CGO_ENABLED=0 go build -o appname.linux appname.go

Change the GOOS and GOARCH to targets you wish to build.

If you encounter problems with CGO include CGO_ENABLED=0 in the command line. Also note that binaries for linux and mac have no extension so you may add extension for the sake of having different files. -o switch instructs Go to make output file similar to old compilers for c/c++ thus above used appname.linux can be any other extension.

Align div with fixed position on the right side

With position fixed, you need to provide values to set where the div will be placed, since it's a fixed position.

Something like....

.test
{
   position:fixed;
   left:100px;
   top:150px;
}

Fixed - Generates an absolutely positioned element, positioned relative to the browser window. The element's position is specified with the "left", "top", "right", and "bottom" properties

More on position here.

Vertically align an image inside a div with responsive height

With flexbox this is easy:

FIDDLE

Just add the following to the image container:

.img-container {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    display: flex; /* add */
    justify-content: center; /* add to align horizontal */
    align-items: center; /* add to align vertical */
}

subsetting a Python DataFrame

I've found that you can use any subset condition for a given column by wrapping it in []. For instance, you have a df with columns ['Product','Time', 'Year', 'Color']

And let's say you want to include products made before 2014. You could write,

df[df['Year'] < 2014]

To return all the rows where this is the case. You can add different conditions.

df[df['Year'] < 2014][df['Color' == 'Red']

Then just choose the columns you want as directed above. For instance, the product color and key for the df above,

df[df['Year'] < 2014][df['Color'] == 'Red'][['Product','Color']]

What is the difference between Dim, Global, Public, and Private as Modular Field Access Modifiers?

Dim and Private work the same, though the common convention is to use Private at the module level, and Dim at the Sub/Function level. Public and Global are nearly identical in their function, however Global can only be used in standard modules, whereas Public can be used in all contexts (modules, classes, controls, forms etc.) Global comes from older versions of VB and was likely kept for backwards compatibility, but has been wholly superseded by Public.

npm - EPERM: operation not permitted on Windows

After trying everything and nothing works. Moving my working project folder to diffrent destination worked for me.

Breaking up long strings on multiple lines in Ruby without stripping newlines

I had this problem when I try to write a very long url, the following works.

image_url = %w(
    http://minio.127.0.0.1.xip.io:9000/
    bucket29/docs/b7cfab0e-0119-452c-b262-1b78e3fccf38/
    28ed3774-b234-4de2-9a11-7d657707f79c?
    X-Amz-Algorithm=AWS4-HMAC-SHA256&
    X-Amz-Credential=ABABABABABABABABA
    %2Fus-east-1%2Fs3%2Faws4_request&
    X-Amz-Date=20170702T000940Z&
    X-Amz-Expires=3600&X-Amz-SignedHeaders=host&
    X-Amz-Signature=ABABABABABABABABABABAB
    ABABABABABABABABABABABABABABABABABABA
).join

Note, there must not be any newlines, white spaces when the url string is formed. If you want newlines, then use HEREDOC.

Here you have indentation for readability, ease of modification, without the fiddly quotes and backslashes on every line. The cost of joining the strings should be negligible.

PHP Constants Containing Arrays?

Starting with PHP 5.6, you can define constant arrays using const keyword like below

const DEFAULT_ROLES = ['test', 'development', 'team'];

and different elements can be accessed as below:

echo DEFAULT_ROLES[1]; 
....

Starting with PHP 7, constant arrays can be defined using define as below:

define('DEFAULT_ROLES', [
    'test',
    'development',
    'team'
]);

and different elements can be accessed same way as before.

How to debug Angular JavaScript Code

Since the add-ons don't work anymore, the most helpful set of tools I've found is using Visual Studio/IE because you can set breakpoints in your JS and inspect your data that way. Of course Chrome and Firefox have much better dev tools in general. Also, good ol' console.log() has been super helpful!

How to place two forms on the same page?

Well you can have each form go to to a different page. (which is preferable)

Or have a different value for the a certain input and base posts on that:

switch($_POST['submit']) {
    case 'login': 
    //...
    break;
    case 'register':
    //...
    break;
}

Convert DateTime to a specified Format

Easy peasy:

var date = DateTime.Parse("14/11/2011"); // may need some Culture help here
Console.Write(date.ToString("yyyy-MM-dd"));

Take a look at DateTime.ToString() method, Custom Date and Time Format Strings and Standard Date and Time Format Strings

string customFormattedDateTimeString = DateTime.Now.ToString("yyyy-MM-dd");

Forking / Multi-Threaded Processes | Bash

Let me try example

for x in 1 2 3 ; do { echo a $x ; sleep 1 ; echo b $x ; } &  done ; sleep 10

And use jobs to see what's running.

Android Material: Status bar color won't change

The status bar is a system window owned by the operating system. On pre-5.0 Android devices, applications do not have permission to alter its color, so this is not something that the AppCompat library can support for older platform versions. The best AppCompat can do is provide support for coloring the ActionBar and other common UI widgets within the application.

Getting All Variables In Scope

I made a fiddle implementing (essentially) above ideas outlined by iman. Here is how it looks when you mouse over the second ipsum in return ipsum*ipsum - ...

enter image description here

The variables which are in scope are highlighted where they are declared (with different colors for different scopes). The lorem with red border is a shadowed variable (not in scope, but be in scope if the other lorem further down the tree wouldn't be there.)

I'm using esprima library to parse the JavaScript, and estraverse, escodegen, escope (utility libraries on top of esprima.) The 'heavy lifting' is done all by those libraries (the most complex being esprima itself, of course.)

How it works

ast = esprima.parse(sourceString, {range: true, sourceType: 'script'});

makes the abstract syntax tree. Then,

analysis = escope.analyze(ast);

generates a complex data structure encapsulating information about all the scopes in the program. The rest is gathering together the information encoded in that analysis object (and the abstract syntax tree itself), and making an interactive coloring scheme out of it.

So the correct answer is actually not "no", but "yes, but". The "but" being a big one: you basically have to rewrite significant parts of the chrome browser (and it's devtools) in JavaScript. JavaScript is a Turing complete language, so of course that is possible, in principle. What is impossible is doing the whole thing without using the entirety of your source code (as a string) and then doing highly complex stuff with that.

Android: long click on a button -> perform actions

Change return false; to return true; in longClickListener

You long click the button, if it returns true then it does the work. If it returns false then it does it's work and also calls the short click and then the onClick also works.

Replacing NULL and empty string within Select statement

Try this

COALESCE(NULLIF(Address.COUNTRY,''), 'United States')

Android : Check whether the phone is dual SIM

I have a Samsung Duos device with Android 4.4.4 and the method suggested by Seetha in the accepted answer (i.e. call getDeviceIdDs) does not work for me, as the method does not exist. I was able to recover all the information I needed by calling method "getDefault(int slotID)", as shown below:

public static void samsungTwoSims(Context context) {
    TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

    try{

        Class<?> telephonyClass = Class.forName(telephony.getClass().getName());

        Class<?>[] parameter = new Class[1];
        parameter[0] = int.class;
        Method getFirstMethod = telephonyClass.getMethod("getDefault", parameter);

        Log.d(TAG, getFirstMethod.toString());

        Object[] obParameter = new Object[1];
        obParameter[0] = 0;
        TelephonyManager first = (TelephonyManager) getFirstMethod.invoke(null, obParameter);

        Log.d(TAG, "Device Id: " + first.getDeviceId() + ", device status: " + first.getSimState() + ", operator: " + first.getNetworkOperator() + "/" + first.getNetworkOperatorName());

        obParameter[0] = 1;
        TelephonyManager second = (TelephonyManager) getFirstMethod.invoke(null, obParameter);

        Log.d(TAG, "Device Id: " + second.getDeviceId() + ", device status: " + second.getSimState()+ ", operator: " + second.getNetworkOperator() + "/" + second.getNetworkOperatorName());
    } catch (Exception e) {
        e.printStackTrace();
    }   
}

Also, I rewrote the code that iteratively tests for methods to recover this information so that it uses an array of method names instead of a sequence of try/catch. For instance, to determine if we have two active SIMs we could do:

private static String[] simStatusMethodNames = {"getSimStateGemini", "getSimState"};


public static boolean hasTwoActiveSims(Context context) {
    boolean first = false, second = false;

    for (String methodName: simStatusMethodNames) {
        // try with sim 0 first
        try {
            first = getSIMStateBySlot(context, methodName, 0);
            // no exception thrown, means method exists
            second = getSIMStateBySlot(context, methodName, 1);
           return first && second;
        } catch (GeminiMethodNotFoundException e) {
            // method does not exist, nothing to do but test the next
        }
    }
    return false;
}

This way, if a new method name is suggested for some device, you can simply add it to the array and it should work.

PHP - Get bool to echo false when false

Try converting your boolean to an integer?

 echo (int)$bool_val;

How to create an empty matrix in R?

The default for matrix is to have 1 column. To explicitly have 0 columns, you need to write

matrix(, nrow = 15, ncol = 0)

A better way would be to preallocate the entire matrix and then fill it in

mat <- matrix(, nrow = 15, ncol = n.columns)
for(column in 1:n.columns){
  mat[, column] <- vector
}

What is Turing Complete?

Here is the simplest explanation

Alan Turing created a machine that can take a program, run that program, and show some result. But then he had to create different machines for different programs. So he created "Universal Turing Machine" that can take ANY program and run it.

Programming languages are similar to those machines (although virtual). They take programs and run them. Now, a programing language is called "Turing complete", if it can run any program (irrespective of the language) that a Turing machine can run given enough time and memory.

For example: Let's say there is a program that takes 10 numbers and adds them. A Turing machine can easily run this program. But now imagine that for some reason your programming language can't perform the same addition. This would make it "Turing incomplete" (so to speak). On the other hand, if it can run any program that the universal Turing machine can run, then it's Turing complete.

Most modern programming languages (e.g. Java, JavaScript, Perl, etc.) are all Turing complete because they each implement all the features required to run programs like addition, multiplication, if-else condition, return statements, ways to store/retrieve/erase data and so on.

Update: You can learn more on my blog post: "JavaScript Is Turing Complete" — Explained

What is the difference between HTML tags and elements?

<p>Here is a quote from WWF's website:</p>.

In this part <p> is a tag.

<blockquote cite="www.facebook.com">facebook is the world's largest socialsite..</blockquote>

in this part <blockquote> is an element.

Transfer data from one HTML file to another

I use this to set Profile image on each page.

On first page set value as:

localStorage.setItem("imageurl", "ur image url");

or on second page get value as :

var imageurl=localStorage.getItem("imageurl");
document.getElementById("profilePic").src = (imageurl);

C++ convert hex string to signed integer

I had the same problem today, here's how I solved it so I could keep lexical_cast<>

typedef unsigned int    uint32;
typedef signed int      int32;

class uint32_from_hex   // For use with boost::lexical_cast
{
    uint32 value;
public:
    operator uint32() const { return value; }
    friend std::istream& operator>>( std::istream& in, uint32_from_hex& outValue )
    {
        in >> std::hex >> outValue.value;
    }
};

class int32_from_hex   // For use with boost::lexical_cast
{
    uint32 value;
public:
    operator int32() const { return static_cast<int32>( value ); }
    friend std::istream& operator>>( std::istream& in, int32_from_hex& outValue )
    {
        in >> std::hex >> outvalue.value;
    }
};

uint32 material0 = lexical_cast<uint32_from_hex>( "0x4ad" );
uint32 material1 = lexical_cast<uint32_from_hex>( "4ad" );
uint32 material2 = lexical_cast<uint32>( "1197" );

int32 materialX = lexical_cast<int32_from_hex>( "0xfffefffe" );
int32 materialY = lexical_cast<int32_from_hex>( "fffefffe" );
// etc...

(Found this page when I was looking for a less sucky way :-)

Cheers, A.

How does the stack work in assembly language?

The stack already exists, so you can assume that when writing your code. The stack contains the return addresses of the functions, the local variables and the variables which are passed between functions. There are also stack registers such as BP, SP (Stack Pointer) built-in that you can use, hence the built-in commands you have mentioned. If the stack wasn't already implemented, functions couldn't run, and code flow couldn't work.

Laravel $q->where() between dates

Didn't wan to mess with carbon. So here's my solution

$start = new \DateTime('now');
$start->modify('first day of this month');
$end = new \DateTime('now');
$end->modify('last day of this month');

$new_releases = Game::whereBetween('release', array($start, $end))->get();

What does 'Unsupported major.minor version 52.0' mean, and how do I fix it?

Actually you have a code compiled targeting a higher JDK (JDK 1.8 in your case) but at runtime you are supplying a lower JRE(JRE 7 or below).

you can fix this problem by adding target parameter while compilation
e.g. if your runtime target is 1.7, you should use 1.7 or below

javac -target 1.7 *.java

if you are using eclipse, you can sent this parameter at Window -> Preferences -> Java -> Compiler -> set "Compiler compliance level" = choose your runtime jre version or lower.

Filter Pyspark dataframe column with None value

None/Null is a data type of the class NoneType in pyspark/python so, Below will not work as you are trying to compare NoneType object with string object

Wrong way of filreting

df[df.dt_mvmt == None].count() 0 df[df.dt_mvmt != None].count() 0

correct

df=df.where(col("dt_mvmt").isNotNull()) returns all records with dt_mvmt as None/Null

An Iframe I need to refresh every 30 seconds (but not the whole page)

I have a simpler solution. In your destination page (irc_online.php) add an auto-refresh tag in the header.

Easy way to convert a unicode list to a list containing python strings?

There are several ways to do this. I converted like this

def clean(s):
    s = s.replace("u'","")
    return re.sub("[\[\]\'\s]", '', s)

EmployeeList = [clean(i) for i in str(EmployeeList).split(',')]

After that you can check

if '1001' in EmployeeList:
    #do something

Hope it will help you.

How to use a variable from a cursor in the select statement of another cursor in pl/sql

Use alter session set current_schema = <username>, in your case as an execute immediate.

See Oracle's documentation for further information.

In your case, that would probably boil down to (untested)

DECLARE

   CURSOR client_cur IS
     SELECT  distinct username 
       from all_users 
      where length(username) = 3;

   -- client cursor 
   CURSOR emails_cur IS
   SELECT id, name 
     FROM org;

BEGIN

   FOR client IN client_cur LOOP

   -- ****
      execute immediate 
     'alter session set current_schema = ' || client.username;
   -- ****

      FOR email_rec in client_cur LOOP

         dbms_output.put_line(
             'Org id is ' || email_rec.id || 
             ' org nam '  || email_rec.name);

      END LOOP;

  END LOOP;
END;
/

How can I select from list of values in Oracle

If you are seeking to convert a comma delimited list of values:

select column_value 
from table(sys.dbms_debug_vc2coll('One', 'Two', 'Three', 'Four'));

-- Or

select column_value 
from table(sys.dbms_debug_vc2coll(1,2,3,4));

If you wish to convert a string of comma delimited values then I would recommend Justin Cave's regular expression SQL solution.

How do I Geocode 20 addresses without receiving an OVER_QUERY_LIMIT response?

EDIT:

Forgot to say that this solution is in pure js, the only thing you need is a browser that supports promises https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Promise


For those who still needs to accomplish such, I've written my own solution that combines promises with timeouts.

Code:

/*
    class: Geolocalizer
        - Handles location triangulation and calculations.
        -- Returns various prototypes to fetch position from strings or coords or dragons or whatever.
*/

var Geolocalizer = function () {
    this.queue          = [];     // queue handler..
    this.resolved       = [];
    this.geolocalizer = new google.maps.Geocoder();  
};

Geolocalizer.prototype = {
    /*
        @fn: Localize
        @scope: resolve single or multiple queued requests.
        @params: <array> needles
        @returns: <deferred> object
    */
    Localize: function ( needles ) {
        var that = this;
        // Enqueue the needles.
        for ( var i = 0; i < needles.length; i++ ) {
            this.queue.push(needles[i]);
        }
        // return a promise and resolve it after every element have been fetched (either with success or failure), then reset the queue.
        return new Promise (
            function (resolve, reject) {
                that.resolveQueueElements().then(function(resolved){
                  resolve(resolved);
                  that.queue    = [];
                  that.resolved = [];
                });
            }
        );
    },

    /*
        @fn: resolveQueueElements
        @scope: resolve queue elements.
        @returns: <deferred> object (promise)
    */

    resolveQueueElements: function (callback) {
        var that = this;
        return new Promise(
            function(resolve, reject) {
                // Loop the queue and resolve each element.
                // Prevent QUERY_LIMIT by delaying actions by one second.
                (function loopWithDelay(such, queue, i){
                    console.log("Attempting the resolution of " +queue[i-1]);
                    setTimeout(function(){
                        such.find(queue[i-1], function(res){
                           such.resolved.push(res); 
                        });
                        if (--i) {
                            loopWithDelay(such,queue,i);
                        }
                    }, 1000);
                })(that, that.queue, that.queue.length);

                // Check every second if the queue has been cleared.
                var it = setInterval(function(){
                    if (that.queue.length == that.resolved.length) {
                        resolve(that.resolved);
                        clearInterval(it);
                    }
                }, 1000);
            }
        );
    },

    /*
        @fn: find
        @scope: resolve an address from string
        @params: <string> s, <fn> Callback
    */
    find: function (s, callback) {
        this.geolocalizer.geocode({
            "address": s
        }, function(res, status){
           if (status == google.maps.GeocoderStatus.OK) {
               var r = {
                   originalString:  s,
                   lat: res[0].geometry.location.lat(),
                   lng: res[0].geometry.location.lng()
               };
               callback(r);
           }
            else {
                callback(undefined);
                console.log(status);
                console.log("could not locate " + s);
            }
        });
    }
};

Please note that it's just a part of a bigger library I wrote to handle google maps stuff, hence comments may be confusing.

Usage is quite simple, the approach, however, is slightly different: instead of looping and resolving one address at a time, you will need to pass an array of addresses to the class and it will handle the search by itself, returning a promise which, when resolved, returns an array containing all the resolved (and unresolved) address.

Example:

var myAmazingGeo = new Geolocalizer();
var locations = ["Italy","California","Dragons are thugs...","China","Georgia"];
myAmazingGeo.Localize(locations).then(function(res){ 
   console.log(res); 
});

Console output:

Attempting the resolution of Georgia
Attempting the resolution of China
Attempting the resolution of Dragons are thugs...
Attempting the resolution of California
ZERO_RESULTS
could not locate Dragons are thugs...
Attempting the resolution of Italy

Object returned:

enter image description here

The whole magic happens here:

(function loopWithDelay(such, queue, i){
                    console.log("Attempting the resolution of " +queue[i-1]);
                    setTimeout(function(){
                        such.find(queue[i-1], function(res){
                           such.resolved.push(res); 
                        });
                        if (--i) {
                            loopWithDelay(such,queue,i);
                    }
                }, 750);
            })(that, that.queue, that.queue.length);

Basically, it loops every item with a delay of 750 milliseconds between each of them, hence every 750 milliseconds an address is controlled.

I've made some further testings and I've found out that even at 700 milliseconds I was sometimes getting the QUERY_LIMIT error, while with 750 I haven't had any issue at all.

In any case, feel free to edit the 750 above if you feel you are safe by handling a lower delay.

Hope this helps someone in the near future ;)

How to vertically align into the center of the content of a div with defined width/height?

margin: all_four_margin

by providing 50% to all_four_margin will place the element at the center

style="margin: 50%"

you can apply it for following too

margin: top right bottom left

margin: top right&left bottom

margin: top&bottom right&left

by giving appropriate % we get the element wherever we want.

gcloud command not found - while installing Google Cloud SDK

If you are on MAC OS and using .zsh shell then do the following:

  1. Edit your .zshrc and add the following

    # The next line updates PATH for the Google Cloud SDK.
    source /Users/USER_NAME/google-cloud-sdk/path.zsh.inc
    
    # The next line enables zsh completion for gcloud.
    source /Users/USER_NAME/google-cloud-sdk/completion.zsh.inc
    
  2. Create new file named path.zsh.inc under your home directory(/Users/USER_NAME/):

    script_link="$( readlink "$0" )" || script_link="$0"
    apparent_sdk_dir="${script_link%/*}"
    if [ "$apparent_sdk_dir" == "$script_link" ]; then
     apparent_sdk_dir=.
    fi
    sdk_dir="$( cd -P "$apparent_sdk_dir" && pwd -P )"
    bin_path="$sdk_dir/bin"
    export PATH=$bin_path:$PATH
    

Checkout more @ Official Docs

How can I quickly sum all numbers in a file?

I prefer to use R for this:

$ R -e 'sum(scan("filename"))'

Add x and y labels to a pandas plot

In Pandas version 1.10 and above you can use parameters xlabel and ylabel in the method plot:

df.plot(xlabel='X Label', ylabel='Y Label', title='Plot Title')

enter image description here

Java, Check if integer is multiple of a number

If I understand correctly, you can use the module operator for this. For example, in Java (and a lot of other languages), you could do:

//j is a multiple of four if
j % 4 == 0

The module operator performs division and gives you the remainder.

How can I read a whole file into a string variable

I'm not with computer,so I write a draft. You might be clear of what I say.

func main(){
    const dir = "/etc/"
    filesInfo, e := ioutil.ReadDir(dir)
    var fileNames = make([]string, 0, 10)
    for i,v:=range filesInfo{
        if !v.IsDir() {
            fileNames = append(fileNames, v.Name())
        }
    }

    var fileNumber = len(fileNames)
    var contents = make([]string, fileNumber, 10)
    wg := sync.WaitGroup{}
    wg.Add(fileNumber)

    for i,_:=range content {
        go func(i int){
            defer wg.Done()
            buf,e := ioutil.Readfile(fmt.Printf("%s/%s", dir, fileName[i]))
            defer file.Close()  
            content[i] = string(buf)
        }(i)   
    }
    wg.Wait()
}

How do I get the web page contents from a WebView?

This is an answer based on jluckyiv's, but I think it is better and simpler to change Javascript as follows.

browser.loadUrl("javascript:HTMLOUT.processHTML(document.documentElement.outerHTML);");

How to export JSON from MongoDB using Robomongo

An extension to Florian Winter answer for people looking to generate ready to execute query.

drop and insertMany query using cursor:

{
    // collection name
    var collection_name = 'foo';

    // query
    var cursor = db.getCollection(collection_name).find({});

    // drop collection and insert script
    print('db.' + collection_name + '.drop();');
    print('db.' + collection_name + '.insertMany([');

    // print documents
    while(cursor.hasNext()) {
        print(tojson(cursor.next()));

        if (cursor.hasNext()) // add trailing "," if not last item
            print(',');
    }

    // end script
    print(']);');
}

Its output will be like:

db.foo.drop();
db.foo.insertMany([
{
    "_id" : ObjectId("abc"),
    "name" : "foo"
}
,
{
    "_id" : ObjectId("xyz"),
    "name" : "bar"
}
]);

Cycles in family tree software

Relax your assertions.

Not by changing the rules, which are mostly likely very helpful to 99.9% of your customers in catching mistakes in entering their data.

Instead, change it from an error "can't add relationship" to a warning with an "add anyway".

warning: Insecure world writable dir /usr/local/bin in PATH, mode 040777

This should resolve your problem: chmod go-w {/path/of/user}

How to access ssis package variables inside script component

Strongly typed var don't seem to be available, I have to do the following in order to get access to them:

String MyVar = Dts.Variables["MyVarName"].Value.ToString();

How to count the number of letters in a string without the spaces?

I found this is working perfectly

str = "count a character occurance"
str = str.replace(' ', '')
print (str)
print (len(str))

Correct way to populate an Array with a Range in Ruby

This works for me in irb:

irb> (1..4).to_a
=> [1, 2, 3, 4]

I notice that:

irb> 1..4.to_a
(irb):1: warning: default `to_a' will be obsolete
ArgumentError: bad value for range
        from (irb):1

So perhaps you are missing the parentheses?

(I am running Ruby 1.8.6 patchlevel 114)

How to use matplotlib tight layout with Figure?

Just call fig.tight_layout() as you normally would. (pyplot is just a convenience wrapper. In most cases, you only use it to quickly generate figure and axes objects and then call their methods directly.)

There shouldn't be a difference between the QtAgg backend and the default backend (or if there is, it's a bug).

E.g.

import matplotlib.pyplot as plt

#-- In your case, you'd do something more like:
# from matplotlib.figure import Figure
# fig = Figure()
#-- ...but we want to use it interactive for a quick example, so 
#--    we'll do it this way
fig, axes = plt.subplots(nrows=4, ncols=4)

for i, ax in enumerate(axes.flat, start=1):
    ax.set_title('Test Axes {}'.format(i))
    ax.set_xlabel('X axis')
    ax.set_ylabel('Y axis')

plt.show()

Before Tight Layout

enter image description here

After Tight Layout

import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=4, ncols=4)

for i, ax in enumerate(axes.flat, start=1):
    ax.set_title('Test Axes {}'.format(i))
    ax.set_xlabel('X axis')
    ax.set_ylabel('Y axis')

fig.tight_layout()

plt.show()

enter image description here

Finding the last index of an array

The array has a Length property that will give you the length of the array. Since the array indices are zero-based, the last item will be at Length - 1.

string[] items = GetAllItems();
string lastItem = items[items.Length - 1];
int arrayLength = array.Length;

When declaring an array in C#, the number you give is the length of the array:

string[] items = new string[5]; // five items, index ranging from 0 to 4.

Case insensitive comparison NSString

A new way to do this. iOS 8

let string: NSString = "Café"
let substring: NSString = "É"

string.localizedCaseInsensitiveContainsString(substring) // true

Flask example with POST

Before actually answering your question:

Parameters in a URL (e.g. key=listOfUsers/user1) are GET parameters and you shouldn't be using them for POST requests. A quick explanation of the difference between GET and POST can be found here.

In your case, to make use of REST principles, you should probably have:

http://ip:5000/users
http://ip:5000/users/<user_id>

Then, on each URL, you can define the behaviour of different HTTP methods (GET, POST, PUT, DELETE). For example, on /users/<user_id>, you want the following:

GET /users/<user_id> - return the information for <user_id>
POST /users/<user_id> - modify/update the information for <user_id> by providing the data
PUT - I will omit this for now as it is similar enough to `POST` at this level of depth
DELETE /users/<user_id> - delete user with ID <user_id> 

So, in your example, you want do a POST to /users/user_1 with the POST data being "John". Then the XPath expression or whatever other way you want to access your data should be hidden from the user and not tightly couple to the URL. This way, if you decide to change the way you store and access data, instead of all your URL's changing, you will simply have to change the code on the server-side.

Now, the answer to your question: Below is a basic semi-pseudocode of how you can achieve what I mentioned above:

from flask import Flask
from flask import request

app = Flask(__name__)

@app.route('/users/<user_id>', methods = ['GET', 'POST', 'DELETE'])
def user(user_id):
    if request.method == 'GET':
        """return the information for <user_id>"""
        .
        .
        .
    if request.method == 'POST':
        """modify/update the information for <user_id>"""
        # you can use <user_id>, which is a str but could
        # changed to be int or whatever you want, along
        # with your lxml knowledge to make the required
        # changes
        data = request.form # a multidict containing POST data
        .
        .
        .
    if request.method == 'DELETE':
        """delete user with ID <user_id>"""
        .
        .
        .
    else:
        # POST Error 405 Method Not Allowed
        .
        .
        .

There are a lot of other things to consider like the POST request content-type but I think what I've said so far should be a reasonable starting point. I know I haven't directly answered the exact question you were asking but I hope this helps you. I will make some edits/additions later as well.

Thanks and I hope this is helpful. Please do let me know if I have gotten something wrong.

How can I inspect element in an Android browser?

Chrome on Android makes it possible to use the Chrome developer tools on the desktop to inspect the HTML that was loaded from the Chrome application on the Android device.

See: https://developers.google.com/chrome-developer-tools/docs/remote-debugging

Prevent screen rotation on Android

You can try This way

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.itclanbd.spaceusers">

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".Login_Activity"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

Total width of element (including padding and border) in jQuery

looks like outerWidth is broken in the latest version of jquery.

The discrepancy happens when

the outer div is floated, the inner div has the width set (smaller than the outer div) the inner div has style="margin:auto"

Sniffing/logging your own Android Bluetooth traffic

Also, this might help finding the actual location the btsnoop_hci.log is being saved:

adb shell "cat /etc/bluetooth/bt_stack.conf | grep FileName"

BadImageFormatException. This will occur when running in 64 bit mode with the 32 bit Oracle client components installed

Please download the correct version of Oracle Client like Oracle Client 11.2 32-Bit; which resolved the problem for me.

How to check Django version

Django version or any other package version

Open the terminal or command prompt

Type

pip show django

or

pip3 show django

You can find any package version...

Example:

pip show tensorflow

pip show numpy

etc....

how to create inline style with :before and :after

You can, using CSS variables (more precisely called CSS custom properties).

  • Set your variable in your style attribute:
    style="--my-color-var: orange;"
  • Use the variable in your stylesheet:
    background-color: var(--my-color-var);

Browser compatibility

Minimal example:

_x000D_
_x000D_
div {
  width: 100px;
  height: 100px;
  position: relative;
  border: 1px solid black;
}

div:after {
  background-color: var(--my-color-var);
  content: '';
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
}
_x000D_
<div style="--my-color-var: orange;"></div>
_x000D_
_x000D_
_x000D_

Your example:

_x000D_
_x000D_
.bubble {
  position: relative;
  width: 30px;
  height: 15px;
  padding: 0;
  background: #FFF;
  border: 1px solid #000;
  border-radius: 5px;
  text-align: center;
  background-color: var(--bubble-color);
}

.bubble:after {
  content: "";
  position: absolute;
  top: 4px;
  left: -4px;
  border-style: solid;
  border-width: 3px 4px 3px 0;
  border-color: transparent var(--bubble-color);
   display: block;
  width: 0;
  z-index: 1;
  
}

.bubble:before {
  content: "";
  position: absolute;
  top: 4px;
  left: -5px;
  border-style: solid;
  border-width: 3px 4px 3px 0;
  border-color: transparent #000;
  display: block;
  width: 0;
  z-index: 0;
}
_x000D_
<div class='bubble' style="--bubble-color: rgb(100,255,255);"> 100 </div>
_x000D_
_x000D_
_x000D_

CodeIgniter Active Record not equal

This should work (which you have tried)

$this->db->where_not_in('emailsToCampaigns.campaignId', $campaignId);

How to use zIndex in react-native

UPDATE: Supposedly, zIndex has been added to the react-native library. I've been trying to get it to work without success. Check here for details of the fix.

git pull from master into the development branch

The steps you listed will work, but there's a longer way that gives you more options:

git checkout dmgr2      # gets you "on branch dmgr2"
git fetch origin        # gets you up to date with origin
git merge origin/master

The fetch command can be done at any point before the merge, i.e., you can swap the order of the fetch and the checkout, because fetch just goes over to the named remote (origin) and says to it: "gimme everything you have that I don't", i.e., all commits on all branches. They get copied to your repository, but named origin/branch for any branch named branch on the remote.

At this point you can use any viewer (git log, gitk, etc) to see "what they have" that you don't, and vice versa. Sometimes this is only useful for Warm Fuzzy Feelings ("ah, yes, that is in fact what I want") and sometimes it is useful for changing strategies entirely ("whoa, I don't want THAT stuff yet").

Finally, the merge command takes the given commit, which you can name as origin/master, and does whatever it takes to bring in that commit and its ancestors, to whatever branch you are on when you run the merge. You can insert --no-ff or --ff-only to prevent a fast-forward, or merge only if the result is a fast-forward, if you like.

When you use the sequence:

git checkout dmgr2
git pull origin master

the pull command instructs git to run git fetch, and then the moral equivalent of git merge origin/master. So this is almost the same as doing the two steps by hand, but there are some subtle differences that probably are not too concerning to you. (In particular the fetch step run by pull brings over only origin/master, and it does not update the ref in your repo:1 any new commits winds up referred-to only by the special FETCH_HEAD reference.)

If you use the more-explicit git fetch origin (then optionally look around) and then git merge origin/master sequence, you can also bring your own local master up to date with the remote, with only one fetch run across the network:

git fetch origin
git checkout master
git merge --ff-only origin/master
git checkout dmgr2
git merge --no-ff origin/master

for instance.


1This second part has been changed—I say "fixed"—in git 1.8.4, which now updates "remote branch" references opportunistically. (It was, as the release notes say, a deliberate design decision to skip the update, but it turns out that more people prefer that git update it. If you want the old remote-branch SHA-1, it defaults to being saved in, and thus recoverable from, the reflog. This also enables a new git 1.9/2.0 feature for finding upstream rebases.)

Nginx Different Domains on Same IP

Your "listen" directives are wrong. See this page: http://nginx.org/en/docs/http/server_names.html.

They should be

server {
    listen      80;
    server_name www.domain1.com;
    root /var/www/domain1;
}

server {
    listen       80;
    server_name www.domain2.com;
    root /var/www/domain2;
}

Note, I have only included the relevant lines. Everything else looked okay but I just deleted it for clarity. To test it you might want to try serving a text file from each server first before actually serving php. That's why I left the 'root' directive in there.

Java 8 method references: provide a Supplier capable of supplying a parameterized result

It appears that you can throw only RuntimeException from the method orElseThrow. Otherwise you will get an error message like MyException cannot be converted to java.lang.RuntimeException

Update:- This was an issue with an older version of JDK. I don't see this issue with the latest versions.

Reading an image file in C/C++

If you decide to go for a minimal approach, without libpng/libjpeg dependencies, I suggest using stb_image and stb_image_write, found here.

It's as simple as it gets, you just need to place the header files stb_image.h and stb_image_write.h in your folder.

Here's the code that you need to read images:

#include <stdint.h>

#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"

int main() {
    int width, height, bpp;

    uint8_t* rgb_image = stbi_load("image.png", &width, &height, &bpp, 3);

    stbi_image_free(rgb_image);

    return 0;
}

And here's the code to write an image:

#include <stdint.h>

#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"

#define CHANNEL_NUM 3

int main() {
    int width = 800; 
    int height = 800;

    uint8_t* rgb_image;
    rgb_image = malloc(width*height*CHANNEL_NUM);

    // Write your code to populate rgb_image here

    stbi_write_png("image.png", width, height, CHANNEL_NUM, rgb_image, width*CHANNEL_NUM);

    return 0;
}

You can compile without flags or dependencies:

g++ main.cpp

Other lightweight alternatives include:

How and when to use SLEEP() correctly in MySQL?

SELECT ...
SELECT SLEEP(5);
SELECT ...

But what are you using this for? Are you trying to circumvent/reinvent mutexes or transactions?

Pass accepts header parameter to jquery ajax

The other answers do not answer the actual question, but rather provide workarounds which is a shame because it literally takes 10 seconds to figure out what the correct syntax for accepts parameter.

The accepts parameter takes an object which maps the dataType to the Accept header. In your case you don't need to even need to pass the accepts object, as setting the data type to json should be sufficient. However if you do want to configure a custom Accept header this is what you do:

accepts: {"*": "my custom mime type" },

How do I know? Open jquery's source code and search for "accepts". The very first find tells you all you need to know:

    accepts: {
        "*": allTypes,
        text: "text/plain",
        html: "text/html",
        xml: "application/xml, text/xml",
        json: "application/json, text/javascript"
    },

As you see the are default mappings to text, html, xml and json data types.

Free tool to Create/Edit PNG Images?

The GIMP (GNU Image Manipulation Program). It's free, open source and runs on Windows and Linux (and maybe Mac?).

How does "FOR" work in cmd batch file?

This works for me:

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION ENABLEEXTENSIONS
@REM insure path is terminated with a ;
set tpath=%path%;
echo.
:again
@REM This FOR statement grabs the first element in the path
FOR /F "delims=;" %%I IN ("%TPATH%") DO (
  echo    %%I 
  @REM remove the current element of the path
  set TPATH=!TPATH:%%I;=!
)
@REM loop back if there is more to do. 
IF DEFINED TPATH GOTO :again

ENDLOCAL

Disable arrow key scrolling in users browser

Summary

Simply prevent the default browser action:

window.addEventListener("keydown", function(e) {
    // space and arrow keys
    if([32, 37, 38, 39, 40].indexOf(e.code) > -1) {
        e.preventDefault();
    }
}, false);

If you need to support Internet Explorer or other older browsers, use e.keyCode instead of e.code, but keep in mind that keyCode is deprecated.

Original answer

I used the following function in my own game:

var keys = {};
window.addEventListener("keydown",
    function(e){
        keys[e.code] = true;
        switch(e.code){
            case 37: case 39: case 38:  case 40: // Arrow keys
            case 32: e.preventDefault(); break; // Space
            default: break; // do not block other keys
        }
    },
false);
window.addEventListener('keyup',
    function(e){
        keys[e.code] = false;
    },
false);

The magic happens in e.preventDefault();. This will block the default action of the event, in this case moving the viewpoint of the browser.

If you don't need the current button states you can simply drop keys and just discard the default action on the arrow keys:

var arrow_keys_handler = function(e) {
    switch(e.code){
        case 37: case 39: case 38:  case 40: // Arrow keys
        case 32: e.preventDefault(); break; // Space
        default: break; // do not block other keys
    }
};
window.addEventListener("keydown", arrow_keys_handler, false);

Note that this approach also enables you to remove the event handler later if you need to re-enable arrow key scrolling:

window.removeEventListener("keydown", arrow_keys_handler, false);

References

Importing project into Netbeans

You may try creating a new project in netbeans and then copy and and paste the files into it. I usually experience this problem when the project wasn't created in netbeans.

How to do a num_rows() on COUNT query in codeigniter?

This will only return 1 row, because you're just selecting a COUNT(). you will use mysql_num_rows() on the $query in this case.

If you want to get a count of each of the ID's, add GROUP BY id to the end of the string.

Performance-wise, don't ever ever ever use * in your queries. If there is 100 unique fields in a table and you want to get them all, you write out all 100, not *. This is because * has to recalculate how many fields it has to go, every single time it grabs a field, which takes a lot more time to call.

javax vs java package

java packages are base, and javax packages are extensions.

Swing was an extension because AWT was the original UI API. Swing came afterwards, in version 1.1.

How do I collapse sections of code in Visual Studio Code for Windows?

As of Visual Studio Code version 1.12.0, April 2017, see Basic Editing > Folding section in the docs.

The default keys are:

Fold All: CTRL+K, CTRL+0 (zero)

Fold Level [n]: CTRL+K, CTRL+[n]*

Unfold All: CTRL+K, CTRL+J

Fold Region: CTRL+K, CTRL+[

Unfold Region: CTRL+K, CTRL+]

*Fold Level: to fold all but the most outer classes, try CTRL+K, CTRL+1

Macs: use ? instead of CTRL (thanks Prajeet)

Java get month string from integer

Try:

import java.text.DateFormatSymbols;
monthString = new DateFormatSymbols().getMonths()[month-1];

Alternatively, you could use SimpleDateFormat:

import java.text.SimpleDateFormat;
System.out.println(new SimpleDateFormat("MMMM").format(date));

(You'll have to put a date with your month in a Date object to use the second option).

Getting value of selected item in list box as string

If you want to retrieve your value from an list box you should try this:

String itemSelected = numberListBox.GetItemText(numberListBox.SelectedItem);

How to check if a string contains an element from a list in Python

It is better to parse the URL properly - this way you can handle http://.../file.doc?foo and http://.../foo.doc/file.exe correctly.

from urlparse import urlparse
import os
path = urlparse(url_string).path
ext = os.path.splitext(path)[1]
if ext in extensionsToCheck:
  print(url_string)

GROUP_CONCAT ORDER BY

In IMPALA, not having order in the GROUP_CONCAT can be problematic, over at Coders'Co. we have some sort of a workaround for that (we need it for Rax/Impala). If you need the GROUP_CONCAT result with an ORDER BY clause in IMPALA, take a look at this blog post: http://raxdb.com/blog/sorting-by-regex/

How to click or tap on a TextView text

OK I have answered my own question (but is it the best way?)

This is how to run a method when you click or tap on some text in a TextView:

package com.textviewy;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

public class TextyView extends Activity implements OnClickListener {

TextView t ;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    t = (TextView)findViewById(R.id.TextView01);
    t.setOnClickListener(this);
}

public void onClick(View arg0) {
    t.setText("My text on click");  
    }
}

and my main.xml is:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 >
<LinearLayout android:id="@+id/LinearLayout01" android:layout_width="wrap_content"             android:layout_height="wrap_content"></LinearLayout>
<ListView android:id="@+id/ListView01" android:layout_width="wrap_content"   android:layout_height="wrap_content"></ListView>
<LinearLayout android:id="@+id/LinearLayout02" android:layout_width="wrap_content"   android:layout_height="wrap_content"></LinearLayout>

<TextView android:text="This is my first text"
 android:id="@+id/TextView01" 
 android:layout_width="wrap_content" 
 android:textStyle="bold"
 android:textSize="28dip"
 android:editable = "true"
 android:clickable="true"
 android:layout_height="wrap_content">
 </TextView>
 </LinearLayout>

How to check if an array value exists?

You can test whether an array has a certain element at all or not with isset() or sometimes even better array_key_exists() (the documentation explains the differences). If you can't be sure if the array has an element with the index 'say' you should test that first or you might get 'warning: undefined index....' messages.

As for the test whether the element's value is equal to a string you can use == or (again sometimes better) the identity operator === which doesn't allow type juggling.

if( isset($something['say']) && 'bla'===$something['say'] ) {
  // ...
}

Validation error: "No validator could be found for type: java.lang.Integer"

You can add hibernate validator dependency, to provide a Validator

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.0.12.Final</version>
</dependency>

How to change the default GCC compiler in Ubuntu?

Now, there is gcc-4.9 available for Ubuntu/precise.

Create a group of compiler alternatives where the distro compiler has a higher priority:

root$ VER=4.6 ; PRIO=60
root$ update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-$VER $PRIO --slave /usr/bin/g++ g++ /usr/bin/g++-$VER
root$ update-alternatives --install /usr/bin/cpp cpp-bin /usr/bin/cpp-$VER $PRIO

root$ VER=4.9 ; PRIO=40
root$ update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-$VER $PRIO --slave /usr/bin/g++ g++ /usr/bin/g++-$VER
root$ update-alternatives --install /usr/bin/cpp cpp-bin /usr/bin/cpp-$VER $PRIO

NOTE: g++ version is changed automatically with a gcc version switch. cpp-bin has to be done separately as there exists a "cpp" master alternative.

List available compiler alternatives:

root$ update-alternatives --list gcc
root$ update-alternatives --list cpp-bin

To select manually version 4.9 of gcc, g++ and cpp, do:

root$ update-alternatives --config gcc
root$ update-alternatives --config cpp-bin

Check compiler versions:

root$ for i in gcc g++ cpp ; do $i --version ; done

Restore distro compiler settings (here: back to v4.6):

root$ update-alternatives --auto gcc
root$ update-alternatives --auto cpp-bin

Cannot resolve symbol 'AppCompatActivity'

If the soft methods via gradle file / "Invalidate caches" and the other IDE tools do not work, use the hard way:

  1. Exit Android Studio
  2. Navigate in your project to the .idea folder
  3. Just Rename the libraries folder
  4. Restart Android Studio. It should now recreate the libraries folder and work again.

This worked for me on

Android Studio 3.1.2
Build #AI-173.4720617, built on April 13, 2018
JRE: 1.8.0_152-release-1024-b01 amd64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Linux 4.13.0-38-generic

Shahbaz Ali confirmed, it works also on

Android Studio 3.1.3
Build #AI-173.4819257, built on June 4, 2018
JRE: 1.8.0_152-release-1024-b01 amd64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Linux 4.13.0-38-generic

moujib confirmed, it works on Android Studio 3.2.1

How to POST using HTTPclient content type = application/x-www-form-urlencoded

Another variant to POST this content type and which does not use a dictionary would be:

StringContent postData = new StringContent(JSON_CONTENT, Encoding.UTF8, "application/x-www-form-urlencoded");
using (HttpResponseMessage result = httpClient.PostAsync(url, postData).Result)
{
    string resultJson = result.Content.ReadAsStringAsync().Result;
}

How to clear APC cache entries?

apc.ini

apc.stat = "1" will force APC to stat (check) the script on each request to determine if it has been modified. If it has been modified it will recompile and cache the new version.

If this setting is off, APC will not check, which usually means that to force APC to recheck files, the web server will have to be restarted or the cache will have to be manually cleared. Note that FastCGI web server configurations may not clear the cache on restart. On a production server where the script files rarely change, a significant performance boost can be achieved by disabled stats.

Python 3: UnboundLocalError: local variable referenced before assignment

I don't like this behavior, but this is how Python works. The question has already been answered by others, but for completeness, let me point out that Python 2 has more such quirks.

def f(x):
    return x

def main():
    print f(3)
    if (True):
        print [f for f in [1, 2, 3]]

main()

Python 2.7.6 returns an error:

Traceback (most recent call last):
  File "weird.py", line 9, in <module>
    main()
  File "weird.py", line 5, in main
    print f(3)
UnboundLocalError: local variable 'f' referenced before assignment

Python sees the f is used as a local variable in [f for f in [1, 2, 3]], and decides that it is also a local variable in f(3). You could add a global f statement:

def f(x):
    return x

def main():
    global f
    print f(3)
    if (True):
        print [f for f in [1, 2, 3]]

main()

It does work; however, f becomes 3 at the end... That is, print [f for f in [1, 2, 3]] now changes the global variable f to 3, so it is not a function any more.

Fortunately, it works fine in Python3 after adding the parentheses to print.

Switch statement for string matching in JavaScript

RegExp can be used on the input string not just technically but practically with the match method too.

Because the output of the match() is an array we need to retrieve the first array element of the result. When the match fails, the function returns null. To avoid an exception error we will add the || conditional operator before accessing the first array element and test against the input property that is a static property of regular expressions that contains the input string.

str = 'XYZ test';
switch (str) {
  case (str.match(/^xyz/) || {}).input:
    console.log("Matched a string that starts with 'xyz'");
    break;
  case (str.match(/test/) || {}).input:
    console.log("Matched the 'test' substring");        
    break;
  default:
    console.log("Didn't match");
    break;
}

Another approach is to use the String() constructor to convert the resulting array that must have only 1 element (no capturing groups) and whole string must be captured with quanitifiers (.*) to a string. In case of a failure the null object will become a "null" string. Not convenient.

str = 'haystack';
switch (str) {
  case String(str.match(/^hay.*/)):
    console.log("Matched a string that starts with 'hay'");
    break;
}

Anyway, a more elegant solution is to use the /^find-this-in/.test(str) with switch (true) method which simply returns a boolean value and it's easier to search without case sensitivity.

SQL Data Reader - handling Null column values

I think you would want to use:

SqlReader.IsDBNull(indexFirstName)

Convert double to Int, rounded down

Another option either using Double or double is use Double.valueOf(double d).intValue();. Simple and clean

Function to Calculate Median in SQL Server

Even better:

SELECT @Median = AVG(1.0 * val)
FROM
(
    SELECT o.val, rn = ROW_NUMBER() OVER (ORDER BY o.val), c.c
    FROM dbo.EvenRows AS o
    CROSS JOIN (SELECT c = COUNT(*) FROM dbo.EvenRows) AS c
) AS x
WHERE rn IN ((c + 1)/2, (c + 2)/2);

From the master Himself, Itzik Ben-Gan!

IOError: [Errno 32] Broken pipe: Python

The top answer (if e.errno == errno.EPIPE:) here didn't really work for me. I got:

AttributeError: 'BrokenPipeError' object has no attribute 'EPIPE'

However, this ought to work if all you care about is ignoring broken pipes on specific writes. I think it's safer than trapping SIGPIPE:

try:
    # writing, flushing, whatever goes here
except BrokenPipeError:
    exit( 0 )

You obviously have to make a decision as to whether your code is really, truly done if you hit the broken pipe, but for most purposes I think that's usually going to be true. (Don't forget to close file handles, etc.)

Datatable select with multiple conditions

Yes, the DataTable.Select method supports boolean operators in the same way that you would use them in a "real" SQL statement:

DataRow[] results = table.Select("A = 'foo' AND B = 'bar' AND C = 'baz'");

See DataColumn.Expression in MSDN for the syntax supported by DataTable's Select method.

Select SQL results grouped by weeks

Base on @increddibelly answer, I applied to my query as below.

I share for whom concerned.

My table structure FamilyData(Id, nodeTime, totalEnergy)

select
   sum(totalEnergy) as TotalEnergy,
   DATEPART ( week, nodeTime ) as weeknr
from FamilyData
group by DATEPART (week, nodeTime)

Dynamically set value of a file input

It is not possible to dynamically change the value of a file field, otherwise you could set it to "c:\yourfile" and steal files very easily.

However there are many solutions to a multi-upload system. I'm guessing that you're wanting to have a multi-select open dialog.

Perhaps have a look at http://www.plupload.com/ - it's a very flexible solution to multiple file uploads, and supports drop zones e.t.c.

How to change color of Toolbar back button in Android?

Use this:

<style name="BaseTheme" parent="Theme.AppCompat.Light.NoActionBar">
  <item name="colorControlNormal">@color/white</item> 
</style>

How to disable or enable viewpager swiping in android

Disable swipe progmatically by-

    final View touchView = findViewById(R.id.Pager); 
    touchView.setOnTouchListener(new View.OnTouchListener() 
    {         
        @Override
        public boolean onTouch(View v, MotionEvent event)
        { 
           return true; 
        }
     });

and use this to swipe manually

touchView.setCurrentItem(int index);

How to get javax.comm API?

Use RXTX.

On Debian install librxtx-java by typing:

sudo apt-get install librxtx-java

On Fedora or Enterprise Linux install rxtx by typing:

sudo yum install rxtx