Programs & Examples On #Cwd

Cool Web Design CWD is global benchmark and source of design inspiration for web designers

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip

You need to add the package containing the executable pg_config.

A prior answer should have details you need: pg_config executable not found

What could cause an error related to npm not being able to find a file? No contents in my node_modules subfolder. Why is that?

Following what @viveknuna suggested, I upgraded to the latest version of node.js and npm using the downloaded installer. I also installed the latest version of yarn using a downloaded installer. Then, as you can see below, I upgraded angular-cli and typescript. Here's what that process looked like:

D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular>npm install -g @angular/cli@latest
C:\Users\Jack\AppData\Roaming\npm\ng -> C:\Users\Jack\AppData\Roaming\npm\node_modules\@angular\cli\bin\ng
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\@angular\cli\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

+ @angular/[email protected]
added 75 packages, removed 166 packages, updated 61 packages and moved 24 packages in 29.084s

D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular>npm install -g typescript
C:\Users\Jack\AppData\Roaming\npm\tsserver -> C:\Users\Jack\AppData\Roaming\npm\node_modules\typescript\bin\tsserver
C:\Users\Jack\AppData\Roaming\npm\tsc -> C:\Users\Jack\AppData\Roaming\npm\node_modules\typescript\bin\tsc
+ [email protected]
updated 1 package in 2.427s

D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular>node -v
v8.10.0

D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular>npm -v
5.6.0

D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular>yarn --version
1.5.1

Thereafter, I ran yarn and npm start in my angular folder and all appears to be well. Here's what that looked like:

D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular>yarn
yarn install v1.5.1
[1/4] Resolving packages...
[2/4] Fetching packages...
info [email protected]: The platform "win32" is incompatible with this module.
info "[email protected]" is an optional dependency and failed compatibility check. Excluding it from installation.
[3/4] Linking dependencies...
warning "@angular/cli > @schematics/[email protected]" has incorrect peer dependency "@angular-devkit/[email protected]".
warning "@angular/cli > @angular-devkit/schematics > @schematics/[email protected]" has incorrect peer dependency "@angular-devkit/[email protected]".
warning " > [email protected]" has incorrect peer dependency "@angular/compiler@^2.3.1 || >=4.0.0-beta <5.0.0".
warning " > [email protected]" has incorrect peer dependency "@angular/core@^2.3.1 || >=4.0.0-beta <5.0.0".
[4/4] Building fresh packages...
Done in 232.79s.

D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular>npm start

> [email protected] start D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular
> ng serve --host 0.0.0.0 --port 4200

** NG Live Development Server is listening on 0.0.0.0:4200, open your browser on http://localhost:4200/ **
Date: 2018-03-22T13:17:28.935Z
Hash: 8f226b6fa069b7c201ea
Time: 22494ms
chunk {account.module} account.module.chunk.js () 129 kB  [rendered]
chunk {app.module} app.module.chunk.js () 497 kB  [rendered]
chunk {common} common.chunk.js (common) 1.46 MB  [rendered]
chunk {inline} inline.bundle.js (inline) 5.79 kB [entry] [rendered]
chunk {main} main.bundle.js (main) 515 kB [initial] [rendered]
chunk {polyfills} polyfills.bundle.js (polyfills) 1.1 MB [initial] [rendered]
chunk {styles} styles.bundle.js (styles) 1.53 MB [initial] [rendered]
chunk {vendor} vendor.bundle.js (vendor) 15.1 MB [initial] [rendered]

webpack: Compiled successfully.

Node.js: Python not found exception due to node-sass and node-gyp

I had node 15.x.x , and "node-sass": "^4.11.0". I saw in the release notes from node-sass and saw the node higest version compatible with node-sass 4.11.0 was 11, so I uninstalled node and reinstall 11.15.0 version (I'm working with Windows). Check node-sass releases. (this is what you should see in the node-sass releases.)

Hope that helps and sorry for my english :)

TypeError: expected str, bytes or os.PathLike object, not _io.BufferedReader

I think it has to do with your second element in storbinary. You are trying to open file, but it is already a pointer to the file you opened in line file = open(local_path,'rb'). So, try to use ftp.storbinary("STOR " + i, file).

How to solve npm error "npm ERR! code ELIFECYCLE"

i tried to solve this problem with this way

rm -rf node_modules && rm ./package-lock.json && npm install

But for me its not work. I just restart my machine and its working perfectly.
Am Linux user ,Machine HP.

Maximum call stack size exceeded on npm install

echo 65536 | sudo tee -a /proc/sys/fs/inotify/max_user_watches

works for me on Ubuntu.

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

For the Collatz problem, you can get a significant boost in performance by caching the "tails". This is a time/memory trade-off. See: memoization (https://en.wikipedia.org/wiki/Memoization). You could also look into dynamic programming solutions for other time/memory trade-offs.

Example python implementation:

import sys

inner_loop = 0

def collatz_sequence(N, cache):
    global inner_loop

    l = [ ]
    stop = False
    n = N

    tails = [ ]

    while not stop:
        inner_loop += 1
        tmp = n
        l.append(n)
        if n <= 1:
            stop = True  
        elif n in cache:
            stop = True
        elif n % 2:
            n = 3*n + 1
        else:
            n = n // 2
        tails.append((tmp, len(l)))

    for key, offset in tails:
        if not key in cache:
            cache[key] = l[offset:]

    return l

def gen_sequence(l, cache):
    for elem in l:
        yield elem
        if elem in cache:
            yield from gen_sequence(cache[elem], cache)
            raise StopIteration

if __name__ == "__main__":
    le_cache = {}

    for n in range(1, 4711, 5):
        l = collatz_sequence(n, le_cache)
        print("{}: {}".format(n, len(list(gen_sequence(l, le_cache)))))

    print("inner_loop = {}".format(inner_loop))

How to install and run Typescript locally in npm?

Note if you are using typings do the following:

rm -r typings
typings install

If your doing the angular 2 tutorial use this:

rm -r typings
npm run postinstall
npm start

if the postinstall command dosen't work, try installing typings globally like so:

npm install -g typings

you can also try the following as opposed to postinstall:

typings install

and you should have this issue fixed!

Add Favicon with React and Webpack

Here is all you need:

new HtmlWebpackPlugin({
    favicon: "./src/favicon.gif"
})

That is definitely after adding "favicon.gif" to the folder "src".

This will transfer the icon to your build folder and include it in your tag like this <link rel="shortcut icon" href="favicon.gif">. This is safer than just importing with copyWebpackPLugin

Angular2 QuickStart npm start is not working correctly

Here's how I solved the problem today after hours of trying all of these different solutions - (for anyone looking for another way still).

Open 2 instances of cmd at your quickstart dir:

window #1:

npm run build:watch

then...

window #2:

npm run serve

It will then open in the browser and work as expected

Can't get private key with openssl (no start line:pem_lib.c:703:Expecting: ANY PRIVATE KEY)

My two cents: came across the same error message in RHEL7.3 while running the openssl command with root CA certificate. The reason being, while downloading the certificate from AD server, Encoding was selected as DER instead of Base64. Once the proper version of encoding was selected for the new certificate download, error was resolved

Hope this helps for new users :-)

"Please try running this command again as Root/Administrator" error when trying to install LESS

I was getting this issue for instaling expo cli and I fixed by just following four steps mentioned in the npm documentation here.

Problem is some version of npm fail to locate folder for global installations of package. Following these steps we can create or modify the .profile file in Home directory of user and give it a proper PATH there so it works like a charm.

Try this it helped me and I spent around an hour for this issue. My node version was 6.0

Steps I follow

Back up your computer. On the command line, in your home directory, create a directory for global installations:

mkdir ~/.npm-global

Configure npm to use the new directory path:

npm config set prefix '~/.npm-global'

In your preferred text editor, open or create a ~/.profile file and add this line:

export PATH=~/.npm-global/bin:$PATH

On the command line, update your system variables:

source ~/.profile

To test your new configuration, install a package globally without using sudo:

npm install -g jshint

Can't install Scipy through pip

After opening up an issue with the SciPy team, we found that you need to upgrade pip with:

pip install --upgrade pip

And in Python 3 this works:

python3 -m pip install --upgrade pip

for SciPy to install properly. Why? Because:

Older versions of pip have to be told to use wheels, IIRC with --use-wheel. Or you can upgrade pip itself, then it should pick up the wheels.

Upgrading pip solves the issue, but you might be able to just use the --use-wheel flag as well.

Spring Boot and multiple external configuration files

With Spring boot , the spring.config.location does work,just provide comma separated properties files.

see the below code

@PropertySource(ignoreResourceNotFound=true,value="classpath:jdbc-${spring.profiles.active}.properties")
public class DBConfig{

     @Value("${jdbc.host}")
        private String jdbcHostName;
     }
}

one can put the default version of jdbc.properties inside application. The external versions can be set lie this.

java -jar target/myapp.jar --spring.config.location=classpath:file:///C:/Apps/springtest/jdbc.properties,classpath:file:///C:/Apps/springtest/jdbc-dev.properties

Based on profile value set using spring.profiles.active property, the value of jdbc.host will be picked up. So when (on windows)

set spring.profiles.active=dev

jdbc.host will take value from jdbc-dev.properties.

for

set spring.profiles.active=default

jdbc.host will take value from jdbc.properties.

Filezilla FTP Server Fails to Retrieve Directory Listing

File > Site Manager > Select your site > Transfer Settings > Active

Works for me.

npm install error from the terminal

Running just "npm install" will look for dependencies listed in your package.json. The error you're getting says that you don't have a package.json file set up (or you're in the wrong directory).

If you're trying to install a specific package, you should use 'npm install {package name}'. See here for more info about the command.

Otherwise, you'll need to create a package.json file for your dependencies or go to the right directory and then run 'npm install'.

Npm Please try using this command again as root/administrator

I had the same problem, what I did to solve it was ran the cmd.exe as administrator even though my account was already set as an administrator.

Failed to install Python Cryptography package with PIP and setup.py

This solved the problem for me (Ubuntu 16.04):

sudo apt-get install build-essential libssl-dev libffi-dev python-dev python3-dev

and then it was working like this:

pip install cryptography
pip install pyopenssl ndg-httpsclient pyasn1

SSL Error: CERT_UNTRUSTED while using npm command

Reinstall node, then update npm.

First I removed node

apt-get purge node

Then install node according to the distibution. Docs here .

Then

npm install npm@latest -g

json: cannot unmarshal object into Go value of type

Determining of root cause is not an issue since Go 1.8; field name now is shown in the error message:

json: cannot unmarshal object into Go struct field Comment.author of type string

Subprocess changing directory

To run your_command as a subprocess in a different directory, pass cwd parameter, as suggested in @wim's answer:

import subprocess

subprocess.check_call(['your_command', 'arg 1', 'arg 2'], cwd=working_dir)

A child process can't change its parent's working directory (normally). Running cd .. in a child shell process using subprocess won't change your parent Python script's working directory i.e., the code example in @glglgl's answer is wrong. cd is a shell builtin (not a separate executable), it can change the directory only in the same process.

NodeJS - Error installing with NPM

gyp ERR! configure error gyp ERR! stack Error: Can't find Python executable "python", you can set the PYT HON env variable.

This means the Python env. variable should point to the executable python file, in my case: SET PYTHON=C:\work\_env\Python27\python.exe

npm not working after clearing cache

try this one npm cache clean --force after that run npm cache verify

How to approach a "Got minus one from a read call" error when connecting to an Amazon RDS Oracle instance

I got this error message from using an oracle database in a docker despite the fact i had publish port to host option "-p 1521:1521". I was using jdbc url that was using ip address 127.0.0.1, i changed it to the host machine real ip address and everything worked then.

npm not working - "read ECONNRESET"

At work, i had to load up my browser and browse a webpage (which authenticates me to our web-filter). Then I retried the command and it worked successfully.

"Couldn't read dependencies" error with npm

I was following a doc on line and thought this error meant a problem with the dependencies in NPM. however after a third look. I realized that it was a typo. I did not add a comma after the first dependency in package.json that the tutorial asked me to edit.

npm install errors with Error: ENOENT, chmod

I encountered similar behavior after upgrading to npm 6.1.0. It seemed to work once, but then I got into a state with this error while trying to install a package that was specified by path on the filesystem:

npm ERR! code ENOENT
npm ERR! errno -2
npm ERR! syscall rename

The following things did not fix the problem:

  • rm -rf node_modules
  • npm cache clean (gave npm ERR! As of npm@5, the npm cache self-heals....use 'npm cache verify' instead.)
  • npm cache verify
  • rm -rf ~/.npm

How I fixed the problem:

  • rm package-lock.json

Can't install via pip because of egg_info error

In my case this error message appeared because the package I was trying to install (storm) was not supported for Python 3.

How to install an npm package from GitHub directly?

Update September 2016

Installing from vanilla https github URLs now works:

npm install https://github.com/fergiemcdowall/search-index.git

EDIT 1: You can't do this for all modules because you are reading from a source control system, which may well contain invalid/uncompiled/buggy code. So to be clear (although it should go without saying): given that the code in the repo is in an npm-usable state, you can now quite happily install directly from github

EDIT 2: (21-10-2019) We are now living through "peak Typescript/React/Babel", and therefore JavaScript compilation has become quite common. If you need to take compilation into account look into prepare. That said, NPM modules do not need to be compiled, and it is wise to assume that compilation is not the default, especially for older node modules (and possibly also for very new, bleeding-edge "ESNext"-y ones).

How to get the current working directory using python 3?

It seems that IDLE changes its current working dir to location of the script that is executed, while when running the script using cmd doesn't do that and it leaves CWD as it is.

To change current working dir to the one containing your script you can use:

import os
os.chdir(os.path.dirname(__file__))
print(os.getcwd())

The __file__ variable is available only if you execute script from file, and it contains path to the file. More on it here: Python __file__ attribute absolute or relative?

Can't install any package with node npm

1.>Go to your this location

C:\Users\{your user name or ID}

2.> open .npmrc & Remove all content from .npmrc file.

3.>reopen your new command prompt

4.>again run the code , will work.

npm throws error without sudo

What to me seems like the best option is the one suggested in the npm documentation, which is to first check where global node_modules are installed by default by running npm config get prefix. If you get, like I do on Trusty, /usr, you might want to change it to a folder that you can safely own without messing things up the way I did.

To do that, choose or create a new folder in your system. You may want to have it in your home directory or, like me, under /usr/local for consistency because I'm also a Mac user (I prefer not to need to look into different places depending on the machine I happen to be in front of). Another good reason to do that is the fact that the /usr/local folder is probably already in your PATH (unless you like to mess around with your PATH) but chances are your newly-created folder isn't and you'd need to add it to the PATH yourself on your .bash-profile or .bashrc file.

Long story short, I changed the default location of the global modules with npm config set prefix '/usr/local', created the folder /usr/local/lib/node_modules (it will be used by npm) and changed permissions for the folders used by npm with the command:

sudo chown -R $(whoami) $(npm config get prefix)/{lib/node_modules,bin,share}

Now you can globally install any module safely. Hope this helps!

nodejs npm global config missing on windows

Even though we have the .NPMRC can be in 3 locations, Please NOTE THAT - the file under the Per-User NPM config location take precedence over the Global & Built-in configurations.

  1. Global NPM config => C:\Users\%username%\AppData\Roaming\npm\etc\npmrc
  2. Per-user NPM config => C:\Users\%username%.npmrc
  3. Built-in NPM config => C:\Program Files\nodejs\node_modules\npm\npmrc

To find out which file is getting updated, try setting the proxy using the following command npm config set https-proxy https://username:[email protected]:6050

After that open the .npmrc files to see which file get updated.

PHP CURL CURLOPT_SSL_VERIFYPEER ignored

We had the same problem on a CentOS7 machine. Disabling the VERIFYHOST VERIFYPEER did not solve the problem, we did not have the cURL error anymore but the response still was invalid. Doing a wget to the same link as the cURL was doing also resulted in a certificate error.

-> Our solution also was to reboot the VPS, this solved it and we were able to complete the request again.

For us this seemed to be a memory corruption problem. Rebooting the VPS reloaded the libary in the memory again and now it works. So if the above solution from @clover does not work try to reboot your machine.

Running Python on Windows for Node.js dependencies

For me after installing windows-build-tools with the below comment

npm --add-python-to-path='true' --debug install --global windows-build-tools

running the code below

npm config set python "%USERPROFILE%\.windows-build-tools\python27\python.exe"

has worked.

Cannot install node modules that require compilation on Windows 7 x64/VS2012

I had also a lot of problem to compile nodejs zmq.

For the problem with with vcbuild.exe, just add it to the PATH

For other problems I could compile just using Windows 7.1 SDK Command Prompt

(Menu Programs -> Microsoft Windows SDK v7.1 -> Windows 7.1 SDK Command Prompt)

And from the prompt:

npm install zmq

That's works :)

Error: Segmentation fault (core dumped)

There is one more reason for such failure which I came to know when mine failed

  • You might be working with a lot of data and your RAM is full

This might not apply in this case but it also throws the same error and since this question comes up on top for this error, I have added this answer here.

Save current directory in variable using Bash?

This saves the absolute path of the current working directory to the variable cwd:

cwd=$(pwd)

In your case you can just do:

export PATH=$PATH:$(pwd)+somethingelse

How to read a file in other directory in python

You can't "open" a directory using the open function. This function is meant to be used to open files.

Here, what you want to do is open the file that's in the directory. The first thing you must do is compute this file's path. The os.path.join function will let you do that by joining parts of the path (the directory and the file name):

fpath = os.path.join(direct, "5_1.txt")

You can then open the file:

f = open(fpath)

And read its content:

content = f.read()

Additionally, I believe that on Windows, using open on a directory does return a PermissionDenied exception, although that's not really the case.

"message failed to fetch from registry" while trying to install any module

It could be that the npm registry was down at the time or your connection dropped.

Either way you should upgrade node and npm.

I would recommend using nave to manage your node environments.

https://npmjs.org/package/nave

It allows you to easily install versions and quickly jump between them.

sh: 0: getcwd() failed: No such file or directory on cited drive

In Ubuntu 16.04.3 LTS, the next command works for me:

exit

Then I've login again.

shell init issue when click tab, what's wrong with getcwd?

Just change the directory to another one and come back. Probably that one has been deleted or moved.

Determine command line working directory when running node bin script

path.resolve('.') is also a reliable and clean option, because we almost always require('path'). It will give you absolute path of the directory from where it is called.

Can't install any packages in Node.js using "npm install"

Npm repository is currently down. See issue #2694 on npm github

EDIT:
To use a mirror in the meanwhile:

 npm set registry http://ec2-46-137-149-160.eu-west-1.compute.amazonaws.com

you can reset this later with:

 npm set registry https://registry.npmjs.org/

source

Not receiving Google OAuth refresh token

This has caused me some confusion so I thought I'd share what I've come to learn the hard way:

When you request access using the access_type=offline and approval_prompt=force parameters you should receive both an access token and a refresh token. The access token expires soon after you receive it and you will need to refresh it.

You correctly made the request to get a new access token and received the response that has your new access token. I was also confused by the fact that I didn't get a new refresh token. However, this is how it is meant to be since you can use the same refresh token over and over again.

I think some of the other answers assume that you wanted to get yourself a new refresh token for some reason and sugggested that you re-authorize the user but in actual fact, you don't need to since the refresh token you have will work until revoked by the user.

How to convert image into byte array and byte array to base64 String in android?

They have wrapped most stuff need to solve your problem, one of the tests looks like this:

String filename = CSSURLEmbedderTest.class.getResource("folder.png").getPath().replace("%20", " ");
String code = "background: url(folder.png);";

StringWriter writer = new StringWriter();
embedder = new CSSURLEmbedder(new StringReader(code), true);
embedder.embedImages(writer, filename.substring(0, filename.lastIndexOf("/")+1));

String result = writer.toString();
assertEquals("background: url(" + folderDataURI + ");", result);

What's the difference between process.cwd() vs __dirname?

As per node js doc process.cwd()

cwd is a method of global object process, returns a string value which is the current working directory of the Node.js process.

As per node js doc __dirname

The directory name of current script as a string value. __dirname is not actually a global but rather local to each module.

Let me explain with example,

suppose we have a main.js file resides inside C:/Project/main.js and running node main.js both these values return same file

or simply with following folder structure

Project 
+-- main.js
+--lib
   +-- script.js

main.js

console.log(process.cwd())
// C:\Project
console.log(__dirname)
// C:\Project
console.log(__dirname===process.cwd())
// true

suppose we have another file script.js files inside a sub directory of project ie C:/Project/lib/script.js and running node main.js which require script.js

main.js

require('./lib/script.js')
console.log(process.cwd())
// C:\Project
console.log(__dirname)
// C:\Project
console.log(__dirname===process.cwd())
// true

script.js

console.log(process.cwd())
// C:\Project
console.log(__dirname)
// C:\Project\lib
console.log(__dirname===process.cwd())
// false

npm can't find package.json

I had a similar problem with npm. The problem was that I had the project inside two folders of the same name. I resolved it by renaming one of the folders to something else (outer folder recommended).

How to find if directory exists in Python

The following code checks the referred directory in your code exists or not, if it doesn't exist in your workplace then, it creates one:

import os

if not os.path.isdir("directory_name"):
    os.mkdir("directory_name")

os.path.dirname(__file__) returns empty

os.path.split(os.path.realpath(__file__))[0]

os.path.realpath(__file__)return the abspath of the current script; os.path.split(abspath)[0] return the current dir

Open file in a relative location in Python

With this type of thing you need to be careful what your actual working directory is. For example, you may not run the script from the directory the file is in. In this case, you can't just use a relative path by itself.

If you are sure the file you want is in a subdirectory beneath where the script is actually located, you can use __file__ to help you out here. __file__ is the full path to where the script you are running is located.

So you can fiddle with something like this:

import os
script_dir = os.path.dirname(__file__) #<-- absolute dir the script is in
rel_path = "2091/data.txt"
abs_file_path = os.path.join(script_dir, rel_path)

How to install lxml on Ubuntu

Many answers here are rather old,
thanks to the pointer from @Simplans (https://stackoverflow.com/a/37759871/417747) and the home page...

What worked for me (Ubuntu bionic):

sudo apt-get install python3-lxml  

(+ sudo apt-get install libxml2-dev libxslt1-dev I installed before it, but not sure if that's the requirement still)

How do I get IntelliJ to recognize common Python modules?

(solved my problem) File -> Project structures -> Modules -> Add (small plus sign) -> Import Module -> Add the path contains the files (e.g. src/mymodule) -> Create Module from existing sources -> Next -> next -> Finish. You should see a file with .iml in the directory where you cannot imoport; that should do the trick

How to input a regex in string.replace?

I would go like this (regex explained in comments):

import re

# If you need to use the regex more than once it is suggested to compile it.
pattern = re.compile(r"</{0,}\[\d+>")

# <\/{0,}\[\d+>
# 
# Match the character “<” literally «<»
# Match the character “/” literally «\/{0,}»
#    Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «{0,}»
# Match the character “[” literally «\[»
# Match a single digit 0..9 «\d+»
#    Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
# Match the character “>” literally «>»

subject = """this is a paragraph with<[1> in between</[1> and then there are cases ... where the<[99> number ranges from 1-100</[99>. 
and there are many other lines in the txt files
with<[3> such tags </[3>"""

result = pattern.sub("", subject)

print(result)

If you want to learn more about regex I recomend to read Regular Expressions Cookbook by Jan Goyvaerts and Steven Levithan.

libxml install error using pip

** make sure the development packages of libxml2 and libxslt are installed **

From the lxml documentation, assuming you are running a Debian-based distribution :

sudo apt-get install libxml2-dev libxslt-dev python-dev

For Debian based systems, it should be enough to install the known build dependencies of python-lxml or python3-lxml, e.g.

sudo apt-get build-dep python3-lxml

How to use S_ISREG() and S_ISDIR() POSIX Macros?

You're using S_ISREG() and S_ISDIR() correctly, you're just using them on the wrong thing.

In your while((dit = readdir(dip)) != NULL) loop in main, you're calling stat on currentPath over and over again without changing currentPath:

if(stat(currentPath, &statbuf) == -1) {
    perror("stat");
    return errno;
}

Shouldn't you be appending a slash and dit->d_name to currentPath to get the full path to the file that you want to stat? Methinks that similar changes to your other stat calls are also needed.

How can I find script's directory?

This is a pretty old thread but I've been having this problem when trying to save files into the current directory the script is in when running a python script from a cron job. getcwd() and a lot of the other path come up with your home directory.

to get an absolute path to the script i used

directory = os.path.abspath(os.path.dirname(__file__))

Non-alphanumeric list order from os.listdir()

From the documentation:

The list is in arbitrary order, and does not include the special entries '.' and '..' even if they are present in the directory.

This means that the order is probably OS/filesystem dependent, has no particularly meaningful order, and is therefore not guaranteed to be anything in particular. As many answers mentioned: if preferred, the retrieved list can be sorted.

Cheers :)

Argparse optional positional arguments?

parser.add_argument also has a switch required. You can use required=False. Here is a sample snippet with Python 2.7:

parser = argparse.ArgumentParser(description='get dir')
parser.add_argument('--dir', type=str, help='dir', default=os.getcwd(), required=False)
args = parser.parse_args()

How to reliably open a file in the same directory as a Python script

After trying all of this solutions, I still had different problems. So what I found the simplest way was to create a python file: config.py, with a dictionary containing the file's absolute path and import it into the script. something like

import config as cfg 
import pandas as pd 
pd.read_csv(cfg.paths['myfilepath'])

where config.py has inside:

paths = {'myfilepath': 'home/docs/...'}

It is not automatic but it is a good solution when you have to work in different directory or different machines.

Python base64 data decode

Python 3 (and 2)

import base64
a = 'eW91ciB0ZXh0'
base64.b64decode(a)

Python 2

A quick way to decode it without importing anything:

'eW91ciB0ZXh0'.decode('base64')

or more descriptive

>>> a = 'eW91ciB0ZXh0'
>>> a.decode('base64')
'your text'

How do I get the path to the current script with Node.js?

Every Node.js program has some global variables in its environment, which represents some information about your process and one of it is __dirname.

List Directories and get the name of the Directory

You seem to be using Python as if it were the shell. Whenever I've needed to do something like what you're doing, I've used os.walk()

For example, as explained here: [x[0] for x in os.walk(directory)] should give you all of the subdirectories, recursively.

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

import os
current_file_path=os.path.dirname(os.path.realpath('__file__'))

"Fatal error: Cannot redeclare <function>"

I want to add my 2 cent experience that might be helpful for many of you.

If you declare a function inside a loop (for, foreach, while), you will face this error message.

Can't get Python to import from a different folder

import user

u=user.User() #error on this line

Because of the lack of __init__ mentioned above, you would expect an ImportError which would make the problem clearer.

You don't get one because 'user' is also an existing module in the standard library. Your import statement grabs that one and tries to find the User class inside it; that doesn't exist and only then do you get the error.

It is generally a good idea to make your import absolute:

import Server.Models.user

to avoid this kind of ambiguity. Indeed from Python 2.7 'import user' won't look relative to the current module at all.

If you really want relative imports, you can have them explicitly in Python 2.5 and up using the somewhat ugly syntax:

from .user import User

SFTP in Python? (platform independent)

You can use the pexpect module

Here is a good intro post

child = pexpect.spawn ('/usr/bin/sftp ' + [email protected] )
child.expect ('.* password:')
child.sendline (your_password)
child.expect ('sftp> ')
child.sendline ('dir')
child.expect ('sftp> ')
file_list = child.before
child.sendline ('bye')

I haven't tested this but it should work

How to list only top level directories in Python?

-- This will exclude files and traverse through 1 level of sub folders in the root

def list_files(dir):
    List = []
    filterstr = ' '
    for root, dirs, files in os.walk(dir, topdown = True):
        #r.append(root)
        if (root == dir):
            pass
        elif filterstr in root:
            #filterstr = ' '
            pass
        else:
            filterstr = root
            #print(root)
            for name in files:
                print(root)
                print(dirs)
                List.append(os.path.join(root,name))
            #print(os.path.join(root,name),"\n")
                print(List,"\n")

    return List

How to get an absolute file path in Python

Today you can also use the unipath package which was based on path.py: http://sluggo.scrapping.cc/python/unipath/

>>> from unipath import Path
>>> absolute_path = Path('mydir/myfile.txt').absolute()
Path('C:\\example\\cwd\\mydir\\myfile.txt')
>>> str(absolute_path)
C:\\example\\cwd\\mydir\\myfile.txt
>>>

I would recommend using this package as it offers a clean interface to common os.path utilities.

How do I get the path and name of the file that is currently executing?

To keep the migration consistency across platforms (macOS/Windows/Linux), try:

path = r'%s' % os.getcwd().replace('\\','/')

How to resolve symbolic links in a shell script

My answer here Bash: how to get real path of a symlink?

but in short very handy in scripts:

script_home=$( dirname $(realpath "$0") )
echo Original script home: $script_home

These are part of GNU coreutils, suitable for use in Linux systems.

To test everything, we put symlink into /home/test2/, amend some additional things and run/call it from root directory:

/$ /home/test2/symlink
/home/test
Original script home: /home/test

Where

Original script is: /home/test/realscript.sh
Called script is: /home/test2/symlink

How to get DATE from DATETIME Column in SQL?

You can use

select * 
from transaction 
where (Card_No='123') and (transaction_date = convert(varchar(10),getdate(),101))

How to use performSelector:withObject:afterDelay: with primitive types in Cocoa?

I would always recomend that you use NSMutableArray as the object to pass on. This is because you can then pass several objects, like the button pressed and other values. NSNumber, NSInteger and NSString are just containers of some value. Make sure that when you get the object from the array that you refer to to a correct container type. You need to pass on NS containers. There you may test the value. Remember that containers use isEqual when values are compared.

#define DELAY_TIME 5

-(void)changePlayerGameOnes:(UIButton*)sender{
    NSNumber *nextPlayer = [NSNumber numberWithInt:[gdata.currentPlayer intValue]+1 ];
    NSMutableArray *array = [[NSMutableArray alloc]initWithObjects:sender, nil];
    [array addObject:nextPlayer];
    [self performSelector:@selector(next:) withObject:array afterDelay:DELAY_TIME];
}
-(void)next:(NSMutableArray*)nextPlayer{
    if(gdata != nil){ //if game choose next player
       [self nextPlayer:[nextPlayer objectAtIndex:1] button:[nextPlayer objectAtIndex:0]];
    }
}

Why does the order in which libraries are linked sometimes cause errors in GCC?

A quick tip that tripped me up: if you're invoking the linker as "gcc" or "g++", then using "--start-group" and "--end-group" won't pass those options through to the linker -- nor will it flag an error. It will just fail the link with undefined symbols if you had the library order wrong.

You need to write them as "-Wl,--start-group" etc. to tell GCC to pass the argument through to the linker.

Where is virtualenvwrapper.sh after pip install?

Using

find / -name virtualenvwrapper.sh

I got a TON of "permissions denied"s, and exactly one printout of the file location. I missed it until I found that file location when I uninstall/installed it again with pip.

In case you were curious, it was in

/usr/local/share/python/virtualenvwrapper.sh

How to send authorization header with axios

Instead of calling axios.get function Use:

axios({ method: 'get', url: 'your URL', headers: { Authorization: `Bearer ${token}` } })

The source was not found, but some or all event logs could not be searched

Had the same exception. In my case, I had to run Command Prompt with Administrator Rights.

From the Start Menu, right click on Command Prompt, select "Run as administrator".

Set Font Color, Font Face and Font Size in PHPExcel

I recommend you start reading the documentation (4.6.18. Formatting cells). When applying a lot of formatting it's better to use applyFromArray() According to the documentation this method is also suppose to be faster when you're setting many style properties. There's an annex where you can find all the possible keys for this function.

This will work for you:

$phpExcel = new PHPExcel();

$styleArray = array(
    'font'  => array(
        'bold'  => true,
        'color' => array('rgb' => 'FF0000'),
        'size'  => 15,
        'name'  => 'Verdana'
    ));

$phpExcel->getActiveSheet()->getCell('A1')->setValue('Some text');
$phpExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray);

To apply font style to complete excel document:

 $styleArray = array(
   'font'  => array(
        'bold'  => true,
        'color' => array('rgb' => 'FF0000'),
        'size'  => 15,
        'name'  => 'Verdana'
    ));      
 $phpExcel->getDefaultStyle()
    ->applyFromArray($styleArray);

How to wait until an element is present in Selenium?

Let me recommend you using Selenide library. It allows writing much more concise and readable tests. It can wait for presence of elements with much shorter syntax:

$("#elementId").shouldBe(visible);

Here is a sample project for testing Google search: https://github.com/selenide-examples/google

update query with join on two tables

Try this one

UPDATE employee 
set EMPLOYEE.MAIDEN_NAME = 
  (SELECT ADD1 
   FROM EMPS 
   WHERE EMP_CODE=EMPLOYEE.EMP_CODE);
WHERE EMPLOYEE.EMP_CODE >='00' 
AND EMPLOYEE.EMP_CODE <='ZZ';

How to set custom favicon in Express?

In Express 4

Install the favicon middleware and then do:

var favicon = require('serve-favicon');

app.use(favicon(__dirname + '/public/images/favicon.ico'));

Or better, using the path module:

app.use(favicon(path.join(__dirname,'public','images','favicon.ico')));

(note that this solution will work in express 3 apps as well)

In Express 3

According to the API, .favicon accepts a location parameter:

app.use(express.favicon("public/images/favicon.ico")); 

Most of the time, you might want this (as vsync suggested):

app.use(express.favicon(__dirname + '/public/images/favicon.ico'));

Or better yet, use the path module (as Druska suggested):

app.use(express.favicon(path.join(__dirname, 'public','images','favicon.ico'))); 

Why favicon is better than static

According to the package description:

  1. This module caches the icon in memory to improve performance by skipping disk access.
  2. This module provides an ETag based on the contents of the icon, rather than file system properties.
  3. This module will serve with the most compatible Content-Type.

Replace NA with 0 in a data frame column

Since nobody so far felt fit to point out why what you're trying doesn't work:

  1. NA == NA doesn't return TRUE, it returns NA (since comparing to undefined values should yield an undefined result).
  2. You're trying to call apply on an atomic vector. You can't use apply to loop over the elements in a column.
  3. Your subscripts are off - you're trying to give two indices into a$x, which is just the column (an atomic vector).

I'd fix up 3. to get to a$x[is.na(a$x)] <- 0

How do I SET the GOPATH environment variable on Ubuntu? What file must I edit?

My go environment looked similar to yours.

$go env
GOARCH="amd64"
GOBIN=""
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH=""
GORACE=""
GOROOT="/usr/lib/go-1.6"
GOTOOLDIR="/usr/lib/go-1.6/pkg/tool/linux_amd64"
GO15VENDOREXPERIMENT="1"
CC="gcc"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0"
CXX="g++"
CGO_ENABLED="1"

I resolved it with setting GOPATH to /usr/lib/go. Try it out.

export GOPATH=/usr/lib/go
export PATH=$PATH:$GOPATH/bin

How can I set the focus (and display the keyboard) on my EditText programmatically

I recommend using a LifecycleObserver which is part of the Handling Lifecycles with Lifecycle-Aware Components of Android Jetpack.

I want to open and close the Keyboard when the Fragment/Activity appears. Firstly, define two extension functions for the EditText. You can put them anywhere in your project:

fun EditText.showKeyboard() {
    requestFocus()
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}

fun EditText.hideKeyboard() {
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(this.windowToken, 0)
}

Then define a LifecycleObserver which opens and closes the keyboard when the Activity/Fragment reaches onResume() or onPause:

class EditTextKeyboardLifecycleObserver(private val editText: WeakReference<EditText>) :
    LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun openKeyboard() {
        editText.get()?.postDelayed({ editText.get()?.showKeyboard() }, 100)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun closeKeyboard() {
        editText.get()?.hideKeyboard()
    }
}

Then add the following line to any of your Fragments/Activities, you can reuse the LifecycleObserver any times. E.g. for a Fragment:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

    // inflate the Fragment layout

    lifecycle.addObserver(EditTextKeyboardLifecycleObserver(WeakReference(myEditText)))

    // do other stuff and return the view

}

How to get the focused element with jQuery?

Try this:

$(":focus").each(function() {
    alert("Focused Elem_id = "+ this.id );
});

How to format DateTime to 24 hours time?

Console.WriteLine(curr.ToString("HH:mm"));

In VBA get rid of the case sensitivity when comparing words?

There is a statement you can issue at the module level:

Option Compare Text

This makes all "text comparisons" case insensitive. This means the following code will show the message "this is true":

Option Compare Text

Sub testCase()
  If "UPPERcase" = "upperCASE" Then
    MsgBox "this is true: option Compare Text has been set!"
  End If
End Sub

See for example http://www.ozgrid.com/VBA/vba-case-sensitive.htm . I'm not sure it will completely solve the problem for all instances (such as the Application.Match function) but it will take care of all the if a=b statements. As for Application.Match - you may want to convert the arguments to either upper case or lower case using the LCase function.

Spring MVC: Error 400 The request sent by the client was syntactically incorrect

Add BindingResult parameter in your method. For reference please my code below.

save(@ModelAttribute Employee employee,BindingResult bindingResult)

How to generate unique ID with node.js

edit: shortid has been deprecated. The maintainers recommend to use nanoid instead.


Another approach is using the shortid package from npm.

It is very easy to use:

var shortid = require('shortid');
console.log(shortid.generate()); // e.g. S1cudXAF

and has some compelling features:

ShortId creates amazingly short non-sequential url-friendly unique ids. Perfect for url shorteners, MongoDB and Redis ids, and any other id users might see.

  • By default 7-14 url-friendly characters: A-Z, a-z, 0-9, _-
  • Non-sequential so they are not predictable.
  • Can generate any number of ids without duplicates, even millions per day.
  • Apps can be restarted any number of times without any chance of repeating an id.

How to do sed like text replace with python?

[None of the answers works properly above !]

I have a case of multiple key-value replacement in one file around 1000 lines. And after replacement the file structure should keep the same. for example:

key1=value_tobe_replaced1
key2=value_tobe_replaced1
.     .
.     .
key1000=value_tobe_replaced1000

I've tried:

  1. the voted answer from @elmotec for massedit.

  2. answer from @Cecil Curry.

  3. answer from @Keithel.

The three answers definitely helped me a lot but after test I found it costs nearly 40-50s for 1st and 2ed. 3rd is not suitable for multi-replacement so I fixed it.

Notice: refer to the answers before go on.

Here's my code:

Line replacement mode:

start_time = datetime.datetime.now()
with tempfile.NamedTemporaryFile(mode='w', delete=False) as tmp_file:
    with open(abs_keypair_file) as kf:
        for line in kf:
            line_to_write = ''
            match_flag = False
            for (key, value) in tuple_list:
                # print '  %s = %r' % (key, value)
                if  not re.search(patten, line, flags=re.I):
                    continue
                line_to_write = re.sub(r'\$\({}\)'.format(key), value, line, flags=re.I)
                match_flag = True

            if not match_flag:
                line_to_write = line
            tmp_file.write(line_to_write)

shutil.copystat(abs_keypair_file, tmp_file.name)
shutil.move(tmp_file.name, abs_keypair_file)

time_costs = datetime.datetime.now() - start_time
print 'time costs: %s' % time_costs
time costs: 0:00:42.533879

file replacement mode:

start_time = datetime.datetime.now()
with tempfile.NamedTemporaryFile(mode='w', delete=False) as tmp_file:
    with open(abs_keypair_file) as kf:
        text = kf.read()
        for (key, value) in tuple_list:
            text = re.sub(patten, value, text, flags=re.M|re.I)
        tmp_file.write(text)
shutil.copystat(abs_keypair_file, tmp_file.name)
shutil.move(tmp_file.name, abs_keypair_file)

time_costs = datetime.datetime.now() - start_time
print 'time costs: %s' % time_costs
time costs: 0:00:00.348458

So I suggest if you match my case and your file size is not too large you may follow file replacement mode.

How to replace if file size is huge? I have no idea.

Hope this helps.

What are the parameters for the number Pipe - Angular 2

'1.0-0' will give you zero decimal places i.e. no decimals. e.g.$500

Java - Opposite of .contains (does not contain)

It seems that Luiggi Mendoza and joey rohan both already answered this, but I think it can be clarified a little.

You can write it as a single if statement:

if (inventory.contains("bread") && !inventory.contains("water")) {
    // do something
}

Android Studio doesn't recognize my device

Click Revoke USB debugging authorization in Developer option and try it again.

adding directory to sys.path /PYTHONPATH

You could use:

import os
path = 'the path you want'
os.environ['PATH'] += ':'+path

Entityframework Join using join method and lambdas

Generally i prefer the lambda syntax with LINQ, but Join is one example where i prefer the query syntax - purely for readability.

Nonetheless, here is the equivalent of your above query (i think, untested):

var query = db.Categories         // source
   .Join(db.CategoryMaps,         // target
      c => c.CategoryId,          // FK
      cm => cm.ChildCategoryId,   // PK
      (c, cm) => new { Category = c, CategoryMaps = cm }) // project result
   .Select(x => x.Category);  // select result

You might have to fiddle with the projection depending on what you want to return, but that's the jist of it.

How to access single elements in a table in R

Maybe not so perfect as above ones, but I guess this is what you were looking for.

data[1:1,3:3]    #works with positive integers
data[1:1, -3:-3] #does not work, gives the entire 1st row without the 3rd element
data[i:i,j:j]    #given that i and j are positive integers

Here indexing will work from 1, i.e,

data[1:1,1:1]    #means the top-leftmost element

Random number generator only generating one random number

Every time you do new Random() it is initialized using the clock. This means that in a tight loop you get the same value lots of times. You should keep a single Random instance and keep using Next on the same instance.

//Function to get a random number 
private static readonly Random random = new Random(); 
private static readonly object syncLock = new object(); 
public static int RandomNumber(int min, int max)
{
    lock(syncLock) { // synchronize
        return random.Next(min, max);
    }
}

Edit (see comments): why do we need a lock here?

Basically, Next is going to change the internal state of the Random instance. If we do that at the same time from multiple threads, you could argue "we've just made the outcome even more random", but what we are actually doing is potentially breaking the internal implementation, and we could also start getting the same numbers from different threads, which might be a problem - and might not. The guarantee of what happens internally is the bigger issue, though; since Random does not make any guarantees of thread-safety. Thus there are two valid approaches:

  • Synchronize so that we don't access it at the same time from different threads
  • Use different Random instances per thread

Either can be fine; but mutexing a single instance from multiple callers at the same time is just asking for trouble.

The lock achieves the first (and simpler) of these approaches; however, another approach might be:

private static readonly ThreadLocal<Random> appRandom
     = new ThreadLocal<Random>(() => new Random());

this is then per-thread, so you don't need to synchronize.

AngularJS: How do I manually set input to $valid in controller?

to get this working for a date error I had to delete the error first before calling $setValidity for the form to be marked valid.

delete currentmodal.form.$error.date;
currentmodal.form.$setValidity('myDate', true);

Visual Studio 2010 always thinks project is out of date, but nothing has changed

I spent many hours spent tearing out my hair over this. The build output wasn't consistent; different projects would be "not up to date" for different reasons from one build to the next consecutive build. I eventually found that the culprit was DropBox (3.0.4). I junction my source folder from ...\DropBox into my projects folder (not sure if this is the reason), but DropBox somehow "touches" files during a build. Paused syncing and everything is consistently up-to-date.

Change color of bootstrap navbar on hover link?

Sorry for late reply. You can only use:

   nav a:hover{

                   background-color:color name !important;


                 }

How to add a button dynamically using jquery

Try this

function test()
{
   $("body").append("<input type='button' id='field' />");
}

Default password of mysql in ubuntu server 16.04

This is what you are looking for:
sudo mysql --defaults-file=/etc/mysql/debian.cnf
MySql on Debian-base Linux usually use a configuration file with the credentials.

How to pass the password to su/sudo/ssh without overriding the TTY?

For ssh you can use sshpass: sshpass -p yourpassphrase ssh user@host.

You just need to download sshpass first :)

$ apt-get install sshpass
$ sshpass -p 'password' ssh username@server

How to add a new audio (not mixing) into a video using ffmpeg?

If you are using an old version of FFMPEG and you cant upgrade you can do the following:

ffmpeg -i PATH/VIDEO_FILE_NAME.mp4 -i PATH/AUDIO_FILE_NAME.mp3 -vcodec copy -shortest DESTINATION_PATH/NEW_VIDEO_FILE_NAME.mp4

Notice that I used -vcodec

How can I match a string with a regex in Bash?

if [[ $STR == *pattern* ]]
then
    echo "It is the string!"
else
    echo "It's not him!"
fi

Works for me! GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu)

List of all index & index columns in SQL Server DB

I didn't go through, but I got what I wanted in the query posted by the original author.

I used it (without conditions/filters) for my requirement but it gave incorrect results

The main problem was the results getting cross product without join condition on index_id

SELECT S.NAME SCHEMA_NAME,T.NAME TABLE_NAME,I.NAME INDEX_NAME,C.NAME COLUMN_NAME
  FROM SYS.TABLES T
       INNER JOIN SYS.SCHEMAS S
    ON T.SCHEMA_ID = S.SCHEMA_ID
       INNER JOIN SYS.INDEXES I
    ON I.OBJECT_ID = T.OBJECT_ID
       INNER JOIN SYS.INDEX_COLUMNS IC
    ON IC.OBJECT_ID = T.OBJECT_ID
       INNER JOIN SYS.COLUMNS C
    ON C.OBJECT_ID  = T.OBJECT_ID
   **AND IC.INDEX_ID    = I.INDEX_ID**
   AND IC.COLUMN_ID = C.COLUMN_ID
 WHERE 1=1

ORDER BY I.NAME,I.INDEX_ID,IC.KEY_ORDINAL

How to connect to local instance of SQL Server 2008 Express

I've just solved a problem related to this which may help other people.

Initially when loading up MSSMSE it had the server as PC_NAME\SQLEXPRESS and when I tried to connect it gave me Error: 26 - Error Locating Server/Instance Specified, so I went into SQL Server Configuration Manager to check if my SQL Server Browser and SQL Server services were running and set to automatic, only to find that instead of saying SQL Server (SQLEXPRESS) it says SQL Server(MSSQLSERVER).

I then tried connecting to PC-NAME\MSSQLSERVER and this time got SQL Network Interfaces, error: 25 - Connection string is not valid) (MicrosoftSQL Server, Error: 87) The parameter is incorrect so I googled this error and found that somebody had suggested that instead of using PC-NAME\MSSQLSERVER just use PC-NAME as the Server Name at the server connection interface, and this seems to work.

There's a link here http://learningsqlserver.wordpress.com/2011/01/21/what-version-of-sql-server-do-i-have/ which explains that MSSQLSERVER is the default instance and can be connected to by using just your hostname.

I think this may have arisen because I've had SQL Server 2008 installed at some point in the past.

Change image source in code behind - Wpf

You just need one line:

ImageViewer1.Source = new BitmapImage(new Uri(@"\myserver\folder1\Customer Data\sample.png"));

Do conditional INSERT with SQL?

It is possible with EXISTS condition. WHERE EXISTS tests for the existence of any records in a subquery. EXISTS returns true if the subquery returns one or more records. Here is an example

UPDATE  TABLE_NAME 
SET val1=arg1 , val2=arg2
WHERE NOT EXISTS
    (SELECT FROM TABLE_NAME WHERE val1=arg1 AND val2=arg2)

Extract XML Value in bash script

I agree with Charles Duffy that a proper XML parser is the right way to go.

But as to what's wrong with your sed command (or did you do it on purpose?).

  • $data was not quoted, so $data is subject to shell's word splitting, filename expansion among other things. One of the consequences being that the spacing in the XML snippet is not preserved.

So given your specific XML structure, this modified sed command should work

title=$(sed -ne '/title/{s/.*<title>\(.*\)<\/title>.*/\1/p;q;}' <<< "$data")

Basically for the line that contains title, extract the text between the tags, then quit (so you don't extract the 2nd <title>)

Programmatically Install Certificate into Mozilla

I was trying to achieve the same thing in Powershell and wrote a script to perform various functions that can be interactively selected. Of course, it's fairly easy to modify the script to automate certain things instead of provide options.

I'm an Infrastructure guy rather than a coder/programmer, so apologies if it's a bit cumbersome (but it does work!!).

Save the following as a PS1:

##################################################################################################
#  
# NAME: RegisterFireFoxCertificates.ps1
#  
# AUTHOR: Andy Pyne
# 
# DATE  : 22.07.2015
#  
# COMMENT: To provide options for listing, adding, deleting and purging
# FireFox Certificates using Mozilla's NSS Util CertUtil
# Source: https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/tools/NSS_Tools_certutil
#
# NOTE: You need a copy of the NSS Util CertUtil and it's associated dll's
# The specific files I used were:
# 
# certutil.exe, fort32.dll, freebl3.dll, libnspr4.dll, libplc4.dll, libplds4.dll, nspr4.dll, 
# nss3.dll, nssckbi.dll, nssdbm3.dll, nssutil3.dll, plc4.dll, plds4.dll, smime3.dll, 
# softokn3.dll, sqlite3.dll, ssl3.dll, swft32.dll
#
##################################################################################################

##################################################################################################

# Setup a few parameters
$ErrorActionPreference = "Silentlycontinue"
$ExecutionPolicyOriginal = Get-ExecutionPolicy
$FireFoxExecutable = "C:\Program Files (x86)\Mozilla Firefox\Firefox.exe" 

# This is the Firefox certificate database
$CertDB = "Cert8.db"

# The Certificate Nickname is a name you want to see on the certificates that you've imported in - so you know they were imported by this process
# However, when you look at the certificates in Firefox, they will be listed under whatever the certificate name was when it was generated
# So if your certificate is listed as 'Company123' when imported, it will still be called that as the Common Name, but when you click to view
# it, you will see that the first item in the Certificate Fields is what you 'nicknamed' it.
$CertificateNickname = "MyCompanyName FF AutoImport Cert"

# The Legacy Certificates are specific/explicit certificates which you wish to delete (The 'purge' option later in the script references these items)
$LegacyCertificates = @("OldCertificate1", "Company Cert XYZ", "Previous Company name", "Unwanted Certificate - 7", "123APTEST123")

# This is the list of databases / Firefox profiles on the machine
$FFDBList = @()

# Making sure our temporary directory is empty
$FFCertLocationLocal = "C:\FFCertTemp"

# The remote location of the certificates and 
$FFCertLocationRemote = "\\myUNC\NETLOGON\FireFoxCert\"

# The local CertUtil executable (this is copied from the remote location above)
$FFCertTool = "$FFCertLocationLocal\CertUtil.exe"

# Making sure our temporary directory is empty
Remove-Item $FFCertLocationLocal -Recurse
New-Item -ItemType Directory -Path $FFCertLocationLocal

##################################################################################################

##################################################################################################


Clear

# We're going to get a list of the Firefox processes on the machine that are open and close them
# Otherwise the add/delete parts might not be successful with Firefox still running
$FireFoxRunningProcessesList = Get-Process | Where-Object {$_.Name -Match "FireFox"} | Select-Object ProcessName,Id | Format-Table -AutoSize
$FireFoxRunningProcesses = Get-Process | Where-Object {$_.Name -Match "FireFox"} | Select-Object -ExpandProperty Id
If (!$FireFoxRunningProcesses) {}
Else {
Write-Host "The following processes will be stopped to perform certificate manipulation:"
$FireFoxRunningProcessesList
$TerminateProcessQuestion = Read-Host "To auto-terminate (ungracefully!) processes, press 'Y', otherwise, press any other key"
If ($TerminateProcessQuestion -ne 'y') {
Clear
Write-Host "Cannot continue as Firefox process is still running, ending script ..."
Exit} 
Else {ForEach ($FireFoxRunningProcess in $FireFoxRunningProcesses) {
[Int]$FireFoxRunningProcess = [Convert]::ToInt32($FireFoxRunningProcess, 10)
Stop-Process -Id $FireFoxRunningProcess -Force}}
}

##################################################################################################

##################################################################################################

# The remote files (certificates and the NSS Tools CertUtil files are copied locally)
$FFCertificateListItemRemote = Get-ChildItem $FFCertLocationRemote -Recurse -Include *.cer,*.dll,certutil.exe
ForEach ($FFCertificateItemRemote in $FFCertificateListItemRemote) {
Copy-Item $FFCertificateItemRemote.FullName -Destination $FFCertLocationLocal}

# Get a list of the local certificates
$FFCertificateListLocal = Get-ChildItem $FFCertLocationLocal -Recurse -filter *.cer

Clear
Set-ExecutionPolicy "Unrestricted"

# Find all Firefox profiles and create an array called FFDBList
# Of course, you'll only be able to get to the ones your permissions allow
$LocalProfiles = Get-ChildItem "C:\Users" | Select-Object -ExpandProperty FullName
ForEach ($LocalProfile in $LocalProfiles) {
$FFProfile = Get-ChildItem "$LocalProfile\AppData\Roaming\Mozilla\Firefox\Profiles" | Select-Object -ExpandProperty FullName
If (!$FFProfile) {Write-Host "There is no Firefox Profile for $LocalProfile"}
ELSE {$FFDBList += $FFProfile}
}

Clear
Write-Host "#################################"
Write-Host "The List of FireFox Profiles is:"
Write-Host "#################################"
$FFDBList
PAUSE

##################################################################################################

##################################################################################################

# Setup 4x functions (List, Delete, Add and Purge)
#
# - List will simply list certificates from the Firefox profiles
#
# - Delete will delete the certificates the same as the certificates you're going to add back in
#   So for example, if you have 2x certificates copied earlier for import, 'CompanyA' and 'CompanyZ'
#   then you can delete certificates with these names beforehand. This will prevent the 
#   certificates you want to import being skipped/duplicated because they already exist
#
# - Add will simply add the list of certificates you've copied locally
#
# - Purge will allow you to delete 'other' certificates that you've manually listed in the
#   variable '$LegacyCertificates' at the top of the script

# Each of the functions perform the same 4x basic steps
#
# 1) Do the following 3x things for each of the Firefox profiles
# 2) Do the 2x following things for each of the certificates
# 3) Generate an expression using parameters based on the certificate nickname specified
#    earlier, and the profile and certificate informaiton
# 4) Invoke the expression

Function ListCertificates {
Write-Host "#############################"
ForEach ($FFDBItem in $FFDBList) {
$FFCertificateListItemFull = $FFCertificateListItem.FullName
Write-Host "Listing Certificates for $FFDBitem"
$ExpressionToListCerts = "$FFCertTool -L -d `"$FFDBItem`""
Invoke-Expression $ExpressionToListCerts
}
PAUSE}

Function DeleteOldCertificates {
Write-Host "#############################"
ForEach ($FFDBItem in $FFDBList) {
ForEach ($FFCertificateListItem in $FFCertificateListLocal) {
$FFCertificateListItemFull = $FFCertificateListItem.FullName
Write-Host "Deleting Cert $FFCertificateListItem for $FFDBitem"
$ExpressionToDeleteCerts = "$FFCertTool -D -n `"$CertificateNickname`" -d `"$FFDBItem`""
Invoke-Expression $ExpressionToDeleteCerts
}}
PAUSE}

Function AddCertificates {
Write-Host "#############################"
ForEach ($FFDBItem in $FFDBList) {
ForEach ($FFCertificateListItem in $FFCertificateListLocal) {
$FFCertificateListItemFull = $FFCertificateListItem.FullName
Write-Host "Adding $FFCertificateListItem Cert for $FFDBitem"
$ExpressionToAddCerts = "$FFCertTool -A -n `"$CertificateNickname`" -t `"CT,C,C`" -d `"$FFDBItem`" -i `"$FFCertificateListItemFull`""
Write-Host $ExpressionToAddCerts
Invoke-Expression $ExpressionToAddCerts
#PAUSE
}}
PAUSE}

Function PurgeLegacyCertificates {
Write-Host "#############################"
ForEach ($FFDBItem in $FFDBList) {
ForEach ($LegacyCertificateItem in $LegacyCertificates) {
$LegacyCertificateItemFull = $LegacyCertificateItem.FullName
Write-Host "Purging Old Certs ($LegacyCertificateItem) for $FFDBitem"
#$ExpressionToDeleteLegacyCerts = "$FFCertTool -D -n `"$OldCertificate`" -d `"$FFDBItem`""
$ExpressionToDeleteLegacyCerts = "$FFCertTool -D -n `"$LegacyCertificateItem`" -d `"$FFDBItem`""
ForEach ($LegacyCertificate in $LegacyCertificates) {
Invoke-Expression $ExpressionToDeleteLegacyCerts}
}}
PAUSE}

##################################################################################################

##################################################################################################

    # Creating a few options to invoke the various functions created above

$CertificateAction = ""

Function CertificateActionSelection {
Do {
Clear
$CertificateAction = Read-Host "Would you like to [L]ist all certificates [D]elete all old certificates, [A]dd new certificates, or [P]urge legacy certificates?"
} Until ($CertificateAction -eq "L" -or $CertificateAction -eq "D" -or $CertificateAction -eq "A" -or $CertificateAction -eq "P" )

If ($CertificateAction -eq "L") {ListCertificates}
If ($CertificateAction -eq "D") {DeleteOldCertificates}
If ($CertificateAction -eq "A") {AddCertificates}
If ($CertificateAction -eq "P") {PurgeLegacyCertificates}
}

Do {
Clear
$MoreCertificateActions = Read-Host "Would you like to [L]aunch Firefox (as $env:USERNAME), take a [C]ertificate action, or [Q]uit?"
If ($MoreCertificateActions -eq "L") {
Invoke-Item $FireFoxExecutable
Exit}
If ($MoreCertificateActions -eq "C") {CertificateActionSelection}

} Until ($MoreCertificateActions -eq "Q")

Remove-Item $FFCertLocationLocal -Recurse
Set-ExecutionPolicy $ExecutionPolicyOriginal

Exit

Git Bash: Could not open a connection to your authentication agent

On Windows, you can use Run with one of the below commands.

For 32-Bit:

"C:\Program Files (x86)\Git\cmd\start-ssh-agent.cmd"

For-64 Bit:

"C:\Program Files\Git\cmd\start-ssh-agent.cmd"

CSS root directory

/Images/myImage.png

this has to be in root of your domain/subdomain

http://website.to/Images/myImage.png

and it will work

However, I think it would work like this, too

  • images
    • yourimage.png
  • styles
    • style.css

style.css:

body{
    background: url(../images/yourimage.png);
}

Create two threads, one display odd & other even numbers

public class ConsecutiveNumberPrint {

private static class NumberGenerator {

    public int MAX = 100;

    private volatile boolean evenNumberPrinted = true;

    public NumberGenerator(int max) {
        this.MAX = max;
    }

    public void printEvenNumber(int i) throws InterruptedException {
        synchronized (this) {
            if (evenNumberPrinted) {
                wait();
            }
            System.out.println("e = \t" + i);
            evenNumberPrinted = !evenNumberPrinted;
            notify();
        }
    }

    public void printOddNumber(int i) throws InterruptedException {
        synchronized (this) {
            if (!evenNumberPrinted) {
                wait();
            }
            System.out.println("o = \t" + i);
            evenNumberPrinted = !evenNumberPrinted;
            notify();
        }
    }

}

private static class EvenNumberGenerator implements Runnable {

    private NumberGenerator numberGenerator;

    public EvenNumberGenerator(NumberGenerator numberGenerator) {
        this.numberGenerator = numberGenerator;
    }

    @Override
    public void run() {
        for(int i = 2; i <= numberGenerator.MAX; i+=2)
            try {
                numberGenerator.printEvenNumber(i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    }
}

private static class OddNumberGenerator implements Runnable {

    private NumberGenerator numberGenerator;

    public OddNumberGenerator(NumberGenerator numberGenerator) {
        this.numberGenerator = numberGenerator;
    }

    @Override
    public void run() {
        for(int i = 1; i <= numberGenerator.MAX; i+=2) {
            try {
                numberGenerator.printOddNumber(i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
public static void main(String[] args) {
    NumberGenerator numberGenerator = new NumberGenerator(100);
    EvenNumberGenerator evenNumberGenerator = new EvenNumberGenerator(numberGenerator);
    OddNumberGenerator oddNumberGenerator = new OddNumberGenerator(numberGenerator);
    new Thread(oddNumberGenerator).start();
    new Thread(evenNumberGenerator).start();

}

}

How to get a password from a shell script without echoing

A POSIX compliant answer. Notice the use of /bin/sh instead of /bin/bash. (It does work with bash, but it does not require bash.)

#!/bin/sh
stty -echo
printf "Password: "
read PASSWORD
stty echo
printf "\n"

jquery - fastest way to remove all rows from a very large table

this works for me :

1- add class for each row "removeRow"

2- in the jQuery

$(".removeRow").remove();

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

Here's a Django logging-based solution. It uses the DEBUG setting rather than actually checking whether or not you're running the development server, but if you find a better way to check for that it should be easy to adapt.

LOGGING = {
    'version': 1,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'simple'
        },
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': '/path/to/your/file.log',
            'formatter': 'simple'
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'DEBUG',
            'propagate': True,
        },
    }
}

if DEBUG:
    # make all loggers use the console.
    for logger in LOGGING['loggers']:
        LOGGING['loggers'][logger]['handlers'] = ['console']

see https://docs.djangoproject.com/en/dev/topics/logging/ for details.

How to query data out of the box using Spring data JPA by both Sort and Pageable?

Pageable has an option to specify sort as well. From the java doc

PageRequest(int page, int size, Sort.Direction direction, String... properties) 

Creates a new PageRequest with sort parameters applied.

Server returned HTTP response code: 401 for URL: https

401 means "Unauthorized", so there must be something with your credentials.

I think that java URL does not support the syntax you are showing. You could use an Authenticator instead.

Authenticator.setDefault(new Authenticator() {

    @Override
    protected PasswordAuthentication getPasswordAuthentication() {          
        return new PasswordAuthentication(login, password.toCharArray());
    }
});

and then simply invoking the regular url, without the credentials.

The other option is to provide the credentials in a Header:

String loginPassword = login+ ":" + password;
String encoded = new sun.misc.BASE64Encoder().encode (loginPassword.getBytes());
URLConnection conn = url.openConnection();
conn.setRequestProperty ("Authorization", "Basic " + encoded);

PS: It is not recommended to use that Base64Encoder but this is only to show a quick solution. If you want to keep that solution, look for a library that does. There are plenty.

Open source PDF library for C/C++ application?

If you're brave and willing to roll your own, you could start with a PostScript library and augment it to deal with PDF, taking advantage of Adobe's free online PDF reference.

Redirecting unauthorized controller in ASP.NET MVC

The code by "tvanfosson" was giving me "Error executing Child Request".. I have changed the OnAuthorization like this:

public override void OnAuthorization(AuthorizationContext filterContext)
    {
        base.OnAuthorization(filterContext);

        if (!_isAuthorized)
        {
            filterContext.Result = new HttpUnauthorizedResult();
        }
        else if (filterContext.HttpContext.User.IsInRole("Administrator") || filterContext.HttpContext.User.IsInRole("User") ||  filterContext.HttpContext.User.IsInRole("Manager"))
        {
            // is authenticated and is in one of the roles 
            SetCachePolicy(filterContext);
        }
        else
        {
            filterContext.Controller.TempData.Add("RedirectReason", "You are not authorized to access this page.");
            filterContext.Result = new RedirectResult("~/Error");
        }
    }

This works well and I show the TempData on error page. Thanks to "tvanfosson" for the code snippet. I am using windows authentication and _isAuthorized is nothing but HttpContext.User.Identity.IsAuthenticated...

How to use JavaScript source maps (.map files)?

Just wanted to focus on the last part of the question; How source map files are created? by listing the build tools I know that can create source maps.

  1. Grunt: using plugin grunt-contrib-uglify
  2. Gulp: using plugin gulp-uglify
  3. Google closure: using parameter --create_source_map

Angular 2 - Redirect to an external URL and open in a new tab

One caveat on using window.open() is that if the url that you pass to it doesn't have http:// or https:// in front of it, angular treats it as a route.

To get around this, test if the url starts with http:// or https:// and append it if it doesn't.

let url: string = '';
if (!/^http[s]?:\/\//.test(this.urlToOpen)) {
    url += 'http://';
}

url += this.urlToOpen;
window.open(url, '_blank');

jQuery animate margin top

check this same effect with less code

$(".item").mouseover(function(){
    $('.info').animate({ marginTop: '-50px' , opacity: 0.5 }, 1000);
}); 

View recent fiddle

How do I resize an image using PIL and maintain its aspect ratio?

You can resize image by below code:

From PIL import Image
img=Image.open('Filename.jpg') # paste image in python folder
print(img.size())
new_img=img.resize((400,400))
new_img.save('new_filename.jpg')

How do you remove a specific revision in the git history?

All the answers so far don't address the trailing concern:

Is there an efficient method when there are hundreds of revisions after the one to be deleted?

The steps follow, but for reference, let's assume the following history:

[master] -> [hundreds-of-commits-including-merges] -> [C] -> [R] -> [B]

C: commit just following the commit to be removed (clean)

R: The commit to be removed

B: commit just preceding the commit to be removed (base)

Because of the "hundreds of revisions" constraint, I'm assuming the following pre-conditions:

  1. there is some embarrassing commit that you wish never existed
  2. there are ZERO subsequent commits that actually depend on that embarassing commit (zero conflicts on revert)
  3. you don't care that you will be listed as the 'Committer' of the hundreds of intervening commits ('Author' will be preserved)
  4. you have never shared the repository
    • or you actually have enough influence over all the people who have ever cloned history with that commit in it to convince them to use your new history
    • and you don't care about rewriting history

This is a pretty restrictive set of constraints, but there is an interesting answer that actually works in this corner case.

Here are the steps:

  1. git branch base B
  2. git branch remove-me R
  3. git branch save
  4. git rebase --preserve-merges --onto base remove-me

If there are truly no conflicts, then this should proceed with no further interruptions. If there are conflicts, you can resolve them and rebase --continue or decide to just live with the embarrassment and rebase --abort.

Now you should be on master that no longer has commit R in it. The save branch points to where you were before, in case you want to reconcile.

How you want to arrange everyone else's transfer over to your new history is up to you. You will need to be acquainted with stash, reset --hard, and cherry-pick. And you can delete the base, remove-me, and save branches

Compare object instances for equality by their attributes

If you're dealing with one or more classes which you can't change from the inside, there are generic and simple ways to do this that also don't depend on a diff-specific library:

Easiest, unsafe-for-very-complex-objects method

pickle.dumps(a) == pickle.dumps(b)

pickle is a very common serialization lib for Python objects, and will thus be able to serialize pretty much anything, really. In the above snippet I'm comparing the str from serialized a with the one from b. Unlike the next method, this one has the advantage of also type checking custom classes.

The biggest hassle: due to specific ordering and [de/en]coding methods, pickle may not yield the same result for equal objects, specially when dealing with more complex ones (e.g. lists of nested custom-class instances) like you'll frequently find in some third-party libs. For those cases, I'd recommend a different approach:

Thorough, safe-for-any-object method

You could write a recursive reflection that'll give you serializable objects, and then compare results

from collections.abc import Iterable

BASE_TYPES = [str, int, float, bool, type(None)]


def base_typed(obj):
    """Recursive reflection method to convert any object property into a comparable form.
    """
    T = type(obj)
    from_numpy = T.__module__ == 'numpy'

    if T in BASE_TYPES or callable(obj) or (from_numpy and not isinstance(T, Iterable)):
        return obj

    if isinstance(obj, Iterable):
        base_items = [base_typed(item) for item in obj]
        return base_items if from_numpy else T(base_items)

    d = obj if T is dict else obj.__dict__

    return {k: base_typed(v) for k, v in d.items()}


def deep_equals(*args):
    return all(base_typed(args[0]) == base_typed(other) for other in args[1:])

Now it doesn't matter what your objects are, deep equality is assured to work

>>> from sklearn.ensemble import RandomForestClassifier
>>>
>>> a = RandomForestClassifier(max_depth=2, random_state=42)
>>> b = RandomForestClassifier(max_depth=2, random_state=42)
>>> 
>>> deep_equals(a, b)
True

The number of comparables doesn't matter as well

>>> c = RandomForestClassifier(max_depth=2, random_state=1000)
>>> deep_equals(a, b, c)
False

My use case for this was checking deep equality among a diverse set of already trained Machine Learning models inside BDD tests. The models belonged to a diverse set of third-party libs. Certainly implementing __eq__ like other answers here suggest wasn't an option for me.

Covering all the bases

You may be in a scenario where one or more of the custom classes being compared do not have a __dict__ implementation. That's not common by any means, but it is the case of a subtype within sklearn's Random Forest classifier: <type 'sklearn.tree._tree.Tree'>. Treat these situations in a case by case basis - e.g. specifically, I decided to replace the content of the afflicted type with the content of a method that gives me representative information on the instance (in this case, the __getstate__ method). For such, the second-to-last row in base_typed became

d = obj if T is dict else obj.__dict__ if '__dict__' in dir(obj) else obj.__getstate__()

Edit: for the sake of organization, I replaced the hideous oneliner above with return dict_from(obj). Here, dict_from is a really generic reflection made to accommodate more obscure libs (I'm looking at you, Doc2Vec)

def isproperty(prop, obj):
    return not callable(getattr(obj, prop)) and not prop.startswith('_')


def dict_from(obj):
    """Converts dict-like objects into dicts
    """
    if isinstance(obj, dict):
        # Dict and subtypes are directly converted
        d = dict(obj)

    elif '__dict__' in dir(obj):
        # Use standard dict representation when available
        d = obj.__dict__

    elif str(type(obj)) == 'sklearn.tree._tree.Tree':
        # Replaces sklearn trees with their state metadata
        d = obj.__getstate__()

    else:
        # Extract non-callable, non-private attributes with reflection
        kv = [(p, getattr(obj, p)) for p in dir(obj) if isproperty(p, obj)]
        d = {k: v for k, v in kv}

    return {k: base_typed(v) for k, v in d.items()}

Do mind none of the above methods yield True for objects with the same key-value pairs in differing order, as in

>>> a = {'foo':[], 'bar':{}}
>>> b = {'bar':{}, 'foo':[]}
>>> pickle.dumps(a) == pickle.dumps(b)
False

But if you want that you could use Python's built-in sorted method beforehand anyway.

How can I find which tables reference a given table in Oracle SQL Developer?

I like to do this with a straight SQL query, rather than messing about with the SQL Developer application.

Here's how I just did it. Best to read through this and understand what's going on, so you can tweak it to fit your needs...

WITH all_primary_keys AS (
  SELECT constraint_name AS pk_name,
         table_name
    FROM all_constraints
   WHERE owner = USER
     AND constraint_type = 'P'
)
  SELECT ac.table_name || ' table has a foreign key called ' || upper(ac.constraint_name)
         || ' which references the primary key ' || upper(ac.r_constraint_name) || ' on table ' || apk.table_name AS foreign_keys
    FROM all_constraints ac
         LEFT JOIN all_primary_keys apk
                ON ac.r_constraint_name = apk.pk_name
   WHERE ac.owner = USER
     AND ac.constraint_type = 'R'
     AND ac.table_name = nvl(upper(:table_name), ac.table_name)
ORDER BY ac.table_name, ac.constraint_name
;

Using routes in Express-js

No one should ever have to keep writing app.use('/someRoute', require('someFile')) until it forms a heap of code.

It just doesn't make sense at all to be spending time invoking/defining routings. Even if you do need custom control, it's probably only for some of the time, and for the most bit you want to be able to just create a standard file structure of routings and have a module do it automatically.

Try Route Magic

As you scale your app, the routing invocations will start to form a giant heap of code that serves no purpose. You want to do just 2 lines of code to handle all the app.use routing invocations with Route Magic like this:

const magic = require('express-routemagic')
magic.use(app, __dirname, '[your route directory]')

For those you want to handle manually, just don't use pass the directory to Magic.

LaTeX beamer: way to change the bullet indentation?

Beamer just delegates responsibility for managing layout of itemize environments back to the base LaTeX packages, so there's nothing funky you need to do in Beamer itself to alter the apperaance / layout of your lists.

Since Beamer redefines itemize, item, etc., the fully proper way to manipulate things like indentation is to redefine the Beamer templates. I get the impression that you're not looking to go that far, but if that's not the case, let me know and I'll elaborate.

There are at least three ways of accomplishing your goal from within your document, without mussing about with Beamer templates.

With itemize

In the following code snippet, you can change the value of \itemindent from 0em to whatever you please, including negative values. 0em is the default item indentation.

The advantage of this method is that the list is styled normally. The disadvantage is that Beamer's redefinition of itemize and \item means that the number of paramters that can be manipulated to change the list layout is limited. It can be very hard to get the spacing right with multi-line items.

\begin{itemize}
  \setlength{\itemindent}{0em}
  \item This is a normally-indented item.
\end{itemize}

With list

In the following code snippet, the second parameter to \list is the bullet to use, and the third parameter is a list of layout parameters to change. The \leftmargin parameter adjusts the indentation of the entire list item and all of its rows; \itemindent alters the indentation of subsequent lines.

The advantage of this method is that you have all of the flexibility of lists in non-Beamer LaTeX. The disadvantage is that you have to setup the bullet style (and other visual elements) manually (or identify the right command for the template you're using). Note that if you leave the second argument empty, no bullet will be displayed and you'll save some horizontal space.

\begin{list}{$\square$}{\leftmargin=1em \itemindent=0em}
  \item This item uses the margin and indentation provided above.
\end{list}

Defining a customlist environment

The shortcomings of the list solution can be ameliorated by defining a new customlist environment that basically redefines the itemize environment from Beamer but also incorporates the \leftmargin and \itemindent (etc.) parameters. Put the following in your preamble:

\makeatletter
\newenvironment{customlist}[2]{
  \ifnum\@itemdepth >2\relax\@toodeep\else
      \advance\@itemdepth\@ne%
      \beamer@computepref\@itemdepth%
      \usebeamerfont{itemize/enumerate \beameritemnestingprefix body}%
      \usebeamercolor[fg]{itemize/enumerate \beameritemnestingprefix body}%
      \usebeamertemplate{itemize/enumerate \beameritemnestingprefix body begin}%
      \begin{list}
        {
            \usebeamertemplate{itemize \beameritemnestingprefix item}
        }
        { \leftmargin=#1 \itemindent=#2
            \def\makelabel##1{%
              {%  
                  \hss\llap{{%
                    \usebeamerfont*{itemize \beameritemnestingprefix item}%
                        \usebeamercolor[fg]{itemize \beameritemnestingprefix item}##1}}%
              }%  
            }%  
        }
  \fi
}
{
  \end{list}
  \usebeamertemplate{itemize/enumerate \beameritemnestingprefix body end}%
}
\makeatother

Now, to use an itemized list with custom indentation, you can use the following environment. The first argument is for \leftmargin and the second is for \itemindent. The default values are 2.5em and 0em respectively.

\begin{customlist}{2.5em}{0em}
   \item Any normal item can go here.
\end{customlist}

A custom bullet style can be incorporated into the customlist solution using the standard Beamer mechanism of \setbeamertemplate. (See the answers to this question on the TeX Stack Exchange for more information.)

Alternatively, the bullet style can just be modified directly within the environment, by replacing \usebeamertemplate{itemize \beameritemnestingprefix item} with whatever bullet style you'd like to use (e.g. $\square$).

Why does checking a variable against multiple values with `OR` only check the first value?

("Jesse" or "jesse")

The above expression tests whether or not "Jesse" evaluates to True. If it does, then the expression will return it; otherwise, it will return "jesse". The expression is equivalent to writing:

"Jesse" if "Jesse" else "jesse"

Because "Jesse" is a non-empty string though, it will always evaluate to True and thus be returned:

>>> bool("Jesse")  # Non-empty strings evaluate to True in Python
True
>>> bool("")  # Empty strings evaluate to False
False
>>>
>>> ("Jesse" or "jesse")
'Jesse'
>>> ("" or "jesse")
'jesse'
>>>

This means that the expression:

name == ("Jesse" or "jesse")

is basically equivalent to writing this:

name == "Jesse"

In order to fix your problem, you can use the in operator:

# Test whether the value of name can be found in the tuple ("Jesse", "jesse")
if name in ("Jesse", "jesse"):

Or, you can lowercase the value of name with str.lower and then compare it to "jesse" directly:

# This will also handle inputs such as "JeSSe", "jESSE", "JESSE", etc.
if name.lower() == "jesse":

Invariant Violation: _registerComponent(...): Target container is not a DOM element

just a wild guess, how about adding to index.html the following:

type="javascript"

like this:

<script type="javascript" src="public/bundle.js"> </script>

For me it worked! :-)

keytool error bash: keytool: command not found

Use

./keytool -genkey -alias mypassword -keyalg RSA

How to select last two characters of a string

Slice can be used to find the substring. When we know the indexes we can use an alternative solution like index wise adder. Both are taking roughly the same time for execution.

_x000D_
_x000D_
const primitiveStringMember = "my name is Mate";

const objectStringMember = new String("my name is Mate");
console.log(typeof primitiveStringMember);//string
console.log(typeof objectStringMember);//object


/* However when we use . operator to string primitive type, JS will wrap up the string with object. That's why we can use the methods String object type for the primitive type string.
*/

//Slice method
const t0 = performance.now();
slicedString = primitiveStringMember.slice(-2);//te
const t1 = performance.now();
console.log(`Call to do slice took ${t1 - t0} milliseconds.`);


//index vise adder method
const t2 = performance.now();
length = primitiveStringMember.length
neededString = primitiveStringMember[length-2]+primitiveStringMember[length-1];//te
const t3 = performance.now();
console.log(`Call to do index adder took ${t3 - t2} milliseconds.`);
_x000D_
_x000D_
_x000D_

Conditional formatting based on another cell's value

I'm disappointed at how long it took to work this out.

I want to see which values in my range are outside standard deviation.

  1. Add the standard deviation calc to a cell somewhere =STDEV(L3:L32)*2
  2. Select the range to be highlighted, right click, conditional formatting
  3. Pick Format Cells if Greater than
  4. In the Value or Formula box type =$L$32 (whatever cell your stdev is in)

I couldn't work out how to put the STDEv inline. I tried many things with unexpected results.

Labels for radio buttons in rails form

Passing the :value option to f.label will ensure the label tag's for attribute is the same as the id of the corresponding radio_button

<% form_for(@message) do |f| %>
  <%= f.radio_button :contactmethod, 'email' %> 
  <%= f.label :contactmethod, 'Email', :value => 'email' %>
  <%= f.radio_button :contactmethod, 'sms' %>
  <%= f.label :contactmethod, 'SMS', :value => 'sms' %>
<% end %>

See ActionView::Helpers::FormHelper#label

the :value option, which is designed to target labels for radio_button tags

How can I read an input string of unknown length?

Take a character pointer to store required string.If you have some idea about possible size of string then use function

char *fgets (char *str, int size, FILE* file);`

else you can allocate memory on runtime too using malloc() function which dynamically provides requested memory.

Build Maven Project Without Running Unit Tests

If you are using eclipse there is a "Skip Tests" checkbox on the configuration page.

Run configurations ? Maven Build ? New ? Main tab ? Skip Tests Snip from eclipse

How to write to a JSON file in the correct format

Require the JSON library, and use to_json.

require 'json'
tempHash = {
    "key_a" => "val_a",
    "key_b" => "val_b"
}
File.open("public/temp.json","w") do |f|
  f.write(tempHash.to_json)
end

Your temp.json file now looks like:

{"key_a":"val_a","key_b":"val_b"}

break out of if and foreach

For those of you landing here but searching how to break out of a loop that contains an include statement use return instead of break or continue.

<?php

for ($i=0; $i < 100; $i++) { 
    if (i%2 == 0) {
        include(do_this_for_even.php);
    }
    else {
        include(do_this_for_odd.php);
    }
}

?>

If you want to break when being inside do_this_for_even.php you need to use return. Using break or continue will return this error: Cannot break/continue 1 level. I found more details here

R : how to simply repeat a command?

It's not clear whether you're asking this because you are new to programming, but if that's the case then you should probably read this article on loops and indeed read some basic materials on programming.

If you already know about control structures and you want the R-specific implementation details then there are dozens of tutorials around, such as this one. The other answer uses replicate and colMeans, which is idiomatic when writing in R and probably blazing fast as well, which is important if you want 10,000 iterations.

However, one more general and (for beginners) straightforward way to approach problems of this sort would be to use a for loop.

> for (ii in 1:5) { + print(ii) + } [1] 1 [1] 2 [1] 3 [1] 4 [1] 5 > 

So in your case, if you just wanted to print the mean of your Tandem object 5 times:

for (ii in 1:5) {     Tandem <- sample(OUT, size = 815, replace = TRUE, prob = NULL)     TandemMean <- mean(Tandem)     print(TandemMean) } 

As mentioned above, replicate is a more natural way to deal with this specific problem using R. Either way, if you want to store the results - which is surely the case - you'll need to start thinking about data structures like vectors and lists. Once you store something you'll need to be able to access it to use it in future, so a little knowledge is vital.

set.seed(1234) OUT <- runif(100000, 1, 2) tandem <- list() for (ii in 1:10000) {     tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) }  tandem[1] tandem[100] tandem[20:25] 

...creates this output:

> set.seed(1234) > OUT <- runif(100000, 1, 2) > tandem <- list() > for (ii in 1:10000) { +     tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) + } >  > tandem[1] [[1]] [1] 1.511923  > tandem[100] [[1]] [1] 1.496777  > tandem[20:25] [[1]] [1] 1.500669  [[2]] [1] 1.487552  [[3]] [1] 1.503409  [[4]] [1] 1.501362  [[5]] [1] 1.499728  [[6]] [1] 1.492798  >  

Fastest way to serialize and deserialize .NET objects

Yet another serializer out there that claims to be super fast is netserializer.

The data given on their site shows performance of 2x - 4x over protobuf, I have not tried this myself, but if you are evaluating various options, try this as well

update to python 3.7 using anaconda

This can be installed via conda with the command conda install -c anaconda python=3.7 as per https://anaconda.org/anaconda/python.

Though not all packages support 3.7 yet, running conda update --all may resolve some dependency failures.

How do you run a .bat file from PHP?

This snippet is from working code.

You can trigger bat file not only from Windows GUI or Task Scheduler, but directly from PHP script when you need it. But in most cases it will have execution for 30-60 sec. depending from your PHP configuration. If job in BAT file is long and you don't want to freeze your PHP scripts, you need to fork BAT job as another process using php.exe and not be dependable from Apache.

This runs in background mode in Windows, seen as separate processes cmd.exe and php.exe from Task Manager not halting your Apache PHP scripts. The messages produced by your script may be stored and retrieved back via log files.

In my case in file_scanner.php I do some heavy calculations in loop for big array of files which may last for few hours with php function sleep() not to overload CPU.

The success poiner result from file $r which you can query via ajax if you want to know success or fauty start. In my case file_scanner.php writes log file with messages somefile.jpg - OK wich you can load to your UI with AJAX every few seconds to show progress.

PHP

/**
 * Runs bat file in background mode
 *
 */
 function run_scanner() {

    $c='start /b D:\Web\example.com\tasks\file_scanner.bat'; 
    $r=pclose(popen($c, 'r')); 
    return json_encode(array('result'=>$r));

 }

BAT

@echo Off
D:\PHP\php.exe D:\Web\example.com\tasks\file_scanner.php > D:\Web\example.com\tasks\file_scanner.log
exit

Adding VirtualHost fails: Access Forbidden Error 403 (XAMPP) (Windows 7)

For me worked when I changed "directory" content into this:

<Directory  "*YourLocation*">
Options All
AllowOverride All
Require all granted  
</Directory>

How to remove MySQL root password

I have also been through this problem,

First i tried setting my password of root to blank using command :

SET PASSWORD FOR root@localhost=PASSWORD('');

But don't be happy , PHPMYADMIN uses 127.0.0.1 not localhost , i know you would say both are same but that is not the case , use the command mentioned underneath and you are done.

SET PASSWORD FOR [email protected]=PASSWORD('');

Just replace localhost with 127.0.0.1 and you are done .

Is the size of C "int" 2 bytes or 4 bytes?

#include <stdio.h>

int main(void) {
    printf("size of int: %d", (int)sizeof(int));
    return 0;
}

This returns 4, but it's probably machine dependant.

Using multiple parameters in URL in express

For what you want I would've used

    app.get('/fruit/:fruitName&:fruitColor', function(request, response) {
       const name = request.params.fruitName 
       const color = request.params.fruitColor 
    });

or better yet

    app.get('/fruit/:fruit', function(request, response) {
       const fruit = request.params.fruit
       console.log(fruit)
    });

where fruit is a object. So in the client app you just call

https://mydomain.dm/fruit/{"name":"My fruit name", "color":"The color of the fruit"}

and as a response you should see:

    //  client side response
    // { name: My fruit name, color:The color of the fruit}

Installing PIL with pip

Install

pip install Pillow

Then, Just import in your file like,

from PIL import Image

I am using windows. It is working for me.

NOTE:

Pillow is a functional drop-in replacement for the Python Imaging Library. To run your existing PIL-compatible code with Pillow, it needs to be modified to import the Imaging module from the PIL namespace instead of the global namespace.

i.e. change:

import Image

to:

from PIL import Image

https://pypi.org/project/Pillow/2.2.1/

SQL command to display history of queries

try

 cat ~/.mysql_history

this will show you all mysql commands ran on the system

How to collapse blocks of code in Eclipse?

For Python it is as follows:

  • collapse all 1 level: Ctrl+9
  • expand all 1 level: Ctrl+0
  • collapse current: Ctrl+-
  • expand current: Ctrl++

Hope that helps.

What is a LAMP stack?

There are various technological stacks present. Have a look:

LAMP:

Linux
Apache
MySQL
PHP

WAMP:

Windows
Apache
MySQL
PHP

MAMP:

Mac operating system
Apache web server
MySQL as database
PHP for scripting

XAMPP:

X is cross-platform
Apache
MySQL
PHP
Perl

MEAN:

MongoDB
Express.js
Angular
Node.js

MERN:

MongoDB
Express.js
React
Node.js

How to launch another aspx web page upon button click?

Edited and fixed (thanks to Shredder)

If you mean you want to open a new tab, try the below:

protected void Page_Load(object sender, EventArgs e)
{
    this.Form.Target = "_blank";
}

protected void Button1_Click(object sender, EventArgs e)
{

    Response.Redirect("Otherpage.aspx");
}

This will keep the original page to stay open and cause the redirects on the current page to affect the new tab only.

-J

Mocking Logger and LoggerFactory with PowerMock and Mockito

In answer to your first question, it should be as simple as replacing:

   when(LoggerFactory.getLogger(GoodbyeController.class)).thenReturn(loggerMock);

with

   when(LoggerFactory.getLogger(any(Class.class))).thenReturn(loggerMock);

Regarding your second question (and possibly the puzzling behavior with the first), I think the problem is that logger is static. So,

private static Logger logger = LoggerFactory.getLogger(GoodbyeController.class);

is executed when the class is initialized, not the when the object is instantiated. Sometimes this can be at about the same time, so you'll be OK, but it's hard to guarantee that. So you set up LoggerFactory.getLogger to return your mock, but the logger variable may have already been set with a real Logger object by the time your mocks are set up.

You may be able to set the logger explicitly using something like ReflectionTestUtils (I don't know if that works with static fields) or change it from a static field to an instance field. Either way, you don't need to mock LoggerFactory.getLogger because you'll be directly injecting the mock Logger instance.

Add a default value to a column through a migration

Here's how you should do it:

change_column :users, :admin, :boolean, :default => false

But some databases, like PostgreSQL, will not update the field for rows previously created, so make sure you update the field manaully on the migration too.

How to change language settings in R

For me worked:

Sys.setlocale("LC_MESSAGES", "en_US.utf8")

Testing:

> Sys.setlocale("LC_MESSAGES", "en_US.utf8")
[1] "en_US.utf8"
> x[3]
Error: object 'x' not found

Also working to get english messages:

Sys.setlocale("LC_MESSAGES", "C")

To reset to german messages I used

Sys.setlocale("LC_MESSAGES", "de_DE.utf8")

Here is the start of my sessionInfo:

> sessionInfo()
R version 3.4.1 (2017-06-30)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 16.04.2 LTS

Open link in new tab or window

You should add the target="_blank" and rel="noopener noreferrer" in the anchor tag.

For example:

<a target="_blank" rel="noopener noreferrer" href="http://your_url_here.html">Link</a>

Adding rel="noopener noreferrer" is not mandatory, but it's a recommended security measure. More information can be found in the links below.

Source:

react router v^4.0.0 Uncaught TypeError: Cannot read property 'location' of undefined

so if you need want use this code )

import { useRoutes } from "./routes";

import { BrowserRouter as Router } from "react-router-dom";

export const App = () => {

const routes = useRoutes(true);

  return (

    <Router>

      <div className="container">{routes}</div>

    </Router>

  );

};

// ./routes.js 

import { Switch, Route, Redirect } from "react-router-dom";

export const useRoutes = (isAuthenticated) => {
  if (isAuthenticated) {
    return (
      <Switch>
        <Route path="/links" exact>
          <LinksPage />
        </Route>
        <Route path="/create" exact>
          <CreatePage />
        </Route>
        <Route path="/detail/:id">
          <DetailPage />
        </Route>
        <Redirect path="/create" />
      </Switch>
    );
  }
  return (
    <Switch>
      <Route path={"/"} exact>
        <AuthPage />
      </Route>
      <Redirect path={"/"} />
    </Switch>
  );
};

Use querystring variables in MVC controller

I had this problem while inheriting from ApiController instead of the regular Controller class. I solved it by using var container = Request.GetQueryNameValuePairs().ToLookup(x => x.Key, x => x.Value);

I followed this thread How to get Request Querystring values?

EDIT: After trying to filter through the container I was getting odd error messages. After going to my project properties and I unchecked the Optimize Code checkbox which changed so that all of a sudden the parameters in my controller where filled up from the url as I wanted.

Hopefully this will help someone with the same problem..

Open a link in browser with java button?

public static void openWebpage(String urlString) {
    try {
        Desktop.getDesktop().browse(new URL(urlString).toURI());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

notifyDataSetChanged not working on RecyclerView

I had same problem. I just solved it with declaring adapter public before onCreate of class.

PostAdapter postAdapter;

after that

postAdapter = new PostAdapter(getActivity(), posts);
recList.setAdapter(postAdapter);

at last I have called:

@Override
protected void onPostExecute(Void aVoid) {
    super.onPostExecute(aVoid);
    // Display the size of your ArrayList
    Log.i("TAG", "Size : " + posts.size());
    progressBar.setVisibility(View.GONE);
    postAdapter.notifyDataSetChanged();
}

May this will helps you.

Reading Excel file using node.js

Useful link

https://ciphertrick.com/read-excel-files-convert-json-node-js/

 var express = require('express'); 
    var app = express(); 
    var bodyParser = require('body-parser');
    var multer = require('multer');
    var xlstojson = require("xls-to-json-lc");
    var xlsxtojson = require("xlsx-to-json-lc");
    app.use(bodyParser.json());
    var storage = multer.diskStorage({ //multers disk storage settings
        destination: function (req, file, cb) {
            cb(null, './uploads/')
        },
        filename: function (req, file, cb) {
            var datetimestamp = Date.now();
            cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length -1])
        }
    });
    var upload = multer({ //multer settings
                    storage: storage,
                    fileFilter : function(req, file, callback) { //file filter
                        if (['xls', 'xlsx'].indexOf(file.originalname.split('.')[file.originalname.split('.').length-1]) === -1) {
                            return callback(new Error('Wrong extension type'));
                        }
                        callback(null, true);
                    }
                }).single('file');
    /** API path that will upload the files */
    app.post('/upload', function(req, res) {
        var exceltojson;
        upload(req,res,function(err){
            if(err){
                 res.json({error_code:1,err_desc:err});
                 return;
            }
            /** Multer gives us file info in req.file object */
            if(!req.file){
                res.json({error_code:1,err_desc:"No file passed"});
                return;
            }
            /** Check the extension of the incoming file and 
             *  use the appropriate module
             */
            if(req.file.originalname.split('.')[req.file.originalname.split('.').length-1] === 'xlsx'){
                exceltojson = xlsxtojson;
            } else {
                exceltojson = xlstojson;
            }
            try {
                exceltojson({
                    input: req.file.path,
                    output: null, //since we don't need output.json
                    lowerCaseHeaders:true
                }, function(err,result){
                    if(err) {
                        return res.json({error_code:1,err_desc:err, data: null});
                    } 
                    res.json({error_code:0,err_desc:null, data: result});
                });
            } catch (e){
                res.json({error_code:1,err_desc:"Corupted excel file"});
            }
        })
    }); 
    app.get('/',function(req,res){
        res.sendFile(__dirname + "/index.html");
    });
    app.listen('3000', function(){
        console.log('running on 3000...');
    });

SQL 'like' vs '=' performance

First things first ,

they are not always equal

    select 'Hello' from dual where 'Hello  ' like 'Hello';

    select 'Hello' from dual where 'Hello  ' =  'Hello';

when things are not always equal , talking about their performance isn't that relevant.

If you are working on strings and only char variables , then you can talk about performance . But don't use like and "=" as being generally interchangeable .

As you would have seen in many posts ( above and other questions) , in cases when they are equal the performance of like is slower owing to pattern matching (collation)

Why does JSHint throw a warning if I am using const?

May 2020 Here's a simple solution i found and it will resolve for all of my projects ,on windows if your project is somewhere inside c: directory , create new file .jshintrc and save it in C directory open this .jshintrc file and write { "esversion": 6} and that's it. the warnings should go away , same will work in d directory

enter image description here

enter image description here yes you can also enable this setting for the specific project only by same creating a .jshintrc file in your project's root and adding { "esversion": 6}

Test only if variable is not null in if statement

I don't believe the expression is sensical as it is.

Elvis means "if truthy, use the value, else use this other thing."

Your "other thing" is a closure, and the value is status != null, neither of which would seem to be what you want. If status is null, Elvis says true. If it's not, you get an extra layer of closure.

Why can't you just use:

(it.description == desc) && ((status == null) || (it.status == status))

Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find calls, just use an intermediate variable.

How do I remove diacritics (accents) from a string in .NET?

this did the trick for me...

string accentedStr;
byte[] tempBytes;
tempBytes = System.Text.Encoding.GetEncoding("ISO-8859-8").GetBytes(accentedStr);
string asciiStr = System.Text.Encoding.UTF8.GetString(tempBytes);

quick&short!

Get folder up one level

You can try

echo realpath(__DIR__ . DIRECTORY_SEPARATOR . '..'); 

Why does Eclipse complain about @Override on interface methods?

Use Eclipse to search and replace (remove) all instances of "@Override". Then add back the non-interface overrides using "Clean Up".

Steps:

  1. Select the projects or folders containing your source files.
  2. Go to "Search > Search..." (Ctrl-H) to bring up the Search dialog.
  3. Go to the "File Search" tab.
  4. Enter "@Override" in "Containing text" and "*.java" in "File name patterns". Click "Replace...", then "OK", to remove all instances of "@Override".
  5. Go to "Window > Preferences > Java > Code Style > Clean Up" and create a new profile.
  6. Edit the profile, and uncheck everything except "Missing Code > Add missing Annotations > @Override". Make sure "Implementations of interface methods" is unchecked.
  7. Select the projects or folders containing your source files.
  8. Select "Source > Clean Up..." (Alt+Shift+s, then u), then "Finish" to add back the non-interface overrides.

How to read .pem file to get private and public key

To get the public key you can simply do:

public static PublicKey getPublicKeyFromCertFile(final String certfile){

     return new X509CertImpl(new FileInputStream(new File(certfile))).getPublicKey();

To get the private key is trickier, you can:

public static PrivateKey getPrivateKeyFromKeyFile(final String keyfile){
    try {
        Process p;
        p = Runtime.getRuntime().exec("openssl pkcs8 -nocrypt -topk8 -inform PEM " +
                "-in " + keyfile + " -outform DER -out " + keyfile + ".der");

        p.waitFor();
        System.out.println("Command executed" + (p.exitValue() == 0 ? " successfully" : " with error" ));
    } catch ( IOException | InterruptedException e) {
        e.printStackTrace();
        System.exit(1);
    }

    PrivateKey myPrivKey = null;
    try {
        byte[] keyArray = Files.readAllBytes(Paths.get(keyfile + ".der"));
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyArray);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        myPrivKey = keyFactory.generatePrivate(keySpec);
    } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e){
        e.printStackTrace();
        System.exit(1);
    }

    return myPrivKey;
}

Android notification is not showing

This tripped me up today, but I realized it was because on Android 9.0 (Pie), Do Not Disturb by default also hides all notifications, rather than just silencing them like in Android 8.1 (Oreo) and before. This doesn't apply to notifications.

I like having DND on for my development device, so going into the DND settings and changing the setting to simply silence the notifications (but not hide them) fixed it for me.

Removing elements from array Ruby

[1,3].inject([1,1,1,2,2,3]) do |memo,element|
  memo.tap do |memo|
    i = memo.find_index(e)
    memo.delete_at(i) if i
  end
end

How to overcome "datetime.datetime not JSON serializable"?

If you are on both sides of the communication you can use repr() and eval() functions along with json.

import datetime, json

dt = datetime.datetime.now()
print("This is now: {}".format(dt))

dt1 = json.dumps(repr(dt))
print("This is serialised: {}".format(dt1))

dt2 = json.loads(dt1)
print("This is loaded back from json: {}".format(dt2))

dt3 = eval(dt2)
print("This is the same object as we started: {}".format(dt3))

print("Check if they are equal: {}".format(dt == dt3))

You shouldn't import datetime as

from datetime import datetime

since eval will complain. Or you can pass datetime as a parameter to eval. In any case this should work.

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

You can put a meta refresh Tag in the irc_online.php

<meta http-equiv="refresh" content="30">

OR you can use Javascript with setInterval to refresh the src of the Source...

<script>
window.setInterval("reloadIFrame();", 30000);

function reloadIFrame() {
 document.frames["frameNameHere"].location.reload();
}
</script>

Selecting the last value of a column

LAST() function is not implemented at the moment in order to select the last cell within a range. However, following your example:

=LAST(G2:G9999)

we are able to obtain last cell using the couple of functions INDEX() and COUNT() in this way:

=INDEX(G2:G; COUNT(G2:G))

There is a live example at the spreedsheet where I have found (and solved) the same problem (sheet Orzamentos, cell I5). Note that it works perfectly even refering to other sheets within the document.

Keras, how do I predict after I trained a model?

You must use the same Tokenizer you used to build your model!

Else this will give different vector to each word.

Then, I am using:

phrase = "not good"
tokens = myTokenizer.texts_to_matrix([phrase])

model.predict(np.array(tokens))

Is java.sql.Timestamp timezone specific?

For Mysql, we have a limitation. In the driver Mysql doc, we have :

The following are some known issues and limitations for MySQL Connector/J: When Connector/J retrieves timestamps for a daylight saving time (DST) switch day using the getTimeStamp() method on the result set, some of the returned values might be wrong. The errors can be avoided by using the following connection options when connecting to a database:

useTimezone=true
useLegacyDatetimeCode=false
serverTimezone=UTC

So, when we do not use this parameters and we call setTimestamp or getTimestamp with calendar or without calendar, we have the timestamp in the jvm timezone.

Example :

The jvm timezone is GMT+2. In the database, we have a timestamp : 1461100256 = 19/04/16 21:10:56,000000000 GMT

Properties props = new Properties();
props.setProperty("user", "root");
props.setProperty("password", "");
props.setProperty("useTimezone", "true");
props.setProperty("useLegacyDatetimeCode", "false");
props.setProperty("serverTimezone", "UTC");
Connection con = DriverManager.getConnection(conString, props);
......
Calendar nowGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
Calendar nowGMTPlus4 = Calendar.getInstance(TimeZone.getTimeZone("GMT+4"));
......
rs.getTimestamp("timestampColumn");//Oracle driver convert date to jvm timezone and Mysql convert date to GMT (specified in the parameter)
rs.getTimestamp("timestampColumn", nowGMT);//convert date to GMT 
rs.getTimestamp("timestampColumn", nowGMTPlus4);//convert date to GMT+4 timezone

The first method returns : 1461100256000 = 19/04/2016 - 21:10:56 GMT

The second method returns : 1461100256000 = 19/04/2016 - 21:10:56 GMT

The third method returns : 1461085856000 = 19/04/2016 - 17:10:56 GMT

Instead of Oracle, when we use the same calls, we have :

The first method returns : 1461093056000 = 19/04/2016 - 19:10:56 GMT

The second method returns : 1461100256000 = 19/04/2016 - 21:10:56 GMT

The third method returns : 1461085856000 = 19/04/2016 - 17:10:56 GMT

NB : It is not necessary to specify the parameters for Oracle.

init-param and context-param

Consider the below definition in web.xml

<servlet>
    <servlet-name>HelloWorld</servlet-name>
    <servlet-class>TestServlet</servlet-class>
    <init-param>
        <param-name>myprop</param-name>
        <param-value>value</param-value>
    </init-param>
</servlet>

You can see that init-param is defined inside a servlet element. This means it is only available to the servlet under declaration and not to other parts of the web application. If you want this parameter to be available to other parts of the application say a JSP this needs to be explicitly passed to the JSP. For instance passed as request.setAttribute(). This is highly inefficient and difficult to code.

So if you want to get access to global values from anywhere within the application without explicitly passing those values, you need to use Context Init parameters.

Consider the following definition in web.xml

 <web-app>
      <context-param>
           <param-name>myprop</param-name>
           <param-value>value</param-value>
      </context-param>
 </web-app>

This context param is available to all parts of the web application and it can be retrieved from the Context object. For instance, getServletContext().getInitParameter(“dbname”);

From a JSP you can access the context parameter using the application implicit object. For example, application.getAttribute(“dbname”);

Have a variable in images path in Sass?

Was searching around for an answer to the same question, but think I found a better solution: http://blog.grayghostvisuals.com/compass/image-url/

Basically, you can set your image path in config.rb and you use the image-url() helper

Clear icon inside input text

According to MDN, <input type="search" /> is currently supported in all modern browsers:

input type=search

_x000D_
_x000D_
<input type="search" value="Clear this." />
_x000D_
_x000D_
_x000D_


However, if you want different behavior that is consistent across browsers here are some light-weight alternatives that only require JavaScript:

Option 1 - Always display the 'x': (example here)

_x000D_
_x000D_
Array.prototype.forEach.call(document.querySelectorAll('.clearable-input>[data-clear-input]'), function(el) {
  el.addEventListener('click', function(e) {
    e.target.previousElementSibling.value = '';
  });
});
_x000D_
.clearable-input {
  position: relative;
  display: inline-block;
}
.clearable-input > input {
  padding-right: 1.4em;
}
.clearable-input > [data-clear-input] {
  position: absolute;
  top: 0;
  right: 0;
  font-weight: bold;
  font-size: 1.4em;
  padding: 0 0.2em;
  line-height: 1em;
  cursor: pointer;
}
.clearable-input > input::-ms-clear {
  display: none;
}
_x000D_
<p>Always display the 'x':</p>

<div class="clearable-input">
  <input type="text" />
  <span data-clear-input>&times;</span>
</div>

<div class="clearable-input">
  <input type="text" value="Clear this." />
  <span data-clear-input>&times;</span>
</div>
_x000D_
_x000D_
_x000D_

Option 2 - Only display the 'x' when hovering over the field: (example here)

_x000D_
_x000D_
Array.prototype.forEach.call(document.querySelectorAll('.clearable-input>[data-clear-input]'), function(el) {
  el.addEventListener('click', function(e) {
    e.target.previousElementSibling.value = '';
  });
});
_x000D_
.clearable-input {
  position: relative;
  display: inline-block;
}
.clearable-input > input {
  padding-right: 1.4em;
}
.clearable-input:hover > [data-clear-input] {
  display: block;
}
.clearable-input > [data-clear-input] {
  display: none;
  position: absolute;
  top: 0;
  right: 0;
  font-weight: bold;
  font-size: 1.4em;
  padding: 0 0.2em;
  line-height: 1em;
  cursor: pointer;
}
.clearable-input > input::-ms-clear {
  display: none;
}
_x000D_
<p>Only display the 'x' when hovering over the field:</p>

<div class="clearable-input">
  <input type="text" />
  <span data-clear-input>&times;</span>
</div>

<div class="clearable-input">
  <input type="text" value="Clear this." />
  <span data-clear-input>&times;</span>
</div>
_x000D_
_x000D_
_x000D_

Option 3 - Only display the 'x' if the input element has a value: (example here)

_x000D_
_x000D_
Array.prototype.forEach.call(document.querySelectorAll('.clearable-input'), function(el) {
  var input = el.querySelector('input');

  conditionallyHideClearIcon();
  input.addEventListener('input', conditionallyHideClearIcon);
  el.querySelector('[data-clear-input]').addEventListener('click', function(e) {
    input.value = '';
    conditionallyHideClearIcon();
  });

  function conditionallyHideClearIcon(e) {
    var target = (e && e.target) || input;
    target.nextElementSibling.style.display = target.value ? 'block' : 'none';
  }
});
_x000D_
.clearable-input {
  position: relative;
  display: inline-block;
}
.clearable-input > input {
  padding-right: 1.4em;
}
.clearable-input >[data-clear-input] {
  display: none;
  position: absolute;
  top: 0;
  right: 0;
  font-weight: bold;
  font-size: 1.4em;
  padding: 0 0.2em;
  line-height: 1em;
  cursor: pointer;
}
.clearable-input > input::-ms-clear {
  display: none;
}
_x000D_
<p>Only display the 'x' if the `input` element has a value:</p>

<div class="clearable-input">
  <input type="text" />
  <span data-clear-input>&times;</span>
</div>

<div class="clearable-input">
  <input type="text" value="Clear this." />
  <span data-clear-input>&times;</span>
</div>
_x000D_
_x000D_
_x000D_

Running an Excel macro via Python?

I did some modification to the SMNALLY's code so it can run in Python 3.5.2. This is my result:

#Import the following library to make use of the DispatchEx to run the macro
import win32com.client as wincl

def runMacro():

    if os.path.exists("C:\\Users\\Dev\\Desktop\\Development\\completed_apps\\My_Macr_Generates_Data.xlsm"):

    # DispatchEx is required in the newest versions of Python.
    excel_macro = wincl.DispatchEx("Excel.application")
    excel_path = os.path.expanduser("C:\\Users\\Dev\\Desktop\\Development\\completed_apps\\My_Macr_Generates_Data.xlsm")
    workbook = excel_macro.Workbooks.Open(Filename = excel_path, ReadOnly =1)
    excel_macro.Application.Run\
        ("ThisWorkbook.Template2G")
    #Save the results in case you have generated data
    workbook.Save()
    excel_macro.Application.Quit()  
    del excel_macro

How to make grep only match if the entire line matches?

I'd prefer:

str="ABB.log"; grep -E "^${str}$" a.tmp

cheers

How to Write text file Java

It does work with me. Make sure that you append ".txt" next to timeLog. I used it in a simple program opened with Netbeans and it writes the program in the main folder (where builder and src folders are).

Python socket receive - incoming packets always have a different size

The network is always unpredictable. TCP makes a lot of this random behavior go away for you. One wonderful thing TCP does: it guarantees that the bytes will arrive in the same order. But! It does not guarantee that they will arrive chopped up in the same way. You simply cannot assume that every send() from one end of the connection will result in exactly one recv() on the far end with exactly the same number of bytes.

When you say socket.recv(x), you're saying 'don't return until you've read x bytes from the socket'. This is called "blocking I/O": you will block (wait) until your request has been filled. If every message in your protocol was exactly 1024 bytes, calling socket.recv(1024) would work great. But it sounds like that's not true. If your messages are a fixed number of bytes, just pass that number in to socket.recv() and you're done.

But what if your messages can be of different lengths? The first thing you need to do: stop calling socket.recv() with an explicit number. Changing this:

data = self.request.recv(1024)

to this:

data = self.request.recv()

means recv() will always return whenever it gets new data.

But now you have a new problem: how do you know when the sender has sent you a complete message? The answer is: you don't. You're going to have to make the length of the message an explicit part of your protocol. Here's the best way: prefix every message with a length, either as a fixed-size integer (converted to network byte order using socket.ntohs() or socket.ntohl() please!) or as a string followed by some delimiter (like '123:'). This second approach often less efficient, but it's easier in Python.

Once you've added that to your protocol, you need to change your code to handle recv() returning arbitrary amounts of data at any time. Here's an example of how to do this. I tried writing it as pseudo-code, or with comments to tell you what to do, but it wasn't very clear. So I've written it explicitly using the length prefix as a string of digits terminated by a colon. Here you go:

length = None
buffer = ""
while True:
  data += self.request.recv()
  if not data:
    break
  buffer += data
  while True:
    if length is None:
      if ':' not in buffer:
        break
      # remove the length bytes from the front of buffer
      # leave any remaining bytes in the buffer!
      length_str, ignored, buffer = buffer.partition(':')
      length = int(length_str)

    if len(buffer) < length:
      break
    # split off the full message from the remaining bytes
    # leave any remaining bytes in the buffer!
    message = buffer[:length]
    buffer = buffer[length:]
    length = None
    # PROCESS MESSAGE HERE

How to open a PDF file in an <iframe>?

It also important to make sure that the web server sends the file with Content-Disposition = inline. this might not be the case if you are reading the file yourself and send it's content to the browser:

in php it will look like this...

...headers...
header("Content-Disposition: inline; filename=doc.pdf");
...headers...

readfile('localfilepath.pdf')

Using the grep and cut delimiter command (in bash shell scripting UNIX) - and kind of "reversing" it?

You don't need to change the delimiter to display the right part of the string with cut.

The -f switch of the cut command is the n-TH element separated by your delimiter : :, so you can just type :

 grep puddle2_1557936 | cut -d ":" -f2

Another solutions (adapt it a bit) if you want fun :

Using :

grep -oP 'puddle2_1557936:\K.*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                        
/home/rogers.williams/folderz/puddle2

or still with look around

grep -oP '(?<=puddle2_1557936:).*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                    
/home/rogers.williams/folderz/puddle2

or with :

perl -lne '/puddle2_1557936:(.*)/ and print $1' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                      
/home/rogers.williams/folderz/puddle2

or using (thanks to glenn jackman)

ruby -F: -ane '/puddle2_1557936/ and puts $F[1]' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

awk -F'puddle2_1557936:' '{print $2}'  <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

python -c 'import sys; print(sys.argv[1].split("puddle2_1557936:")[1])' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or using only :

IFS=: read _ a <<< "puddle2_1557936:/home/rogers.williams/folderz/puddle2"
echo "$a"
/home/rogers.williams/folderz/puddle2

or using in a :

js<<EOF
var x = 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
print(x.substr(x.indexOf(":")+1))
EOF
/home/rogers.williams/folderz/puddle2

or using in a :

php -r 'preg_match("/puddle2_1557936:(.*)/", $argv[1], $m); echo "$m[1]\n";' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2' 
/home/rogers.williams/folderz/puddle2

Efficiently checking if arbitrary object is NaN in Python / numpy / pandas?

Is your type really arbitrary? If you know it is just going to be a int float or string you could just do

 if val.dtype == float and np.isnan(val):

assuming it is wrapped in numpy , it will always have a dtype and only float and complex can be NaN

How to get the hostname of the docker host from inside a docker container on that host without env vars

I'm adding this because it's not mentioned in any of the other answers. You can give a container a specific hostname at runtime with the -h directive.

docker run -h=my.docker.container.example.com ubuntu:latest

You can use backticks (or whatever equivalent your shell uses) to get the output of hosthame into the -h argument.

docker run -h=`hostname` ubuntu:latest

There is a caveat, the value of hostname will be taken from the host you run the command from, so if you want the hostname of a virtual machine that's running your docker container then using hostname as an argument may not be correct if you are using the host machine to execute docker commands on the virtual machine.

Allowing Java to use an untrusted certificate for SSL/HTTPS connection

Here is some relevant code:

// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]{
    new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
        public void checkClientTrusted(
            java.security.cert.X509Certificate[] certs, String authType) {
        }
        public void checkServerTrusted(
            java.security.cert.X509Certificate[] certs, String authType) {
        }
    }
};

// Install the all-trusting trust manager
try {
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
}

// Now you can access an https URL without having the certificate in the truststore
try {
    URL url = new URL("https://hostname/index.html");
} catch (MalformedURLException e) {
}

This will completely disable SSL checking—just don't learn exception handling from such code!

To do what you want, you would have to implement a check in your TrustManager that prompts the user.

jquery draggable: how to limit the draggable area?

See excerpt from official documentation for containment option:

containment

Default: false

Constrains dragging to within the bounds of the specified element or region.
Multiple types supported:

  • Selector: The draggable element will be contained to the bounding box of the first element found by the selector. If no element is found, no containment will be set.
  • Element: The draggable element will be contained to the bounding box of this element.
  • String: Possible values: "parent", "document", "window".
  • Array: An array defining a bounding box in the form [ x1, y1, x2, y2 ].

Code examples:
Initialize the draggable with the containment option specified:

$( ".selector" ).draggable({
    containment: "parent" 
}); 

Get or set the containment option, after initialization:

// Getter
var containment = $( ".selector" ).draggable( "option", "containment" );
// Setter
$( ".selector" ).draggable( "option", "containment", "parent" );

Application_Start not firing?

Weird and crazy stuff... but debugging on a server machine and another user left IIS Express running on their session. I had to logoff that user to kill his running IIS Express processes. That seems to have fixed the problem!

Update

After spending more than 1 hour chasing what was causing the problem... here's the deal: I somewhat managed to type an s inside the <appSettings> section in Web.config. Visual Studio tried to warn me in the Error List window with a warning. I confess I rarely check warnings... should start checking it from now on. :D As soon as I removed the offending s the breakpoint got hit in Application_Start.

enter image description here

Split string into array of characters?

You can just assign the string to a byte array (the reverse is also possible). The result is 2 numbers for each character, so Xmas converts to a byte array containing {88,0,109,0,97,0,115,0}
or you can use StrConv

Dim bytes() as Byte
bytes = StrConv("Xmas", vbFromUnicode)

which will give you {88,109,97,115} but in that case you cannot assign the byte array back to a string.
You can convert the numbers in the byte array back to characters using the Chr() function

add a string prefix to each value in a string column using Pandas

You can use pandas.Series.map :

df['col'].map('str{}'.format)

It will apply the word "str" before all your values.

How do I set default value of select box in angularjs

  <select ng-model="selectedCar" ><option ng-repeat="car in cars "  value="{{car.model}}">{{car.model}}</option></select>
<script>var app = angular.module('myApp', []);app.controller('myCtrl', function($scope) { $scope.cars = [{model : "Ford Mustang", color : "red"}, {model : "Fiat 500", color : "white"},{model : "Volvo XC90", color : "black"}];
$scope.selectedCar=$scope.cars[0].model ;});

Why does visual studio 2012 not find my tests?

I ran into the same issue while trying to open the solution on a network share. No unit test would be detected by Test Explorer in this case. The solution turns out to be:

Control Panel -> Internet Options -> "Security" Tab -> Click "Intranet" and add the server IP address or host name holding the network share to the "Sites" list.

After doing this, I recompiled the solution and now tests appeared. This should be quite similar to the answer made by @BigT.

Query to check index on a table

First you check your table id (aka object_id)

SELECT * FROM sys.objects WHERE type = 'U' ORDER BY name

then you can get the column's names. For example assuming you obtained from previous query the number 4 as object_id

SELECT c.name
FROM sys.index_columns ic
INNER JOIN sys.columns c ON  c.column_id = ic.column_id
WHERE ic.object_id = 4 
AND c.object_id = 4

jquery function val() is not equivalent to "$(this).value="?

You want:

this.value = ''; // straight JS, no jQuery

or

$(this).val(''); // jQuery

With $(this).value = '' you're assigning an empty string as the value property of the jQuery object that wraps this -- not the value of this itself.

How do I set the path to a DLL file in Visual Studio?

Go through project properties -> Reference Paths

Then add folder with DLL's

How to replace deprecated android.support.v4.app.ActionBarDrawerToggle

Insted of

drawer.setDrawerListener(toggle);

You can use

drawer.addDrawerListener(toggle);

Get current date/time in seconds

You can met another way to get time in seconds/milliseconds since 1 Jan 1970:

var milliseconds = +new Date;        
var seconds = milliseconds / 1000;

But be careful with such approach, cause it might be tricky to read and understand it.

Use string in switch case in java

We can apply Switch just on data type compatible int :short,Shor,byte,Byte,int,Integer,char,Character or enum type.

How get permission for camera in android.(Specifically Marshmallow)

This works for me, the source is here

int MY_PERMISSIONS_REQUEST_CAMERA=0;
// Here, this is the current activity
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
{
     if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA))
     {

     }
     else
     {
          ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST_CAMERA );
          // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
          // app-defined int constant. The callback method gets the
          // result of the request.
      }
}

Easiest way to flip a boolean value?

For integers with values of 0 and 1 you can try:

value = abs(value - 1);

MWE in C:

#include <stdio.h>
#include <stdlib.h>
int main()
{
        printf("Hello, World!\n");
        int value = 0;
        int i;
        for (i=0; i<10; i++)
        {
                value = abs(value -1);
                printf("%d\n", value);
        }
        return 0;
}

"E: Unable to locate package python-pip" on Ubuntu 18.04

Try the following commands in terminal, this will work better:

apt-get install curl

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

python get-pip.py

Send Outlook Email Via Python?

For a solution that uses outlook see TheoretiCAL's answer below.

Otherwise, use the smtplib that comes with python. Note that this will require your email account allows smtp, which is not necessarily enabled by default.

SERVER = "smtp.example.com"
FROM = "[email protected]"
TO = ["listOfEmails"] # must be a list

SUBJECT = "Subject"
TEXT = "Your Text"

# Prepare actual message
message = """From: %s\r\nTo: %s\r\nSubject: %s\r\n\

%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)

# Send the mail
import smtplib
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()

EDIT: this example uses reserved domains like described in RFC2606

SERVER = "smtp.example.com"
FROM = "[email protected]"
TO = ["[email protected]"] # must be a list

SUBJECT = "Hello!"
TEXT = "This is a test of emailing through smtp of example.com."

# Prepare actual message
message = """From: %s\r\nTo: %s\r\nSubject: %s\r\n\

%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)

# Send the mail
import smtplib
server = smtplib.SMTP(SERVER)
server.login("MrDoe", "PASSWORD")
server.sendmail(FROM, TO, message)
server.quit()

For it to actually work with gmail, Mr. Doe will need to go to the options tab in gmail and set it to allow smtp connections.

Note the addition of the login line to authenticate to the remote server. The original version does not include this, an oversight on my part.

Plot multiple boxplot in one graph

ggplot version of the lattice plot:

library(reshape2)
library(ggplot2)
df <- read.csv("TestData.csv", header=T)
df.m <- melt(df, id.var = "Label")

ggplot(data = df.m, aes(x=Label, y=value)) + 
         geom_boxplot() + facet_wrap(~variable,ncol = 4)

Plot: enter image description here

How to set image in circle in swift

// code to make the image round


import UIKit

extension UIImageView {
public func maskCircle(anyImage: UIImage) {


    self.contentMode = UIViewContentMode.ScaleAspectFill
    self.layer.cornerRadius = self.frame.height / 2
    self.layer.masksToBounds = false
    self.clipsToBounds = true




    // make square(* must to make circle),
    // resize(reduce the kilobyte) and
    // fix rotation.
    //        self.image = prepareImage(anyImage)
}
}

// to call the function from the view controller

self.imgCircleSmallImage.maskCircle(imgCircleSmallImage.image!)

Setting button text via javascript

Create a text node and append it to the button element:

var t = document.createTextNode("test content");
b.appendChild(t);

Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6

I'm using Kotlin and Gradle for normal JVM development, (not android) and this worked for me in build.gradle:

allprojects {
    tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach {
        kotlinOptions.jvmTarget = JavaVersion.VERSION_11.toString()
    }
}

http://localhost:50070 does not work HADOOP

Enable the port in your system it is for CentOS 7 flow the commands below

1.firewall-cmd --get-active-zones

2.firewall-cmd --zone=dmz --add-port=50070/tcp --permanent

3.firewall-cmd --zone=public --add-port=50070/tcp --permanent

4.firewall-cmd --zone=dmz --add-port=9000/tcp --permanent

5.firewall-cmd --zone=public --add-port=9000/tcp --permanent 6.firewall-cmd --reload

How can I get the intersection, union, and subset of arrays in Ruby?

If Multiset extends from the Array class

x = [1, 1, 2, 4, 7]
y = [1, 2, 2, 2]
z = [1, 1, 3, 7]

UNION

x.union(y)           # => [1, 2, 4, 7]      (ONLY IN RUBY 2.6)
x.union(y, z)        # => [1, 2, 4, 7, 3]   (ONLY IN RUBY 2.6)
x | y                # => [1, 2, 4, 7]

DIFFERENCE

x.difference(y)      # => [4, 7] (ONLY IN RUBY 2.6)
x.difference(y, z)   # => [4] (ONLY IN RUBY 2.6)
x - y                # => [4, 7]

INTERSECTION

x & y                # => [1, 2]

For more info about the new methods in Ruby 2.6, you can check this blog post about its new features

How do you get a list of the names of all files present in a directory in Node.js?

Use npm list-contents module. It reads the contents and sub-contents of the given directory and returns the list of files' and folders' paths.

const list = require('list-contents');

list("./dist",(o)=>{
  if(o.error) throw o.error;
   console.log('Folders: ', o.dirs);
   console.log('Files: ', o.files);
});

Any way to write a Windows .bat file to kill processes?

You can do this with 'taskkill'. With the /IM parameter, you can specify image names.

Example:

taskkill /im somecorporateprocess.exe

You can also do this to 'force' kill:

Example:

taskkill /f /im somecorporateprocess.exe

Just add one line per process you want to kill, save it as a .bat file, and add in your startup directory. Problem solved!

If this is a legacy system, PsKill will do the same.

How do I fix the npm UNMET PEER DEPENDENCY warning?

you can resolve by installing the UNMET dependencies globally.

example : npm install -g @angular/[email protected]

install each one by one. its worked for me.

How to get the concrete class name as a string?

 instance.__class__.__name__

example:

>>> class A():
    pass
>>> a = A()
>>> a.__class__.__name__
'A'

Selecting one row from MySQL using mysql_* API

Functions mysql_ are not supported any longer and have been removed in PHP 7. You must use mysqli_ instead. However it's not recommended method now. You should consider PDO with better security solutions.

$result = mysqli_query($con, "SELECT option_value FROM wp_10_options WHERE option_name='homepage' LIMIT 1");
$row = mysqli_fetch_assoc($result);
echo $row['option_value'];

How to reset a timer in C#?

You can do timer.Interval = timer.Interval

awk without printing newline

awk '{sum+=$3}; END {printf "%f",sum/NR}' ${file}_${f}_v1.xls >> to-plot-p.xls

print will insert a newline by default. You dont want that to happen, hence use printf instead.

How to use custom font in a project written in Android Studio

There are many ways to set custom font family on field and I am using like that below.

To add fonts as resources, perform the following steps in the Android Studio:

1) Right-click the res folder and go to New > Android resource directory. The New Resource Directory window appears.

2) In the Resource type list, select font, and then click OK.

Note: The name of the resource directory must be font.

3) Add your font files in the font folder. enter image description here

Add font in desired view in your xml file:

enter image description here

Note: But you required the following things for that:

  1. Android Studio above to 3.0 canary.

  2. Your Activity extends AppCompatActivity.

  3. Update your Gradle file like that:

    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    defaultConfig {        
        minSdkVersion 19
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }

buildtoolsVersion above to 26 and minimum targetSdkVersion required 26

  1. Add dependencies in build.gradle file:
classpath 'com.android.tools.build:gradle:3.0.0-beta4'
  1. gradle-wrapper.properties:
distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip

How to easily import multiple sql files into a MySQL database?

in windows open windows powershell and go to the folder where sql files are then run this command

cat *.sql |  C:\xampp\mysql\bin\mysql.exe -u username -p databasename

Querying Windows Active Directory server using ldapsearch from command line

The short answer is "yes". A sample ldapsearch command to query an Active Directory server is:

ldapsearch \
    -x -h ldapserver.mydomain.com \
    -D "[email protected]" \
    -W \
    -b "cn=users,dc=mydomain,dc=com" \
    -s sub "(cn=*)" cn mail sn

This would connect to an AD server at hostname ldapserver.mydomain.com as user [email protected], prompt for the password on the command line and show name and email details for users in the cn=users,dc=mydomain,dc=com subtree.

See Managing LDAP from the Command Line on Linux for more samples. See LDAP Query Basics for Microsoft Exchange documentation for samples using LDAP queries with Active Directory.

Refresh Fragment at reload

I think you want to refresh the fragment contents upon db update

If so, detach the fragment and reattach it

// Reload current fragment
Fragment frg = null;
frg = getSupportFragmentManager().findFragmentByTag("Your_Fragment_TAG");
final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.detach(frg);
ft.attach(frg);
ft.commit();

Your_Fragment_TAG is the name you gave your fragment when you created it

This code is for support library.

If you're not supporting older devices, just use getFragmentManager instead of getSupportFragmentManager

[EDIT]

This method requires the Fragment to have a tag.
In case you don't have it, then @Hammer's method is what you need.

Curl: Fix CURL (51) SSL error: no alternative certificate subject name matches

As the error code says, "no alternative certificate subject name matches target host name" - so there is an issue with the SSL certificate.

The certificate should include SAN, and only SAN will be used. Some browsers ignore the deprecated Common Name.

RFC 2818 clearly states "If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead."

Assertion failure in dequeueReusableCellWithIdentifier:forIndexPath:

This might seem stupid to some people but it got me. I was getting this error and the problem for me was that I was trying to use static cells but then dynamically add more stuff. If you are calling this method your cells need to be dynamic prototypes. Select the cell in storyboard and under the Attributes inspector, the very first thing says 'Content' and you should select dynamic prototypes not static.

Adding an onclick event to a table row

Simple way is generating code as bellow:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
_x000D_
<style>_x000D_
  table, td {_x000D_
      border:1px solid black;_x000D_
  }_x000D_
</style>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<p>Click on each tr element to alert its index position in the table:</p>_x000D_
<table>_x000D_
  <tr onclick="myFunction(this)">_x000D_
    <td>Click to show rowIndex</td>_x000D_
  </tr>_x000D_
  <tr onclick="myFunction(this)">_x000D_
    <td>Click to show rowIndex</td>_x000D_
  </tr>_x000D_
  <tr onclick="myFunction(this)">_x000D_
    <td>Click to show rowIndex</td>_x000D_
  </tr>_x000D_
</table>_x000D_
_x000D_
<script>_x000D_
  function myFunction(x) {_x000D_
      alert("Row index is: " + x.rowIndex);_x000D_
  }_x000D_
</script>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How can I give access to a private GitHub repository?

Your team members must be accessing the repository using SSH & for that they have to have their ssh key mapped with github account. This will work if they map their ssh key with github account and also the repository has public rights, which they want to access.

Java generics: multiple generic parameters?

You can follow one of the below approaches:

1) Basic, single type :

//One type
public static <T> void fill(List <T> list, T val) {

    for(int i=0; i<list.size(); i++){
        list.set(i, val);
    }

}

2) Multiple Types :

// multiple types as parameters
public static <T1, T2> String multipleTypeArgument(T1 val1, T2 val2) {

    return val1+" "+val2;

}

3) Below will raise compiler error as 'T3 is not in the listing of generic types that are used in function declaration part.

//Raised compilation error
public static <T1, T2> T3 returnTypeGeneric(T1 val1, T2 val2) {
    return 0;
}

Correct : Compiles fine

public static <T1, T2, T3> T3 returnTypeGeneric(T1 val1, T2 val2) {
    return 0;
}

Sample Class Code :

package generics.basics;

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

public class GenericMethods {

/*
 Declare the generic type parameter T in this method. 

 After the qualifiers public and static, you put <T> and 
 then followed it by return type, method name, and its parameters.

 Observe : type of val is 'T' and not '<T>'

 * */
//One type
public static <T> void fill(List <T> list, T val) {

    for(int i=0; i<list.size(); i++){
        list.set(i, val);
    }

}

// multiple types as parameters
public static <T1, T2> String multipleTypeArgument(T1 val1, T2 val2) {

    return val1+" "+val2;

}

/*// Q: To audience -> will this compile ? 
 * 
 * public static <T1, T2> T3 returnTypeGeneric(T1 val1, T2 val2) {

    return 0;

}*/

 public static <T1, T2, T3> T3 returnTypeGeneric(T1 val1, T2 val2) {

    return null;

}

public static void main(String[] args) {
    List<Integer> list = new ArrayList<>();
    list.add(10);
    list.add(20);
    System.out.println(list.toString());
    fill(list, 100);
    System.out.println(list.toString());

    List<String> Strlist = new ArrayList<>();
    Strlist.add("Chirag");
    Strlist.add("Nayak");
    System.out.println(Strlist.toString());
    fill(Strlist, "GOOD BOY");
    System.out.println(Strlist.toString());


    System.out.println(multipleTypeArgument("Chirag", 100));
    System.out.println(multipleTypeArgument(100,"Nayak"));

}

}

// class definition ends

Sample Output:

[10, 20]
[100, 100]
[Chirag, Nayak]
[GOOD BOY, GOOD BOY]
Chirag 100
100 Nayak

error CS0234: The type or namespace name 'Script' does not exist in the namespace 'System.Web'

I had the same. Script been underlined. I added a reference to System.Web.Extensions. Thereafter the Script was no longer underlined. Hope this helps someone.

Fit cell width to content

There are many ways to do this!

correct me if I'm wrong but the question is looking for this kind of result.

<table style="white-space:nowrap;width:100%;">
<tr>
<td class="block" style="width:50%">this should stretch</td>
<td class="block" style="width:50%">this should stretch</td>
<td class="block" style="width:auto">this should be the content width</td>
</tr>
</table>

The first 2 fields will "share" the remaining page (NOTE: if you add more text to either 50% fields it will take more space), and the last field will dominate the table constantly.

If you are happy to let text wrap you can move white-space:nowrap; to the style of the 3rd field
will be the only way to start a new line in that field.

alternatively, you can set a length on the last field ie. width:150px, and leave percentage's on the first 2 fields.

Hope this helps!

Annotation @Transactional. How to rollback?

or programatically

TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

How to delete/remove nodes on Firebase

To remove a record.

 var db = firebase.database();                   
 var ref = db.ref(); 
 var survey=db.ref(path+'/'+path);    //Eg path is company/employee                
 survey.child(key).remove();          //Eg key is employee id

Why does javascript replace only first instance when using replace?

You can use:

String.prototype.replaceAll = function(search, replace) {
if (replace === undefined) {
    return this.toString();
}
return this.split(search).join(replace);
}

Width of input type=text element

input width is 10 + 2 times 1 px for border

Class has been compiled by a more recent version of the Java Environment

This is just a version mismatch. You have compiled your code using java version 9 and your current JRE is version 8. Try upgrading your JRE to 9.

49 = Java 5
50 = Java 6
51 = Java 7
52 = Java 8
53 = Java 9
54 = Java 10
55 = Java 11
56 = Java 12
57 = Java 13
58 = Java 14

How does one create an InputStream from a String?

Instead of CharSet.forName, using com.google.common.base.Charsets from Google's Guava (http://code.google.com/p/guava-libraries/wiki/StringsExplained#Charsets) is is slightly nicer:

InputStream is = new ByteArrayInputStream( myString.getBytes(Charsets.UTF_8) );

Which CharSet you use depends entirely on what you're going to do with the InputStream, of course.

List vs tuple, when to use each?

Tuples are fixed size in nature whereas lists are dynamic.
In other words, a tuple is immutable whereas a list is mutable.

  1. You can't add elements to a tuple. Tuples have no append or extend method.
  2. You can't remove elements from a tuple. Tuples have no remove or pop method.
  3. You can find elements in a tuple, since this doesn’t change the tuple.
  4. You can also use the in operator to check if an element exists in the tuple.

  • Tuples are faster than lists. If you're defining a constant set of values and all you're ever going to do with it is iterate through it, use a tuple instead of a list.

  • It makes your code safer if you “write-protect” data that does not need to be changed. Using a tuple instead of a list is like having an implied assert statement that this data is constant, and that special thought (and a specific function) is required to override that.

  • Some tuples can be used as dictionary keys (specifically, tuples that contain immutable values like strings, numbers, and other tuples). Lists can never be used as dictionary keys, because lists are not immutable.

Source: Dive into Python 3

How to get first 5 characters from string

Use substr():

$result = substr($myStr, 0, 5);

Nested JSON objects - do I have to use arrays for everything?

You have too many redundant nested arrays inside your jSON data, but it is possible to retrieve the information. Though like others have said you might want to clean it up.

use each() wrap within another each() until the last array.

for result.data[0].stuff[0].onetype[0] in jQuery you could do the following:

`

$.each(data.result.data, function(index0, v) {
    $.each(v, function (index1, w) {
        $.each(w, function (index2, x) {
            alert(x.id);
        });
    });

});

`

Get the element triggering an onclick event in jquery?

It's top google stackoverflow question, but all answers are not jQuery related!

$(".someclass").click(
    function(event)
    {
        console.log(event, this);
    }
);

'event' contains 2 important values:

event.currentTarget - element to which event is triggered ('.someclass' element)

event.target - element clicked (in case when inside '.someclass' [div] are other elements and you clicked on of them)

this - is set to triggered element ('.someclass'), but it's JavaScript element, not jQuery element, so if you want to use some jQuery function on it, you must first change it to jQuery element: $(this)

When your refresh the page and reload the scripts again; this method not work. You have to use jquery "unbind" method.

Is there a library function for Root mean square error (RMSE) in python?

from sklearn import metrics              
import numpy as np
print(np.sqrt(metrics.mean_squared_error(y_test,y_predict)))

Javascript Print iframe contents only

At this time, there is no need for the script tag inside the iframe. This works for me (tested in Chrome, Firefox, IE11 and node-webkit 0.12):

<script>
window.onload = function() {
    var body = 'dddddd';
    var newWin = document.getElementById('printf').contentWindow;
    newWin.document.write(body);
    newWin.document.close(); //important!
    newWin.focus(); //IE fix
    newWin.print();
}
</script>

<iframe id="printf"></iframe>

Thanks to all answers, save my day.

POST data to a URL in PHP

cURL-less you can use in php5

$url = 'URL';
$data = array('field1' => 'value', 'field2' => 'value');
$options = array(
        'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data),
    )
);

$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);
var_dump($result);

Python: "Indentation Error: unindent does not match any outer indentation level"

It's possible that you have mixed tabs and spaces in your file. You can have python help check for such errors with

python -m tabnanny <name of python file>

How to bundle an Angular app for production

Angular 2 with Webpack (without CLI setup)

1- The tutorial by the Angular2 team

The Angular2 team published a tutorial for using Webpack

I created and placed the files from the tutorial in a small GitHub seed project. So you can quickly try the workflow.

Instructions:

  • npm install

  • npm start. For development. This will create a virtual "dist" folder that will be livereloaded at your localhost address.

  • npm run build. For production. "This will create a physical "dist" folder version than can be sent to a webserver. The dist folder is 7.8MB but only 234KB is actually required to load the page in a web browser.

2 - A Webkit starter kit

This Webpack Starter Kit offers some more testing features than the above tutorial and seem quite popular.

Why does ENOENT mean "No such file or directory"?

It's an abbreviation of Error NO ENTry (or Error NO ENTity), and can actually be used for more than files/directories.

It's abbreviated because C compilers at the dawn of time didn't support more than 8 characters in symbols.

Maximum Length of Command Line String

As @Sugrue I'm also digging out an old thread.

To explain why there is 32768 (I think it should be 32767, but lets believe experimental testing result) characters limitation we need to dig into Windows API.

No matter how you launch program with command line arguments it goes to ShellExecute, CreateProcess or any extended their version. These APIs basically wrap other NT level API that are not officially documented. As far as I know these calls wrap NtCreateProcess, which requires OBJECT_ATTRIBUTES structure as a parameter, to create that structure InitializeObjectAttributes is used. In this place we see UNICODE_STRING. So now lets take a look into this structure:

typedef struct _UNICODE_STRING {
    USHORT Length;
    USHORT MaximumLength;
    PWSTR  Buffer;
} UNICODE_STRING;

It uses USHORT (16-bit length [0; 65535]) variable to store length. And according this, length indicates size in bytes, not characters. So we have: 65535 / 2 = 32767 (because WCHAR is 2 bytes long).

There are a few steps to dig into this number, but I hope it is clear.


Also, to support @sunetos answer what is accepted. 8191 is a maximum number allowed to be entered into cmd.exe, if you exceed this limit, The input line is too long. error is generated. So, answer is correct despite the fact that cmd.exe is not the only way to pass arguments for new process.

How do I change Bootstrap 3's glyphicons to white?

You can just create your own .white class and add it to the glyphicon element.

.white, .white a {
  color: #fff;
}
<i class="glyphicon glyphicon-home white"></i>

How can I detect if this dictionary key exists in C#?

I use a Dictionary and because of the repetetiveness and possible missing keys, I quickly patched together a small method:

 private static string GetKey(IReadOnlyDictionary<string, string> dictValues, string keyValue)
 {
     return dictValues.ContainsKey(keyValue) ? dictValues[keyValue] : "";
 }

Calling it:

var entry = GetKey(dictList,"KeyValue1");

Gets the job done.

Pandas sum by groupby, but exclude certain columns

If you are looking for a more generalized way to apply to many columns, what you can do is to build a list of column names and pass it as the index of the grouped dataframe. In your case, for example:

columns = ['Y'+str(i) for year in range(1967, 2011)]

df.groupby('Country')[columns].agg('sum')

How to create an empty R vector to add new items

In rpy2, the way to get the very same operator as "[" with R is to use ".rx". See the documentation about extracting with rpy2

For creating vectors, if you know your way around with Python there should not be any issue. See the documentation about creating vectors

Format in kotlin string templates

Kotlin's String class has a format function now, which internally uses Java's String.format method:

/**
 * Uses this string as a format string and returns a string obtained by substituting the specified arguments,
 * using the default locale.
 */
@kotlin.internal.InlineOnly
public inline fun String.Companion.format(format: String, vararg args: Any?): String = java.lang.String.format(format, *args)

Usage

val pi = 3.14159265358979323
val formatted = String.format("%.2f", pi) ;
println(formatted)
>>3.14

Python Request Post with param data

Assign the response to a value and test the attributes of it. These should tell you something useful.

response = requests.post(url,params=data,headers=headers)
response.status_code
response.text
  • status_code should just reconfirm the code you were given before, of course

Center text output from Graphics.DrawString()

To draw a centered text:

TextRenderer.DrawText(g, "my text", Font, Bounds, ForeColor, BackColor, 
  TextFormatFlags.HorizontalCenter | 
  TextFormatFlags.VerticalCenter |
  TextFormatFlags.GlyphOverhangPadding);

Determining optimal font size to fill an area is a bit more difficult. One working soultion I found is trial-and-error: start with a big font, then repeatedly measure the string and shrink the font until it fits.

Font FindBestFitFont(Graphics g, String text, Font font, 
  Size proposedSize, TextFormatFlags flags)
{ 
  // Compute actual size, shrink if needed
  while (true)
  {
    Size size = TextRenderer.MeasureText(g, text, font, proposedSize, flags);

    // It fits, back out
    if ( size.Height <= proposedSize.Height && 
         size.Width <= proposedSize.Width) { return font; }

    // Try a smaller font (90% of old size)
    Font oldFont = font;
    font = new Font(font.FontFamily, (float)(font.Size * .9)); 
    oldFont.Dispose();
  }
}

You'd use this as:

Font bestFitFont = FindBestFitFont(g, text, someBigFont, sizeToFitIn, flags);
// Then do your drawing using the bestFitFont
// Don't forget to dispose the font (if/when needed)

How does delete[] know it's an array?

delete or delete[] would probably both free the memory allocated (memory pointed), but the big difference is that delete on an array won't call the destructor of each element of the array.

Anyway, mixing new/new[] and delete/delete[] is probably UB.

Maven 3 warnings about build.plugins.plugin.version

I'm using a parent pom for my projects and wanted to specify the versions in one place, so I used properties to specify the version:

parent pom:

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
         http://maven.apache.org/xsd/maven-4.0.0.xsd">
    ....
    <properties>
        <maven-compiler-plugin-version>2.3.2</maven-compiler-plugin-version>
    </properties>
    ....
</project>

project pom:

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
         http://maven.apache.org/xsd/maven-4.0.0.xsd">
    ....
    <build>
        <finalName>helloworld</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven-compiler-plugin-version}</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

See also: https://www.allthingsdigital.nl/2011/04/10/maven-3-and-the-versions-dilemma/

What is a good regular expression to match a URL?

(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})

Will match the following cases

  • http://www.foufos.gr
  • https://www.foufos.gr
  • http://foufos.gr
  • http://www.foufos.gr/kino
  • http://werer.gr
  • www.foufos.gr
  • www.mp3.com
  • www.t.co
  • http://t.co
  • http://www.t.co
  • https://www.t.co
  • www.aa.com
  • http://aa.com
  • http://www.aa.com
  • https://www.aa.com

Will NOT match the following

  • www.foufos
  • www.foufos-.gr
  • www.-foufos.gr
  • foufos.gr
  • http://www.foufos
  • http://foufos
  • www.mp3#.com

_x000D_
_x000D_
var expression = /(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})/gi;_x000D_
var regex = new RegExp(expression);_x000D_
_x000D_
var check = [_x000D_
  'http://www.foufos.gr',_x000D_
  'https://www.foufos.gr',_x000D_
  'http://foufos.gr',_x000D_
  'http://www.foufos.gr/kino',_x000D_
  'http://werer.gr',_x000D_
  'www.foufos.gr',_x000D_
  'www.mp3.com',_x000D_
  'www.t.co',_x000D_
  'http://t.co',_x000D_
  'http://www.t.co',_x000D_
  'https://www.t.co',_x000D_
  'www.aa.com',_x000D_
  'http://aa.com',_x000D_
  'http://www.aa.com',_x000D_
  'https://www.aa.com',_x000D_
  'www.foufos',_x000D_
  'www.foufos-.gr',_x000D_
  'www.-foufos.gr',_x000D_
  'foufos.gr',_x000D_
  'http://www.foufos',_x000D_
  'http://foufos',_x000D_
  'www.mp3#.com'_x000D_
];_x000D_
_x000D_
check.forEach(function(entry) {_x000D_
  if (entry.match(regex)) {_x000D_
    $("#output").append( "<div >Success: " + entry + "</div>" );_x000D_
  } else {_x000D_
    $("#output").append( "<div>Fail: " + entry + "</div>" );_x000D_
  }_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="output"></div>
_x000D_
_x000D_
_x000D_

Check it in rubular - NEW version

Check it in rubular - old version

Need to ZIP an entire directory using Node.js

To pipe the result to the response object (scenarios where there is a need to download the zip rather than store locally)

 archive.pipe(res);

Sam's hints for accessing the content of the directory worked for me.

src: ["**/*"]

How to select all instances of selected region in Sublime Text

On Mac:

?+CTRL+g

However, you can reset any key any way you'd like using "Customize your Sublime Text 2 configuration for awesome coding." for Mac.


On Windows/Linux:

Alt+F3

If anyone has how-tos or articles on this, I'd be more than happy to update.

C free(): invalid pointer

From where did you get the idea that you need to free(token) and free(tk)? You don't. strsep() doesn't allocate memory, it only returns pointers inside the original string. Of course, those are not pointers allocated by malloc() (or similar), so free()ing them is undefined behavior. You only need to free(s) when you are done with the entire string.

Also note that you don't need dynamic memory allocation at all in your example. You can avoid strdup() and free() altogether by simply writing char *s = p;.

Remove characters except digits from string using Python?

s=''.join(i for i in s if i.isdigit())

Another generator variant.

How do I get the resource id of an image if I know its name?

One other scenario which I encountered.

String imageName ="Hello" and then when it is passed into getIdentifier function as first argument, it will pass the name with string null termination and will always return zero. Pass this imageName.substring(0, imageName.length()-1)

Getting cursor position in Python

Use pygame

import pygame

mouse_pos = pygame.mouse.get_pos()

This returns the x and y position of the mouse.

See this website: https://www.pygame.org/docs/ref/mouse.html#pygame.mouse.set_pos

Why Python 3.6.1 throws AttributeError: module 'enum' has no attribute 'IntFlag'?

Installing version 1.1.8 of enum34 worked for me.

I was able to fix this by adding enum34 = "==1.1.8" to pyproject.toml. Apparently enum34 had a feature in v1.1.8 that avoided this error, but this regressed in v1.1.9+. This is just a workaround though. The better solution would be for packages to use environment markers so you don't have to install enum34 at all unless needed.

Source: https://github.com/python-poetry/poetry/issues/1122

ES6 Class Multiple inheritance

My answer seems like less code and it works for me:

_x000D_
_x000D_
    class Nose {
      constructor() {
        this.booger = 'ready'; 
      }
      
      pick() {
        console.log('pick your nose')
      } 
    }
    
    class Ear {
      constructor() {
        this.wax = 'ready'; 
      }
      
      dig() {
        console.log('dig in your ear')
      } 
    }
    
    class Gross extends Classes([Nose,Ear]) {
      constructor() {
        super();
        this.gross = true;
      }
    }
    
    function Classes(bases) {
      class Bases {
        constructor() {
          bases.forEach(base => Object.assign(this, new base()));
        }
      }
      bases.forEach(base => {
        Object.getOwnPropertyNames(base.prototype)
        .filter(prop => prop != 'constructor')
        .forEach(prop => Bases.prototype[prop] = base.prototype[prop])
      })
      return Bases;
    }

    
    // test it
    
    var grossMan = new Gross();
    grossMan.pick(); // eww
    grossMan.dig();  // yuck!
_x000D_
_x000D_
_x000D_

Websocket onerror - how to read error description?

The error Event the onerror handler receives is a simple event not containing such information:

If the user agent was required to fail the WebSocket connection or the WebSocket connection is closed with prejudice, fire a simple event named error at the WebSocket object.

You may have better luck listening for the close event, which is a CloseEvent and indeed has a CloseEvent.code property containing a numerical code according to RFC 6455 11.7 and a CloseEvent.reason string property.

Please note however, that CloseEvent.code (and CloseEvent.reason) are limited in such a way that network probing and other security issues are avoided.