Programs & Examples On #Nfsclient

Force unmount of NFS-mounted directory

Your NFS server disappeared.

Ideally your best bet is if the NFS server comes back.

If not, the "umount -f" should have done the trick. It doesn't ALWAYS work, but it often will.

If you happen to know what processes are USING the NFS filesystem, you could try killing those processes and then maybe an unmount would work.

Finally, I'd guess you need to reboot.

Also, DON'T soft-mount your NFS drives. You use hard-mounts to guarantee that they worked. That's necessary if you're doing writes.

Align button to the right

Bootstrap 4 uses .float-right as opposed to .pull-right in Bootstrap 3. Also, don't forget to properly nest your rows with columns.

<div class="row">
    <div class="col-lg-12">
        <h3 class="one">Text</h3>
        <button class="btn btn-secondary float-right">Button</button>
    </div>
</div>

TypeError: 'dict' object is not callable

it's number_map[int(x)], you tried to actually call the map with one argument

Combining node.js and Python

I'd recommend using some work queue using, for example, the excellent Gearman, which will provide you with a great way to dispatch background jobs, and asynchronously get their result once they're processed.

The advantage of this, used heavily at Digg (among many others) is that it provides a strong, scalable and robust way to make workers in any language to speak with clients in any language.

Gradle does not find tools.jar

I was struggling as well for this Solution. Found a better way to it with Gradle as described here. We can get the JVM/JDK information from Gradle itself.

dependencies {
   runtime files(org.gradle.internal.jvm.Jvm.current().toolsJar)
}

So simple.

How do I connect to this localhost from another computer on the same network?

Provided both machines are in the same workgroup, open cmd.exe on the machine you want to connect to, type ipconfig and note the IP at the IPv4 Address line.

Then, on the machine you want to connect with, use http:// + the IP of the target machine.

That should do it.

The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security

See creating a registry key.

This problem can occur not only due to permissions, but also due to event source key missing because it wasn't registered successfully (you need admin privileges to do it - if you just open Visual Studio as usual and run the program normally it won't be enough). Make sure that your event source "MyApp" is actually registered, i.e. that it appears in the registry under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\Application.

From MSDN EventLog.CreateEventSource():

To create an event source in Windows Vista and later or Windows Server 2003, you must have administrative privileges.

So you must either run the event source registration code as an admin (also, check if the source already exists before - see the above MSDN example) or you can manually add the key to the registry:

  1. create a regkey HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\Application\MyApp;
  2. inside, create a string value EventMessageFile and set its value to e.g. C:\Windows\Microsoft.NET\Framework\v2.0.50727\EventLogMessages.dll

Convert list of ASCII codes to string (byte array) in Python

struct.pack('B' * len(integers), *integers)

*sequence means "unpack sequence" - or rather, "when calling f(..., *args ,...), let args = sequence".

Only allow Numbers in input Tag without Javascript

Try this with the + after [0-9]:

input type="text" pattern="[0-9]+" title="number only"

Echo equivalent in PowerShell for script testing

By far the easiest way to echo in powershell, is just create the string object and let the pipeline output it:

$filesizecounter = 8096
"filesizecounter : $filesizecounter"

Of course, you do give up some flexibility when not using the Write-* methods.

Sort a single String in Java

toCharArray followed by Arrays.sort followed by a String constructor call:

import java.util.Arrays;

public class Test
{
    public static void main(String[] args)
    {
        String original = "edcba";
        char[] chars = original.toCharArray();
        Arrays.sort(chars);
        String sorted = new String(chars);
        System.out.println(sorted);
    }
}

EDIT: As tackline points out, this will fail if the string contains surrogate pairs or indeed composite characters (accent + e as separate chars) etc. At that point it gets a lot harder... hopefully you don't need this :) In addition, this is just ordering by ordinal, without taking capitalisation, accents or anything else into account.

Run-time error '3061'. Too few parameters. Expected 1. (Access 2007)

I got the same error with something like:

Set rs = dbs.OpenRecordset _
( _
  "SELECT Field1, Field2, FieldN " _
  & "FROM Query1 " _
  & "WHERE Query2.Field1 = """ & Value1 & """;" _
, dbOpenSnapshot _
)

I fixed the error by replacing "Query1" with "Query2"

Integer expression expected error in shell script

If you are just comparing numbers, I think there's no need to change syntax, just correct those lines, lines 6 and 9 brackets.

Line 6 before: if [ "$age" -le "7"] -o [ "$age" -ge " 65" ]

After: if [ "$age" -le "7" -o "$age" -ge "65" ]

Line 9 before: elif [ "$age" -gt "7"] -a [ "$age" -lt "65"]

After: elif [ "$age" -gt "7" -a "$age" -lt "65" ]

How to get "their" changes in the middle of conflicting Git rebase?

If you want to pull a particular file from another branch just do

git checkout branch1 -- filenamefoo.txt

This will pull a version of the file from one branch into the current tree

How do you use "git --bare init" repository?

You could also ask git to create directory for you:

git init --bare test_repo.git

Is it possible to dynamically compile and execute C# code fragments?

Found this useful - ensures the compiled Assembly references everything you currently have referenced, since there's a good chance you wanted the C# you're compiling to use some classes etc in the code that's emitting this:

(string code is the dynamic C# being compiled)

        var refs = AppDomain.CurrentDomain.GetAssemblies();
        var refFiles = refs.Where(a => !a.IsDynamic).Select(a => a.Location).ToArray();
        var cSharp = (new Microsoft.CSharp.CSharpCodeProvider()).CreateCompiler();
        var compileParams = new System.CodeDom.Compiler.CompilerParameters(refFiles);
        compileParams.GenerateInMemory = true;
        compileParams.GenerateExecutable = false;

        var compilerResult = cSharp.CompileAssemblyFromSource(compileParams, code);
        var asm = compilerResult.CompiledAssembly;

In my case I was emitting a class, whose name was stored in a string, className, which had a single public static method named Get(), that returned with type StoryDataIds. Here's what calling that method looks like:

        var tempType = asm.GetType(className);
        var ids = (StoryDataIds)tempType.GetMethod("Get").Invoke(null, null);

Warning: Compilation can be surprisingly, extremely slow. A small, relatively simple 10-line chunk of code compiles at normal priority in 2-10 seconds on our relatively fast server. You should never tie calls to CompileAssemblyFromSource() to anything with normal performance expectations, like a web request. Instead, proactively compile code you need on a low-priority thread and have a way of dealing with code that requires that code to be ready, until it's had a chance to finish compiling. For example you could use it in a batch job process.

How do I deal with "signed/unsigned mismatch" warnings (C4018)?

If you can't/won't use iterators and if you can't/won't use std::size_t for the loop index, make a .size() to int conversion function that documents the assumption and does the conversion explicitly to silence the compiler warning.

#include <cassert>
#include <cstddef>
#include <limits>

// When using int loop indexes, use size_as_int(container) instead of
// container.size() in order to document the inherent assumption that the size
// of the container can be represented by an int.
template <typename ContainerType>
/* constexpr */ int size_as_int(const ContainerType &c) {
    const auto size = c.size();  // if no auto, use `typename ContainerType::size_type`
    assert(size <= static_cast<std::size_t>(std::numeric_limits<int>::max()));
    return static_cast<int>(size);
}

Then you write your loops like this:

for (int i = 0; i < size_as_int(things); ++i) { ... }

The instantiation of this function template will almost certainly be inlined. In debug builds, the assumption will be checked. In release builds, it won't be and the code will be as fast as if you called size() directly. Neither version will produce a compiler warning, and it's only a slight modification to the idiomatic loop.

If you want to catch assumption failures in the release version as well, you can replace the assertion with an if statement that throws something like std::out_of_range("container size exceeds range of int").

Note that this solves both the signed/unsigned comparison as well as the potential sizeof(int) != sizeof(Container::size_type) problem. You can leave all your warnings enabled and use them to catch real bugs in other parts of your code.

Javascript "Not a Constructor" Exception while creating objects

It is happening because you must have used another variable named "project" in your code. Something like var project = {}

For you to make the code work, change as follows:

var project = {} into var project1 = {}

How to Detect Browser Back Button event - Cross Browser

I solved it by keeping track of the original event that triggered the hashchange (be it a swipe, a click or a wheel), so that the event wouldn't be mistaken for a simple landing-on-page, and using an additional flag in each of my event bindings. The browser won't set the flag again to false when hitting the back button:

var evt = null,
canGoBackToThePast = true;

$('#next-slide').on('click touch', function(e) {
    evt = e;
    canGobackToThePast = false;
    // your logic (remember to set the 'canGoBackToThePast' flag back to 'true' at the end of it)
}

Organizing a multiple-file Go project

I would recommend reviewing this page on How to Write Go Code

It documents both how to structure your project in a go build friendly way, and also how to write tests. Tests do not need to be a cmd using the main package. They can simply be TestX named functions as part of each package, and then go test will discover them.

The structure suggested in that link in your question is a bit outdated, now with the release of Go 1. You no longer would need to place a pkg directory under src. The only 3 spec-related directories are the 3 in the root of your GOPATH: bin, pkg, src . Underneath src, you can simply place your project mypack, and underneath that is all of your .go files including the mypack_test.go

go build will then build into the root level pkg and bin.

So your GOPATH might look like this:

~/projects/
    bin/
    pkg/
    src/
      mypack/
        foo.go
        bar.go
        mypack_test.go

export GOPATH=$HOME/projects

$ go build mypack
$ go test mypack

Update: as of >= Go 1.11, the Module system is now a standard part of the tooling and the GOPATH concept is close to becoming obsolete.

INFO: No Spring WebApplicationInitializer types detected on classpath

I had similar problem with Tomcat 8 embedded in java7 application.

When I launched Tomcat in my application, it worked. But when I launched it through Maven for integration test purpose, I got this error : "No Spring WebApplicationInitializer types detected on classpath".

I fixed it by upgrading org.apache.tomcat.embed:tomcat-embed-* dependencies from version 8.0.29 to 8.0.47.

Permissions for /var/www/html

I have just been in a similar position with regards to setting the 777 permissions on the apache website hosting directory. After a little bit of tinkering it seems that changing the group ownership of the folder to the "apache" group allowed access to the folder based on the user group.

1) make sure that the group ownership of the folder is set to the group apache used / generates for use. (check /etc/groups, mine was www-data on Ubuntu)

2) set the folder permissions to 774 to stop "everyone" from having any change access, but allowing the owner and group permissions required.

3) add your user account to the group that has permission on the folder (mine was www-data).

Docker: Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock

I have Jenkins running in Docker and connected Jenkins is using Docker socket from host machine Ubuntu 16.04 via volume to /var/run/docker.sock.

For me solution was:

1) Inside Docker container of Jenkins (docker exec -it jenkins bash on host machine)

usermod -a -G docker jenkins
chmod 664 /var/run/docker.sock
service jenkins restart (or systemctl restart jenkins.service)
su jenkins

2) On host machine:

sudo service docker restart

664 means - read and write(but not execute) for owner and users from group.

How can I convert an Int to a CString?

Here's one way:

CString str;
str.Format("%d", 5);

In your case, try _T("%d") or L"%d" rather than "%d"

History or log of commands executed in Git

If you use Windows PowerShell, you could type "git" and the press F8. Continue to press F8 to cycle through all your git commands.

Or, if you use cygwin, you could do the same thing with ^R.

Replace the single quote (') character from a string

You can escape the apostrophe with a \ character as well:

mystring.replace('\'', '')

Reloading the page gives wrong GET request with AngularJS HTML5 mode

From the angular docs

Server side
Using this mode requires URL rewriting on server side, basically you have to rewrite all your links to entry point of your application (e.g. index.html)

The reason for this is that when you first visit the page (/about), e.g. after a refresh, the browser has no way of knowing that this isn't a real URL, so it goes ahead and loads it. However if you have loaded up the root page first, and all the javascript code, then when you navigate to /about Angular can get in there before the browser tries to hit the server and handle it accordingly

START_STICKY and START_NOT_STICKY

Both codes are only relevant when the phone runs out of memory and kills the service before it finishes executing. START_STICKY tells the OS to recreate the service after it has enough memory and call onStartCommand() again with a null intent. START_NOT_STICKY tells the OS to not bother recreating the service again. There is also a third code START_REDELIVER_INTENT that tells the OS to recreate the service and redeliver the same intent to onStartCommand().

This article by Dianne Hackborn explained the background of this a lot better than the official documentation.

Source: http://android-developers.blogspot.com.au/2010/02/service-api-changes-starting-with.html

The key part here is a new result code returned by the function, telling the system what it should do with the service if its process is killed while it is running:

START_STICKY is basically the same as the previous behavior, where the service is left "started" and will later be restarted by the system. The only difference from previous versions of the platform is that it if it gets restarted because its process is killed, onStartCommand() will be called on the next instance of the service with a null Intent instead of not being called at all. Services that use this mode should always check for this case and deal with it appropriately.

START_NOT_STICKY says that, after returning from onStartCreated(), if the process is killed with no remaining start commands to deliver, then the service will be stopped instead of restarted. This makes a lot more sense for services that are intended to only run while executing commands sent to them. For example, a service may be started every 15 minutes from an alarm to poll some network state. If it gets killed while doing that work, it would be best to just let it be stopped and get started the next time the alarm fires.

START_REDELIVER_INTENT is like START_NOT_STICKY, except if the service's process is killed before it calls stopSelf() for a given intent, that intent will be re-delivered to it until it completes (unless after some number of more tries it still can't complete, at which point the system gives up). This is useful for services that are receiving commands of work to do, and want to make sure they do eventually complete the work for each command sent.

You must enable the openssl extension to download files via https

I had to uncomment extension=openssl in php.ini file for everything to work!

Best way to format integer as string with leading zeros?

One-liner alternative to the built-in zfill.

This function takes x and converts it to a string, and adds zeros in the beginning only and only if the length is too short:

def zfill_alternative(x,len=4): return ( (('0'*len)+str(x))[-l:] if len(str(x))<len else str(x) )

To sum it up - build-in: zfill is good enough, but if someone is curious on how to implement this by hand, here is one more example.

How do I get the height of a div's full content with jQuery?

  1. Using scrollHeight is not only buggy, but doesn't work when your container has a hardcoded height (which is probably most cases, since you wanna get contents height without doing container.height() itself)
  2. @shazboticus-s-shazbot solution is good when you can mess around with the container height temporarily / have a hard-coded height.
  3. An alternative solution would be:

_x000D_
_x000D_
$('#outer')_x000D_
    // Get children in array format, as we'll be reducing them into a single number_x000D_
    .contents().toArray()_x000D_
    // Filter out text and comment nodes, only allowing tags_x000D_
    .filter(el => el.nodeType === 1)_x000D_
    // Sum up all the children individual heights_x000D_
    .reduce((accumulator, el) => $(el).outerHeight(true) + accumulator, 0);
_x000D_
_x000D_
_x000D_

Of course, this latter alternative only works when #outer doesn't have immediate text childrens that take up space and you want to measure. Those are my 2 cents.

  1. If you want to measure unwrapped text, I'd suggest modifying your DOM tree and having an inner <div> of which you can measure easily by doing $('#outer').children().height()

npm - "Can't find Python executable "python", you can set the PYTHON env variable."

I installed python2.7 to solve this issue. I wish can help you.

Correct way to work with vector of arrays

Every element of your vector is a float[4], so when you resize every element needs to default initialized from a float[4]. I take it you tried to initialize with an int value like 0?

Try:

static float zeros[4] = {0.0, 0.0, 0.0, 0.0};
myvector.resize(newsize, zeros);

How do I escape only single quotes?

To replace only single quotes, use this simple statement:

$string = str_replace("'", "\\'", $string);

Pretty git branch graphs

A more branch-like colored version for shells.

e

Some other answers show graph trees nicely colored by external tools, partly with colored line information. This is my approach for shells, which is a combination with my first answer here for a table-like output (https://stackoverflow.com/a/61487052).

Features:

  • You can define all the tree colors
  • You can dye every column in the corresponding branch color
  • You can place the tree column at different positions
  • You can use various git log aliases
  • You can define a tree column number for each alias
  • You can pipe it into less -r for huge histories

How you use it:

Define your git log alias as in several answers shown, e.g. from Slipp D., albfan, kaoru, with the formatting instructions mentioned below and paste it into your .gitconfig along with the code snippet. Call it from your projcet path, as usually with

git colored YourLogAlias or with

git colored YourLogAlias TreeColumnNumber to place the tree column on the fly.

Formatting Instructions:

Your git log alias must follow these format rules:

  • use an unique character as column seperator for every commit placeholder, i.e. ^
    ...format:'%h%cr%s' -->
    ...format:'^%h^%cr^%s'
  • color a whole column in one color or leave it blank to adopt the respective branch color
    ...format:'^%h^%cr^%s' -->
    ...format:'^%h^%cr^%C(white)%s%C(reset)' (hashes and time in branch color)
  • you have to specify the width of any column by %><(<N>[,ltrunc|mtrunc|trunc]) with one of the trunc options, but any last commit placeholder on a line can be used without it
    ...format:'^%h^%cr^%C(white)%s%C(reset)' -->
    ...format:'^%<(7,trunc)%h^%<(12,trunc)%cr^%C(white)%<(50,trunc)%s%C(reset)'
  • if you need extra decoration charaters, place them directly around the commit placeholder, i.e. Commit:
    ...^%C(white)%<(50,trunc)%s%C(reset)... -->
    ...^%C(white)%<(50,trunc)Commit:%s%C(reset)...
  • if you use newlines %n put them before a column seperator or at the end
    ...^%C(white)%<(50,trunc)Commit:%s%C(reset)' -->
    ...%n^%C(white)%<(50,trunc)Commit:%s%C(reset)%n'
  • if you use column colors like %C(white) above you need to add the --color option
    ...format:'^%<(7,trunc)%h... -->
    ...--color...format:'^%<(7,trunc)%h...
  • if you use the --stat option or similar, add a newline %n at the end
    ...--stat...format:'...' -->
    ...--stat...format:'...%n'

Miscellaneous:

  • for your git log aliases with non-empty newlines ...%n%CommitPlaceholder..., you can place the git graph at every column n+1 only if all n-th columns of each line exist and use the same width

  • YourLogAlias-col has to be the name if you define a TreeColumnNumber in .gitconfig for YourLogAlias

  • compared to the normal git log output, this one is slow, but nice

Examples:

git colored lgc1 e

git colored lgc2 e

git colored lgc3 e

git colored lgc4 e

Code-Snippet:

Add the following lines to your .gitconfig

[alias]

# Define your unique column seperator
delim      = ^

# Define your git log aliases and optional tree column numbers
lgc1       = log --all --graph --color --pretty=format:'^%<(7,trunc)%h^%C(white)%<(15,trunc)- %ar -%C(reset)^%<(35,trunc)%s^%C(white)%an%C(reset)'

lgc2       = log --all --graph --color --pretty=format:'%D^%<(7,trunc)%h^%<(35,trunc)%s^%C(white)%<(20,trunc)%an%C(reset)^%C(white) (%ar)%C(reset)'
lgc2-col   = 2

lgc3       = log --all --graph --color --pretty=format:'%<(7,trunc)%h%d^%<(11,trunc)%cs%C(reset)^%s%n^%C(white)%<(11,trunc)%cr%C(reset)^%C(white)%<(25,trunc)From %an%C(reset)^%C(white)%ae%C(reset)%n'
lgc3-col   = 2

lgc4       = log --all --graph --color --pretty=format:'%h^%C(white)%<(25,trunc)%an%C(reset)^%C(white)%<(31,trunc)%aD%C(reset)^%s%n^%C(dim white)%<(25,trunc)%ae%C(reset)^%>(31,trunc)%D%C(reset)%n'
lgc4-col   = 3

# Define your whitespace seperated tree color list
color-list = "1;38;5;222 1;38;5;69 1;38;5;250 1;38;5;70 1;31 1;38;5;93 1;33 2;38;5;11 1;38;5;48 1;35 1;32 1;38;5;111 1;38;5;160 1;38;5;130 1;36 38;5;21"

Add the bash snippet to your .gitconfig too

# This is the bash snippet which does all the magic
colored = !bash -c '" \
  \
  \
  declare -A col_length col_colored; \
  apost=$(echo -e \"\\u0027\"); \
  delim=$(git config alias.delim); \
  git_log_cmd=$(git config alias.$1); \
  graph_col=${2:-$(git config alias.$1-col)}; \
  color_list=( $(git config alias.color-list) ); \
  [[ -z \"$graph_col\" ]] && graph_col=1; \
  [[ -z \"$git_log_cmd\" ]] && { git $1;exit; }; \
  \
  \
  i=0; \
  n=0; \
  while IFS= read -r line; do \
    ((n++)); \
    while read -d\"$delim\" -r col_info;do \
      ((i++)); \
      [[ -z \"$col_info\" ]] && col_length[\"$n:$i\"]=${col_length[\"${last[$i]:-1}:$i\"]} && ((i--)) && continue; \
      [[ $i -gt ${i_max:-0} ]] && i_max=$i; \
      [[ \"${col_info:1:1}\" = \"C\" ]] && col_colored[\"$n:$i\"]=1; \
      col_length[\"$n:$i\"]=$(grep -Eo \"\\([0-9]*,[lm]*trunc\\)\" <<< \"$col_info\" | grep -Eo \"[0-9]*\" | head -n 1); \
      [[ -n \"${col_length[\"$n:$i\"]}\" ]] && last[$i]=$n; \
      chars_extra=$(grep -Eo \"\\trunc\\).*\" <<< \"$col_info\"); \
      chars_extra=${chars_extra#trunc)}; \
      chars_begin=${chars_extra%%\\%*}; \
      chars_extra=${chars_extra%$apost*}; \
      chars_extra=${chars_extra#*\\%}; \
      case \" ad aD ae aE ai aI al aL an aN ar as at b B cd cD ce cE ci cI cl cL cn cN cr \
              cs ct d D e f G? gd gD ge gE GF GG GK gn gN GP gs GS GT h H N p P s S t T \" in \
        *\" ${chars_extra:0:2} \"*) \
          chars_extra=${chars_extra:2}; \
          chars_after=${chars_extra%%\\%*}; \
          ;; \
        *\" ${chars_extra:0:1} \"*) \
          chars_extra=${chars_extra:1}; \
          chars_after=${chars_extra%%\\%*}; \
          ;; \
        *) \
          echo \"No Placeholder found. Probably no tablelike output.\"; \
          continue; \
          ;; \
      esac; \
      if [[ -n \"$chars_begin$chars_after\" ]];then \
        len_extra=$(echo \"$chars_begin$chars_after\" | wc -m); \
        col_length[\"$n:$i\"]=$((${col_length[\"$n:$i\"]}+$len_extra-1)); \
      fi; \
    done <<< \"${line#*=format:}$delim\"; \
    i=1; \
  done <<< \"$(echo -e \"${git_log_cmd//\\%n/\\\\n}\")\"; \
  \
  \
  git_log_fst_part=\"${git_log_cmd%%\"$apost\"*}\"; \
  git_log_lst_part=\"${git_log_cmd##*\"$apost\"}\"; \
  git_log_tre_part=\"${git_log_cmd%%\"$delim\"*}\"; \
  git_log_tre_part=\"${git_log_tre_part##*\"$apost\"}\"; \
  git_log_cmd_count=\"$git_log_fst_part$apost $git_log_tre_part$apost$git_log_lst_part\"; \
  col_length[\"1:1\"]=$(eval git \"${git_log_cmd_count// --color}\" | wc -L); \
  \
  \
  i=0; \
  while IFS=\"$delim\" read -r graph rest;do \
    ((i++)); \
    graph_line[$i]=\"$graph\"; \
  done < <(eval git \"${git_log_cmd/ --color}\" && echo); \
  \
  \
  i=0; \
  l=0; \
  msg_err=; \
  color_list_ind=-1; \
  color_list_num=${#color_list[*]}; \
  color_repeat_ind=1; \
  if [[ $color_list_num -eq 0 ]];then \
    echo \"No tree colors specified via color-list under section [alias] in your .gitconfig\"; \
    echo \"Therefore collecting available git colors, which may take a while ...\"; \
    while read -d\"[\" -r char;do \
      color=$(sed -nl99 \"l\" <<< \"$char\"); \
      case \"$color\" in \
        *\"m\"*) \
          color=${color%%m*}; \
          ;; \
        *) \
          continue; \
          ;; \
      esac; \
      case \" $color_list \" in \
        *\" $color \"*) \
          continue; \
          ;; \
        *) \
          color_list=\"$color_list$color \"; \
          ;; \
      esac; \
    done <<< \"$(git log --all --color --graph --pretty=format:)\"; \
    echo -e \"Temporary used color-list = \\\"${color_list% }\\\"\\n\"; \
    color_list=( ${color_list% } ); \
    color_list_num=${#color_list[*]}; \
  fi; \
  while IFS= read -r line;do \
    ((i++)); \
    j=-1; \
    case_off=; \
    graph_colored=; \
    graph_line_last=\"${graph_line[$i-1]}\"; \
    graph_line=\"${graph_line[$i]}\"; \
    graph_line_next=\"${graph_line[$i+1]}\"; \
    while IFS= read -r char;do \
      ((j++)); \
      case \"$case_off$char\" in \
        [^\\ \\_\\*\\/\\|\\\\]|\"case_off\"*) \
          graph_colored=\"${graph_colored}\\033[${point_color}m$char\\033[0m\"; \
          case_off=\"case_off\"; \
          ;; \
        \" \") \
          graph_colored=\"${graph_colored}$char\"; \
          case \"$char_last\" in \
            \" \") \
              unset color_ind[$j]; \
              ;; \
          esac; \
          ;; \
        \"*\") \
          case \"${graph_line_last:$j:1}\" in \
            \"*\") \
              :; \
              ;; \
            \"|\") \
              case \"${graph_line_last:$(($j-1)):1}\" in \
                \"\\\\\") \
                  color_ind[$j]=${color_ind_last[$j-1]:-${color_ind[$j-1]}}; \
                  ;; \
                *) \
                  :; \
                  ;; \
              esac; \
              ;; \
            \" \") \
              case \"${graph_line_last:$(($j-1)):1}\" in \
                \"\\\\\") \
                  color_ind[$j]=${color_ind_last[$j-1]:-${color_ind[$j-1]}}; \
                  ;; \
                \"/\") \
                  case \"${graph_line_last:$(($j+1)):1}\" in \
                    \"/\") \
                      color_ind[$j]=${color_ind[$j+1]}; \
                      ;; \
                    \" \") \
                      new_col_ind=${#color[*]}; \
                      while true;do \
                        ((color_list_ind++)); \
                        [[ $color_list_ind -ge $color_list_num ]] && color_list_ind=$color_repeat_ind; \
                        [[ $color_list_ind -ge $color_list_num ]] && break; \
                        new_color=${color_list[$color_list_ind]}; \
                        case \"$new_color\" in \
                          \"\"|[\\ ]*) \
                            continue; \
                            ;; \
                          \"${color[${color_ind[$j-1]}]}\") \
                            [[ $(($color_list_num-$color_repeat_ind)) -gt 1 ]] && continue; \
                            ;;& \
                          *) \
                            color[$new_col_ind]=$new_color; \
                            color_ind[$j]=$new_col_ind; \
                            last_new_colored_line=$i; \
                            break; \
                            ;; \
                        esac 2>/dev/null; \
                      done; \
                      ;; \
                    *) \
                      [[ -n \"$msg_err\" ]] && echo -e \"Unknown case in graph_line $i: $graph_line for char $char at position $j\nwith the former graph_line $(($i-1)): $graph_line_last\"; \
                      ;; \
                  esac; \
                  ;; \
                \" \") \
                  case \"${graph_line_last:$(($j+1)):1}\" in \
                    \"/\") \
                      color_ind[$j]=${color_ind[$j+1]}; \
                      ;; \
                    *) \
                      new_col_ind=${#color[*]}; \
                      while true;do \
                        ((color_list_ind++)); \
                        [[ $color_list_ind -ge $color_list_num ]] && color_list_ind=$color_repeat_ind; \
                        [[ $color_list_ind -ge $color_list_num ]] && break; \
                        new_color=${color_list[$color_list_ind]}; \
                        case \"$new_color\" in \
                          \"\"|[\\ ]*) \
                            continue; \
                            ;; \
                          \"${color[${color_ind[$j-1]}]}\") \
                            [[ $(($color_list_num-$color_repeat_ind)) -gt 1 ]] && continue; \
                            ;;& \
                          *) \
                            color[$new_col_ind]=$new_color; \
                            color_ind[$j]=$new_col_ind; \
                            last_new_colored_line=$i; \
                            break; \
                            ;; \
                        esac 2>/dev/null; \
                      done; \
                      ;; \
                  esac; \
                  ;; \
                *) \
                  [[ -n \"$msg_err\" ]] && echo -e \"Unknown case in graph_line $i: $graph_line for char $char at position $j\nwith the former graph_line $(($i-1)): $graph_line_last\"; \
                  ;; \
              esac; \
              ;; \
            \"\"|[^\\ \\_\\*\\/\\|\\\\]) \
              new_col_ind=${#color[*]}; \
              while true;do \
                ((color_list_ind++)); \
                [[ $color_list_ind -ge $color_list_num ]] && color_list_ind=$color_repeat_ind; \
                [[ $color_list_ind -ge $color_list_num ]] && break; \
                new_color=${color_list[$color_list_ind]}; \
                case \"$new_color\" in \
                  \"\"|[\\ ]*) \
                    continue; \
                    ;; \
                  \"${color[${color_ind[$j-1]}]}\") \
                    [[ $(($color_list_num-$color_repeat_ind)) -gt 1 ]] && continue; \
                    ;;& \
                  *) \
                    color[$new_col_ind]=$new_color; \
                    color_ind[$j]=$new_col_ind; \
                    last_new_colored_line=$i; \
                    break; \
                    ;; \
                esac 2>/dev/null; \
              done; \
              ;; \
            *) \
              [[ -n \"$msg_err\" ]] && echo -e \"Unknown case in graph_line $i: $graph_line for char $char at position $j\nwith the former graph_line $(($i-1)): $graph_line_last\"; \
              ;; \
          esac; \
          graph_colored=\"${graph_colored}\\033[${color[${color_ind[$j]}]}m$char\\033[0m\"; \
          point_color=${color[${color_ind[$j]}]}; \
          ;; \
        \"|\") \
          case \"${graph_line_last:$j:1}\" in \
            \" \") \
              case \"${graph_line_last:$(($j-1)):1}\" in \
                \"/\") \
                  color_ind[$j]=${color_ind[$j+1]}; \
                  ;; \
                \"\\\\\") \
                  color_ind[$j]=${color_ind_last[$j-1]:-${color_ind[$j-1]}}; \
                  ;; \
                *) \
                  case \"${graph_line_last:$(($j+1)):1}\" in \
                    \"/\") \
                      color_ind[$j]=${color_ind[$j+1]}; \
                      ;; \
                    *) \
                      [[ -n \"$msg_err\" ]] && echo -e \"Unknown case in graph_line $i: $graph_line for char $char at position $j\nwith the former graph_line $(($i-1)): $graph_line_last\"; \
                      ;; \
                  esac; \
                  ;; \
              esac; \
              ;; \
            \"|\") \
              case \"${graph_line_last:$(($j-1)):1}\" in \
                \"\\\\\") \
                  case \"${graph_line:$(($j+1)):1}\" in \
                    \"\\\\\") \
                       :; \
                       ;; \
                    \" \") \
                      color_ind[$j]=${color_ind_last[$j-1]}; \
                      ;; \
                    *) \
                      [[ -n \"$msg_err\" ]] && echo -e \"Unknown case in graph_line $i: $graph_line for char $char at position $j\nwith the former graph_line $(($i-1)): $graph_line_last\"; \
                      ;; \
                  esac; \
                  ;; \
                *) \
                  :; \
                  ;; \
              esac; \
              ;; \
            \"*\") \
              case \"${graph_line:$(($j-1)):1}\" in \
                \"/\") \
                  if [[ $last_new_colored_line -eq $(($i-1)) ]];then \
                    new_col_ind=${#color[*]}; \
                    while true;do \
                      ((color_list_ind++)); \
                      [[ $color_list_ind -ge $color_list_num ]] && color_list_ind=$color_repeat_ind; \
                      [[ $color_list_ind -ge $color_list_num ]] && break; \
                      new_color=${color_list[$color_list_ind]}; \
                      case \"$new_color\" in \
                        \"\"|[\\ ]*) \
                          continue; \
                          ;; \
                        \"${color[${color_ind[$j-1]}]}\") \
                          [[ $(($color_list_num-$color_repeat_ind)) -gt 1 ]] && continue; \
                          ;;& \
                        *) \
                          color[$new_col_ind]=$new_color; \
                          color_ind[$j]=$new_col_ind; \
                          break; \
                          ;; \
                      esac 2>/dev/null; \
                    done; \
                  else \
                    color_ind[$j]=${color_ind_last[$j]}; \
                  fi; \
                  ;; \
                *) \
                  :; \
                  ;; \
              esac; \
              ;; \
            \"/\") \
              color_ind[$j]=${color_ind[$j]}; \
              ;; \
            *) \
              [[ -n \"$msg_err\" ]] && echo -e \"Unknown case in graph_line $i: $graph_line for char $char at position $j\nwith the former graph_line $(($i-1)): $graph_line_last\"; \
              ;; \
          esac; \
          graph_colored=\"${graph_colored}\\033[${color[${color_ind[$j]}]}m$char\\033[0m\"; \
          ;; \
        \"/\") \
          case \"${graph_line_last:$(($j)):1}\" in \
            \"|\") \
              case \"${graph_line_last:$(($j+1)):1}\" in \
                \"/\") \
                  case \"${graph_line_next:$j:1}\" in \
                    \"|\") \
                      color_ind[$j]=${color_ind[$j+1]}; \
                      ;; \
                    \" \") \
                      color_ind[$j]=${color_ind[$j]}; \
                      ;; \
                    *) \
                      [[ -n \"$msg_err\" ]] && echo -e \"Unknown case in graph_line $i: $graph_line for char $char at position $j\nwith the former graph_line $(($i-1)): $graph_line_last\"; \
                      ;; \
                  esac; \
                  ;; \
                *) \
                  color_ind[$j]=${color_ind[$j]}; \
                  ;; \
              esac; \
              ;; \
            *) \
              case \"${graph_line_last:$(($j+2)):1}\" in \
                \"/\"|\"_\") \
                  color_ind[$j]=${color_ind[$j+2]}; \
                  ;; \
                *) \
                  case \"${graph_line_last:$(($j+1)):1}\" in \
                    \"/\"|\"_\"|\"|\") \
                      color_ind[$j]=${color_ind[$j+1]}; \
                      ;; \
                    \"*\") \
                      case \"${graph_line:$(($j+1)):1}\" in \
                        \"|\") \
                          if [[ $last_new_colored_line -eq $(($i-1)) ]];then \
                            color_ind[$j]=${color_ind_last[$j+1]}; \
                          else \
                            new_col_ind=${#color[*]}; \
                            while true;do \
                              ((color_list_ind++)); \
                              [[ $color_list_ind -ge $color_list_num ]] && color_list_ind=$color_repeat_ind; \
                              [[ $color_list_ind -ge $color_list_num ]] && break; \
                              new_color=${color_list[$color_list_ind]}; \
                              case \"$new_color\" in \
                                \"\"|[\\ ]*) \
                                  continue; \
                                  ;; \
                                \"${color[${color_ind[$j-1]}]}\") \
                                  [[ $(($color_list_num-$color_repeat_ind)) -gt 1 ]] && continue; \
                                  ;;& \
                                *) \
                                  color[$new_col_ind]=$new_color; \
                                  color_ind[$j]=$new_col_ind; \
                                  break; \
                                  ;; \
                              esac 2>/dev/null; \
                            done; \
                          fi; \
                          ;; \
                        *) \
                          color_ind[$j]=${color_ind_last[$j+1]}; \
                          ;; \
                      esac; \
                      ;; \
                    *) \
                      case \"${graph_line_last:$j:1}\" in \
                        \"\\\\\") \
                          :; \
                          ;; \
                        \" \") \
                          case \"${graph_line_last:$(($j+1)):1}\" in \
                            \"*\") \
                              color_ind[$j]=${color_ind[$j+1]}; \
                              ;; \
                            *) \
                              [[ -n \"$msg_err\" ]] && echo -e \"Unknown case in graph_line $i: $graph_line for char $char at position $j\nwith the former graph_line $(($i-1)): $graph_line_last\"; \
                              ;; \
                          esac; \
                          ;; \
                        *) \
                          [[ -n \"$msg_err\" ]] && echo -e \"Unknown case in graph_line $i: $graph_line for char $char at position $j\nwith the former graph_line $(($i-1)): $graph_line_last\"; \
                          ;; \
                      esac; \
                      ;; \
                  esac; \
                  ;; \
              esac; \
              ;; \
          esac; \
          graph_colored=\"${graph_colored}\\033[${color[${color_ind[$j]}]}m$char\\033[0m\"; \
          ;; \
        \"\\\\\") \
          case \"${graph_line_last:$(($j-1)):1}\" in \
            \"|\"|\"\\\\\") \
              color_ind[$j]=${color_ind_last[$j-1]:-${color_ind[$j-1]}}; \
              ;; \
            \"*\") \
              new_col_ind=${#color[*]}; \
              while true;do \
                ((color_list_ind++)); \
                [[ $color_list_ind -ge $color_list_num ]] && color_list_ind=$color_repeat_ind; \
                [[ $color_list_ind -ge $color_list_num ]] && break; \
                new_color=${color_list[$color_list_ind]}; \
                case \"$new_color\" in \
                  \"\"|[\\ ]*) \
                    continue; \
                    ;; \
                  \"${color[${color_ind[$j-1]}]}\") \
                    [[ $(($color_list_num-$color_repeat_ind)) -gt 1 ]] && continue; \
                    ;;& \
                  *) \
                    color[$new_col_ind]=$new_color; \
                    color_ind[$j]=$new_col_ind; \
                    break; \
                    ;; \
                esac 2>/dev/null; \
              done; \
              ;; \
            \" \") \
              case \"${graph_line_last:$(($j-2)):1}\" in \
                \"\\\\\"|\"_\") \
                  color_ind[$j]=${color_ind_last[$j-2]:-${color_ind[$j-2]}}; \
                  ;; \
                *) \
                  case \"${graph_line_last:$j:1}\" in \
                    \"|\") \
                      color_ind[$j]=${color_ind_last[$j]:-${color_ind[$j]}}; \
                      ;; \
                    *) \
                      [[ -n \"$msg_err\" ]] && echo -e \"Unknown case in graph_line $i: $graph_line for char $char at position $j\nwith the former graph_line $(($i-1)): $graph_line_last\"; \
                      ;; \
                  esac; \
                  ;; \
              esac; \
              ;; \
            *) \
              [[ -n \"$msg_err\" ]] && echo -e \"Unknown case in graph_line $i: $graph_line for char $char at position $j\nwith the former graph_line $(($i-1)): $graph_line_last\"; \
              ;; \
          esac; \
          graph_colored=\"${graph_colored}\\033[${color[${color_ind[$j]}]}m$char$char\\033[0m\"; \
          ;; \
        \"_\") \
          case \"${graph_line:$(($j-2)):1}\" in \
            \"\\\\\"|\"_\") \
              color_ind[$j]=${color_ind[$j-2]}; \
              ;; \
            \" \"|\"/\") \
              k=2; \
              while [[ \"${graph_line:$(($j+$k)):1}\" = \"_\" ]];do \
                k=$(($k+2)); \
              done; \
              case \"${graph_line:$(($j+$k)):1}\" in \
                \"/\") \
                  case \"${graph_line_last:$(($j+$k+1)):1}\" in \
                    \"*\") \
                      color_ind[$j]=${color_ind[$j+$k+1]}; \
                      ;; \
                    \" \") \
                      case \"${graph_line_last:$(($j+$k)):1}\" in \
                        \"\\\\\") \
                          color_ind[$j]=${color_ind[$j+$k]}; \
                          ;; \
                        *) \
                          [[ -n \"$msg_err\" ]] && echo -e \"Unknown case in graph_line $i: $graph_line for char $char at position $j\nwith the former graph_line $(($i-1)): $graph_line_last\"; \
                          ;; \
                      esac; \
                      ;; \
                    \"|\") \
                      case \"${graph_line:$(($j+$k+1)):1}\" in \
                        \"|\") \
                          color_ind[$j]=${color_ind[$j+$k+2]}; \
                          ;; \
                        \" \") \
                          color_ind[$j]=${color_ind[$j+$k+1]}; \
                          ;; \
                        *) \
                          [[ -n \"$msg_err\" ]] && echo -e \"Unknown case in graph_line $i: $graph_line for char $char at position $j\nwith the former graph_line $(($i-1)): $graph_line_last\"; \
                          ;; \
                      esac; \
                      ;; \
                    *) \
                      [[ -n \"$msg_err\" ]] && echo -e \"Unknown case in graph_line $i: $graph_line for char $char at position $j\nwith the former graph_line $(($i-1)): $graph_line_last\"; \
                      ;; \
                  esac; \
                  ;; \
                *) \
                  [[ -n \"$msg_err\" ]] && echo -e \"Unknown case in graph_line $i: $graph_line for char $char at position $j\nwith the former graph_line $(($i-1)): $graph_line_last\"; \
                  ;; \
              esac; \
              ;; \
            *) \
              [[ -n \"$msg_err\" ]] && echo -e \"Unknown case in graph_line $i: $graph_line for char $char at position $j\nwith the former graph_line $(($i-1)): $graph_line_last\"; \
              ;; \
          esac; \
          graph_colored=\"${graph_colored}\\033[${color[${color_ind[$j]}]}m$char\\033[0m\"; \
          ;; \
      esac; \
      char_last=$char; \
    done <<< \"$(grep -Eo \".\" <<< \"${graph_line%%$delim*}\")\"; \
    for key in ${!color_ind[*]};do \
      color_ind_last[$key]=${color_ind[$key]}; \
    done; \
    \
    \
    c=0; \
    ((l++)); \
    [[ $l -gt $n ]] && l=1; \
    while IFS= read -d\"$delim\" -r col_content;do \
      ((c++)); \
      [[ $c -le $graph_col ]] && c_corr=-1 || c_corr=0; \
      if [[ $c -eq 1 ]];then \
        [[ \"${col_content/\\*}\" = \"$col_content\" ]] && [[ $l -eq 1 ]] && l=$n; \
        whitespaces=$(seq -s\" \" $((${col_length[\"1:1\"]}-$j))|tr -d \"[:digit:]\"); \
        col_content[$graph_col]=\"${graph_colored}$whitespaces\"; \
      elif [[ ${col_colored[\"$l:$c\"]:-0} -eq 0 ]];then \
        col_content[$c+$c_corr]=\"\\033[${point_color:-0}m$(printf \"%-${col_length[\"$l:$c\"]}s\" \"${col_content:-\"\"}\")\\033[0m\"; \
      else \
        col_content[$c+$c_corr]=\"$(printf \"%-${col_length[\"$l:$c\"]}s\" \"${col_content:-\"\"}\")\"; \
      fi; \
    done <<< \"$line$delim\"; \
    for ((k=$c+1;k<=$i_max;k++));do \
      [[ $k -le $graph_col ]] && c_corr=-1 || c_corr=0; \
      col_content[$k+$c_corr]=\"$(printf \"%-${col_length[\"$l:$k\"]:-${col_length[\"${last[$k]:-1}:$k\"]:-0}}s\" \"\")\"; \
    done; \
    unset col_content[0]; \
    echo -e \"${col_content[*]}\"; \
    unset col_content[*]; \
  done < <(git $1 && echo); \
  "' "git-colored"

Explanations:

  • The first paragraph loads the del

Set cookie and get cookie with JavaScript

I find the following code to be much simpler than anything else:

function setCookie(name,value,days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}
function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
function eraseCookie(name) {   
    document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}

Now, calling functions

setCookie('ppkcookie','testcookie',7);

var x = getCookie('ppkcookie');
if (x) {
    [do something with x]
}

Source - http://www.quirksmode.org/js/cookies.html

They updated the page today so everything in the page should be latest as of now.

How to JUnit test that two List<E> contain the same elements in the same order?

org.junit.Assert.assertEquals() and org.junit.Assert.assertArrayEquals() do the job.

To avoid next questions: If you want to ignore the order put all elements to set and then compare: Assert.assertEquals(new HashSet<String>(one), new HashSet<String>(two))

If however you just want to ignore duplicates but preserve the order wrap you list with LinkedHashSet.

Yet another tip. The trick Assert.assertEquals(new HashSet<String>(one), new HashSet<String>(two)) works fine until the comparison fails. In this case it shows you error message with to string representations of your sets that can be confusing because the order in set is almost not predictable (at least for complex objects). So, the trick I found is to wrap the collection with sorted set instead of HashSet. You can use TreeSet with custom comparator.

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

You can also use a MultiValue Map to hold the requestBody in. here is the example for it.

    foosId -> pathVariable
    user -> extracted from the Map of request Body 

unlike the @RequestBody annotation when using a Map to hold the request body we need to annotate with @RequestParam

and send the user in the Json RequestBody

  @RequestMapping(value = "v1/test/foos/{foosId}", method = RequestMethod.POST, headers = "Accept=application"
            + "/json",
            consumes = MediaType.APPLICATION_JSON_UTF8_VALUE ,
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String postFoos(@PathVariable final Map<String, String> pathParam,
            @RequestParam final MultiValueMap<String, String> requestBody) {
        return "Post some Foos " + pathParam.get("foosId") + " " + requestBody.get("user");
    }

How to show first commit by 'git log'?

Not the most beautiful way of doing it I guess:

git log --pretty=oneline | wc -l

This gives you a number then

git log HEAD~<The number minus one>

How can I select the record with the 2nd highest salary in database Oracle?

I believe this will accomplish the same result, without a subquery or a ranking function:

SELECT *
FROM emp
ORDER BY sal DESC
LIMIT 1
OFFSET 2

What is the difference between CHARACTER VARYING and VARCHAR in PostgreSQL?

The only difference is that CHARACTER VARYING is more human friendly than VARCHAR

Algorithm to detect overlapping periods

There is a wonderful library with good reviews on CodeProject: http://www.codeproject.com/Articles/168662/Time-Period-Library-for-NET

That library does a lot of work concerning overlap, intersecting them, etc. It's too big to copy/paste all of it, but I'll see which specific parts which can be useful to you.

What is the default access modifier in Java?

From Java documentation

If a class has no modifier (the default, also known as package-private), it is visible only within its own package (packages are named groups of related classes — you will learn about them in a later lesson.)

At the member level, you can also use the public modifier or no modifier (package-private) just as with top-level classes, and with the same meaning.

Full story you can read here (Which I wrote recently):

http://codeinventions.blogspot.com/2014/09/default-access-modifier-in-java-or-no.html

How display only years in input Bootstrap Datepicker?

$("#year").datepicker( {
    format: "yyyy",
    viewMode: "years", 
    minViewMode: "years"
}).on('changeDate', function(e){
    $(this).datepicker('hide');
});

How do I download a package from apt-get without installing it?

There are a least these apt-get extension packages that can help:

apt-offline - offline apt package manager
apt-zip - Update a non-networked computer using apt and removable media

This is specifically for the case of wanting to download where you have network access but to install on another machine where you do not.

Otherwise, the --download-only option to apt-get is your friend:

 -d, --download-only
     Download only; package files are only retrieved, not unpacked or installed.
     Configuration Item: APT::Get::Download-Only.

How to move a file?

The accepted answer is not the right one, because the question is not about renaming a file into a file, but moving many files into a directory. shutil.move will do the work, but for this purpose os.rename is useless (as stated on comments) because destination must have an explicit file name.

How to make two plots side-by-side using Python?

You can use - matplotlib.gridspec.GridSpec

Check - https://matplotlib.org/stable/api/_as_gen/matplotlib.gridspec.GridSpec.html

The below code displays a heatmap on right and an Image on left.

#Creating 1 row and 2 columns grid
gs = gridspec.GridSpec(1, 2) 
fig = plt.figure(figsize=(25,3))

#Using the 1st row and 1st column for plotting heatmap
ax=plt.subplot(gs[0,0])
ax=sns.heatmap([[1,23,5,8,5]],annot=True)

#Using the 1st row and 2nd column to show the image
ax1=plt.subplot(gs[0,1])
ax1.grid(False)
ax1.set_yticklabels([])
ax1.set_xticklabels([])

#The below lines are used to display the image on ax1
image = io.imread("https://images-na.ssl-images- amazon.com/images/I/51MvhqY1qdL._SL160_.jpg")

plt.imshow(image)
plt.show()

Output image

Git Pull is Not Possible, Unmerged Files

Solved, using the following command set:

git reset --hard
git pull --rebase
git rebase --skip
git pull

The trick is to rebase the changes... We had some trouble rebasing one trivial commit, and so we simply skipped it using git rebase --skip (after having copied the files).

How to define relative paths in Visual Studio Project?

If I get you right, you need ..\..\src

Printing all variables value from a class

Generic toString() one-liner, using reflection and style customization:

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
...
public String toString()
{
  return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}

How do I get data from a table?

This is how I accomplished reading a table in javascript. Basically I drilled down into the rows and then I was able to drill down into the individual cells for each row. This should give you an idea

//gets table
var oTable = document.getElementById('myTable');

//gets rows of table
var rowLength = oTable.rows.length;

//loops through rows    
for (i = 0; i < rowLength; i++){

   //gets cells of current row
   var oCells = oTable.rows.item(i).cells;

   //gets amount of cells of current row
   var cellLength = oCells.length;

   //loops through each cell in current row
   for(var j = 0; j < cellLength; j++){
      /* get your cell info here */
      /* var cellVal = oCells.item(j).innerHTML; */
   }
}

UPDATED - TESTED SCRIPT

<table id="myTable">
    <tr>
        <td>A1</td>
        <td>A2</td>
        <td>A3</td>
    </tr>
    <tr>
        <td>B1</td>
        <td>B2</td>
        <td>B3</td>
    </tr>
</table>
<script>
    //gets table
    var oTable = document.getElementById('myTable');

    //gets rows of table
    var rowLength = oTable.rows.length;

    //loops through rows    
    for (i = 0; i < rowLength; i++){

      //gets cells of current row  
       var oCells = oTable.rows.item(i).cells;

       //gets amount of cells of current row
       var cellLength = oCells.length;

       //loops through each cell in current row
       for(var j = 0; j < cellLength; j++){

              // get your cell info here

              var cellVal = oCells.item(j).innerHTML;
              alert(cellVal);
           }
    }
</script>

XML parsing of a variable string in JavaScript

Update: For a more correct answer see Tim Down's answer.

Internet Explorer and, for example, Mozilla-based browsers expose different objects for XML parsing, so it's wise to use a JavaScript framework like jQuery to handle the cross-browsers differences.

A really basic example is:

var xml = "<music><album>Beethoven</album></music>";

var result = $(xml).find("album").text();

Note: As pointed out in comments; jQuery does not really do any XML parsing whatsoever, it relies on the DOM innerHTML method and will parse it like it would any HTML so be careful when using HTML element names in your XML. But I think it works fairly good for simple XML 'parsing', but it's probably not suggested for intensive or 'dynamic' XML parsing where you do not upfront what XML will come down and this tests if everything parses as expected.

Gulp error: The following tasks did not complete: Did you forget to signal async completion?

For me the issue was different: Angular-cli was not installed (I installed a new Node version using NVM and simply forgot to reinstall angular cli)

You can check running "ng version".

If you don't have it just run "npm install -g @angular/cli"

How to preview a part of a large pandas DataFrame, in iPython notebook?

You can just use nrows. For instance

pd.read_csv('data.csv',nrows=6)

will show the first 6 rows from data.csv.

How to specify more spaces for the delimiter using cut?

My approach is to store the PID to a file in /tmp, and to find the right process using the -S option for ssh. That might be a misuse but works for me.

#!/bin/bash

TARGET_REDIS=${1:-redis.someserver.com}
PROXY="proxy.somewhere.com"

LOCAL_PORT=${2:-6379}

if [ "$1" == "stop" ] ; then
    kill `cat /tmp/sshTunel${LOCAL_PORT}-pid`
    exit
fi

set -x

ssh -f -i ~/.ssh/aws.pem centos@$PROXY -L $LOCAL_PORT:$TARGET_REDIS:6379 -N -S /tmp/sshTunel$LOCAL_PORT  ## AWS DocService dev, DNS alias
# SSH_PID=$! ## Only works with &
SSH_PID=`ps aux | grep sshTunel${LOCAL_PORT} | grep -v grep | awk '{print $2}'`
echo $SSH_PID > /tmp/sshTunel${LOCAL_PORT}-pid

Better approach might be to query for the SSH_PID right before killing it, since the file might be stale and it would kill a wrong process.

The type arguments cannot be inferred from the usage. Try specifying the type arguments explicitly

I had this same problem, my solution:
In the web.config file :

<compilation debug="true>
had to be changed to
<compilation debug="true" targetFramework="4.0">

JSP tricks to make templating easier?

Use tiles. It saved my life.

But if you can't, there's the include tag, making it similar to php.

The body tag might not actually do what you need it to, unless you have super simple content. The body tag is used to define the body of a specified element. Take a look at this example:

<jsp:element name="${content.headerName}"   
   xmlns:jsp="http://java.sun.com/JSP/Page">    
   <jsp:attribute name="lang">${content.lang}</jsp:attribute>   
   <jsp:body>${content.body}</jsp:body> 
</jsp:element>

You specify the element name, any attributes that element might have ("lang" in this case), and then the text that goes in it--the body. So if

  • content.headerName = h1,
  • content.lang = fr, and
  • content.body = Heading in French

Then the output would be

<h1 lang="fr">Heading in French</h1>

Calculating a 2D Vector's Cross Product

I'm using 2d cross product in my calculation to find the new correct rotation for an object that is being acted on by a force vector at an arbitrary point relative to its center of mass. (The scalar Z one.)

BitBucket - download source as ZIP

For the latest version of Bitbucket (2016+), the download link can be found in the Download menu item.

enter image description here


Pre-2016

First method

In the Overview page of the repo, there is a link to download the project.

Direct download of a repo


Second method

Go to Downloads -> Branches -> Download the branch that you want (as .zip, .gz or .bz2). There you'll find download links for all tags. The links will be in the format:

https://bitbucket.org/owner/repository/get/v0.1.2.tar.gz

By tweaking it a little bit, you can also have access to any revision by changing the tag to the commit hash:

https://bitbucket.org/owner/repository/get/A0B1C2D.tar.gz

Appending items to a list of lists in python

import csv
cols = [' V1', ' I1'] # define your columns here, check the spaces!
data = [[] for col in cols] # this creates a list of **different** lists, not a list of pointers to the same list like you did in [[]]*len(positions) 
with open('data.csv', 'r') as f:
    for rec in csv.DictReader(f):
        for l, col in zip(data, cols):
            l.append(float(rec[col]))
print data

# [[3.0, 3.0], [0.01, 0.01]]

Using the passwd command from within a shell script

This is the definitive answer for a teradata node admin.

Go to your /etc/hosts file and create a list of IP's or node names in a text file.

SMP007-1
SMP007-2
SMP007-3

Put the following script in a file.

#set a password across all nodes
printf "User ID: "
read MYUSERID
printf "New Password: "
read MYPASS

while read -r i; do
    echo changing password on "$i"
    ssh root@"$i" sudo echo "$MYUSERID":"$MYPASS" | chpasswd
    echo password changed on "$i"
done< /usr/bin/setpwd.srvrs

Okay I know I've broken a cardinal security rule with ssh and root but I'll let you security folks deal with it.

Now put this in your /usr/bin subdir along with your setpwd.srvrs config file.

When you run the command it prompts you one time for the User ID then one time for the password. Then the script traverses all nodes in the setpwd.srvrs file and does a passwordless ssh to each node, then sets the password without any user interaction or secondary password validation.

How do I retrieve query parameters in Spring Boot?

Use @RequestParam

@RequestMapping(value="user", method = RequestMethod.GET)
public @ResponseBody Item getItem(@RequestParam("data") String itemid){

    Item i = itemDao.findOne(itemid);              
    String itemName = i.getItemName();
    String price = i.getPrice();
    return i;
}

Simplest way to read json from a URL in java

Here are couple of alternatives versions with Jackson (since there are more than one ways you might want data as):

  ObjectMapper mapper = new ObjectMapper(); // just need one
  // Got a Java class that data maps to nicely? If so:
  FacebookGraph graph = mapper.readValue(url, FaceBookGraph.class);
  // Or: if no class (and don't need one), just map to Map.class:
  Map<String,Object> map = mapper.readValue(url, Map.class);

And specifically the usual (IMO) case where you want to deal with Java objects, can be made one liner:

FacebookGraph graph = new ObjectMapper().readValue(url, FaceBookGraph.class);

Other libs like Gson also support one-line methods; why many examples show much longer sections is odd. And even worse is that many examples use obsolete org.json library; it may have been the first thing around, but there are half a dozen better alternatives so there is very little reason to use it.

How to make System.out.println() shorter

Using System.out.println() is bad practice (better use logging framework) -> you should not have many occurences in your code base. Using another method to simply shorten it does not seem a good option.

How to add action listener that listens to multiple buttons

I'm amazed that nobody has mentioned using an action command. This is a pretty standard way of associating sources and listeners. Its really useful if;

  • you have multiple event sources that need to do the same thing (eg if you want the use to be able to press the enter key on a text field as an alternative to clicking a button next to it)
  • you don't have a ref to the component generating the event

see;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;    
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class DontExtendJFrame implements ActionListener {

  private enum Actions {
    HELLO,
    GOODBYE
  }

  public static void main(String[] args) {

    DontExtendJFrame instance = new DontExtendJFrame();

    JFrame frame = new JFrame("Test");
    frame.setLayout(new FlowLayout());
    frame.setSize(200, 100);

    JButton hello = new JButton("Hello");
    hello.setActionCommand(Actions.HELLO.name());
    hello.addActionListener(instance);
    frame.add(hello);

    JButton goodbye = new JButton("Goodbye");
    goodbye.setActionCommand(Actions.GOODBYE.name());
    goodbye.addActionListener(instance);
    frame.add(goodbye);

    frame.setVisible(true);
  }

  @Override
  public void actionPerformed(ActionEvent evt) {
    if (evt.getActionCommand() == Actions.HELLO.name()) {
      JOptionPane.showMessageDialog(null, "Hello");
    } else if (evt.getActionCommand() == Actions.GOODBYE.name()) {
      JOptionPane.showMessageDialog(null, "Goodbye");
    }
  }
}

How do I get the RootViewController from a pushed controller?

For all who are interested in a swift extension, this is what I'm using now:

extension UINavigationController {
    var rootViewController : UIViewController? {
        return self.viewControllers.first
    }
}

How to convert XML to java.util.Map and vice versa

Underscore-java library can convert Map to xml. I am the maintainer of the project. Live example

Code example:

import com.github.underscore.lodash.U;
import java.util.*;
    
public class Main {

  public static void main(String[] args) {
    
    Map<String, Object> map = new LinkedHashMap<String, Object>();
    map.put("name", "chris");
    map.put("island", "faranga");

    System.out.println(U.toXml(map));

    //  <?xml version="1.0" encoding="UTF-8"?>
    //  <root>
    //    <name>chris</name>
    //    <island>faranga</island>
    //  </root>

    // and back:
    map = U.fromXmlMap("<?xml version=\"1.0\" encoding=\"UTF-8\"?><root>"
        + "    <name>chris</name>"
        + "    <island>faranga</island>"
        + "  </root>");
        
    System.out.println(map);
    // {name=chris, island=faranga}
  }
}

for-in statement

edit 2018: This is outdated, js and typescript now have for..of loops.
http://www.typescriptlang.org/docs/handbook/iterators-and-generators.html


The book "TypeScript Revealed" says

"You can iterate through the items in an array by using either for or for..in loops as demonstrated here:

// standard for loop
for (var i = 0; i < actors.length; i++)
{
  console.log(actors[i]);
}

// for..in loop
for (var actor in actors)
{
  console.log(actor);
}

"

Turns out, the second loop does not pass the actors in the loop. So would say this is plain wrong. Sadly it is as above, loops are untouched by typescript.

map and forEach often help me and are due to typescripts enhancements on function definitions more approachable, lke at the very moment:

this.notes = arr.map(state => new Note(state));

My wish list to TypeScript;

  1. Generic collections
  2. Iterators (IEnumerable, IEnumerator interfaces would be best)

Delete all the queues from RabbitMQ?

Actually super easy with management plugin and policies:

  • Goto Management Console (localhost:15672)

  • Goto Admin tab

  • Goto Policies tab(on the right side)

  • Add Policy

  • Fill Fields

    • Virtual Host: Select
    • Name: Expire All Policies(Delete Later)
    • Pattern: .*
    • Apply to: Queues
    • Definition: expires with value 1 (change type from String to Number)
  • Save

  • Checkout Queues tab again

  • All Queues must be deleted

  • And don't forget to remove policy!!!!!!.

How do I get Month and Date of JavaScript in 2 digit format?

If it might spare some time I was looking to get:

YYYYMMDD

for today, and got along with:

const dateDocumentID = new Date()
  .toISOString()
  .substr(0, 10)
  .replace(/-/g, '');

Html.Partial vs Html.RenderPartial & Html.Action vs Html.RenderAction

Differences:

  1. The return type of RenderPartial is void, where as Partial returns MvcHtmlString

  2. Syntax for invoking Partial() and RenderPartial() methods in Razor views

    @Html.Partial("PartialViewName")
    @{ Html.RenderPartial("PartialViewName"); }

  3. Syntax for invoking Partial() and RenderPartial() methods in webform views

[%: Html.Partial("PartialViewName") %]
[% Html.RenderPartial("PartialViewName"); %]

The following are the 2 common interview questions related to Partial() and RenderPartial() When would you use Partial() over RenderPartial() and vice versa?

The main difference is that RenderPartial() returns void and the output will be written directly to the output stream, where as the Partial() method returns MvcHtmlString, which can be assigned to a variable and manipulate it if required. So, when there is a need to assign the output to a variable for manipulating it, then use Partial(), else use RenderPartial().

Which one is better for performance?

From a performance perspective, rendering directly to the output stream is better. RenderPartial() does exactly the same thing and is better for performance over Partial().

Check if a given time lies between two times regardless of date

Based on the ideas and solutions of most authors here, I'd like to share my refined solution with a presumably cleaner code:

    /**
 * Checks if some date is within a time window given by start and end dates
 *
 * @param checkDate - date to check if its hours and minutes is between the startDate and endDate
 * @param startDate - startDate of the time window
 * @param endDate - endDate of the time window
 * @return - returns true if hours and minutes of checkDate is between startDate and endDate
 */
public static boolean isDateBetweenStartAndEndHoursAndMinutes(Date checkDate, Date startDate, Date endDate) {
    if (startDate == null || endDate == null)
        return false;

    LocalDateTime checkLdt = LocalDateTime.ofInstant(Instant.ofEpochMilli(checkDate.getTime()), ZoneId.systemDefault());
    LocalDateTime startLdt = LocalDateTime.ofInstant(Instant.ofEpochMilli(startDate.getTime()), ZoneId.systemDefault());
    LocalDateTime endLdt = LocalDateTime.ofInstant(Instant.ofEpochMilli(endDate.getTime()), ZoneId.systemDefault());

    // Table of situations:
    // Input dates: start (a), end (b), check (c)
    // Interpretations:
    // t(x) = time of point x on timeline; v(x) = nominal value of x

    // Situation A - crossing midnight:
    // c INSIDE
    //      1) t(a) < t(c) < t(b) | v(b) < v(a) < v(c) // e.g. a=22:00, b=03:00, c=23:00 (before midnight)
    //      2) t(a) < t(c) < t(b) | v(c) < v(b) < v(a) // e.g. a=22:00, b=03:00, c=01:00 (after midnight)
    // c OUTSIDE
    //      3) t(c) < t(a) < t(b) | v(b) < v(c) < v(a) // e.g. a=22:00, b=03:00, c=21:00
    //      4) t(a) < t(b) < t(c) | v(b) < v(c) < v(a) // e.g. a=22:00, b=03:00, c=04:00

    //                              ^--- v(b) < v(a) always when shift spans around midnight!

    // Situation B - after/before midnight:
    // c INSIDE
    //      1) t(a) = t(c) < t(b) | v(a) = v(c) < v(b) // e.g. a=06:00, b=14:00, c=06:00
    //      2) t(a) < t(c) < t(b) | v(a) < v(c) < v(b) // e.g. a=06:00, b=14:00, c=08:00
    // c OUTSIDE
    //      3) t(c) < t(a) < t(b) | v(c) < v(a) < v(b) // e.g. a=06:00, b=14:00, c=05:00
    //      4) t(a) < t(b) = t(c) | v(a) < v(b) = v(c) // e.g. a=06:00, b=14:00, c=14:00
    //      5) t(a) < t(b) < t(c) | v(a) < v(b) < v(c) // e.g. a=06:00, b=14:00, c=15:00

    //                              ^--- v(a) < v(b) if shift starts after midnight and ends before midnight!

    // Check for situation A - crossing midnight?
    boolean crossingMidnight = endLdt.isBefore(startLdt);

    if (crossingMidnight) {
        // A.1
        if ((startLdt.isBefore(checkLdt) || startLdt.isEqual(checkLdt))  // t(a) < t(c)
                && checkLdt.isBefore(endLdt.plusDays(1))) // t(c) < t(b+1D)
            return true;

        // A.2
        if (startLdt.isBefore(checkLdt.plusDays(1))   // t(a) < t(c+1D)
                && checkLdt.isBefore(endLdt)) // t(c) < t(b)
            return true;

        // A.3
        if (startLdt.isBefore(endLdt.plusDays(1))   // t(a) < t(b+1D)
                && checkLdt.isBefore(startLdt)) // t(c) < t(a)
            return false;

        // A.4
        if (startLdt.isBefore(endLdt.plusDays(1))   // t(a) < t(b+1D)
                && checkLdt.isAfter(endLdt)) // t(b) < t(c)
            return false;
    } else {
        // B.1 + B.2
        if ((startLdt.isEqual(checkLdt) || startLdt.isBefore(checkLdt))  // t(a) = t(c) || t(a) < t(c)
                && checkLdt.isBefore(endLdt)) // t(c) < t(b)
            return true;
    }

    return false;
}

For the sake of completeness I've added the conditions of A.3 and A.4, but in productive code you can leave it out.

Now you can simply create your start and end dates, as well as your time you want to check and call this static method. The code would go then as follows:

Date check = new SimpleDateFormat("HH:mm:ss").parse("01:00:00");
Date start = new SimpleDateFormat("HH:mm:ss").parse("20:11:13");
Date end = new SimpleDateFormat("HH:mm:ss").parse("14:49:00");

if (isDateBetweenStartAndEndHoursAndMinutes(check, start, end)) {
    Print("checkDate is within start and End date!"); // adjust this true condition to your needs
}

For the TDD aspect I've added unit tests for the scenarios A and B as given above. Please feel free to check it out and report back if you find any errors or spots for optimization.

import org.junit.jupiter.api.Test;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

class LogiqDateUtilsTest  {

    private LocalDateTime startShiftSituationALdt = LocalDateTime.of(0, 1, 1, 22, 0);
    private Date startOfShiftSituationA = Date.from(startShiftSituationALdt.atZone(ZoneId.systemDefault()).toInstant());

    private LocalDateTime endShiftSituationALdt = LocalDateTime.of(0, 1, 1, 3, 0);
    private Date endOfShiftSituationA = Date.from(endShiftSituationALdt.atZone(ZoneId.systemDefault()).toInstant());

    private LocalDateTime startShiftSituationBLdt = LocalDateTime.of(0, 1, 1, 6, 0);
    private Date startOfShiftSituationB = Date.from(startShiftSituationBLdt.atZone(ZoneId.systemDefault()).toInstant());

    private LocalDateTime endShiftSituationBLdt = LocalDateTime.of(0, 1, 1, 14, 0);
    private Date endOfShiftSituationB = Date.from(endShiftSituationBLdt.atZone(ZoneId.systemDefault()).toInstant());

    @Test
    void testSituationA1() {
        LocalDateTime checkLdt = LocalDateTime.of(0, 1, 1, 23, 0);
        Date checkBetween = Date.from(checkLdt.atZone(ZoneId.systemDefault()).toInstant());

        assertTrue(isDateBetweenStartAndEndHoursAndMinutes(checkBetween, startOfShiftSituationA, endOfShiftSituationA));
    }

    @Test
    void testSituationA2() {
        LocalDateTime checkLdt = LocalDateTime.of(0, 1, 1, 1, 0);
        Date checkBetween = Date.from(checkLdt.atZone(ZoneId.systemDefault()).toInstant());

        assertTrue(isDateBetweenStartAndEndHoursAndMinutes(checkBetween, startOfShiftSituationA, endOfShiftSituationA));
    }

    @Test
    void testSituationA3() {
        LocalDateTime checkLdt = LocalDateTime.of(0, 1, 1, 21, 1);
        Date checkBetween = Date.from(checkLdt.atZone(ZoneId.systemDefault()).toInstant());

        assertFalse(isDateBetweenStartAndEndHoursAndMinutes(checkBetween, startOfShiftSituationA, endOfShiftSituationA));
    }

    @Test
    void testSituationA4() {
        LocalDateTime checkLdt = LocalDateTime.of(0, 1, 1, 4, 1);
        Date checkBetween = Date.from(checkLdt.atZone(ZoneId.systemDefault()).toInstant());

        assertFalse(isDateBetweenStartAndEndHoursAndMinutes(checkBetween, startOfShiftSituationA, endOfShiftSituationA));
    }

    @Test
    void testSituationB1() {
        LocalDateTime checkLdt = LocalDateTime.of(0, 1, 1, 6, 0);
        Date checkBetween = Date.from(checkLdt.atZone(ZoneId.systemDefault()).toInstant());

        assertTrue(isDateBetweenStartAndEndHoursAndMinutes(checkBetween, startOfShiftSituationB, endOfShiftSituationB));
    }

    @Test
    void testSituationB2() {
        LocalDateTime checkLdt = LocalDateTime.of(0, 1, 1, 8, 0);
        Date checkBetween = Date.from(checkLdt.atZone(ZoneId.systemDefault()).toInstant());

        assertTrue(isDateBetweenStartAndEndHoursAndMinutes(checkBetween, startOfShiftSituationB, endOfShiftSituationB));
    }

    @Test
    void testSituationB3() {
        LocalDateTime checkLdt = LocalDateTime.of(0, 1, 1, 5, 0);
        Date checkBetween = Date.from(checkLdt.atZone(ZoneId.systemDefault()).toInstant());

        assertFalse(isDateBetweenStartAndEndHoursAndMinutes(checkBetween, startOfShiftSituationB, endOfShiftSituationB));
    }

    @Test
    void testSituationB4() {
        LocalDateTime checkLdt = LocalDateTime.of(0, 1, 1, 14, 0);
        Date checkBetween = Date.from(checkLdt.atZone(ZoneId.systemDefault()).toInstant());

        assertFalse(isDateBetweenStartAndEndHoursAndMinutes(checkBetween, startOfShiftSituationB, endOfShiftSituationB));
    }

    @Test
    void testSituationB5() {
        LocalDateTime checkLdt = LocalDateTime.of(0, 1, 1, 15, 0);
        Date checkBetween = Date.from(checkLdt.atZone(ZoneId.systemDefault()).toInstant());

        assertFalse(isDateBetweenStartAndEndHoursAndMinutes(checkBetween, startOfShiftSituationB, endOfShiftSituationB));
    }
}

Cheers!

Convert a Map<String, String> to a POJO

Well, you can achieve that with Jackson, too. (and it seems to be more comfortable since you were considering using jackson).

Use ObjectMapper's convertValue method:

final ObjectMapper mapper = new ObjectMapper(); // jackson's objectmapper
final MyPojo pojo = mapper.convertValue(map, MyPojo.class);

No need to convert into JSON string or something else; direct conversion does much faster.

Convert SVG image to PNG with PHP

That's funny you asked this, I just did this recently for my work's site and I was thinking I should write a tutorial... Here is how to do it with PHP/Imagick, which uses ImageMagick:

$usmap = '/path/to/blank/us-map.svg';
$im = new Imagick();
$svg = file_get_contents($usmap);

/*loop to color each state as needed, something like*/ 
$idColorArray = array(
     "AL" => "339966"
    ,"AK" => "0099FF"
    ...
    ,"WI" => "FF4B00"
    ,"WY" => "A3609B"
);

foreach($idColorArray as $state => $color){
//Where $color is a RRGGBB hex value
    $svg = preg_replace(
         '/id="'.$state.'" style="fill:#([0-9a-f]{6})/'
        , 'id="'.$state.'" style="fill:#'.$color
        , $svg
    );
}

$im->readImageBlob($svg);

/*png settings*/
$im->setImageFormat("png24");
$im->resizeImage(720, 445, imagick::FILTER_LANCZOS, 1);  /*Optional, if you need to resize*/

/*jpeg*/
$im->setImageFormat("jpeg");
$im->adaptiveResizeImage(720, 445); /*Optional, if you need to resize*/

$im->writeImage('/path/to/colored/us-map.png');/*(or .jpg)*/
$im->clear();
$im->destroy();

the steps regex color replacement may vary depending on the svg path xml and how you id & color values are stored. If you don't want to store a file on the server, you can output the image as base 64 like

<?php echo '<img src="data:image/jpg;base64,' . base64_encode($im) . '"  />';?>

(before you use clear/destroy) but ie has issues with PNG as base64 so you'd probably have to output base64 as jpeg

you can see an example here I did for a former employer's sales territory map:

Start: https://upload.wikimedia.org/wikipedia/commons/1/1a/Blank_US_Map_(states_only).svg

Finish: enter image description here

Edit

Since writing the above, I've come up with 2 improved techniques:

1) instead of a regex loop to change the fill on state , use CSS to make style rules like

<style type="text/css">
#CA,#FL,HI{
    fill:blue;
}
#Al, #NY, #NM{
    fill:#cc6699;
}
/*etc..*/
</style>

and then you can do a single text replace to inject your css rules into the svg before proceeding with the imagick jpeg/png creation. If the colors don't change, check to make sure you don't have any inline fill styles in your path tags overriding the css.

2) If you don't have to actually create a jpeg/png image file (and don't need to support outdated browsers), you can manipulate the svg directly with jQuery. You can't access the svg paths when embedding the svg using img or object tags, so you'll have to directly include the svg xml in your webpage html like:

<div>
<?php echo file_get_contents('/path/to/blank/us-map.svg');?>
</div>

then changing the colors is as easy as:

<script type="text/javascript" src="/path/to/jquery.js"></script>
<script type="text/javascript">
    $('#CA').css('fill', 'blue');
    $('#NY').css('fill', '#ff0000');
</script>

How do I use FileSystemObject in VBA?

In excel 2013 the object creation string is:

Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")

instead of the code in the answer above:

Dim fs,fname
Set fs=Server.CreateObject("Scripting.FileSystemObject")

Adding headers to requests module

You can also do this to set a header for all future gets for the Session object, where x-test will be in all s.get() calls:

s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})

# both 'x-test' and 'x-test2' are sent
s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})

from: http://docs.python-requests.org/en/latest/user/advanced/#session-objects

What does yield mean in PHP?

The below code illustrates how using a generator returns a result before completion, unlike the traditional non generator approach that returns a complete array after full iteration. With the generator below, the values are returned when ready, no need to wait for an array to be completely filled:

<?php 

function sleepiterate($length) {
    for ($i=0; $i < $length; $i++) {
        sleep(2);
        yield $i;
    }
}

foreach (sleepiterate(5) as $i) {
    echo $i, PHP_EOL;
}

Random String Generator Returning Same String

Another sample (tested in vs2013):

    Random R = new Random();
    public static string GetRandomString(int Length)
    {
        char[] ArrRandomChar = new char[Length];
        for (int i = 0; i < Length; i++)
            ArrRandomChar[i] = (char)('a' + R.Next(0, 26));
        return new string(ArrRandomChar);
    }

    string D = GetRandomString(12);

Implemented by myself.

How can I compare a date and a datetime in Python?

I am trying to compare date which are in string format like '20110930'

benchMark = datetime.datetime.strptime('20110701', "%Y%m%d") 

actualDate = datetime.datetime.strptime('20110930', "%Y%m%d")

if actualDate.date() < benchMark.date():
    print True

How to use string.substr() function?

You can get the above output using following code in c

#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
  char *str;
  clrscr();
  printf("\n Enter the string");
  gets(str);
  for(int i=0;i<strlen(str)-1;i++)
  {
    for(int j=i;j<=i+1;j++)
      printf("%c",str[j]);
    printf("\t");
  }
  getch();
  return 0;
}

How to convert a list of numbers to jsonarray in Python

import json
row = [1L,[0.1,0.2],[[1234L,1],[134L,2]]]
row_json = json.dumps(row)

MySQL duplicate entry error even though there is no duplicate entry

I had a similar issue, but in my case it turned out that I used case insensitive collation - utf8_general_ci.

Thus, when I tried to insert two strings which were different in a case-sensitive comparison, but the same in the case-insensitive one, MySQL fired the error and I couldn't understand what a problem, because I used a case-sensitive search.

The solution is to change the collation of a table, e.g. I used utf8_bin which is case-sensitive (or utf8_general_cs should be appropriate one too).

How to upsert (update or insert) in SQL Server 2005

Try to check for existence:

IF NOT EXISTS (SELECT * FROM dbo.Employee WHERE ID = @SomeID)

    INSERT INTO dbo.Employee(Col1, ..., ColN)
    VALUES(Val1, .., ValN)

ELSE

    UPDATE dbo.Employee
    SET Col1 = Val1, Col2 = Val2, ...., ColN = ValN
    WHERE ID = @SomeID

You could easily wrap this into a stored procedure and just call that stored procedure from the outside (e.g. from a programming language like C# or whatever you're using).

Update: either you can just write this entire statement in one long string (doable - but not really very useful) - or you can wrap it into a stored procedure:

CREATE PROCEDURE dbo.InsertOrUpdateEmployee
       @ID INT,
       @Name VARCHAR(50),
       @ItemName VARCHAR(50),  
       @ItemCatName VARCHAR(50),
       @ItemQty DECIMAL(15,2)
AS BEGIN
    IF NOT EXISTS (SELECT * FROM dbo.Table1 WHERE ID = @ID)
       INSERT INTO dbo.Table1(ID, Name, ItemName, ItemCatName, ItemQty)
       VALUES(@ID, @Name, @ItemName, @ItemCatName, @ItemQty)
    ELSE
       UPDATE dbo.Table1
       SET Name = @Name,
           ItemName = @ItemName,
           ItemCatName = @ItemCatName,
           ItemQty = @ItemQty
       WHERE ID = @ID
END

and then just call that stored procedure from your ADO.NET code

PPT to PNG with transparent background

It can't be done, either manually or progamatically. This is because the color behind every slide master is white. If you set your background to 100% transparent, it will print as white.

The best you could do is design your slide with all the stuff you want, group everything you want to appear in the transparent image and then right-click/save as picture/.PNG (or you could do that with a macro as well). In this way you would retain transparency.

Here's an example of how to export all slides' shapes to seperate PNG files. Note:

  1. This does not get any background shapes on the Slide Master.
  2. Resulting PNGs will not be the same size as each other, depending on where the shapes are located on each slide.
  3. This uses a depreciated function, namely Shape.Export. This means that while the function is still available up to PowerPoint 2010, it may be removed from PowerPoint VBA later.

    Sub PrintShapesToPng()
        Dim ap As Presentation: Set ap = ActivePresentation
        Dim sl As slide
        Dim shGroup As ShapeRange
        For Each sl In ap.Slides
            ActiveWindow.View.GotoSlide (sl.SlideIndex)
            sl.Shapes.SelectAll
            Set shGroup = ActiveWindow.Selection.ShapeRange
            shGroup.Export ap.Path & "\Slide" & sl.SlideIndex & ".png", _
                                ppShapeFormatPNG, , , ppRelativeToSlide
        Next
    End Sub
    

Single Form Hide on Startup

    static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Form1 form1 = new Form1();
            form1.Visible = false;
            Application.Run();

        }
 private void ExitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
            Application.Exit();
        }

How can I update npm on Windows?

this is best tool to maintain version of NODE.Js i NVM

Node Version Manager (nvm) for Windows but for Windows, with an installer. Download Now! This has always been a node version manager, not an io.js manager, so there is no back-support for io.js. However, node 4+ is supported. enter image description here

Angular 2 Scroll to top on Route Change

Angular lately introduced a new feature, inside angular routing module make changes like below

@NgModule({
  imports: [RouterModule.forRoot(routes,{
    scrollPositionRestoration: 'top'
  })],

What causes the Broken Pipe Error?

When peer close, you just do not know whether it just stop sending or both sending and receiving.Because TCP allows this, btw, you should know the difference between close and shutdown. If peer both stop sending and receiving, first you send some bytes, it will succeed. But the peer kernel will send you RST. So subsequently you send some bytes, your kernel will send you SIGPIPE signal, if you catch or ignore this signal, when your send returns, you just get Broken pipe error, or if you don't , the default behavior of your program is crashing.

Starting the week on Monday with isoWeekday()

This way you can set the initial day of the week.

moment.locale('en', {
    week: {
        dow: 6
    }
});
moment.locale('en');

Make sure to use it with moment().weekday(1); instead of moment.isoWeekday(1)

How to get element by class name?

Another option is to use querySelector('.foo') or querySelectorAll('.foo') which have broader browser support than getElementsByClassName.

http://caniuse.com/#feat=queryselector

http://caniuse.com/#feat=getelementsbyclassname

Passing parameter to controller from route in laravel

You can add them like this

  Route::get('company/{name}', 'PublicareaController@companydetails');

Formula to check if string is empty in Crystal Reports

On the formula menu just Select "Default Values for Nulls" then just add all the fields like the below:

{@Table.Field1} + {@Table.Field2} + {@Table.Field3} + {@Table.Field4} + {@Table.Field5}

curl POST format for CURLOPT_POSTFIELDS

Do not pass a string at all!

You can pass an array and let php/curl do the dirty work of encoding etc.

Calling a particular PHP function on form submit

PHP is run on a server, Your browser is a client. Once the server sends all the info to the client, nothing can be done on the server until another request is made.

To make another request without refreshing the page you are going to have to look into ajax. Look into jQuery as it makes ajax requests easy

Issue in installing php7.2-mcrypt

Mcrypt PECL extenstion

 sudo apt-get -y install gcc make autoconf libc-dev pkg-config
 sudo apt-get -y install libmcrypt-dev
 sudo pecl install mcrypt-1.0.1

When you are shown the prompt

 libmcrypt prefix? [autodetect] :

Press [Enter] to autodetect.

After success installing mcrypt trought pecl, you should add mcrypt.so extension to php.ini.

The output will look like this:

...
Build process completed successfully
Installing '/usr/lib/php/20170718/mcrypt.so'    ---->   this is our path to mcrypt extension lib
install ok: channel://pecl.php.net/mcrypt-1.0.1
configuration option "php_ini" is not set to php.ini location
You should add "extension=mcrypt.so" to php.ini

Grab installing path and add to cli and apache2 php.ini configuration.

sudo bash -c "echo extension=/usr/lib/php/20170718/mcrypt.so > /etc/php/7.2/cli/conf.d/mcrypt.ini"
sudo bash -c "echo extension=/usr/lib/php/20170718/mcrypt.so > /etc/php/7.2/apache2/conf.d/mcrypt.ini"

Verify that the extension was installed

Run command:

php -i | grep "mcrypt"

The output will look like this:

/etc/php/7.2/cli/conf.d/mcrypt.ini
Registered Stream Filters => zlib.*, string.rot13, string.toupper, string.tolower, string.strip_tags, convert.*, consumed, dechunk, convert.iconv.*, mcrypt.*, mdecrypt.*
mcrypt
mcrypt support => enabled
mcrypt_filter support => enabled
mcrypt.algorithms_dir => no value => no value
mcrypt.modes_dir => no value => no value

Cannot read property 'push' of undefined when combining arrays

answer to your question is simple order is not a object make it an array. var order = new Array(); order.push(/item to push/); when ever this error appears just check the left of which property the error is in this case it is push which is order[] so it is undefined.

Finding duplicate values in MySQL

SELECT 
    t.*,
    (SELECT COUNT(*) FROM city AS tt WHERE tt.name=t.name) AS count 
FROM `city` AS t 
WHERE 
    (SELECT count(*) FROM city AS tt WHERE tt.name=t.name) > 1 ORDER BY count DESC

How to open up a form from another form in VB.NET?

Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) _
                          Handles Button3.Click

    Dim box = New AboutBox1()
    box.Show()

End Sub

Select value from list of tuples where condition

If you have named tuples you can do this:

results = [t.age for t in mylist if t.person_id == 10]

Otherwise use indexes:

results = [t[1] for t in mylist if t[0] == 10]

Or use tuple unpacking as per Nate's answer. Note that you don't have to give a meaningful name to every item you unpack. You can do (person_id, age, _, _, _, _) to unpack a six item tuple.

How to loop through a checkboxlist and to find what's checked and not checked?

for (int i = 0; i < clbIncludes.Items.Count; i++)
  if (clbIncludes.GetItemChecked(i))
    // Do selected stuff
  else
    // Do unselected stuff

If the the check is in indeterminate state, this will still return true. You may want to replace

if (clbIncludes.GetItemChecked(i))

with

if (clbIncludes.GetItemCheckState(i) == CheckState.Checked)

if you want to only include actually checked items.

How can I do a case insensitive string comparison?

I think you will find more information in this link:

http://codeidol.com/community/dotnet/controlling-case-sensitivity-when-comparing-two-st/8873/

Use the Compare static method on the String class to compare the two strings. Whether the comparison is case-insensitive is determined by the third parameter of one of its overloads. For example:

string lowerCase = "abc";
string upperCase = "AbC";
int caseInsensitiveResult = string.Compare(lowerCase, upperCase,
  StringComparison.CurrentCultureIgnoreCase);
int caseSensitiveResult = string.Compare(lowerCase,
  StringComparison.CurrentCulture);

The caseSensitiveResult value is -1 (indicating that lowerCase is "less than" upperCase) and the caseInsensitiveResult is zero (indicating that lowerCase "equals" upperCase).

Associating existing Eclipse project with existing SVN repository

I came across the same issue. I checked out using Tortoise client and then tried to import the projects in Eclipse using import wizard. Eclipse did not recognize the svn location. I tried share option as mentioned in the above posts and it tried to commit these projects into SVN. But my issue was a version mismatch. I selected svn 1.8 version in eclipse (I was using 1.7 in eclipse and 1.8.8 in tortoise) and then re imported the projects. It resolved with no issues.

How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure?

The linked list holds operations on the shared data structure.

For example, if I have a stack, it will be manipulated with pushes and pops. The linked list would be a set of pushes and pops on the pseudo-shared stack. Each thread sharing that stack will actually have a local copy, and to get to the current shared state, it'll walk the linked list of operations, and apply each operation in order to its local copy of the stack. When it reaches the end of the linked list, its local copy holds the current state (though, of course, it's subject to becoming stale at any time).

In the traditional model, you'd have some sort of locks around each push and pop. Each thread would wait to obtain a lock, then do a push or pop, then release the lock.

In this model, each thread has a local snapshot of the stack, which it keeps synchronized with other threads' view of the stack by applying the operations in the linked list. When it wants to manipulate the stack, it doesn't try to manipulate it directly at all. Instead, it simply adds its push or pop operation to the linked list, so all the other threads can/will see that operation and they can all stay in sync. Then, of course, it applies the operations in the linked list, and when (for example) there's a pop it checks which thread asked for the pop. It uses the popped item if and only if it's the thread that requested this particular pop.

How can I make IntelliJ IDEA update my dependencies from Maven?

For some reason IntelliJ (at least in version 2019.1.2) ignores dependencies in local .m2 directory. None of above solutions worked for me. The only thing finally forced IntelliJ to discover local dependencies was:

  1. Close project
  2. Open project clicking on pom.xml (not on a project directory)
  3. Click Open as Project

List item

  1. Click Delete Existing Project and Import

enter image description here

Regular Expressions- Match Anything

<?php
$str = "I bought _ sheep";
preg_match("/I bought (.*?) sheep", $str, $match);
print_r($match);
?>

http://sandbox.phpcode.eu/g/b2243.php

How to mock location on device?

If you use this phone only in development lab, there is a chance you can solder away GPS chip and feed serial port directly with NMEA sequences from other device.

Convert base64 png data to javascript file objects

Way 1: only works for dataURL, not for other types of url.

function dataURLtoFile(dataurl, filename) {
    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while(n--){
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, {type:mime});
}

//Usage example:
var file = dataURLtoFile('data:image/png;base64,......', 'a.png');
console.log(file);

Way 2: works for any type of url, (http url, dataURL, blobURL, etc...)

//return a promise that resolves with a File instance
function urltoFile(url, filename, mimeType){
    mimeType = mimeType || (url.match(/^data:([^;]+);/)||'')[1];
    return (fetch(url)
        .then(function(res){return res.arrayBuffer();})
        .then(function(buf){return new File([buf], filename, {type:mimeType});})
    );
}

//Usage example:
urltoFile('data:image/png;base64,......', 'a.png')
.then(function(file){
    console.log(file);
})

Both works in Chrome and Firefox.

Anaconda vs. miniconda

Miniconda gives you the Python interpreter itself, along with a command-line tool called conda which operates as a cross-platform package manager geared toward Python packages, similar in spirit to the apt or yum tools that Linux users might be familiar with.

Anaconda includes both Python and conda, and additionally bundles a suite of other pre-installed packages geared toward scientific computing. Because of the size of this bundle, expect the installation to consume several gigabytes of disk space.

Source: Jake VanderPlas's Python Data Science Handbook

C library function to perform sort

try qsort in stdlib.h.

I have Python on my Ubuntu system, but gcc can't find Python.h

You need the python-dev package which contains Python.h

Expansion of variables inside single quotes in a command in Bash

Below is what worked for me -

QUOTE="'"
hive -e "alter table TBL_NAME set location $QUOTE$TBL_HDFS_DIR_PATH$QUOTE"

Pass a list to a function to act as multiple arguments

Since Python 3.5 you can unpack unlimited amount of lists.

PEP 448 - Additional Unpacking Generalizations

So this will work:

a = ['1', '2', '3', '4']
b = ['5', '6']
function_that_needs_strings(*a, *b)

How to HTML encode/escape a string? Is there a built-in?

You can use either h() or html_escape(), but most people use h() by convention. h() is short for html_escape() in rails.

In your controller:

@stuff = "<b>Hello World!</b>"

In your view:

<%=h @stuff %>

If you view the HTML source: you will see the output without actually bolding the data. I.e. it is encoded as &lt;b&gt;Hello World!&lt;/b&gt;.

It will appear an be displayed as <b>Hello World!</b>

ImportError: No module named PytQt5

pip install pyqt5 for python3 for ubuntu

Getting Python error "from: can't read /var/mail/Bio"

I ran into a similar error

"from: can't read /var/mail/django.test.utils"

when trying to run a command

>>> from django.test.utils import setup_test_environment
>>> setup_test_environment()

in the tutorial at https://docs.djangoproject.com/en/1.8/intro/tutorial05/

after reading the answer by Tamás I realized I was not trying this command in the python shell but in the termnial (this can happen to those new to linux)

solution was to first enter in the python shell with the command python and when you get these >>> then run any python commands

What are the differences between ArrayList and Vector?

ArrayList is newer and 20-30% faster.

If you don't need something explitly apparent in Vector, use ArrayList

How to specify function types for void (not Void) methods in Java8?

When you need to accept a function as argument which takes no arguments and returns no result (void), in my opinion it is still best to have something like

  public interface Thunk { void apply(); }

somewhere in your code. In my functional programming courses the word 'thunk' was used to describe such functions. Why it isn't in java.util.function is beyond my comprehension.

In other cases I find that even when java.util.function does have something that matches the signature I want - it still doesn't always feel right when the naming of the interface doesn't match the use of the function in my code. I guess it's a similar point that is made elsewhere here regarding 'Runnable' - which is a term associated with the Thread class - so while it may have he signature I need, it is still likely to confuse the reader.

Hot deploy on JBoss - how do I make JBoss "see" the change?

This worked for me in Eclipse Mars with WildFly 11. Double-click on WildFly server under Servers to open the configuration page. In the Overview tab -> Publishing, choose "Automatically publish when resources change" and set the interval to 1. Next, Overview tab -> Application Reload Behavior, uncheck the use default pattern and set the pattern to \.jar$|\.class$. In the Deployment tab, uncheck Deploy project as compressed archives. Hope this helps.

XmlSerializer giving FileNotFoundException at constructor

Believe it or not, this is normal behaviour. An exception is thrown but handled by the XmlSerializer, so if you just ignore it everything should continue on fine.

I have found this very annoying, and there have been many complaints about this if you search around a bit, but from what I've read Microsoft don't plan on doing anything about it.

You can avoid getting Exception popups all the time while debugging if you switch off first chance exceptions for that specific exception. In Visual Studio, go to Debug -> Exceptions (or press Ctrl + Alt + E), Common Language Runtime Exceptions -> System.IO -> System.IO.FileNotFoundException.

You can find information about another way around it in the blog post C# XmlSerializer FileNotFound exception (which discusses Chris Sells' tool XmlSerializerPreCompiler).

' << ' operator in verilog

1 << ADDR_WIDTH means 1 will be shifted 8 bits to the left and will be assigned as the value for RAM_DEPTH.

In addition, 1 << ADDR_WIDTH also means 2^ADDR_WIDTH.

Given ADDR_WIDTH = 8, then 2^8 = 256 and that will be the value for RAM_DEPTH

How do I jump to a closing bracket in Visual Studio Code?

Simply adding opening tag and writing element name and while adding closing tag with pressing shift button keyword will do the job.

For example, If i need to write <Text></Text>

I will write, <Text and will press > + Shifttogether, it will provide me desired opening closing tag of Text element.

Thanks, Nirmala

Database development mistakes made by application developers

Treating the database as just a storage mechanism (i.e. glorified collections library) and hence subordinate to their application (ignoring other applications which share the data)

How to list all Git tags?

To list tags I prefer:

git tag -n

The -n flag displays the first line of the annotation message along with the tag, or the first commit message line if the tag is not annotated.

You can also do git tag -n5 to show the first 5 lines of the annotation.

Callback after all asynchronous forEach callbacks are completed

It's odd how many incorrect answers has been given to asynchronous case! It can be simply shown that checking index does not provide expected behavior:

// INCORRECT
var list = [4000, 2000];
list.forEach(function(l, index) {
    console.log(l + ' started ...');
    setTimeout(function() {
        console.log(index + ': ' + l);
    }, l);
});

output:

4000 started
2000 started
1: 2000
0: 4000

If we check for index === array.length - 1, callback will be called upon completion of first iteration, whilst first element is still pending!

To solve this problem without using external libraries such as async, I think your best bet is to save length of list and decrement if after each iteration. Since there's just one thread we're sure there no chance of race condition.

var list = [4000, 2000];
var counter = list.length;
list.forEach(function(l, index) {
    console.log(l + ' started ...');
    setTimeout(function() {
        console.log(index + ': ' + l);
        counter -= 1;
        if ( counter === 0)
            // call your callback here
    }, l);
});

Why doesn't calling a Python string method do anything unless you assign its output?

Example for String Methods

Given a list of filenames, we want to rename all the files with extension hpp to the extension h. To do this, we would like to generate a new list called newfilenames, consisting of the new filenames. Fill in the blanks in the code using any of the methods you’ve learned thus far, like a for loop or a list comprehension.

filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]
# Generate newfilenames as a list containing the new filenames
# using as many lines of code as your chosen method requires.
newfilenames = []
for i in filenames:
    if i.endswith(".hpp"):
        x = i.replace("hpp", "h")
        newfilenames.append(x)
    else:
        newfilenames.append(i)


print(newfilenames)
# Should be ["program.c", "stdio.h", "sample.h", "a.out", "math.h", "hpp.out"]

Minimal web server using netcat

while true; do (echo -e 'HTTP/1.1 200 OK\r\nConnection: close\r\n';) | timeout 1  nc -lp 8080 ; done

Closes connection after 1 sec, so curl doesn't hang on it.

How to overwrite the output directory in spark

df.write.mode('overwrite').parquet("/output/folder/path") works if you want to overwrite a parquet file using python. This is in spark 1.6.2. API may be different in later versions

Windows batch: sleep

Microsoft has a sleep function you can call directly.

    Usage:  sleep      time-to-sleep-in-seconds
            sleep [-m] time-to-sleep-in-milliseconds
            sleep [-c] commited-memory ratio (1%-100%)

You can just say sleep 1 for example to sleep for 1 second in your batch script.

IMO Ping is a bit of a hack for this use case.

Recursively look for files with a specific extension

The syntax I use is a bit different than what @Matt suggested:

find $directory -type f -name \*.in

(it's one less keystroke).

How do you check in python whether a string contains only numbers?

As every time I encounter an issue with the check is because the str can be None sometimes, and if the str can be None, only use str.isdigit() is not enough as you will get an error

AttributeError: 'NoneType' object has no attribute 'isdigit'

and then you need to first validate the str is None or not. To avoid a multi-if branch, a clear way to do this is:

if str and str.isdigit():

Hope this helps for people have the same issue like me.

SQL - IF EXISTS UPDATE ELSE INSERT INTO

Try this:

INSERT INTO `center_course_fee` (`fk_course_id`,`fk_center_code`,`course_fee`) VALUES ('69', '4920153', '6000') ON DUPLICATE KEY UPDATE `course_fee` = '6000';

laravel-5 passing variable to JavaScript

Is very easy, I use this code:

Controller:

$langs = Language::all()->toArray();
return view('NAATIMockTest.Admin.Language.index', compact('langs'));

View:

<script type="text/javascript">
    var langs = <?php echo json_decode($langs); ?>;
    console.log(langs);
</script>

hope it has been helpful, regards!

AJAX post error : Refused to set unsafe header "Connection"

Remove these two lines:

xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");

XMLHttpRequest isn't allowed to set these headers, they are being set automatically by the browser. The reason is that by manipulating these headers you might be able to trick the server into accepting a second request through the same connection, one that wouldn't go through the usual security checks - that would be a security vulnerability in the browser.

Add MIME mapping in web.config for IIS Express

Thanks for this post. I got this worked for using mustache templates in my asp.net mvc project I used the following, and it worked for me.

<system.webServer>   
  <staticContent>
   <mimeMap fileExtension=".mustache" mimeType="text/html"/>
  </staticContent>
</system.WebServer>

Fetching distinct values on a column using Spark DataFrame

This solution demonstrates how to transform data with Spark native functions which are better than UDFs. It also demonstrates how dropDuplicates which is more suitable than distinct for certain queries.

Suppose you have this DataFrame:

+-------+-------------+
|country|    continent|
+-------+-------------+
|  china|         asia|
| brazil|south america|
| france|       europe|
|  china|         asia|
+-------+-------------+

Here's how to take all the distinct countries and run a transformation:

df
  .select("country")
  .distinct
  .withColumn("country", concat(col("country"), lit(" is fun!")))
  .show()
+--------------+
|       country|
+--------------+
|brazil is fun!|
|france is fun!|
| china is fun!|
+--------------+

You can use dropDuplicates instead of distinct if you don't want to lose the continent information:

df
  .dropDuplicates("country")
  .withColumn("description", concat(col("country"), lit(" is a country in "), col("continent")))
  .show(false)
+-------+-------------+------------------------------------+
|country|continent    |description                         |
+-------+-------------+------------------------------------+
|brazil |south america|brazil is a country in south america|
|france |europe       |france is a country in europe       |
|china  |asia         |china is a country in asia          |
+-------+-------------+------------------------------------+

See here for more information about filtering DataFrames and here for more information on dropping duplicates.

Ultimately, you'll want to wrap your transformation logic in custom transformations that can be chained with the Dataset#transform method.

How to use DISTINCT and ORDER BY in same SELECT statement?

Try next, but it's not useful for huge data...

SELECT DISTINCT Cat FROM (
  SELECT Category as Cat FROM MonitoringJob ORDER BY CreationDate DESC
);

Display Yes and No buttons instead of OK and Cancel in Confirm box?

As far as I know, it's not possible to change the content of the buttons, at least not easily. It's fairly easy to have your own custom alert box using JQuery UI though

post checkbox value

There are many links that lets you know how to handle post values from checkboxes in php. Look at this link: http://www.html-form-guide.com/php-form/php-form-checkbox.html

Single check box

HTML code:

<form action="checkbox-form.php" method="post">
    Do you need wheelchair access?
    <input type="checkbox" name="formWheelchair" value="Yes" />
    <input type="submit" name="formSubmit" value="Submit" />
</form>

PHP Code:

<?php

if (isset($_POST['formWheelchair']) && $_POST['formWheelchair'] == 'Yes') 
{
    echo "Need wheelchair access.";
}
else
{
    echo "Do not Need wheelchair access.";
}    

?>

Check box group

<form action="checkbox-form.php" method="post">
    Which buildings do you want access to?<br />
    <input type="checkbox" name="formDoor[]" value="A" />Acorn Building<br />
    <input type="checkbox" name="formDoor[]" value="B" />Brown Hall<br />
    <input type="checkbox" name="formDoor[]" value="C" />Carnegie Complex<br />
    <input type="checkbox" name="formDoor[]" value="D" />Drake Commons<br />
    <input type="checkbox" name="formDoor[]" value="E" />Elliot House

    <input type="submit" name="formSubmit" value="Submit" />
 /form>

<?php
  $aDoor = $_POST['formDoor'];
  if(empty($aDoor)) 
  {
    echo("You didn't select any buildings.");
  } 
  else
  {
    $N = count($aDoor);

    echo("You selected $N door(s): ");
    for($i=0; $i < $N; $i++)
    {
      echo($aDoor[$i] . " ");
    }
  }
?>

EditorFor() and html properties

UPDATE: hm, obviously this won't work because model is passed by value so attributes are not preserved; but I leave this answer as an idea.

Another solution, I think, would be to add your own TextBox/etc helpers, that will check for your own attributes on model.

public class ViewModel
{
  [MyAddAttribute("class", "myclass")]
  public string StringValue { get; set; }
}

public class MyExtensions
{
  public static IDictionary<string, object> GetMyAttributes(object model)
  {
     // kind of prototype code...
     return model.GetType().GetCustomAttributes(typeof(MyAddAttribute)).OfType<MyAddAttribute>().ToDictionary(
          x => x.Name, x => x.Value);
  }
}

<!-- in the template -->
<%= Html.TextBox("Name", Model, MyExtensions.GetMyAttributes(Model)) %>

This one is easier but not as convinient/flexible.

Is there a simple way that I can sort characters in a string in alphabetical order

You can use LINQ:

String.Concat(str.OrderBy(c => c))

If you want to remove duplicates, add .Distinct().

Install MySQL on Ubuntu without a password prompt

This should do the trick

export DEBIAN_FRONTEND=noninteractive
sudo -E apt-get -q -y install mysql-server

Of course, it leaves you with a blank root password - so you'll want to run something like

mysqladmin -u root password mysecretpasswordgoeshere

Afterwards to add a password to the account.

how to insert value into DataGridView Cell?

int index= datagridview.rows.add();
datagridview.rows[index].cells[1].value=1;
datagridview.rows[index].cells[2].value="a";
datagridview.rows[index].cells[3].value="b";

hope this help! :)

Embed YouTube video - Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

You only need to copy <iframe> from the YouTube Embed section (click on SHARE below the video and then EMBED and copy the entire iframe).

How to add class active on specific li on user click with jQuery

        // Remove active for all items.
        $('.sidebar-menu li').removeClass('active');
        // highlight submenu item
        $('li a[href="' + this.location.pathname + '"]').parent().addClass('active');
        // Highlight parent menu item.
        $('ul a[href="' + this.location.pathname + '"]').parents('li').addClass('active')

How to group by week in MySQL?

Just ad this in the select :

DATE_FORMAT($yourDate, \'%X %V\') as week

And

group_by(week);

What is Domain Driven Design?

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

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

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

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

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

Can Windows' built-in ZIP compression be scripted?

There are VBA methods to zip and unzip using the windows built in compression as well, which should give some insight as to how the system operates. You may be able to build these methods into a scripting language of your choice.

The basic principle is that within windows you can treat a zip file as a directory, and copy into and out of it. So to create a new zip file, you simply make a file with the extension .zip that has the right header for an empty zip file. Then you close it, and tell windows you want to copy files into it as though it were another directory.

Unzipping is easier - just treat it as a directory.

In case the web pages are lost again, here are a few of the relevant code snippets:

ZIP

Sub NewZip(sPath)
'Create empty Zip File
'Changed by keepITcool Dec-12-2005
    If Len(Dir(sPath)) > 0 Then Kill sPath
    Open sPath For Output As #1
    Print #1, Chr$(80) & Chr$(75) & Chr$(5) & Chr$(6) & String(18, 0)
    Close #1
End Sub


Function bIsBookOpen(ByRef szBookName As String) As Boolean
' Rob Bovey
    On Error Resume Next
    bIsBookOpen = Not (Application.Workbooks(szBookName) Is Nothing)
End Function


Function Split97(sStr As Variant, sdelim As String) As Variant
'Tom Ogilvy
    Split97 = Evaluate("{""" & _
                       Application.Substitute(sStr, sdelim, """,""") & """}")
End Function

Sub Zip_File_Or_Files()
    Dim strDate As String, DefPath As String, sFName As String
    Dim oApp As Object, iCtr As Long, I As Integer
    Dim FName, vArr, FileNameZip

    DefPath = Application.DefaultFilePath
    If Right(DefPath, 1) <> "\" Then
        DefPath = DefPath & "\"
    End If

    strDate = Format(Now, " dd-mmm-yy h-mm-ss")
    FileNameZip = DefPath & "MyFilesZip " & strDate & ".zip"

    'Browse to the file(s), use the Ctrl key to select more files
    FName = Application.GetOpenFilename(filefilter:="Excel Files (*.xl*), *.xl*", _
                    MultiSelect:=True, Title:="Select the files you want to zip")
    If IsArray(FName) = False Then
        'do nothing
    Else
        'Create empty Zip File
        NewZip (FileNameZip)
        Set oApp = CreateObject("Shell.Application")
        I = 0
        For iCtr = LBound(FName) To UBound(FName)
            vArr = Split97(FName(iCtr), "\")
            sFName = vArr(UBound(vArr))
            If bIsBookOpen(sFName) Then
                MsgBox "You can't zip a file that is open!" & vbLf & _
                       "Please close it and try again: " & FName(iCtr)
            Else
                'Copy the file to the compressed folder
                I = I + 1
                oApp.Namespace(FileNameZip).CopyHere FName(iCtr)

                'Keep script waiting until Compressing is done
                On Error Resume Next
                Do Until oApp.Namespace(FileNameZip).items.Count = I
                    Application.Wait (Now + TimeValue("0:00:01"))
                Loop
                On Error GoTo 0
            End If
        Next iCtr

        MsgBox "You find the zipfile here: " & FileNameZip
    End If
End Sub

UNZIP

Sub Unzip1()
    Dim FSO As Object
    Dim oApp As Object
    Dim Fname As Variant
    Dim FileNameFolder As Variant
    Dim DefPath As String
    Dim strDate As String

    Fname = Application.GetOpenFilename(filefilter:="Zip Files (*.zip), *.zip", _
                                        MultiSelect:=False)
    If Fname = False Then
        'Do nothing
    Else
        'Root folder for the new folder.
        'You can also use DefPath = "C:\Users\Ron\test\"
        DefPath = Application.DefaultFilePath
        If Right(DefPath, 1) <> "\" Then
            DefPath = DefPath & "\"
        End If

        'Create the folder name
        strDate = Format(Now, " dd-mm-yy h-mm-ss")
        FileNameFolder = DefPath & "MyUnzipFolder " & strDate & "\"

        'Make the normal folder in DefPath
        MkDir FileNameFolder

        'Extract the files into the newly created folder
        Set oApp = CreateObject("Shell.Application")

        oApp.Namespace(FileNameFolder).CopyHere oApp.Namespace(Fname).items

        'If you want to extract only one file you can use this:
        'oApp.Namespace(FileNameFolder).CopyHere _
         'oApp.Namespace(Fname).items.Item("test.txt")

        MsgBox "You find the files here: " & FileNameFolder

        On Error Resume Next
        Set FSO = CreateObject("scripting.filesystemobject")
        FSO.deletefolder Environ("Temp") & "\Temporary Directory*", True
    End If
End Sub

Remove style attribute from HTML tags

In addition to Lorenzo Marcon's answer:

Using preg_replace to select everything except style attribute:

$html = preg_replace('/(<p.+?)style=".+?"(>.+?)/i', "$1$2", $html);

Disable sorting on last column when using jQuery DataTables

This is work perfect for me if you don't allow sorting the first column then use

<script>
    $(document).ready(function () {
        $('#example2').DataTable({               
            'order':[],
            'columnDefs': [{
                "targets": 0,
                "orderable": false
            }]
        });
    });
</script>

here index row starts with 0, so put 0 in targets.
And if you disable sorting for one or more column then use,

<script>
    $(document).ready(function () {
        $('#example2').DataTable({               
            'order':[],
            'columnDefs': [{
                "targets": [0,3],
                "orderable": false
            }]
        });
    });
</script>

Here you can see , disable sorting in datatable js

Above my checkbox column at 0 positions and Action column at 3rd position so sorting disable in both table.

How do I restart a service on a remote machine in Windows?

Several good solutions here. If you're still on Win2K and can't install anything on the remote computer, this also works:

Open the Computer Management Console (right click My Computer, choose Manage; open from Administrative Tools in the Start Menu; or open from the MMC using the snap-in).

Right click on your computer name and choose "Connect to Remote Computer"

Put in the computer name and credentials and you have full access to many admin functions including the services control panel.

Better way to represent array in java properties file

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

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

Where does npm install packages?

In Ubuntu 14.04 they are installed at

/usr/lib/node_modules

Checking if float is an integer

I'm not 100% sure but when you cast f to an int, and subtract it from f, I believe it is getting cast back to a float. This probably won't matter in this case, but it could present problems down the line if you are expecting that to be an int for some reason.

I don't know if it's a better solution per se, but you could use modulus math instead, for example: float f = 4.5886; bool isInt; isInt = (f % 1.0 != 0) ? false : true; depending on your compiler you may or not need the .0 after the 1, again the whole implicit casts thing comes into play. In this code, the bool isInt should be true if the right of the decimal point is all zeroes, and false otherwise.

What is "runtime"?

I found that the following folder structure makes a very insightful context for understanding what runtime is:

Runtimes of Mozilla XulRunner

You can see that there is the 'source', there is the 'SDK' or 'Software Development Kit' and then there is the Runtime, eg. the stuff that gets run - at runtime. It's contents are like:

runtimes' folder contents

The win32 zip contains .exe -s and .dll -s.

So eg. the C runtime would be the files like this -- C runtime libraries, .so-s or .dll -s -- you run at runtime, made special by their (or their contents' or purposes') inclusion in the definition of the C language (on 'paper'), then implemented by your C implementation of choice. And then you get the runtime of that implementation, to use it and to build upon it.

That is, with a little polarisation, the runnable files that the users of your new C-based program will need. As a developer of a C-based program, so do you, but you need the C compiler and the C library headers, too; the users don't need those.

How to generate a Dockerfile from an image?

This is derived from @fallino's answer, with some adjustments and simplifications by using the output format option for docker history. Since macOS and Gnu/Linux have different command-line utilities, a different version is necessary for Mac. If you only need one or the other, you can just use those lines.

#!/bin/bash
case "$OSTYPE" in
    linux*)
        docker history --no-trunc --format "{{.CreatedBy}}" $1 | # extract information from layers
        tac                                                    | # reverse the file
        sed 's,^\(|3.*\)\?/bin/\(ba\)\?sh -c,RUN,'             | # change /bin/(ba)?sh calls to RUN
        sed 's,^RUN #(nop) *,,'                                | # remove RUN #(nop) calls for ENV,LABEL...
        sed 's,  *&&  *, \\\n \&\& ,g'                           # pretty print multi command lines following Docker best practices
    ;;
    darwin*)
        docker history --no-trunc --format "{{.CreatedBy}}" $1 | # extract information from layers
        tail -r                                                | # reverse the file
        sed -E 's,^(\|3.*)?/bin/(ba)?sh -c,RUN,'               | # change /bin/(ba)?sh calls to RUN
        sed 's,^RUN #(nop) *,,'                                | # remove RUN #(nop) calls for ENV,LABEL...
        sed $'s,  *&&  *, \\\ \\\n \&\& ,g'                      # pretty print multi command lines following Docker best practices
    ;;
    *)
        echo "unknown OSTYPE: $OSTYPE"
    ;;
esac

How to convert Seconds to HH:MM:SS using T-SQL

You want to multiply out to milliseconds as the fractional part is discarded.

SELECT DATEADD(ms, 121.25 * 1000, 0)

If you want it without the date portion you can use CONVERT, with style 114

SELECT CONVERT(varchar, DATEADD(ms, 121.25 * 1000, 0), 114)

How to replace a character by a newline in Vim

But if one has to substitute, then the following thing works:

:%s/\n/\r\|\-\r/g

In the above, every next line is substituted with next line, and then |- and again a new line. This is used in wiki tables.

If the text is as follows:

line1
line2
line3

It is changed to

line1
|-
line2
|-
line3

Capturing count from an SQL query

int count = 0;    
using (new SqlConnection connection = new SqlConnection("connectionString"))
{
    sqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM table_name", connection);
    connection.Open();
    count = (int32)cmd.ExecuteScalar();
}

HttpListener Access Denied

If you use http://localhost:80/ as a prefix, you can listen to http requests with no need for Administrative privileges.

upstream sent too big header while reading response header from upstream

Add:

fastcgi_buffers 16 16k;
fastcgi_buffer_size 32k;
proxy_buffer_size   128k;
proxy_buffers   4 256k;
proxy_busy_buffers_size   256k;

To server{} in nginx.conf

Works for me.

MongoDB: How to query for records where field is null or not set?

Seems you can just do single line:

{ "sent_at": null }

Get Last Part of URL PHP

One of the most elegant solutions was here Get characters after last / in url

by DisgruntledGoat

$id = substr($url, strrpos($url, '/') + 1);

strrpos gets the position of the last occurrence of the slash; substr returns everything after that position.

How to show loading spinner in jQuery?

Try this code How To Show Loading Spinner In JQuery?

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>How To Show Loading Spinner In JQuery? - phpcodingstuff.com</title>
<style>
.overlay{
    display: none;
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    z-index: 999;
    background: rgba(255,255,255,0.8) url("loader-img.gif") center no-repeat;
}
/* Turn off scrollbar when body element has the loading class */
body.loading{
    overflow: hidden;   
}
/* Make spinner image visible when body element has the loading class */
body.loading .overlay{
    display: block;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
// Initiate an Ajax request on button click
$(document).on("click", "button", function(){
    $.get("customers.php", function(data){
        $("body").html(data);
    });       
});
 

$(document).on({
    ajaxStart: function(){
        $("body").addClass("loading"); 
    },
    ajaxStop: function(){ 
        $("body").removeClass("loading"); 
    }    
});
</script>
</head>
<body style="text-align: center;">
    <button type="button">Get Customers Details</button>
    <p>Click the above button to get the customers details from the web server via Ajax.</p>
    <div class="overlay"></div>
</body>
</html>

How do I compute the intersection point of two lines?

Here is a solution using the Shapely library. Shapely is often used for GIS work, but is built to be useful for computational geometry. I changed your inputs from lists to tuples.

Problem

# Given these endpoints
#line 1
A = (X, Y)
B = (X, Y)

#line 2
C = (X, Y)
D = (X, Y)

# Compute this:
point_of_intersection = (X, Y)

Solution

import shapely
from shapely.geometry import LineString, Point

line1 = LineString([A, B])
line2 = LineString([C, D])

int_pt = line1.intersection(line2)
point_of_intersection = int_pt.x, int_pt.y

print(point_of_intersection)

How to provide a mysql database connection in single file in nodejs

var mysql = require('mysql');

var pool  = mysql.createPool({
    host     : 'yourip',
    port    : 'yourport',
    user     : 'dbusername',
    password : 'dbpwd',
    database : 'database schema name',
    dateStrings: true,
    multipleStatements: true
});


// TODO - if any pool issues need to try this link for connection management
// https://stackoverflow.com/questions/18496540/node-js-mysql-connection-pooling

module.exports = function(qry, qrytype, msg, callback) {

if(qrytype != 'S') {
    console.log(qry);
}

pool.getConnection(function(err, connection) {
    if(err) {
        if(connection)
            connection.release();
        throw err;
    } 

    // Use the connection
    connection.query(qry, function (err, results, fields) {
        connection.release();

        if(err) {
            callback('E#connection.query-Error occurred.#'+ err.sqlMessage);    
            return;         
        }

        if(qrytype==='S') {
            //for Select statement
            // setTimeout(function() {
                callback(results);      
            // }, 500);
        } else if(qrytype==='N'){
            let resarr = results[results.length-1];
            let newid= '';
            if(resarr.length)               
                newid = resarr[0]['@eid'];
            callback(msg + newid);
        } else if(qrytype==='U'){
            //let ret = 'I#' + entity + ' updated#Updated rows count: ' + results[1].changedRows;
            callback(msg);                      
        } else if(qrytype==='D'){
            //let resarr = results[1].affectedRows;
            callback(msg);
        }
    });

    connection.on('error', function (err) {
        connection.release();
        callback('E#connection.on-Error occurred.#'+ err.sqlMessage);   
        return;         
    });
});

}

Copy every nth line from one sheet to another

In my opinion the answers given to this question are too specific. Here's an attempt at a more general answer with two different approaches and a complete example.

The OFFSET approach

OFFSET takes 3 mandatory arguments. The first is a given cell that we want to offset from. The next two are the number of rows and columns we want to offset (downwards and rightwards). OFFNET returns the content of the cell this results in. For instance, OFFSET(A1, 1, 2) returns the contents of cell C2 because A1 is cell (1,1) and if we add (1,2) to that we get (2,3) which corresponds to cell C2.

To get this to return every nth row from another column, we can make use of the ROW function. When this function is given no argument, it returns the row number of the current cell. We can thus combine OFFSET and ROW to make a function that returns every nth cell by adding a multiplier to the value returned by ROW. For instance OFFSET(A$1,ROW()*3,0). Note the use of $1 in the target cell. If this is not used, the offsetting will offset from different cells, thus in effect adding 1 to the multiplier.

The ADDRESS + INDIRECT approach

ADDRESS takes two integer inputs and returns the address/name of the cell as a string. For instance, ADDRESS(1,1) return "$A$1". INDIRECT takes the address of a cell and returns the contents. For instance, INDIRECT("A1") returns the contents of cell A1 (it also accepts input with $'s in it). If we use ROW inside ADDRESS with a multiplier, we can get the address of every nth cell. For instance, ADDRESS(ROW(), 1) in row 1 will return "$A$1", in row 2 will return "$A$2" and so on. So, if we put this inside INDIRECT, we can get the content of every nth cells. For instance, INDIRECT(ADDRESS(1*ROW()*3,1)) returns the contents of every 3rd cell in the first column when dragged downwards.

Example

Consider the following screenshot of a spreadsheet. The headers (first row) contains the call used in the rows below. enter image description here Column A contains our example data. In this case, it's just the positive integers (the counting continues outside the shown area). These are the values that we want to get every 3rd of, that is, we want to get 1, 4, 7, 10, and so on.

Column B contains an incorrect attempt at using the OFFSET approach but where we forgot to use $. As can be seen, while we multiply by 3, we actually get every 4th row.

Column C contains an incorrect attempt at using the OFFSET approach where we remembered to use $, but forgot to subtract. So while we do get every 3rd value, we skipped some values (1 and 4).

Column D contains a correct function using the OFFSET approach.

Column E contains an incorrect attempt at using the ADDRESS + INDRECT approach, but where we forgot to subtract. Thus we skipped some rows initially. The same problem as with column C.

Column F contains a correct function using the ADDRESS + INDRECT approach.

File Upload using AngularJS

You may consider IaaS for file upload, such as Uploadcare. There is an Angular package for it: https://github.com/uploadcare/angular-uploadcare

Technically it's implemented as a directive, providing different options for uploading, and manipulations for uploaded images within the widget:

<uploadcare-widget
  ng-model="object.image.info.uuid"
  data-public-key="YOURKEYHERE"
  data-locale="en"
  data-tabs="file url"
  data-images-only="true"
  data-path-value="true"
  data-preview-step="true"
  data-clearable="true"
  data-multiple="false"
  data-crop="400:200"
  on-upload-complete="onUCUploadComplete(info)"
  on-widget-ready="onUCWidgetReady(widget)"
  value="{{ object.image.info.cdnUrl }}"
 />

More configuration options to play with: https://uploadcare.com/widget/configure/

What is the SQL command to return the field names of a table?

PostgreSQL understands the

select column_name from information_schema.columns where table_name = 'myTable'

syntax. If you're working in the psql shell, you can also use

\d myTable

for a description (columns, and their datatypes and constraints)

tomcat - CATALINA_BASE and CATALINA_HOME variables

Pointing CATALINA_BASE to a different directory from CATALINA_HOME allows you to separate the configuration directory from the binaries directory.

By default, CATALINA_BASE (configurations) and CATALINA_HOME (binaries) point to the same folder, but separating the configurations from the binaries can help you to run multiple instances of Tomcat side by side without duplicating the binaries.

It is also useful when you want to update the binaries, without modifying, or needing to backup/restore your configuration files for Tomcat.

Update 2018

There is an easier way to set CATALINA_BASE now with the makebase utility. I have posted a tutorial that covers this subject at http://blog.rasia.io/blog/how-to-easily-setup-lucee-in-tomcat.html along with a video tutorial at https://youtu.be/nuugoG5c-7M

Original answer continued below

To take advantage of this feature, simply create the config directory and point to it with the CATALINA_BASE environment variable. You will have to put some files in that directory:

  • Copy the conf directory from the original Tomcat installation directory, including its contents, and ensure that Tomcat has read permissions to it. Edit the configuration files according to your needs.
  • Create a logs directory if conf/logging.properties points to ${catalina.base}/logs, and ensure that Tomcat has read/write permissions to it.
  • Create a temp directory if you are not overriding the default of $CATALINA_TMPDIR which points to ${CATALINA_BASE}/temp, and ensure that Tomcat has write permissions to it.
  • Create a work directory which defaults to ${CATALINA_BASE}/work, and ensure that Tomcat has write permissions to it.

require_once :failed to open stream: no such file or directory

It says that the file C:\wamp\www\mysite\php\includes\dbconn.inc doesn't exist, so the error is, you're missing the file.

Editable text to string

If I understand correctly, you want to get the String of an Editable object, right? If yes, try using toString().

Changing the size of a column referenced by a schema-bound view in SQL Server

See this link

Resize or Modify a MS SQL Server Table Column with Default Constraint using T-SQL Commands

the solution for such a SQL Server problem is going to be

Dropping or disabling the DEFAULT Constraint on the table column.

Modifying the table column data type and/or data size.

Re-creating or enabling the default constraint back on the sql table column.

Bye

How do I protect Python code?

The best you can do with Python is to obscure things.

  • Strip out all docstrings
  • Distribute only the .pyc compiled files.
  • freeze it
  • Obscure your constants inside a class/module so that help(config) doesn't show everything

You may be able to add some additional obscurity by encrypting part of it and decrypting it on the fly and passing it to eval(). But no matter what you do someone can break it.

None of this will stop a determined attacker from disassembling the bytecode or digging through your api with help, dir, etc.

Run react-native application on iOS device directly from command line?

If you get this error [email protected] preinstall: ./src/scripts/check_reqs.js && xcodebuild ... using npm install -g ios-deploy

Try this. It works for me:

  1. sudo npm uninstall -g ios-deploy
  2. brew install ios-deploy

How do you rename a Git tag?

If it's published, you can't delete it (without risking being tarred and feathered, that is). The 'Git way' is to do:

The sane thing. Just admit you screwed up, and use a different name. Others have already seen one tag-name, and if you keep the same name, you may be in the situation that two people both have "version X", but they actually have different "X"'s. So just call it "X.1" and be done with it.

Alternatively,

The insane thing. You really want to call the new version "X" too, even though others have already seen the old one. So just use git-tag -f again, as if you hadn't already published the old one.

It's so insane because:

Git does not (and it should not) change tags behind users back. So if somebody already got the old tag, doing a git-pull on your tree shouldn't just make them overwrite the old one.

If somebody got a release tag from you, you cannot just change the tag for them by updating your own one. This is a big security issue, in that people MUST be able to trust their tag-names. If you really want to do the insane thing, you need to just fess up to it, and tell people that you messed up.

All courtesy of the man pages.

How to add anchor tags dynamically to a div in Javascript?

here's a pure Javascript alternative:

var mydiv = document.getElementById("myDiv");
var aTag = document.createElement('a');
aTag.setAttribute('href',"yourlink.htm");
aTag.innerText = "link text";
mydiv.appendChild(aTag);

\r\n, \r and \n what is the difference between them?

A carriage return (\r) makes the cursor jump to the first column (begin of the line) while the newline (\n) jumps to the next line and eventually to the beginning of that line. So to be sure to be at the first position within the next line one uses both.

How do I enable TODO/FIXME/XXX task tags in Eclipse?

There are apparently distributions or custom builds in which the ability to set Task Tags for non-Java files is not present. This post mentions that ColdFusion Builder (built on Eclipse) does not let you set non-Java Task Tags, but the beta version of CF Builder 2 does. (I know the OP wasn't using CF Builder, but I am, and I was wondering about this question myself ... because he didn't see the ability to set non-Java tags, I thought others might be in the same position.)

Span inside anchor or anchor inside span or doesn't matter?

It will work both, but personally I'd prefer option 2 so the span is "around" the link.

Has anyone ever got a remote JMX JConsole to work?

I'm trying to JMC to run the Flight Recorder (JFR) to profile NiFi on a remote server that doesn't offer a graphical environment on which to run JMC.

Based on the other answers given here, and upon much trial and error, here is what I'm supplying to the JVM (conf/bootstrap.conf)when I launch NiFi:

java.arg.90=-Dcom.sun.management.jmxremote=true
java.arg.91=-Dcom.sun.management.jmxremote.port=9098
java.arg.92=-Dcom.sun.management.jmxremote.rmi.port=9098
java.arg.93=-Dcom.sun.management.jmxremote.authenticate=false
java.arg.94=-Dcom.sun.management.jmxremote.ssl=false
java.arg.95=-Dcom.sun.management.jmxremote.local.only=false
java.arg.96=-Djava.rmi.server.hostname=10.10.10.92  (the IP address of my server running NiFi)

I did put this in /etc/hosts, though I doubt it's needed:

10.10.10.92   localhost

Then, upon launching JMC, I create a remote connection with these properties:

Host: 10.10.10.92
Port: 9098
User: (nothing)
Password: (ibid)

Incidentally, if I click the Custom JMX service URL, I see:

service:jmx:rmi:///jndi/rmi://10.10.10.92:9098/jmxrmi

This finally did it for me.

Use and meaning of "in" in an if statement?

It depends on what next is.

If it's a string (as in your example), then in checks for substrings.

>>> "in" in "indigo"
True
>>> "in" in "violet"
False
>>> "0" in "10"
True
>>> "1" in "10"
True

If it's a different kind of iterable (list, tuple, set, dictionary...), then in checks for membership.

>>> "in" in ["in", "out"]
True
>>> "in" in ["indigo", "violet"]
False

In a dictionary, membership is seen as "being one of the keys":

>>> "in" in {"in": "out"}
True
>>> "in" in {"out": "in"}
False

How to enable core dump in my Linux C++ program

You can do it this way inside a program:

#include <sys/resource.h>

// core dumps may be disallowed by parent of this process; change that
struct rlimit core_limits;
core_limits.rlim_cur = core_limits.rlim_max = RLIM_INFINITY;
setrlimit(RLIMIT_CORE, &core_limits);

How to insert the current timestamp into MySQL database using a PHP insert query

Forgot to put the variable in the sql statement without quotations.

 $update_query = 
      "UPDATE db.tablename SET insert_time=NOW() WHERE username='" .$somename."'";

Post request with Wget?

Wget currently only supports x-www-form-urlencoded data. --post-file is not for transmitting files as form attachments, it expects data with the form: key=value&otherkey=example.

--post-data and --post-file work the same way: the only difference is that --post-data allows you to specify the data in the command line, while --post-file allows you to specify the path of the file that contain the data to send.

Here's the documentation:

 --post-data=string
       --post-file=file
           Use POST as the method for all HTTP requests and send the specified data
           in the request body.  --post-data sends string as data, whereas
           --post-file sends the contents of file.  Other than that, they work in
           exactly the same way. In particular, they both expect content of the
           form "key1=value1&key2=value2", with percent-encoding for special
           characters; the only difference is that one expects its content as a
           command-line parameter and the other accepts its content from a file. In
           particular, --post-file is not for transmitting files as form
           attachments: those must appear as "key=value" data (with appropriate
           percent-coding) just like everything else. Wget does not currently
           support "multipart/form-data" for transmitting POST data; only
           "application/x-www-form-urlencoded". Only one of --post-data and
           --post-file should be specified.

Regarding your authentication token, it should either be provided in the header, in the path of the url, or in the data itself. This must be indicated somewhere in the documentation of the service you use. In a POST request, as in a GET request, you must specify the data using keys and values. This way the server will be able to receive multiple information with specific names. It's similar with variables.

Hence, you can't just send a magic token to the server, you also need to specify the name of the key. If the key is "token", then it should be token=YOUR_TOKEN.

wget --post-data 'user=foo&password=bar' http://example.com/auth.php

Also, you should consider using curl if you can because it is easier to send files using it. There are many examples on the Internet for that.

Symbol for any number of any characters in regex?

You can use this regular expression (any whitespace or any non-whitespace) as many times as possible down to and including 0.

[\s\S]*

This expression will match as few as possible, but as many as necessary for the rest of the expression.

[\s\S]*?

For example, in this regex [\s\S]*?B will match aB in aBaaaaB. But in this regex [\s\S]*B will match aBaaaaB in aBaaaaB.

How do I use Linq to obtain a unique list of properties from a list of objects?

        int[] numbers = {1,2,3,4,5,3,6,4,7,8,9,1,0 };
        var nonRepeats = (from n in numbers select n).Distinct();


        foreach (var d in nonRepeats)
        {

            Response.Write(d);
        }

OUTPUT

1234567890

How to simulate a button click using code?

Just to clarify what moonlightcheese stated: To trigger a button click event through code in Android provide the following:

buttonName.performClick();

Compiling problems: cannot find crt1.o

What helped me is to create a symbolic link:

sudo ln -s /usr/lib/x86_64-linux-gnu /usr/lib64

gitbash command quick reference

git-bash uses standard unix commands.

ls for directory listing cd for change directory

more here -> http://ss64.com/bash/ Not all of these will work, but the file based ones mostly do.

Table header to stay fixed at the top when user scrolls it out of view with jQuery

you can use this approach, pure HTML and CSS no JS needed :)

_x000D_
_x000D_
.table-fixed-header {_x000D_
  display: flex;_x000D_
  justify-content: space-between;_x000D_
  margin-right: 18px_x000D_
}_x000D_
_x000D_
.table-fixed {_x000D_
  display: flex;_x000D_
  justify-content: space-between;_x000D_
  height: 150px;_x000D_
  overflow: scroll;_x000D_
}_x000D_
_x000D_
.column {_x000D_
  flex-basis: 24%;_x000D_
  border-radius: 5px;_x000D_
  padding: 5px;_x000D_
  text-align: center;_x000D_
}_x000D_
.column .title {_x000D_
  border-bottom: 2px grey solid;_x000D_
  border-top: 2px grey solid;_x000D_
  text-align: center;_x000D_
  display: block;_x000D_
  font-weight: bold;_x000D_
}_x000D_
_x000D_
.cell {_x000D_
  padding: 5px;_x000D_
  border-right: 1px solid;_x000D_
  border-left: 1px solid;_x000D_
}_x000D_
_x000D_
.cell:nth-of-type(even) {_x000D_
  background-color: lightgrey;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport" content="width=device-width">_x000D_
  <title>Fixed header Bin</title>_x000D_
</head>_x000D_
<body>_x000D_
<div class="table-fixed-header">_x000D_
    _x000D_
    <div class="column">_x000D_
      <span class="title">col 1</span>_x000D_
    </div>_x000D_
    <div class="column">_x000D_
      <span class="title">col 2</span>_x000D_
    </div>_x000D_
    <div class="column">_x000D_
      <span class="title">col 3</span>_x000D_
    </div>_x000D_
    <div class="column">_x000D_
      <span class="title">col 4</span>_x000D_
    </div>_x000D_
    _x000D_
  </div>_x000D_
  _x000D_
  <div class="table-fixed">_x000D_
    _x000D_
    <div class="column">_x000D_
      <div class="cell">alpha</div>_x000D_
      <div class="cell">beta</div>_x000D_
      <div class="cell">ceta</div>_x000D_
    </div>_x000D_
    _x000D_
    <div class="column">_x000D_
      <div class="cell">alpha</div>_x000D_
      <div class="cell">beta</div>_x000D_
      <div class="cell">ceta</div>_x000D_
      <div class="cell">alpha</div>_x000D_
      <div class="cell">beta</div>_x000D_
      <div class="cell">ceta</div>_x000D_
      <div class="cell">alpha</div>_x000D_
      <div class="cell">beta</div>_x000D_
      <div class="cell">ceta</div>_x000D_
    </div>_x000D_
    _x000D_
    <div class="column">_x000D_
      <div class="cell">alpha</div>_x000D_
      <div class="cell">beta</div>_x000D_
      <div class="cell">ceta</div>_x000D_
      <div class="cell">beta</div>_x000D_
      <div class="cell">beta</div>_x000D_
      <div class="cell">beta</div>_x000D_
      _x000D_
    </div>_x000D_
    _x000D_
    <div class="column">_x000D_
      <div class="cell">alpha</div>_x000D_
      <div class="cell">beta</div>_x000D_
      <div class="cell">ceta</div>_x000D_
    </div>_x000D_
    _x000D_
  </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

What is the difference between ManualResetEvent and AutoResetEvent in .NET?

OK, normally it does not a good practice to add 2 answers in same thread, but I did not want to edit/delete my previous answer, since it can help on another manner.

Now, I created, much more comprehensive, and easy to understand, run-to-learn console app snippet below.

Just run the examples on two different consoles, and observe behaviour. You will get much more clear idea there what is happening behind the scenes.

Manual Reset Event

using System;
using System.Threading;

namespace ConsoleApplicationDotNetBasics.ThreadingExamples
{
    public class ManualResetEventSample
    {
        private readonly ManualResetEvent _manualReset = new ManualResetEvent(false);

        public void RunAll()
        {
            new Thread(Worker1).Start();
            new Thread(Worker2).Start();
            new Thread(Worker3).Start();
            Console.WriteLine("All Threads Scheduled to RUN!. ThreadId: {0}", Thread.CurrentThread.ManagedThreadId);
            Console.WriteLine("Main Thread is waiting for 15 seconds, observe 3 thread behaviour. All threads run once and stopped. Why? Because they call WaitOne() internally. They will wait until signals arrive, down below.");
            Thread.Sleep(15000);
            Console.WriteLine("1- Main will call ManualResetEvent.Set() in 5 seconds, watch out!");
            Thread.Sleep(5000);
            _manualReset.Set();
            Thread.Sleep(2000);
            Console.WriteLine("2- Main will call ManualResetEvent.Set() in 5 seconds, watch out!");
            Thread.Sleep(5000);
            _manualReset.Set();
            Thread.Sleep(2000);
            Console.WriteLine("3- Main will call ManualResetEvent.Set() in 5 seconds, watch out!");
            Thread.Sleep(5000);
            _manualReset.Set();
            Thread.Sleep(2000);
            Console.WriteLine("4- Main will call ManualResetEvent.Reset() in 5 seconds, watch out!");
            Thread.Sleep(5000);
            _manualReset.Reset();
            Thread.Sleep(2000);
            Console.WriteLine("It ran one more time. Why? Even Reset Sets the state of the event to nonsignaled (false), causing threads to block, this will initial the state, and threads will run again until they WaitOne().");
            Thread.Sleep(10000);
            Console.WriteLine();
            Console.WriteLine("This will go so on. Everytime you call Set(), ManualResetEvent will let ALL threads to run. So if you want synchronization between them, consider using AutoReset event, or simply user TPL (Task Parallel Library).");
            Thread.Sleep(5000);
            Console.WriteLine("Main thread reached to end! ThreadId: {0}", Thread.CurrentThread.ManagedThreadId);

        }

        public void Worker1()
        {
            for (int i = 1; i <= 10; i++)
            {
                Console.WriteLine("Worker1 is running {0}/10. ThreadId: {1}.", i, Thread.CurrentThread.ManagedThreadId);
                Thread.Sleep(5000);
                // this gets blocked until _autoReset gets signal
                _manualReset.WaitOne();
            }
            Console.WriteLine("Worker1 is DONE. ThreadId: {0}", Thread.CurrentThread.ManagedThreadId);
        }
        public void Worker2()
        {
            for (int i = 1; i <= 10; i++)
            {
                Console.WriteLine("Worker2 is running {0}/10. ThreadId: {1}.", i, Thread.CurrentThread.ManagedThreadId);
                Thread.Sleep(5000);
                // this gets blocked until _autoReset gets signal
                _manualReset.WaitOne();
            }
            Console.WriteLine("Worker2 is DONE. ThreadId: {0}", Thread.CurrentThread.ManagedThreadId);
        }
        public void Worker3()
        {
            for (int i = 1; i <= 10; i++)
            {
                Console.WriteLine("Worker3 is running {0}/10. ThreadId: {1}.", i, Thread.CurrentThread.ManagedThreadId);
                Thread.Sleep(5000);
                // this gets blocked until _autoReset gets signal
                _manualReset.WaitOne();
            }
            Console.WriteLine("Worker3 is DONE. ThreadId: {0}", Thread.CurrentThread.ManagedThreadId);
        }
    }

}

Manual Reset Event Output

Auto Reset Event

using System;
using System.Threading;

namespace ConsoleApplicationDotNetBasics.ThreadingExamples
{
    public class AutoResetEventSample
    {
        private readonly AutoResetEvent _autoReset = new AutoResetEvent(false);

        public void RunAll()
        {
            new Thread(Worker1).Start();
            new Thread(Worker2).Start();
            new Thread(Worker3).Start();
            Console.WriteLine("All Threads Scheduled to RUN!. ThreadId: {0}", Thread.CurrentThread.ManagedThreadId);
            Console.WriteLine("Main Thread is waiting for 15 seconds, observe 3 thread behaviour. All threads run once and stopped. Why? Because they call WaitOne() internally. They will wait until signals arrive, down below.");
            Thread.Sleep(15000);
            Console.WriteLine("1- Main will call AutoResetEvent.Set() in 5 seconds, watch out!");
            Thread.Sleep(5000);
            _autoReset.Set();
            Thread.Sleep(2000);
            Console.WriteLine("2- Main will call AutoResetEvent.Set() in 5 seconds, watch out!");
            Thread.Sleep(5000);
            _autoReset.Set();
            Thread.Sleep(2000);
            Console.WriteLine("3- Main will call AutoResetEvent.Set() in 5 seconds, watch out!");
            Thread.Sleep(5000);
            _autoReset.Set();
            Thread.Sleep(2000);
            Console.WriteLine("4- Main will call AutoResetEvent.Reset() in 5 seconds, watch out!");
            Thread.Sleep(5000);
            _autoReset.Reset();
            Thread.Sleep(2000);
            Console.WriteLine("Nothing happened. Why? Becasuse Reset Sets the state of the event to nonsignaled, causing threads to block. Since they are already blocked, it will not affect anything.");
            Thread.Sleep(10000);
            Console.WriteLine("This will go so on. Everytime you call Set(), AutoResetEvent will let another thread to run. It will make it automatically, so you do not need to worry about thread running order, unless you want it manually!");
            Thread.Sleep(5000);
            Console.WriteLine("Main thread reached to end! ThreadId: {0}", Thread.CurrentThread.ManagedThreadId);

        }

        public void Worker1()
        {
            for (int i = 1; i <= 5; i++)
            {
                Console.WriteLine("Worker1 is running {0}/5. ThreadId: {1}.", i, Thread.CurrentThread.ManagedThreadId);
                Thread.Sleep(500);
                // this gets blocked until _autoReset gets signal
                _autoReset.WaitOne();
            }
            Console.WriteLine("Worker1 is DONE. ThreadId: {0}", Thread.CurrentThread.ManagedThreadId);
        }
        public void Worker2()
        {
            for (int i = 1; i <= 5; i++)
            {
                Console.WriteLine("Worker2 is running {0}/5. ThreadId: {1}.", i, Thread.CurrentThread.ManagedThreadId);
                Thread.Sleep(500);
                // this gets blocked until _autoReset gets signal
                _autoReset.WaitOne();
            }
            Console.WriteLine("Worker2 is DONE. ThreadId: {0}", Thread.CurrentThread.ManagedThreadId);
        }
        public void Worker3()
        {
            for (int i = 1; i <= 5; i++)
            {
                Console.WriteLine("Worker3 is running {0}/5. ThreadId: {1}.", i, Thread.CurrentThread.ManagedThreadId);
                Thread.Sleep(500);
                // this gets blocked until _autoReset gets signal
                _autoReset.WaitOne();
            }
            Console.WriteLine("Worker3 is DONE. ThreadId: {0}", Thread.CurrentThread.ManagedThreadId);
        }
    }

}

Auto Reset Event Output

What is process.env.PORT in Node.js?

In many environments (e.g. Heroku), and as a convention, you can set the environment variable PORT to tell your web server what port to listen on.

So process.env.PORT || 3000 means: whatever is in the environment variable PORT, or 3000 if there's nothing there.

So you pass that to app.listen, or to app.set('port', ...), and that makes your server able to accept a "what port to listen on" parameter from the environment.

If you pass 3000 hard-coded to app.listen(), you're always listening on port 3000, which might be just for you, or not, depending on your requirements and the requirements of the environment in which you're running your server.

How to set a bitmap from resource

Try this

This is from sdcard

ImageView image = (ImageView) findViewById(R.id.test_image);
Bitmap bMap = BitmapFactory.decodeFile("/sdcard/test2.png");
image.setImageBitmap(bMap);

This is from resources

Bitmap bMap = BitmapFactory.decodeResource(getResources(), R.drawable.icon);

Get HTML inside iframe using jQuery

This can be another solution if jquery is loaded in iframe.html.

$('#iframe')[0].contentWindow.$("html").html()

Fastest Way to Find Distance Between Two Lat/Long Points

Have a read of Geo Distance Search with MySQL, a solution based on implementation of Haversine Formula to MySQL. This is a complete solution description with theory, implementation and further performance optimization. Although the spatial optimization part didn't work correctly in my case.

I noticed two mistakes in this:

  1. the use of abs in the select statement on p8. I just omitted abs and it worked.

  2. the spatial search distance function on p27 does not convert to radians or multiply longitude by cos(latitude), unless his spatial data is loaded with this in consideration (cannot tell from context of article), but his example on p26 indicates that his spatial data POINT is not loaded with radians or degrees.

Can't check signature: public key not found

You need the public key in your gpg key ring. To import the public key into your public keyring, place the public key block in a text file with a .gpg extension, and then issue the following command:

gpg --import <your-file>.gpg

The entity that encrypted the file should provide you with such a block. For example, ftp://ftp.gnu.org/gnu/gnu-keyring.gpg has the block for gnu.org.

For an even more in-depth explanation see Verifying files with GPG, without a .sig or .asc file?

maven "cannot find symbol" message unhelpful

This occurs because of this issue also i.e repackaging which you defined in POM file.

Remove this from pom file under maven plugin. It will work

<executions>
    <execution>
        <goals>
             <goal>repackage</goal>
        </goals>
    </execution>
</executions>