Programs & Examples On #Configuration

Configuration is the process of specifying the settings used for a system or application

Creating a simple configuration file and parser in C++

How about formatting your configuration as JSON, and using a library like jsoncpp?


{"url": "http://mysite dot com",
"file": "main.exe",
"true": 0}

You can then read it into named variables, or even store it all in a std::map, etc. The latter means you can add options without having to change and recompile your configuration parser.

Node.js/Express.js App Only Works on Port 3000

The line you found just looks for the environmental variable PORT, if it's defined it uses it, otherwise uses the default port 3000. You have to define this environmental variable first (no need to be root)

export PORT=8080
node <your-app.js>

sendmail: how to configure sendmail on ubuntu?

Combine two answers above, I finally make it work. Just be careful that the first single quote for each string is a backtick (`) in file

#Change to your mail config directory:
cd /etc/mail

#Make a auth subdirectory
mkdir auth
chmod 700 auth  #maybe not, because I cannot apply cmd "cd auth" if I do so.

#Create a file with your auth information to the smtp server
cd auth
touch client-info

#In the file, put the following, matching up to your smtp server: "U:root" "I:user" "P:password"

#Generate the Authentication database, make both files readable only by root
makemap hash client-info < client-info
chmod 600 client-info
cd ..

#Add the following lines to Make sure you update your smtp server
#The first single quote for each string should be changed to a backtick (`) like this:
FEATURE(`authinfo',`hash /etc/mail/auth/client-info')dnl

sudo sendmailconfig

My eclipse won't open, i download the bundle pack it keeps saying error log

Make sure you have the prerequisite, a JVM ( installed.

This will be a JRE and JDK package.

There are a number of sources which includes:

How to get config parameters in Symfony2 Twig Templates

You can also take advantage of the built-in Service Parameters system, which lets you isolate or reuse the value:

# app/config/parameters.yml
    ga_tracking: UA-xxxxx-x

# app/config/config.yml
        ga_tracking: "%ga_tracking%"

Now, the variable ga_tracking is available in all Twig templates:

<p>The google tracking code is: {{ ga_tracking }}</p>

The parameter is also available inside the controllers:


You can also define a service as a global Twig variable (Symfony2.2+):

# app/config/config.yml
    # ...
        user_management: "@acme_user.user_management"

If the global variable you want to set is more complicated - say an object - then you won't be able to use the above method. Instead, you'll need to create a Twig Extension and return the global variable as one of the entries in the getGlobals method.

tmux status bar configuration

Do C-b, :show which will show you all your current settings. /green, nnn will find you which properties have been set to green, the default. Do C-b, :set window-status-bg cyan and the bottom bar should change colour.

List available colours for tmux

You can tell more easily by the titles and the colours as they're actually set in your live session :show, than by searching through the man page, in my opinion. It is a very well-written man page when you have the time though.

If you don't like one of your changes and you can't remember how it was originally set, you can open do a new tmux session. To change settings for good edit ~/.tmux.conf with a line like set window-status-bg -g cyan. Here's mine:

Getting Spring Application Context

There are many way to get application context in Spring application. Those are given bellow:

  1. Via ApplicationContextAware:

    import org.springframework.beans.BeansException;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ApplicationContextAware;
    public class AppContextProvider implements ApplicationContextAware {
    private ApplicationContext applicationContext;
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;

Here setApplicationContext(ApplicationContext applicationContext) method you will get the applicationContext


Interface to be implemented by any object that wishes to be notified of the ApplicationContext that it runs in. Implementing this interface makes sense for example when an object requires access to a set of collaborating beans.

  1. Via Autowired:

    private ApplicationContext applicationContext;

Here @Autowired keyword will provide the applicationContext. Autowired has some problem. It will create problem during unit-testing.

Unix command-line JSON parser?

For Bash/Python, here is a basic wrapper around python's simplejson:

json_parser() {
    local jsonfile="my_json_file.json"
    local tc="import simplejson,sys;; "`
    # Build python print command based on $@
    local printcmd="print myjson"
    for (( argn=1; argn<=$#; argn++ )); do
    local result=$(python -c "$tc $printcmd.keys()" <$jsonfile 2>/dev/null \
        || python -c "$tc $printcmd" <$jsonfile 2>/dev/null)
    # For returning space-separated values
    echo $result|sed -e "s/[]|[|,|']//g"
    #echo $result 

It really only handles the nested-dictionary style of data, but it works for what I needed, and is useful for walking through the json. It could probably be adapted to taste.

Anyway, something homegrown for those not wanting to source in yet another external dependency. Except for python, of course.

Ex. json_parser {field1} {field2} would run print myjson['{field1}']['{field2}'], yielding either the keys or the values associated with {field2}, space-separated.

Hadoop cluster setup - Connection refused

hduser@marta-komputer:/usr/local/hadoop$ jps

11696 ResourceManager

11842 NodeManager

11171 NameNode

11523 SecondaryNameNode

12167 Jps

Where is your DataNode? Connection refused problem might also be due to no active DataNode. Check datanode logs for issues.


For this error:

15/03/01 00:59:34 INFO client.RMProxy: Connecting to ResourceManager at / Call From marta-komputer.home/ to marta-komputer:9000 failed on connection exception: Connection refused; For more details see:

Add these lines in yarn-site.xml:


Restart the hadoop processes.

Splitting applicationContext to multiple files

I find the following setup the easiest.

Use the default config file loading mechanism of DispatcherServlet:

The framework will, on initialization of a DispatcherServlet, look for a file named [servlet-name]-servlet.xml in the WEB-INF directory of your web application and create the beans defined there (overriding the definitions of any beans defined with the same name in the global scope).

In your case, simply create a file intrafest-servlet.xml in the WEB-INF dir and don't need to specify anything specific information in web.xml.

In intrafest-servlet.xml file you can use import to compose your XML configuration.

  <bean id="bean1" class="..."/>
  <bean id="bean2" class="..."/>

  <import resource="foo-services.xml"/>
  <import resource="foo-persistence.xml"/>

Note that the Spring team actually prefers to load multiple config files when creating the (Web)ApplicationContext. If you still want to do it this way, I think you don't need to specify both context parameters (context-param) and servlet initialization parameters (init-param). One of the two will do. You can also use commas to specify multiple config locations.

Difference between using bean id and name in Spring configuration file

Either one would work. It depends on your needs:
If your bean identifier contains special character(s) for example (/viewSummary.html), it wont be allowed as the bean id, because it's not a valid XML ID. In such cases you could skip defining the bean id and supply the bean name instead.
The name attribute also helps in defining aliases for your bean, since it allows specifying multiple identifiers for a given bean.

Query a parameter (postgresql.conf setting) like "max_connections"

You can use SHOW:

SHOW max_connections;

This returns the currently effective setting. Be aware that it can differ from the setting in postgresql.conf as there are a multiple ways to set run-time parameters in PostgreSQL. To reset the "original" setting from postgresql.conf in your current session:

RESET max_connections;

However, not applicable to this particular setting. The manual:

This parameter can only be set at server start.

To see all settings:


There is also pg_settings:

The view pg_settings provides access to run-time parameters of the server. It is essentially an alternative interface to the SHOW and SET commands. It also provides access to some facts about each parameter that are not directly available from SHOW, such as minimum and maximum values.

For your original request:

FROM   pg_settings
WHERE  name = 'max_connections';

Finally, there is current_setting(), which can be nested in DML statements:

SELECT current_setting('max_connections');


How to add a filter class in Spring Boot?

Step 1: Create a filter component by implementing Filter interface.

public class PerformanceFilter implements Filter {

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {



Step 2: Set this filter to the uri patterns using FilterRegistrationBean.

public class FilterConfig {
    public FilterRegistrationBean<PerformanceFilter> perfFilter() {
        FilterRegistrationBean<PerformanceFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new PerformanceFilter());
        return registration;

You can refer this link for complete application.

How to run multiple sites on one apache instance

Your question is mixing a few different concepts. You started out saying you wanted to run sites on the same server using the same domain, but in different folders. That doesn't require any special setup. Once you get the single domain running, you just create folders under that docroot.

Based on the rest of your question, what you really want to do is run various sites on the same server with their own domain names.

The best documentation you'll find on the topic is the virtual host documentation in the apache manual.

There are two types of virtual hosts: name-based and IP-based. Name-based allows you to use a single IP address, while IP-based requires a different IP for each site. Based on your description above, you want to use name-based virtual hosts.

The initial error you were getting was due to the fact that you were using different ports than the NameVirtualHost line. If you really want to have sites served from ports other than 80, you'll need to have a NameVirtualHost entry for each port.

Assuming you're starting from scratch, this is much simpler than it may seem.

If you are using 2.3 or earlier, the first thing you need to do is tell Apache that you're going to use name-based virtual hosts.

NameVirtualHost *:80

If you are using 2.4 or later do not add a NameVirtualHost line. Version 2.4 of Apache deprecated the NameVirtualHost directive, and it will be removed in a future version.

Now your vhost definitions:

<VirtualHost *:80>
    DocumentRoot "/home/user/site1/"
    ServerName site1

<VirtualHost *:80>
    DocumentRoot "/home/user/site2/"
    ServerName site2

You can run as many sites as you want on the same port. The ServerName being different is enough to tell Apache which vhost to use. Also, the ServerName directive is always the domain/hostname and should never include a path.

If you decide to run sites on a port other than 80, you'll always have to include the port number in the URL when accessing the site. So instead of going to you would have to go to

How do I use Notepad++ (or other) with msysgit?

Update 2010-2011:

zumalifeguard's solution (upvoted) is simpler than the original one, as it doesn't need anymore a shell wrapper script.

As I explain in "How can I set up an editor to work with Git on Windows?", I prefer a wrapper, as it is easier to try and switch editors, or change the path of one editor, without having to register said change with a git config again.
But that is just me.

Additional information: the following solution works with Cygwin, while the zuamlifeguard's solution does not.

Original answer.

The following:

C:\prog\git>git config --global core.editor C:/prog/git/

"c:/Program Files/Notepad++/notepad++.exe" -multiInst "$*"

does work. Those commands are interpreted as shell script, hence the idea to wrap any windows set of commands in a sh script.
(As Franky comments: "Remember to save your .sh file with Unix style line endings or receive mysterious error messages!")

More details on the SO question How can I set up an editor to work with Git on Windows?

Note the '-multiInst' option, for ensuring a new instance of notepad++ for each call from Git.

Note also that, if you are using Git on Cygwin (and want to use Notepad++ from Cygwin), then scphantm explains in "using Notepad++ for Git inside Cygwin" that you must be aware that:

git is passing it a cygwin path and npp doesn't know what to do with it

So the script in that case would be:

"C:/Program Files (x86)/Notepad++/notepad++.exe" -multiInst -notabbar -nosession -noPlugin "$(cygpath -w "$*")"

Multiple lines for readability:

"C:/Program Files (x86)/Notepad++/notepad++.exe" -multiInst -notabbar \
  -nosession -noPlugin "$(cygpath -w "$*")"

With "$(cygpath -w "$*")" being the important part here.

Val commented (and then deleted) that you should not use -notabbar option:

It makes no good to disable the tab during rebase, but makes a lot of harm to general Notepad usability since -notab becomes the default setting and you must Settings>Preferences>General>TabBar> Hide>uncheck every time you start notepad after rebase. This is hell. You recommended the hell.

So use rather:

"C:/Program Files (x86)/Notepad++/notepad++.exe" -multiInst -nosession -noPlugin "$(cygpath -w "$*")"

That is:

"C:/Program Files (x86)/Notepad++/notepad++.exe" -multiInst -nosession \
  -noPlugin "$(cygpath -w "$*")"

If you want to place the script '' in a path with spaces (as in 'c:\program files\...',), you have three options:

  • Either try to quote the path (single or double quotes), as in:

    git config --global core.editor 'C:/program files/git/'
  • or try the shortname notation (not fool-proofed):

    git config --global core.editor C:/progra~1/git/
  • or (my favorite) place '' in a directory part of your %PATH% environment variable. You would not have then to specify any path for the script.

    git config --global core.editor
  • Steiny reports in the comments having to do:

    git config --global core.editor '"C:/Program Files (x86)/Git/scripts/"'

Warning about `$HTTP_RAW_POST_DATA` being deprecated

I experienced the same issue on nginx server (DigitalOcean) - all I had to do is to log in as root and modify the file /etc/php5/fpm/php.ini.

To find the line with the always_populate_raw_post_data I first run grep:

grep -n 'always_populate_raw_post_data' php.ini

That returned the line 704

704:;always_populate_raw_post_data = -1

Then simply open php.ini on that line with vi editor:

vi +704 php.ini

Remove the semi colon to uncomment it and save the file :wq

Lastly reboot the server and the error went away.

Add MIME mapping in web.config for IIS Express

I'm not using IIS Express but developing against my Local Full IIS 7.

So if anyone else get's here trying to do that, I had to add the mime type for woff via IIS Manager

Mime Types >> Click Add link on right and then enter Extension: .woff MIME type: application/font-woff

Datanode process not running in Hadoop

Instead of deleting everything under the "hadoop tmp dir", you can set another one. For example, if your core-site.xml has this property:


You can change this to:


and then scp core-site.xml to each node, and then "hadoop namenode -format", and then restart hadoop.

Given URL is not permitted by the application configuration

  1. From the menu item of your app name which is located on the top left corner, create a test app.
  2. In the settings section of the new test app: add 'http://localhost:3000' to the Website url and add 'localhost' to App domains.
  3. Update your app with the new Facebook APP Id
  4. Use Facebook sdk v2.2 or whatever the latest in your app.

How can I show line numbers in Eclipse?

The top answer is good but you can also bind it to a key ( shorcut ) to toggle it..

Window > Preferences > Keys then enter "Line Numbers" in filter and bind it to a key.

I use CTRL + S + L.

How to set the java.library.path from Eclipse

I think there is another reason for wanting to set java.library.path. Subversion comes with many libraries and Eclipse won't see these unless java.library.path can be appended. For example I'm on OS-X, so the libraries are under \opt\subversion\lib. There are a lot of them and I'd like to keep them where they are (not copy them into a standard lib directory).

Project settings won't fix this.

Environment variable to control

It isn't an environment variable, but still gives you control over the temp dir:



Maven Jacoco Configuration - Exclude classes/packages from report not working

Your XML is slightly wrong, you need to add any class exclusions within an excludes parent field, so your above configuration should look like the following as per the Jacoco docs


The values of the exclude fields should be class paths (not package names) of the compiled classes relative to the directory target/classes/ using the standard wildcard syntax

*   Match zero or more characters
**  Match zero or more directories
?   Match a single character

You may also exclude a package and all of its children/subpackages this way:


This will exclude every class in some.package, as well as any children. For example, some.package.child wouldn't be included in the reports either.

I have tested and my report goal reports on a reduced number of classes using the above.

If you are then pushing this report into Sonar, you will then need to tell Sonar to exclude these classes in the display which can be done in the Sonar settings

Settings > General Settings > Exclusions > Code Coverage

Sonar Docs explains it a bit more

Running your command above

mvn clean verify

Will show the classes have been excluded

No exclusions

[INFO] --- jacoco-maven-plugin: (post-test) @ ** ---
[INFO] Analyzed bundle '**' with 37 classes

With exclusions

[INFO] --- jacoco-maven-plugin: (post-test) @ ** ---
[INFO] Analyzed bundle '**' with 34 classes

Hope this helps

Difference between <context:annotation-config> and <context:component-scan>

<context:annotation-config> activates many different annotations in beans, whether they are defined in XML or through component scanning.

<context:component-scan> is for defining beans without using XML

For further information, read:

How do I revert back to an OpenWrt router configuration?

Some addition to previous comments: 'firstboot' won't be available until you run 'mount_root' command.

So here is a full recap of what needs to be done. All manipulations I did on Windows 8.1.

  • Enter Failsafe mode (hold the reset button on boot for a few seconds)
  • Assign a static IP address,, to your PC. Example of a command: netsh interface ip set address name="Ethernet" static
  • Connect to address from telnet (I use PuTTY) and login/password isn't required).
  • Run 'mount_root' (otherwise 'firstboot' won't be available).
  • Run 'firstboot' to reset.
  • Run 'reboot -f' to reboot.

Now you can enter to the router console from a browser. Also don't forget to return your PC from static to DHCP address assignment. Example: netsh interface ip set address name="Ethernet" source=dhcp

Change connection string & reload app.config at run time

IIRC, the ConfigurationManager.RefreshSection requires a string parameter specifying the name of the Section to refresh :


I think that the ASP.NET application should automatically reload when the ConnectionStrings element is modified and the configuration does not need to be manually reloaded.

Multiple commands in an alias for bash

Adding my 2 cents to the 11 year old discussion try this:

alias lock="gnome-screensaver \gnome-screensaver-command --lock"

Setting up Vim for Python

For those arriving around summer 2013, I believe some of this thread is outdated.

I followed this howto which recommends Vundle over Pathogen. After one days use I found installing plugins trivial.

The klen/python-mode plugin deserves special mention. It provides pyflakes and pylint amongst other features.

I have just started using Valloric/YouCompleteMe and I love it. It has C-lang auto-complete and python also works great thanks to jedi integration. It may well replace jedi-vim as per this discussion /davidhalter/jedi-vim/issues/119

Finally browsing the /carlhuda/janus plugins supplied is a good guide to useful scripts you might not know you are looking for such as NerdTree, vim-fugitive, syntastic, powerline, ack.vim, snipmate...

All the above '{}/{}' are found on github you can find them easily with Google.

How to import a module given the full path?

I believe you can use imp.find_module() and imp.load_module() to load the specified module. You'll need to split the module name off of the path, i.e. if you wanted to load /home/mypath/ you'd need to do:

imp.find_module('mymodule', '/home/mypath/')

...but that should get the job done.

Nginx 403 error: directory index of [folder] is forbidden

Here's how I managed to fix it on my Kali machine:

  • Locate to the directory:

    cd /etc/nginx/sites-enabled/

  • Edit the 'default' configuration file:

    sudo nano default

  • Add the following lines in the location block:

    location /yourdirectory {
      autoindex on;
      autoindex_exact_size off;
  • Note that I have activated auto-indexing in a specific directory /yourdirectory only. Otherwise, it will be enabled for all of your folders on your computer and you don't want it.

  • Now restart your server and it should be working now:

    sudo service nginx restart

Spring cannot find bean xml configuration file when it does exist

I was experiencing this issue and it was driving me nuts; I ultimately found the following lying in my POM.xml, which was the cause of the problem:


Debugging Spring configuration

If you use Spring Boot, you can also enable a “debug” mode by starting your application with a --debug flag.

java -jar myapp.jar --debug

You can also specify debug=true in your

When the debug mode is enabled, a selection of core loggers (embedded container, Hibernate, and Spring Boot) are configured to output more information. Enabling the debug mode does not configure your application to log all messages with DEBUG level.

Alternatively, you can enable a “trace” mode by starting your application with a --trace flag (or trace=true in your Doing so enables trace logging for a selection of core loggers (embedded container, Hibernate schema generation, and the whole Spring portfolio).

What should I set JAVA_HOME environment variable on macOS X 10.6?

I tend to use /Library/Java/Home. The way the preferences pane works this should be up to date with your preferred version.

Turning off auto indent when pasting text into vim

When working inside a terminal the vim-bracketed-paste vim plugin will automatically handle pastes without needing any keystrokes before or after the paste.

It works by detecting bracketed paste mode which is an escape sequence sent by "modern" x-term compatible terminals like iTerm2, gnome-terminal, and other terminals using libvte. As an added bonus it works also for tmux sessions. I am using it successfully with iTerm2 on a Mac connecting to a linux server and using tmux.

I can not find my.cnf on my windows computer

you can search this file : resetroot.bat

just double click it so that your root accout will be reset and all the privileges are turned into YES

How to configure Glassfish Server in Eclipse manually

I had the same problem, to resolve it, go windows -> preferences -> servers and select runtime environment, and now you will see a new window, in the upper right you will see a option: Download additional server adapter, click and install the glassfish server.

What's the best practice using a settings file in Python?

Yaml and Json are the simplest and most commonly used file formats to store settings/config. PyYaml can be used to parse yaml. Json is already part of python from 2.5. Yaml is a superset of Json. Json will solve most uses cases except multi line strings where escaping is required. Yaml takes care of these cases too.

>>> import json
>>> config = {'handler' : '', 'timeoutsec' : 5 }
>>> json.dump(config, open('/tmp/config.json', 'w'))
>>> json.load(open('/tmp/config.json'))   
{u'handler': u'', u'timeoutsec': 5}

How to store Configuration file and read it using React

You can use the dotenv package no matter what setup you use. It allows you to create a .env in your project root and specify your keys like so


In your applications entry file your just call dotenv(); before accessing the keys like so


Reload nginx configuration

If your system has systemctl

sudo systemctl reload nginx

If your system supports service (using debian/ubuntu) try this

sudo service nginx reload

If not (using centos/fedora/etc) you can try the init script

sudo /etc/init.d/nginx reload

How to make spring inject value into a static field

I've had a similar requirement: I needed to inject a Spring-managed repository bean into my Person entity class ("entity" as in "something with an identity", for example an JPA entity). A Person instance has friends, and for this Person instance to return its friends, it shall delegate to its repository and query for friends there.

public class Person {
    private static PersonRepository personRepository;

    private long id;

    public static void setPersonRepository(PersonRepository personRepository){
        this.personRepository = personRepository;

    public Set<Person> getFriends(){
        return personRepository.getFriends(id);



public class PersonRepository {

    public Person get Person(long id) {
        // do database-related stuff

    public Set<Person> getFriends(long id) {
        // do database-related stuff


So how did I inject that PersonRepository singleton into the static field of the Person class?

I created a @Configuration, which gets picked up at Spring ApplicationContext construction time. This @Configuration gets injected with all those beans that I need to inject as static fields into other classes. Then with a @PostConstruct annotation, I catch a hook to do all static field injection logic.

public class StaticFieldInjectionConfiguration {

    private PersonRepository personRepository;

    private void init() {

Using ConfigurationManager to load config from an arbitrary location

I provided the configuration values to word hosted .nET Compoent as follows.

A .NET Class Library component being called/hosted in MS Word. To provide configuration values to my component, I created winword.exe.config in C:\Program Files\Microsoft Office\OFFICE11 folder. You should be able to read configurations values like You do in Traditional .NET.

string sMsg = System.Configuration.ConfigurationManager.AppSettings["WSURL"];

Where to install Android SDK on Mac OS X?

In homebrew the android-sdk has migrated from homebrew/core to homebrew/cask.

brew tap homebrew/cask

and install android-sdk using

brew cask install android-sdk

You will have to add the ANDROID_HOME to profile (.zshrc or .bashrc)

export ANDROID_HOME=/usr/local/share/android-sdk

If you prefer otherwise, copy the package to


How can I get the current screen orientation?


Why do I need to configure the SQL dialect of a data source?

Dialect property is used by hibernate in following ways

  1. To generate Optimized SQL queries.
  2. If you have more than one DB then to talk with particular DB you want.
  3. To set default values for hibernate configuration file properties based on the DB software we use even though they are not specifed in configuration file.

How to use ConfigurationManager

Go to tools >> nuget >> console and type:

Install-Package System.Configuration.ConfigurationManager 

If you want a specific version:

Install-Package System.Configuration.ConfigurationManager -Version 4.5.0

Your ConfigurationManager dll will now be imported and the code will begin to work.

correct configuration for nginx to localhost?

Fundamentally you hadn't declare location which is what nginx uses to bind URL with resources.

 server {
            listen       80;
            server_name  localhost;

            access_log  logs/localhost.access.log  main;

            location / {
                root /var/www/board/public;
                index index.html index.htm index.php;

Enable tcp\ip remote connections to sql server express already installed database with code or script(query)

I recommend to use SMO (Enable TCP/IP Network Protocol for SQL Server). However, it was not available in my case.

I rewrote the WMI commands from Krzysztof Kozielczyk to PowerShell.

# Enable TCP/IP

Get-CimInstance -Namespace root/Microsoft/SqlServer/ComputerManagement10 -ClassName ServerNetworkProtocol -Filter "InstanceName = 'SQLEXPRESS' and ProtocolName = 'Tcp'" |
Invoke-CimMethod -Name SetEnable

# Open the right ports in the firewall
New-NetFirewallRule -DisplayName 'MSSQL$SQLEXPRESS' -Direction Inbound -Action Allow -Protocol TCP -LocalPort 1433

# Modify TCP/IP properties to enable an IP address

$properties = Get-CimInstance -Namespace root/Microsoft/SqlServer/ComputerManagement10 -ClassName ServerNetworkProtocolProperty -Filter "InstanceName='SQLEXPRESS' and ProtocolName = 'Tcp' and IPAddressName='IPAll'"
$properties | ? { $_.PropertyName -eq 'TcpPort' } | Invoke-CimMethod -Name SetStringValue -Arguments @{ StrValue = '1433' }
$properties | ? { $_.PropertyName -eq 'TcpPortDynamic' } | Invoke-CimMethod -Name SetStringValue -Arguments @{ StrValue = '' }

# Restart SQL Server

Restart-Service 'MSSQL$SQLEXPRESS'

Best practices when running Node.js with port 80 (Ubuntu / Linode)

Give Safe User Permission To Use Port 80

Remember, we do NOT want to run your applications as the root user, but there is a hitch: your safe user does not have permission to use the default HTTP port (80). You goal is to be able to publish a website that visitors can use by navigating to an easy to use URL like http://ip:port/

Unfortunately, unless you sign on as root, you’ll normally have to use a URL like http://ip:port - where port number > 1024.

A lot of people get stuck here, but the solution is easy. There a few options but this is the one I like. Type the following commands:

sudo apt-get install libcap2-bin
sudo setcap cap_net_bind_service=+ep `readlink -f \`which node\``

Now, when you tell a Node application that you want it to run on port 80, it will not complain.

Check this reference link

How can I change the language (to english) in Oracle SQL Developer?

On MAC High Sierra (10.13.6)

cd /Users/vkrishna/.sqldeveloper/18.2.0

nano product.conf

on the last line add

AddVMOption -Duser.language=en

Save the file and restart.


If you are using standalone Oracle Data Modeller

find ~/ -name "datamodeler.conf"

and edit this file

cd /Users/vkrishna//Desktop/

Add somewhere in the last

AddVMOption -Duser.language=en

save and restart, done!

Is the buildSessionFactory() Configuration method deprecated in Hibernate


Yes, it is. There are better ways to bootstrap Hibernate, like the following ones.

Hibernate-native bootstrap

The legacy Configuration object is less powerful than using the BootstrapServiceRegistryBuilder, introduced since Hibernate 4:

final BootstrapServiceRegistryBuilder bsrb = new BootstrapServiceRegistryBuilder()

Integrator integrator = integrator();
if (integrator != null) {
    bsrb.applyIntegrator( integrator );

final BootstrapServiceRegistry bsr =;

final StandardServiceRegistry serviceRegistry = 
    new StandardServiceRegistryBuilder(bsr)

final MetadataSources metadataSources = new MetadataSources(serviceRegistry);

for (Class annotatedClass : entities()) {

String[] packages = packages();
if (packages != null) {
    for (String annotatedPackage : packages) {

String[] resources = resources();
if (resources != null) {
    for (String resource : resources) {

final MetadataBuilder metadataBuilder = metadataSources.getMetadataBuilder()

final List<Type> additionalTypes = additionalTypes();
if (additionalTypes != null) { -> {
        metadataBuilder.applyTypes((typeContributions, sr) -> {
            if(type instanceof BasicType) {
                typeContributions.contributeType((BasicType) type);
            } else if (type instanceof UserType ){
                typeContributions.contributeType((UserType) type);
            } else if (type instanceof CompositeUserType) {
                typeContributions.contributeType((CompositeUserType) type);


MetadataImplementor metadata = (MetadataImplementor);

final SessionFactoryBuilder sfb = metadata.getSessionFactoryBuilder();
Interceptor interceptor = interceptor();
if(interceptor != null) {

SessionFactory sessionFactory =;

JPA bootstrap

You can also bootstrap Hibernate using JPA:

PersistenceUnitInfo persistenceUnitInfo = persistenceUnitInfo(getClass().getSimpleName());
Map configuration = properties();

Interceptor interceptor = interceptor();
if (interceptor != null) {
    configuration.put(AvailableSettings.INTERCEPTOR, interceptor);

Integrator integrator = integrator();
if (integrator != null) {
        (IntegratorProvider) () -> Collections.singletonList(integrator));

EntityManagerFactoryBuilderImpl entityManagerFactoryBuilder = 
    new EntityManagerFactoryBuilderImpl(
        new PersistenceUnitInfoDescriptor(persistenceUnitInfo), 
EntityManagerFactory entityManagerFactory =;

This way, you are building the EntityManagerFactory instead of a SessionFactory. However, the SessionFactory extends the EntityManagerFactory, so the actual object that's built is aSessionFactoryImpl` too.


These two bootstrapping methods affect Hibernate behavior. When using the native bootstrap, Hibernate behaves in the legacy mode, which predates JPA.

When bootstrapping using JPA, Hibernate will behave according to the JPA specification.

There are several differences between these two modes:

For more details about these differences, check out the JpaCompliance class.

Spring Boot JPA - configuring auto reconnect

I just moved to Spring Boot 1.4 and found these properties were renamed:

spring.datasource.dbcp.validation-query=SELECT 1

What's the difference of $host and $http_host in Nginx

$host is a variable of the Core module.


This variable is equal to line Host in the header of request or name of the server processing the request if the Host header is not available.

This variable may have a different value from $http_host in such cases: 1) when the Host input header is absent or has an empty value, $host equals to the value of server_name directive; 2)when the value of Host contains port number, $host doesn't include that port number. $host's value is always lowercase since 0.8.17.

$http_host is also a variable of the same module but you won't find it with that name because it is defined generically as $http_HEADER (ref).


The value of the HTTP request header HEADER when converted to lowercase and with 'dashes' converted to 'underscores', e.g. $http_user_agent, $http_referer...;


  • $http_host equals always the HTTP_HOST request header.
  • $host equals $http_host, lowercase and without the port number (if present), except when HTTP_HOST is absent or is an empty value. In that case, $host equals the value of the server_name directive of the server which processed the request.

Cannot use a leading ../ to exit above the top directory

You have an image or a favicon link of the style ="../" somewhere, that if the "../" were valid, would go beyond the top of the site, like this:



Valid on that page: ../Images/test.jpg
Would throw an error: ../../Images/test.jpg

How do I increase the RAM and set up host-only networking in Vagrant?

You can easily increase your VM's RAM by modifying the memory property of config.vm.provider section in your vagrant file.

config.vm.provider "virtualbox" do |vb|
 vb.memory = "4096"

This allocates about 4GB of RAM to your VM. You can change this according to your requirement. For example, following setting would allocate 2GB of RAM to your VM.

config.vm.provider "virtualbox" do |vb|
 vb.memory = "2048"

Try removing the config.vm.customize ["modifyvm", :id, "--memory", 1024] in your file, and adding the above code.

For the network configuration, try modifying the :hostonly, "" in your file "private_network", ip: ""

How to set up default schema name in JPA configuration?

Don't know of JPA property for this either. But you could just add the Hibernate property (assuming you use Hibernate as provider) as


<property name="hibernate.default_schema" value="myschema"/>


Hibernate should pick that up

Where to place and how to read configuration resource files in servlet based application?

Assume your code is looking for the file say Copy this file to any dir and add this dir to classpath, by creating a in the bin dir of tomcat.

In your of tomcat( if this file is not existing, create one , tomcat will load this file. #!/bin/sh CLASSPATH="$CLASSPATH:/home/user/config_my_prod/"

You should not have your properties files in ./webapps//WEB-INF/classes/

Tomcat class loader will override the with the one from WEB-INF/classes/

A good read:

Turning off eslint rule for a specific file

It's better to add "overrides" in your .eslintrc.js config file. For example if you wont to disable camelcase rule for all js files ending on Actions add this code after rules scope in .eslintrc.js.

"rules": {    
"overrides": [
  "files": ["*Actions.js"],
     "rules": {
        "camelcase": "off"   

app.config for a class library

There is no automatic addition of app.config file when you add a class library project to your solution.

To my knowledge, there is no counter indication about doing so manualy. I think this is a common usage.

About log4Net config, you don't have to put the config into app.config, you can have a dedicated conf file in your project as well as an app.config file at the same time.

this link will give you examples about both ways (section in app.config and standalone log4net conf file)

How to initialize log4j properly?

As explained earlier there are 2 approaches

First one is to just add this line to your main method:


Second approach is to add this standard file to your classpath:

While taking second approach you need to make sure you initialize the file properly.


Properties props = new Properties();

props.load(new FileInputStream("log4j property file path"));

props.setProperty("log4j.appender.File.File", "Folder where you want to store log files/" + "File Name");

Make sure you create required folder to store log files.

How to read AppSettings values from a .json file in ASP.NET Core

First off: The assembly name and namespace of Microsoft.Framework.ConfigurationModel has changed to Microsoft.Framework.Configuration. So you should use: e.g.

"Microsoft.Framework.Configuration.Json": "1.0.0-beta7"

as a dependency in project.json. Use beta5 or 6 if you don't have 7 installed. Then you can do something like this in Startup.cs.

public IConfiguration Configuration { get; set; }

public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
     var configurationBuilder = new ConfigurationBuilder(appEnv.ApplicationBasePath)
     Configuration = configurationBuilder.Build();

If you then want to retrieve a variable from the config.json you can get it right away using:

public void Configure(IApplicationBuilder app)
    // Add .Value to get the token string
    var token = Configuration.GetSection("AppSettings:token");
    app.Run(async (context) =>
        await context.Response.WriteAsync("This is a token with key (" + token.Key + ") " + token.Value);

or you can create a class called AppSettings like this:

public class AppSettings
    public string token { get; set; }

and configure the services like this:

public void ConfigureServices(IServiceCollection services)

    services.Configure<MvcOptions>(options =>
        //mvc options


and then access it through e.g. a controller like this:

public class HomeController : Controller
    private string _token;

    public HomeController(IOptions<AppSettings> settings)
        _token = settings.Options.token;

Getting value from appsettings.json in .net core

Its simple: In appsettings.json

  "MyValues": {
    "Value1": "Xyz"

In .cs file:

static IConfiguration conf = (new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json").Build());
        public static string myValue1= conf["MyValues:Value1"].ToString();

How to configure postgresql for the first time?

Just browse up to your installation's directory and execute this file "pg_env.bat", so after go at bin folder and execute pgAdmin.exe. This must work no doubt!

If using maven, usually you put under java or resources?

Add the below code from the resources tags in your pom.xml inside build tags. so it means resources tags must be inside of build tags in your pom.xml


Location of ini/config files in linux/unix?

You should adhere your application to the XDG Base Directory Specification. Most answers here are either obsolete or wrong.

Your application should store and load data and configuration files to/from the directories pointed by the following environment variables:

  • $XDG_DATA_HOME (default: "$HOME/.local/share"): user-specific data files.
  • $XDG_CONFIG_HOME (default: "$HOME/.config"): user-specific configuration files.
  • $XDG_DATA_DIRS (default: "/usr/local/share/:/usr/share/"): precedence-ordered set of system data directories.
  • $XDG_CONFIG_DIRS (default: "/etc/xdg"): precedence-ordered set of system configuration directories.
  • $XDG_CACHE_HOME (default: "$HOME/.cache"): user-specific non-essential data files.

You should first determine if the file in question is:

  1. A configuration file ($XDG_CONFIG_HOME:$XDG_CONFIG_DIRS);
  2. A data file ($XDG_DATA_HOME:$XDG_DATA_DIRS); or
  3. A non-essential (cache) file ($XDG_CACHE_HOME).

It is recommended that your application put its files in a subdirectory of the above directories. Usually, something like $XDG_DATA_DIRS/<application>/filename or $XDG_DATA_DIRS/<vendor>/<application>/filename.

When loading, you first try to load the file from the user-specific directories ($XDG_*_HOME) and, if failed, from system directories ($XDG_*_DIRS). When saving, save to user-specific directories only (since the user probably won't have write access to system directories).

For other, more user-oriented directories, refer to the XDG User Directories Specification. It defines directories for the Desktop, downloads, documents, videos, etc.

How to define custom configuration variables in rails

Since Rails 4.2, without additional gems, you can load config/hi.yml simply by using Rails.application.config_for :hi.

For example:

  1. touch config/passwords.yml

          username: 'a'
          password: 'b'
          username: 'aa'
          password: 'bb'
  1. touch config/initializers/constants.rb

    AUTHENTICATION = Rails.application.config_for :passwords
  1. and now you can use AUTHENTICATION constant everywhere in your application:

    #rails c production
    :001> AUTHENTICATION['username'] => 'aa'
  2. then add passwords.yml to .gitignore: echo /config/passwords.yml >> .gitignore, create an example file for your comfort cp /config/passwords.yml /config/passwords.example.yml and then just edit your example file in your production console with actual production values.

How to select Python version in PyCharm?

Go to:

Files -> Settings -> Project -> *"Your Project Name"* -> Project Interpreter

There you can see which external libraries you have installed for python2 and which for python3.

Select the required python version according to your requirements.


How to implement a ConfigurationSection with a ConfigurationElementCollection

The previous answer is correct but I'll give you all the code as well.

Your app.config should look like this:

<?xml version="1.0" encoding="utf-8" ?>
      <section name="ServicesSection" type="RT.Core.Config.ServiceConfigurationSection, RT.Core"/>
         <add Port="6996" ReportType="File" />
         <add Port="7001" ReportType="Other" />

Your ServiceConfig and ServiceCollection classes remain unchanged.

You need a new class:

public class ServiceConfigurationSection : ConfigurationSection
   [ConfigurationProperty("Services", IsDefaultCollection = false)]
       AddItemName = "add",
       ClearItemsName = "clear",
       RemoveItemName = "remove")]
   public ServiceCollection Services
         return (ServiceCollection)base["Services"];

And that should do the trick. To consume it you can use:

ServiceConfigurationSection serviceConfigSection =
   ConfigurationManager.GetSection("ServicesSection") as ServiceConfigurationSection;

ServiceConfig serviceConfig = serviceConfigSection.Services[0];

ASP.NET Core configuration for .NET Core console application

Install these packages:

  • Microsoft.Extensions.Configuration
  • Microsoft.Extensions.Configuration.Binder
  • Microsoft.Extensions.Configuration.EnvironmentVariables
  • Microsoft.Extensions.Configuration.FileExtensions
  • Microsoft.Extensions.Configuration.Json


static void Main(string[] args)
        var environmentName = Environment.GetEnvironmentVariable("ENVIRONMENT");
        Console.WriteLine("ENVIRONMENT: " + environmentName);

        var builder = new ConfigurationBuilder()
           .AddJsonFile("appsettings.json", false)
           .AddJsonFile($"appsettings.{environmentName}.json", true)

        IConfigurationRoot configuration = builder.Build();
        var mySettingsConfig = configuration.Get<MySettingsConfig>();

        Console.WriteLine("URL: " + mySettingsConfig.Url);
        Console.WriteLine("NAME: " + mySettingsConfig.Name);


MySettingsConfig Class:

public class MySettingsConfig
    public string Url { get; set; }
    public string Name { get; set; }

Your appsettings can be as simple as this: enter image description here

Also, set the appsettings files to Content / Copy if newer: content

How can you change Network settings (IP Address, DNS, WINS, Host Name) with code in C#

A slightly more concise example that builds on top of the other answers here. I leveraged the code generation that is shipped with Visual Studio to remove most of the extra invocation code and replaced it with typed objects instead.

    using System;
    using System.Management;

    namespace Utils
        class NetworkManagement
            /// <summary>
            /// Returns a list of all the network interface class names that are currently enabled in the system
            /// </summary>
            /// <returns>list of nic names</returns>
            public static string[] GetAllNicDescriptions()
                List<string> nics = new List<string>();

                using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
                    using (var networkConfigs = networkConfigMng.GetInstances())
                        foreach (var config in networkConfigs.Cast<ManagementObject>()
                                                                           .Where(mo => (bool)mo["IPEnabled"])
                                                                           .Select(x=> new NetworkAdapterConfiguration(x)))

                return nics.ToArray();

            /// <summary>
            /// Set's the DNS Server of the local machine
            /// </summary>
            /// <param name="nicDescription">The full description of the network interface class</param>
            /// <param name="dnsServers">Comma seperated list of DNS server addresses</param>
            /// <remarks>Requires a reference to the System.Management namespace</remarks>
            public static bool SetNameservers(string nicDescription, string[] dnsServers, bool restart = false)
                using (ManagementClass networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
                    using (ManagementObjectCollection networkConfigs = networkConfigMng.GetInstances())
                        foreach (ManagementObject mboDNS in networkConfigs.Cast<ManagementObject>().Where(mo => (bool)mo["IPEnabled"] && (string)mo["Description"] == nicDescription))
                            // NAC class was generated by opening a developer console and entering:
                            // mgmtclassgen Win32_NetworkAdapterConfiguration -p NetworkAdapterConfiguration.cs
                            // See:

                            using (NetworkAdapterConfiguration config = new NetworkAdapterConfiguration(mboDNS))
                                if (config.SetDNSServerSearchOrder(dnsServers) == 0)

                return false;

            /// <summary>
            /// Restarts a given Network adapter
            /// </summary>
            /// <param name="nicDescription">The full description of the network interface class</param>
            public static void RestartNetworkAdapter(string nicDescription)
                using (ManagementClass networkConfigMng = new ManagementClass("Win32_NetworkAdapter"))
                    using (ManagementObjectCollection networkConfigs = networkConfigMng.GetInstances())
                        foreach (ManagementObject mboDNS in networkConfigs.Cast<ManagementObject>().Where(mo=> (string)mo["Description"] == nicDescription))
                            // NA class was generated by opening dev console and entering
                            // mgmtclassgen Win32_NetworkAdapter -p NetworkAdapter.cs
                            using (NetworkAdapter adapter = new NetworkAdapter(mboDNS))
                                Thread.Sleep(4000); // Wait a few secs until exiting, this will give the NIC enough time to re-connect

            /// <summary>
            /// Get's the DNS Server of the local machine
            /// </summary>
            /// <param name="nicDescription">The full description of the network interface class</param>
            public static string[] GetNameservers(string nicDescription)
                using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
                    using (var networkConfigs = networkConfigMng.GetInstances())
                        foreach (var config  in networkConfigs.Cast<ManagementObject>()
                                                              .Where(mo => (bool)mo["IPEnabled"] && (string)mo["Description"] == nicDescription)
                                                              .Select( x => new NetworkAdapterConfiguration(x)))
                            return config.DNSServerSearchOrder;

                return null;

            /// <summary>
            /// Set's a new IP Address and it's Submask of the local machine
            /// </summary>
            /// <param name="nicDescription">The full description of the network interface class</param>
            /// <param name="ipAddresses">The IP Address</param>
            /// <param name="subnetMask">The Submask IP Address</param>
            /// <param name="gateway">The gateway.</param>
            /// <remarks>Requires a reference to the System.Management namespace</remarks>
            public static void SetIP(string nicDescription, string[] ipAddresses, string subnetMask, string gateway)
                using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
                    using (var networkConfigs = networkConfigMng.GetInstances())
                        foreach (var config in networkConfigs.Cast<ManagementObject>()
                                                                       .Where(mo => (bool)mo["IPEnabled"] && (string)mo["Description"] == nicDescription)
                                                                       .Select( x=> new NetworkAdapterConfiguration(x)))
                            // Set the new IP and subnet masks if needed
                            config.EnableStatic(ipAddresses, Array.ConvertAll(ipAddresses, _ => subnetMask));

                            // Set mew gateway if needed
                            if (!String.IsNullOrEmpty(gateway))
                                config.SetGateways(new[] {gateway}, new ushort[] {1});


Full source:

Copying text outside of Vim with set mouse=a enabled

Compilation settings that vim was compiled with, are part of the issue. vim --version shows these.

In OSX, the default vim has -clipboard But you need +clipboard

On osx you can and apparently generally should, use macvim. You can do brew cask install macvim That one has +clipboard.

Them you'll have two vims.

~$ ls -l /usr/bin/vim   <--- default vim
-rwxr-xr-x  1 root  wheel  1745984 15 Jul  2017 /usr/bin/vim

~$ ls -l /usr/local/bin/vim   <-- macvim, installed recently via that mentioned brew line. 
lrwxr-xr-x  1 apple  admin  42 16 May 23:32 /usr/local/bin/vim -> /Applications/

running vim will run macvim 'cos /usr/local/bin should be before /usr/bin in the path, though you can check with which vim.

running vim(to run macvim), is fine but you may want to map vi to macvim 'cos otherwise running vi stays at the default vim! You can rewrite or delete(with rm) and recreate the vi sym link, with ln. And to do that without an 'operation not permitted" error, you have to (temporarily) disable SIL. .

macvim has +clipboard as shown by vim --version

Here is a working ~/.vim/vimrc with just the required lines.

:set mouse=a
:map <leader>c "+y
:map <leader>v "+p

The default leader key is backslash.

I read a suggestion that one should use the leader key.. (certainly control has many keys already in use, so the suggestion was to not use control. I don't know if that applies to command key too, but anyhow).

With that mentioned mapping, \c will do "+y which will copy from the register known as +, to the clipboard. And \v will paste from the register known as +.

So that's a copy/paste that works between windows.

Another OS may require "* rather than "+

Reading settings from app.config or web.config in .NET

Another possible solution:

var MyReader = new System.Configuration.AppSettingsReader();
string keyvalue = MyReader.GetValue("keyalue",typeof(string)).ToString();

How to select different app.config for several build configurations

I'm using XmlPreprocess tool for config files manipulation. It is using one mapping file for multiple environments(or multiple build targets in your case). You can edit mapping file by Excel. It is very easy to use.

Access denied for user 'root'@'localhost' (using password: Yes) after password reset LINUX

You can try this solution :-

To have mysql asking you for a password, you also need to specify the -p-option: (try with space between -p and password)

mysql -u root -p new_password

MySQLl access denied

In the Second link someone has commented the same problem.

Where are my postgres *.conf files?

If you have just installed it, it is possible that locate doesn't help. In that case, the service should be running and you can run

ps aux  | grep 'postgres *-D'

to see where the postgresql-master is loading the config files from.

What does upstream mean in nginx?

It's used for proxying requests to other servers.

An example from is:

http {
  upstream myproject {
    server weight=3;

  server {
    listen 80;
    location / {
      proxy_pass http://myproject;

This means all requests for / go to the any of the servers listed under upstream XXX, with a preference for port 8000.

Encrypt Password in Configuration Files?

I think that the best approach is to ensure that your config file (containing your password) is only accessible to a specific user account. For example, you might have an application specific user appuser to which only trusted people have the password (and to which they su to).

That way, there's no annoying cryptography overhead and you still have a password which is secure.

EDIT: I am assuming that you are not exporting your application configuration outside of a trusted environment (which I'm not sure would make any sense, given the question)

OpenSSL and error in reading openssl.conf file

I had the same issue on Windows. It was resolved by setting the environment variable as follow:

Variable name: OPENSSL_CONF Variable value: C:(OpenSSl Directory)\bin\openssl.cnf

Spring Boot: Is it possible to use external files in arbitrary directories with a fat jar?

This may be coming in Late but I think I figured out a better way to load external configurations especially when you run your spring-boot app using java jar myapp.war instead of @PropertySource("")

The configuration would be loaded form the root of the project or from the location the war/jar file is being run from

public class Application implements EnvironmentAware {

    public static void main(String[] args) throws Exception {, args);

    public void setEnvironment(Environment environment) {
        //Set up Relative path of Configuration directory/folder, should be at the root of the project or the same folder where the jar/war is placed or being run from
        String configFolder = "config";
        //All static property file names here
        List<String> propertyFiles = Arrays.asList("","");
        //This is also useful for appending the profile names
        Arrays.asList(environment.getActiveProfiles()).stream().forEach(environmentName -> propertyFiles.add(String.format("", environmentName))); 
        for (String configFileName : propertyFiles) {
            File configFile = new File(configFolder, configFileName);
  "looking for configuration %s from %s", configFileName, configFolder));
            FileSystemResource springResource = new FileSystemResource(configFile);
            LOGGER.log(Level.INFO, "Config file : {0}", (configFile.exists() ? "FOund" : "Not Found"));
            if (configFile.exists()) {
                try {
          "Loading configuration file %s", configFileName));
                    PropertiesFactoryBean pfb = new PropertiesFactoryBean();
                    Properties properties = pfb.getObject();
                    PropertiesPropertySource externalConfig = new PropertiesPropertySource("externalConfig", properties);
                    ((ConfigurableEnvironment) environment).getPropertySources().addFirst(externalConfig);
                } catch (IOException ex) {
                    LOGGER.log(Level.SEVERE, null, ex);
            } else {
      "Cannot find Configuration file %s... \n\n\n\n", configFileName));




Hope it helps.

Can .NET load and parse a properties file equivalent to Java Properties class?

I don't know of any built-in way to do this. However, it would seem easy enough to do, since the only delimiters you have to worry about are the newline character and the equals sign.

It would be very easy to write a routine that will return a NameValueCollection, or an IDictionary given the contents of the file.

How do I prevent a Gateway Timeout with FastCGI on Nginx

In http nginx section (/etc/nginx/nginx.conf) add or modify:

keepalive_timeout 300s

In server nginx section (/etc/nginx/sites-available/ add these lines:

client_max_body_size 50M;
fastcgi_buffers 8 1600k;
fastcgi_buffer_size 3200k;
fastcgi_connect_timeout 300s;
fastcgi_send_timeout 300s;
fastcgi_read_timeout 300s;

In php file in the case (/etc/php/7.X/fpm/pool.d/www.conf) modify:

request_terminate_timeout = 300

I hope help you.

How to use a App.config file in WPF applications?

In your app.config, change your appsetting to:

        <setting name="appsetting" serializeAs="String">

Then, in the code-behind:

string xmlDataDirectory = WpfApplication1.Properties.Settings.Default.appsetting.ToString()

How to set index.html as root file in Nginx?

According to the documentation Checks the existence of files in the specified order and uses the first found file for request processing; the processing is performed in the current context. The path to a file is constructed from the file parameter according to the root and alias directives. It is possible to check directory’s existence by specifying a slash at the end of a name, e.g. “$uri/”. If none of the files were found, an internal redirect to the uri specified in the last parameter is made. Important

an internal redirect to the uri specified in the last parameter is made.

So in last parameter you should add your page or code if first two parameters returns false.

location / {
  try_files $uri $uri/index.html index.html;

Determine which MySQL configuration file is being used

An alternative is to use

mysqladmin variables

Eclipse fonts and background color

Under Windows ? Preferences ? General ? Apperance you can find a dark theme.

How to fix: Handler "PageHandlerFactory-Integrated" has a bad module "ManagedPipelineHandler" in its module list

The accepted answer is correct, however sometimes you would get the "Aspnet_regiis.exe is not recognized as an internal or external command, operable program or batch file." error message.

To resolve it try the following:

  1. Make sure that your .NET 4.0 installation is not corrupted (run the installer and 'Repair' it). There's also a chance it is not installed on your machine at all.

  2. If you're sure you don't have .NET 4.0 installed and want to run it as .NET 2.0, try this:

If you see the message "Aspnet_regiis.exe is not recognized as an internal or external command, operable program or batch file.", switch to the C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Aspnet_regiis.exe -i at the command prompt.

Visual studio - getting error "Metadata file 'XYZ' could not be found" after edit continue

I had this issue too.

It started after I did a little folder tidying in my project. I then tried to compile and got many duplicate class errors. (despite them not being duplicated. I think the linking was just out of wack)

Upon checking these, the errors would all disappear leaving only the "Metadata file ...debug\application.exe could not be found" error.

I solved this by looking in the build output window to find which classes were duplicated.

I would then right click the class name and "go to definition".

there will be two definitions to select from, open them both, the second definition will seem to open the same file again, however the second one will identify as the error source(red underline).

Delete all the code out of the file and save(This will not effect your actual file).
This should now compile correctly.

ssl_error_rx_record_too_long and Apache SSL

If you have the error after setup a new https vhost and the config seems to be right, remember to link in sites-enabled too.

Error message "Forbidden You don't have permission to access / on this server"

This article Creating virtual hosts on Apache 2.2 helps me (point 9) permissions to the top virtual hosts directory.

I simply add this lines to my vhosts.conf file:

<Directory I:/projects/webserver>
    Order Deny,Allow
    Allow from all

PHP Warning: Module already loaded in Unknown on line 0

For shared hosting, in cPanel I unchecked the Module in question under "Select PHP Version" > "Extensions" and the error disappeared for PHP 7.4.

pgadmin4 : postgresql application server could not be contacted.

try this

I encountered the same problem and activated the setup file, it created a database, and was restarting again

sudo /usr/pgadmin4/bin/

Apache won't follow symlinks (403 Forbidden)

For anyone having trouble after upgrading to 14.04 as root changed before upgrade = /var/www after upgrade = /var/www/html

How to change Vagrant 'default' machine name?

In case there are many people using your vagrant file - you might want to set name dynamically. Below is the example how to do it using username from your HOST machine as the name of the box and hostname:

require 'etc'
vagrant_name = "yourProjectName-" + Etc.getlogin
Vagrant.configure("2") do |config| = "ubuntu/xenial64"
  config.vm.hostname = vagrant_name
  config.vm.provider "virtualbox" do |v| = vagrant_name

Redis - Connect to Remote Server

First I'd check to verify it is listening on the IPs you expect it to be:

netstat -nlpt | grep 6379

Depending on how you start/stop you may not have actually restarted the instance when you thought you had. The netstat will tell you if it is listening where you think it is. If not, restart it and be sure it restarts. If it restarts and still is not listening where you expect, check your config file just to be sure.

After establishing it is listening where you expect it to, from a remote node which should have access try:

redis-cli -h REMOTE.HOST ping

You could also try that from the local host but use the IP you expect it to be listening on instead of a hostname or localhost. You should see it PONG in response in both cases.

If not, your firewall(s) is/are blocking you. This would be either the local IPTables or possibly a firewall in between the nodes. You could add a logging statement to your IPtables configuration to log connections over 6379 to see what is happening. Also, trying he redis ping from local and non-local to the same IP should be illustrative. If it responds locally but not remotely, I'd lean toward an intervening firewall depending on the complexity of your on-node IP Tables rules.

how to set start page in webconfig file in c#

The same problem arrised for me when I installed Kaliko CMS Nuget Package. When I removed it, it started working fine again. So, your problem could be because of a recently installed Nuget Package. Uninstall it and your solution will work just fine.

Configuring Hibernate logging using Log4j XML config file?

You can configure your log4j file with the category tag like this (with a console appender for the example):

<appender name="console" class="org.apache.log4j.ConsoleAppender">
    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="%d{yy-MM-dd HH:mm:ss} %p %c - %m%n" />
<category name="org.hibernate">
    <priority value="WARN" />
    <priority value="INFO" />
    <appender-ref ref="console" />

So every warning, error or fatal message from hibernate will be displayed, nothing more. Also, your code and library code will be in info level (so info, warn, error and fatal)

To change log level of a library, just add a category, for example, to desactive spring info log:

<category name="org.springframework">
    <priority value="WARN" />

Or with another appender, break the additivity (additivity default value is true)

<category name="org.springframework" additivity="false">
    <priority value="WARN" />
    <appender-ref ref="anotherAppender" />

And if you don't want that hibernate log every query, set the hibernate property show_sql to false.

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

I learnt a easy way from code example of

1) notice the ZendeskBlueFormBundle and file location

# myproject/app/config/config.yml

    - { resource: parameters.yml }
    - { resource: security.yml }
    - { resource: @ZendeskBlueFormBundle/Resources/config/config.yml }


2) notice Zendesk_BlueForm.emails.contact_email and file location

# myproject/src/Zendesk/BlueFormBundle/Resources/config/config.yml

    # Zendesk contact email address
    Zendesk_BlueForm.emails.contact_email: [email protected]

3) notice how i get it in $client and file location of controller

# myproject/src/Zendesk/BlueFormBundle/Controller/PageController.php

    public function blueFormAction($name, $arg1, $arg2, $arg3, Request $request)
    $client = new ZendeskAPI($this->container->getParameter("Zendesk_BlueForm.emails.contact_email"));

Creating a Pandas DataFrame from a Numpy array: How do I specify the index column and column headers?

Here simple example to create pandas dataframe by using numpy array.

import numpy as np
import pandas as pd

# create an array 
var1  = np.arange(start=1, stop=21, step=1).reshape(-1)
var2 = np.random.rand(20,1).reshape(-1)

dataset = pd.DataFrame()
dataset['col1'] = var1
dataset['col2'] = var2

How to define the basic HTTP authentication using cURL correctly?

curl -u username:password http://
curl -u username http://

From the documentation page:

-u, --user <user:password>

Specify the user name and password to use for server authentication. Overrides -n, --netrc and --netrc-optional.

If you simply specify the user name, curl will prompt for a password.

The user name and passwords are split up on the first colon, which makes it impossible to use a colon in the user name with this option. The password can, still.

When using Kerberos V5 with a Windows based server you should include the Windows domain name in the user name, in order for the server to succesfully obtain a Kerberos Ticket. If you don't then the initial authentication handshake may fail.

When using NTLM, the user name can be specified simply as the user name, without the domain, if there is a single domain and forest in your setup for example.

To specify the domain name use either Down-Level Logon Name or UPN (User Principal Name) formats. For example, EXAMPLE\user and [email protected] respectively.

If you use a Windows SSPI-enabled curl binary and perform Kerberos V5, Negotiate, NTLM or Digest authentication then you can tell curl to select the user name and password from your environment by specifying a single colon with this option: "-u :".

If this option is used several times, the last one will be used.

Note that you do not need --basic flag as it is the default.

How do I convert an integer to string as part of a PostgreSQL query?

You can cast an integer to a string in this way


and so in your case

SELECT * FROM table WHERE <some integer>::text = 'string of numbers'

Proper use of mutexes in Python

You have to unlock your Mutex at sometime...

Getting a directory name from a filename

Just use this: ExtractFilePath(your_path_file_name)

Getting ORA-01031: insufficient privileges while querying a table instead of ORA-00942: table or view does not exist

In SQL Developer: Everything was working fine and I had all the permissions to login and there was no password change and I could click the table and see the data tab.

But when I run query (simple select statement) it was showing "ORA-01031: insufficient privileges" message.

The solution is simply disconnect the connection and reconnect. Note: only doing Reconnect did not work for me. SQL Developer Disconnect Snapshot

Get content uri from file path in android

Its late, but may help someone in future.

To get content URI for a file, you may use the following method:

FileProvider.getUriForFile(Context context, String authority, File file)

It returns the content URI.

Check this out to learn how to setup a FileProvider

Laravel Eloquent update just if changes have been made

I like to add this method, if you are using an edit form, you can use this code to save the changes in your update(Request $request, $id) function:

$post = Post::find($id);    

keep in mind that you have to name your inputs with the same column name. The fill() function will do all the work for you :)

How to add image in Flutter

  1. Create images folder in root level of your project.

    enter image description here

    enter image description here

  2. Drop your image in this folder, it should look like

    enter image description here

  3. Go to your pubspec.yaml file, add assets header and pay close attention to all the spaces.

      uses-material-design: true
      # add this
        - images/profile.jpg
  4. Tap on Packages get at the top right corner of the IDE.

    enter image description here

  5. Now you can use your image anywhere using


Nginx 403 error: directory index of [folder] is forbidden

In my case it was related to SELinux in CentOS 7:

You can check if it is enabled running the following command:

cat /etc/selinux/config

Sample outputs:


Disabling SELinux permanently Edit the /etc/selinux/config file, run:

sudo vi /etc/selinux/config

Set SELINUX to disabled:


Save and close the file in vi/vim. Reboot the Linux system:

sudo reboot

How to get the caret column (not pixels) position in a textarea, in characters, from the start?

Updated 5 September 2010

Seeing as everyone seems to get directed here for this issue, I'm adding my answer to a similar question, which contains the same code as this answer but with full background for those who are interested:

IE's document.selection.createRange doesn't include leading or trailing blank lines

To account for trailing line breaks is tricky in IE, and I haven't seen any solution that does this correctly, including any other answers to this question. It is possible, however, using the following function, which will return you the start and end of the selection (which are the same in the case of a caret) within a <textarea> or text <input>.

Note that the textarea must have focus for this function to work properly in IE. If in doubt, call the textarea's focus() method first.

function getInputSelection(el) {
    var start = 0, end = 0, normalizedValue, range,
        textInputRange, len, endRange;

    if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
        start = el.selectionStart;
        end = el.selectionEnd;
    } else {
        range = document.selection.createRange();

        if (range && range.parentElement() == el) {
            len = el.value.length;
            normalizedValue = el.value.replace(/\r\n/g, "\n");

            // Create a working TextRange that lives only in the input
            textInputRange = el.createTextRange();

            // Check if the start and end of the selection are at the very end
            // of the input, since moveStart/moveEnd doesn't return what we want
            // in those cases
            endRange = el.createTextRange();

            if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
                start = end = len;
            } else {
                start = -textInputRange.moveStart("character", -len);
                start += normalizedValue.slice(0, start).split("\n").length - 1;

                if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
                    end = len;
                } else {
                    end = -textInputRange.moveEnd("character", -len);
                    end += normalizedValue.slice(0, end).split("\n").length - 1;

    return {
        start: start,
        end: end

Jquery function BEFORE form submission

You can use the onsubmit function.

If you return false the form won't get submitted. Read up about it here.

$('#myform').submit(function() {
  // your code here

Pyspark: Exception: Java gateway process exited before sending the driver its port number

For Linux (Ubuntu 18.04) with a JAVA_HOME issue, a key is to point it to the master folder:

  1. Set Java 8 as default by: sudo update-alternatives --config java. If Jave 8 is not installed, install by: sudo apt install openjdk-8-jdk.
  2. Set JAVA_HOME environment variable as the master java 8 folder. The location is given by the first command above removing jre/bin/java. Namely: export JAVA_HOME="/usr/lib/jvm/java-8-openjdk-amd64/". If done on the command line, this will be relevant only for the current session (ref: export command on Linux). To verify: echo $JAVA_HOME.
  3. In order to have this permanently set, add the bolded line above to a file that runs before you start your IDE/Jupyter/python interpreter. This could be by adding the bolded line above to .bashrc. This file loads when a bash is started interactively ref: .bashrc

How to use getJSON, sending data with post method?

The $.getJSON() method does an HTTP GET and not POST. You need to use $.post()

$.post(url, dataToBeSent, function(data, textStatus) {
  //data contains the JSON object
  //textStatus contains the status: success, error, etc
}, "json");

In that call, dataToBeSent could be anything you want, although if are sending the contents of a an html form, you can use the serialize method to create the data for the POST from your form.

var dataToBeSent = $("form").serialize();

Angular2 dynamic change CSS property

I did this plunker to explore one way to do what you want.

Here I get mystyle from the parent component but you can get it from a service.

import {Component, View} from 'angular2/angular2'

  selector: '[my-person]',
  inputs: [
    'mystyle: customstyle'
  host: {
    '[style.backgroundColor]': 'mystyle.backgroundColor'
  template: `My Person Component: {{ name }}`
export class Person {}

How do you read a CSV file and display the results in a grid in Visual Basic 2010?

Use the TextFieldParser class built into the .Net framework.

Here's some code copied from an MSDN forum post by Paul Clement. It converts the CSV into a new in-memory DataTable and then binds the DataGridView to the DataTable

    Dim TextFileReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\Documents and Settings\...\My Documents\My Database\Text\SemiColonDelimited.txt")

    TextFileReader.TextFieldType = FileIO.FieldType.Delimited

    Dim TextFileTable As DataTable = Nothing

    Dim Column As DataColumn
    Dim Row As DataRow
    Dim UpperBound As Int32
    Dim ColumnCount As Int32
    Dim CurrentRow As String()

    While Not TextFileReader.EndOfData
            CurrentRow = TextFileReader.ReadFields()
            If Not CurrentRow Is Nothing Then
                ''# Check if DataTable has been created
                If TextFileTable Is Nothing Then
                    TextFileTable = New DataTable("TextFileTable")
                    ''# Get number of columns
                    UpperBound = CurrentRow.GetUpperBound(0)
                    ''# Create new DataTable
                    For ColumnCount = 0 To UpperBound
                        Column = New DataColumn()
                        Column.DataType = System.Type.GetType("System.String")
                        Column.ColumnName = "Column" & ColumnCount
                        Column.Caption = "Column" & ColumnCount
                        Column.ReadOnly = True
                        Column.Unique = False
                End If
                Row = TextFileTable.NewRow
                For ColumnCount = 0 To UpperBound
                    Row("Column" & ColumnCount) = CurrentRow(ColumnCount).ToString
            End If
        Catch ex As _
            MsgBox("Line " & ex.Message & _
            "is not valid and will be skipped.")
        End Try
    End While
    frmMain.DataGrid1.DataSource = TextFileTable

Java Error opening registry key

In case a virus scanner (like McAfee) is running, try:

  1. Disable virus scanner
  2. Uninstall Java (via Control Panel / Programs and Features)
  3. Reinstall Java (from
  4. Re-enable virus scanner

Will Google Android ever support .NET?

A modified port of Mono is also entirely possible.

Running a script inside a docker container using shell script

You could also mount a local directory into your docker image and source the script in your .bashrc. Don't forget the script has to consist of functions unless you want it to execute on every new shell. (This is outdated see the update notice.)

I'm using this solution to be able to update the script outside of the docker instance. This way I don't have to rerun the image if changes occur, I just open a new shell. (Got rid of reopening a shell - see the update notice)

Here is how you bind your current directory:

docker run -it -v $PWD:/scripts $my_docker_build /bin/bash

Now your current directory is bound to /scripts of your docker instance.

(Outdated) To save your .bashrc changes commit your working image with this command:

docker commit $container_id $my_docker_build


To solve the issue to open up a new shell for every change I now do the following:

In the dockerfile itself I add RUN echo "/scripts/bashrc" > /root/.bashrc". Inside zshrc I export the scripts directory to the path. The scripts directory now contains multiple files instead of one. Now I can directly call all scripts without having open a sub shell on every change.

BTW you can define the history file outside of your container too. This way it's not necessary to commit on a bash change anymore.

ORDER BY date and time BEFORE GROUP BY name in mysql

Another way to solve this would be with a LEFT JOIN, which could be more efficient. I'll first start with an example that considers only the date field, as probably it is more common to store date + time in one datetime column, and I also want to keep the query simple so it's easier to understand.

So, with this particular example, if you want to show the oldest record based on the date column, and assuming that your table name is called people you can use the following query:

SELECT p.* FROM people p
LEFT JOIN people p2 ON = AND >

What the LEFT JOIN does, is when the column is at its minimum value, there will be no with a smaller value on the left join and therefore the corresponding will be NULL. So, by adding WHERE is NULL, we make sure to show only the records with the oldest date.

And similarly, if you want to show the newest record instead, you can just change the comparison operator in the LEFT JOIN:

SELECT p.* FROM people p
LEFT JOIN people p2 ON = AND <

Now, for this particular example where date+time are separate columns, you would need to add them in some way if you want to query based on the datetime of two columns combined, for example:

SELECT p.* FROM people p

You can read more about this (and also see some other ways to accomplish this) on the The Rows Holding the Group-wise Maximum of a Certain Column page.

Angles between two n-dimensional vectors in Python

If you're working with 3D vectors, you can do this concisely using the toolbelt vg. It's a light layer on top of numpy.

import numpy as np
import vg

vec1 = np.array([1, 2, 3])
vec2 = np.array([7, 8, 9])

vg.angle(vec1, vec2)

You can also specify a viewing angle to compute the angle via projection:

vg.angle(vec1, vec2, look=vg.basis.z)

Or compute the signed angle via projection:

vg.signed_angle(vec1, vec2, look=vg.basis.z)

I created the library at my last startup, where it was motivated by uses like this: simple ideas which are verbose or opaque in NumPy.

Transfer data between databases with PostgreSQL

Just like leonbloy suggested, using two schemas in a database is the way to go. Suppose a source schema (old DB) and a target schema (new DB), you can try something like this (you should consider column names, types, etc.):

INSERT INTO target.Awards SELECT * FROM source.Nominations;

appending array to FormData and send via AJAX

add all type inputs to FormData

const formData = new FormData();
for (let key in form) {
        ? form[key].forEach(value => formData.append(key + '[]', value))
        : formData.append(key, form[key]) ;

How to iterate a table rows with JQuery and access some cell values?

do this:

$("tr.item").each(function(i, tr) {
    var value = $("span.value", tr).text();
    var quantity = $("input.quantity", tr).val();

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-resources-plugin:2.6 or one of its dependencies could not be resolved

Try update your Eclipse with the newest Maven repository as follows:

  1. Open "Install" dialog box by choosing "Help/Install New Software..." in Eclipse
  2. Insert following link into "Work with:" input box
    and press Enter
  3. Select (check) "Maven Integration for Eclipse" and choose "Next >" button
  4. Continue with the installation, confirm the License agreement, let the installation download what is necessary
  5. After successful installation you should restart Eclipse
  6. Your project should be loaded without Maven-related errors now

How do I implement a progress bar in C#?

I have not compiled this as it is meant for a proof of concept. This is how I have implemented a Progress bar for database access in the past. This example shows access to a SQLite database using the System.Data.SQLite module

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    // Get the BackgroundWorker that raised this event.
    BackgroundWorker worker = sender as BackgroundWorker;
    using(SQLiteConnection cnn = new SQLiteConnection("Data Source=MyDatabase.db"))
        int TotalQuerySize = GetQueryCount("Query", cnn); // This needs to be implemented and is not shown in example
        using (SQLiteCommand cmd = cnn.CreateCommand())
            cmd.CommandText = "Query is here";
            using(SQLiteDataReader reader = cmd.ExecuteReader())
                int i = 0;
                    // Access the database data using the reader[].  Each .Read() provides the next Row
                    if(worker.WorkerReportsProgress) worker.ReportProgress(++i * 100/ TotalQuerySize);
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    this.progressBar1.Value = e.ProgressPercentage;

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    // Notify someone that the database access is finished.  Do stuff to clean up if needed
    // This could be a good time to hide, clear or do somthign to the progress bar

public void AcessMySQLiteDatabase()
    BackgroundWorker backgroundWorker1 = new BackgroundWorker();
    backgroundWorker1.DoWork += 
        new DoWorkEventHandler(backgroundWorker1_DoWork);
    backgroundWorker1.RunWorkerCompleted += 
        new RunWorkerCompletedEventHandler(
    backgroundWorker1.ProgressChanged += 
        new ProgressChangedEventHandler(

How To Check If A Key in **kwargs Exists?

One way is to add it by yourself! How? By merging kwargs with a bunch of defaults. This won't be appropriate on all occasions, for example, if the keys are not known to you in advance. However, if they are, here is a simple example:

import sys

def myfunc(**kwargs):
    args = {'country':'England','town':'London',
            'currency':'Pound', 'language':'English'}

    diff = set(kwargs.keys()) - set(args.keys())
    if diff:
        print("Invalid args:",tuple(diff),file=sys.stderr)


The defaults are set in the dictionary args, which includes all the keys we are expecting. We first check to see if there are any unexpected keys in kwargs. Then we update args with kwargs which will overwrite any new values that the user has set. We don't need to test if a key exists, we now use args as our argument dictionary and have no further need of kwargs.

Does Java have a path joining method?

One way is to get system properties that give you the path separator for the operating system, this tutorial explains how. You can then use a standard string join using the file.separator.

Is it possible to set an object to null?

You can set any pointer to NULL, though NULL is simply defined as 0 in C++:

myObject *foo = NULL;

Also note that NULL is defined if you include standard headers, but is not built into the language itself. If NULL is undefined, you can use 0 instead, or include this:

#ifndef NULL
#define NULL 0

As an aside, if you really want to set an object, not a pointer, to NULL, you can read about the Null Object Pattern.

Assembly Language - How to do Modulo?

If you don't care too much about performance and want to use the straightforward way, you can use either DIV or IDIV.

DIV or IDIV takes only one operand where it divides a certain register with this operand, the operand can be register or memory location only.

When operand is a byte: AL = AL / operand, AH = remainder (modulus).


MOV AL,31h ; Al = 31h

DIV BL ; Al (quotient)= 08h, Ah(remainder)= 01h

when operand is a word: AX = (AX) / operand, DX = remainder (modulus).


MOV AX,9031h ; Ax = 9031h

DIV BX ; Ax=1808h & Dx(remainder)= 01h

JQuery Error: cannot call methods on dialog prior to initialization; attempted to call method 'close'

it seems for some reason jQuery UI will try to run all code defined in buttons at definition time. It is crazy but I had the same issue and it stoped once I made this change.

if ($(this).dialog.isOpen === true) { 

Facebook API: Get fans of / people who like a page

For s3m3n's answer, Facebook fans plugin (e.g. LAMODA) has limitation now, you get less and less new fans on continuous requests. You may try my modified PHP script to visualize results:

Another approach is Facebook graph search. On search result page: People who like pages named "Lamoda" , open Chrome console and run JavaScript:

var run = 0;
var mails = {}
total = 3000; //????,??????????

function getEmails (cont) {
    var friendbutton=cont.getElementsByClassName("_ohe");
    for(var i=0; i<friendbutton.length; i++) {
        var link = friendbutton[i].getAttribute("href");

        if(link && link.substr(0,25)=="") {
            var parser = document.createElement('a');
            parser.href = link;
            if (parser.pathname) {
                path = parser.pathname.substr(1);
                if (path == "profile.php") {
                    search =;
                    var args = search.split('&');
                    email = args[0].split('=')[1] + "\n";
                } else {
                    email = parser.pathname.substr(1) + "\n";
                if (mails[email] > 0) {
                mails[email] = 1;

function moreScroll() {
    var text="";
    containerID = "BrowseResultsContainer"
    if (run > 0) {
        containerID = "fbBrowseScrollingPagerContainer" + (run-1);
    var cont = document.getElementById(containerID);
    if (cont) {
        var id = run - 2;
        if (id >= 0) {
            setTimeout(function() {
                containerID = "fbBrowseScrollingPagerContainer" + (id);
                var delcont = document.getElementById(containerID);
                if (delcont) {
                window.scrollTo(0, document.body.scrollHeight - 10);
            }, 1000);
    } else {
        console.log("# " + containerID);
    if (run < total) {
        window.scrollTo(0, document.body.scrollHeight + 10);
    setTimeout(moreScroll, 2000);


It would load new fans and print user id/email, remove old DOM nodes to avoid page crash. You may find this script here

How can I strip first and last double quotes?

If you can't assume that all the strings you process have double quotes you can use something like this:

if string.startswith('"') and string.endswith('"'):
    string = string[1:-1]


I'm sure that you just used string as the variable name for exemplification here and in your real code it has a useful name, but I feel obliged to warn you that there is a module named string in the standard libraries. It's not loaded automatically, but if you ever use import string make sure your variable doesn't eclipse it.

Creating a new database and new connection in Oracle SQL Developer

This tutorial should help you:

Getting Started with Oracle SQL Developer

See the prerequisites:

  1. Install Oracle SQL Developer. You already have it.
  2. Install the Oracle Database. Download available here.
  3. Unlock the HR user. Login to SQL*Plus as the SYS user and execute the following command:

    alter user hr identified by hr account unlock;

  4. Download and unzip the file that contains all the files you need to perform this tutorial.

Another version from May 2011: Getting Started with Oracle SQL Developer

For more info check this related question:

How to create a new database after initally installing oracle database 11g Express Edition?

How to store Java Date to Mysql datetime with JPA

Are you perhaps using java.sql.Date? While that has millisecond granularity as a Java class (it is a subclass of java.util.Date, bad design decision), it will be interpreted by the JDBC driver as a date without a time component. You have to use java.sql.Timestamp instead.

Searching if value exists in a list of objects using Linq

LINQ defines an extension method that is perfect for solving this exact problem:

using System.Linq;
    bool has = list.Any(cus => cus.FirstName == "John");

make sure you reference System.Core.dll, that's where LINQ lives.

"You may need an appropriate loader to handle this file type" with Webpack and Babel

When using Typescript:

In my case I used the newer syntax of webpack v3.11 from their documentation page I just copied the css and style loaders configuration form their website. The commented out code (newer API) causes this error, see below.

  module: {
        loaders: [{
                test: /\.ts$/,
                loaders: ['ts-loader']
                test: /\.css$/,
                loaders: [
        // ,
        // rules: [{
        //     test: /\.css$/,
        //     use: [
        //         'style-loader',
        //         'css-loader'
        //     ]
        // }]

The right way is to put this:

        test: /\.css$/,
        loaders: [

in the array of the loaders property.

python pandas remove duplicate columns

An update on @kalu's answer, which uses the latest pandas:

def find_duplicated_columns(df):
    dupes = []

    columns = df.columns

    for i in range(len(columns)):
        col1 = df.iloc[:, i]
        for j in range(i + 1, len(columns)):
            col2 = df.iloc[:, j]
            # break early if dtypes aren't the same (helps deal with
            # categorical dtypes)
            if col1.dtype is not col2.dtype:
            # otherwise compare values
            if col1.equals(col2):

    return dupes

remove objects from array by object property

You can use filter. This method always returns the element if the condition is true. So if you want to remove by id you must keep all the element that doesn't match with the given id. Here is an example:

arrayOfObjects = arrayOfObjects.filter(obj => != idToRemove)

Django auto_now and auto_now_add

You can use for created and auto_now for modified:

from django.utils import timezone
class User(models.Model):
    created = models.DateTimeField(
    modified = models.DateTimeField(auto_now=True)

If you are using a custom primary key instead of the default auto- increment int, auto_now_add will lead to a bug.

Here is the code of Django's default DateTimeField.pre_save withauto_now and auto_now_add:

def pre_save(self, model_instance, add):
    if self.auto_now or (self.auto_now_add and add):
        value =
        setattr(model_instance, self.attname, value)
        return value
        return super(DateTimeField, self).pre_save(model_instance, add)

I am not sure what the parameter add is. I hope it will some thing like:

add = True if getattr(model_instance, 'id') else False

The new record will not have attr id, so getattr(model_instance, 'id') will return False will lead to not setting any value in the field.

application/x-www-form-urlencoded or multipart/form-data?

I agree with much that Manuel has said. In fact, his comments refer to this url...

... which states:

The content type "application/x-www-form-urlencoded" is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.

However, for me it would come down to tool/framework support.

  • What tools and frameworks do you expect your API users to be building their apps with?
  • Do they have frameworks or components they can use that favour one method over the other?

If you get a clear idea of your users, and how they'll make use of your API, then that will help you decide. If you make the upload of files hard for your API users then they'll move away, of you'll spend a lot of time on supporting them.

Secondary to this would be the tool support YOU have for writing your API and how easy it is for your to accommodate one upload mechanism over the other.

Including non-Python files with

I just wanted to follow up on something I found working with Python 2.7 on Centos 6. Adding the package_data or data_files as mentioned above did not work for me. I added a MANIFEST.IN with the files I wanted which put the non-python files into the tarball, but did not install them on the target machine via RPM.

In the end, I was able to get the files into my solution using the "options" in the setup/setuptools. The option files let you modify various sections of the spec file from As follows.

from setuptools import setup

    author_email='[email protected]',
    options={'bdist_rpm': {'install_script': 'filewithinstallcommands'}},

file -

include license.txt

file - filewithinstallcommands:

mkdir -p $RPM_BUILD_ROOT/pathtoinstall/
#this line installs your python files
python install -O1 --root=$RPM_BUILD_ROOT --record=INSTALLED_FILES
#install license.txt into /pathtoinstall folder
install -m 700 license.txt $RPM_BUILD_ROOT/pathtoinstall/
echo /pathtoinstall/license.txt >> INSTALLED_FILES

How to Join to first row

EDIT: nevermind, Quassnoi has a better answer.

For SQL2K, something like this:

, LineItems.Quantity
, LineItems.Description
FROM (  
  , Orders.OrderNumber
  , FirstLineItemID = (
      SELECT TOP 1 LineItemID
      FROM LineItems
      WHERE LineItems.OrderID = Orders.OrderID
      ORDER BY LineItemID -- or whatever else
  FROM Orders
  ) Orders
JOIN LineItems 
  ON LineItems.OrderID = Orders.OrderID 
 AND LineItems.LineItemID = Orders.FirstLineItemID

A project with an Output Type of Class Library cannot be started directly

Just needs to go:

Solution Explorer-->Go to Properties --->change(Single Startup project) from.dll to .web

Then try to debug it.

Surely your problem will be solved.

Inner join with count() on three tables

One needs to understand what a JOIN or a series of JOINs does to a set of data. With strae's post, a pe_id of 1 joined with corresponding order and items on pe_id = 1 will give you the following data to "select" from:

[ table people portion ] [ table orders portion ] [ table items portion ]

| people.pe_id | people.pe_name | orders.ord_id | orders.pe_id | orders.ord_title | item.item_id | item.ord_id | item.pe_id | item.title |

| 1 | Foo | 1 | 1 | First order | 1 | 1 | 1 | Apple |
| 1 | Foo | 1 | 1 | First order | 2 | 1 | 1 | Pear |

The joins essentially come up with a cartesian product of all the tables. You basically have that data set to select from and that's why you need a distinct count on orders.ord_id and items.item_id. Otherwise both counts will result in 2 - because you effectively have 2 rows to select from.

How to remove/ignore :hover css style on touch devices

tl;dr use this:

If you're interested why or what other options there are, read on.

Quick'n'dirty - remove :hover styles using JS

You can remove all the CSS rules containing :hover using Javascript. This has the advantage of not having to touch CSS and being compatible even with older browsers.

function hasTouch() {
  return 'ontouchstart' in document.documentElement
         || navigator.maxTouchPoints > 0
         || navigator.msMaxTouchPoints > 0;

if (hasTouch()) { // remove all the :hover stylesheets
  try { // prevent exception on browsers not supporting DOM styleSheets properly
    for (var si in document.styleSheets) {
      var styleSheet = document.styleSheets[si];
      if (!styleSheet.rules) continue;

      for (var ri = styleSheet.rules.length - 1; ri >= 0; ri--) {
        if (!styleSheet.rules[ri].selectorText) continue;

        if (styleSheet.rules[ri].selectorText.match(':hover')) {
  } catch (ex) {}

Limitations: stylesheets must be hosted on the same domain (that means no CDNs). Disables hovers on mixed mouse & touch devices like Surface or iPad Pro, which hurts the UX.

CSS-only - use media queries

Place all your :hover rules in a @media block:

@media (hover: hover) {
  a:hover { color: blue; }

or alternatively, override all your hover rules (compatible with older browsers):

a:hover { color: blue; }

@media (hover: none) {
  a:hover { color: inherit; }

Limitations: works only on iOS 9.0+, Chrome for Android or Android 5.0+ when using WebView. hover: hover breaks hover effects on older browsers, hover: none needs overriding all the previously defined CSS rules. Both are incompatible with mixed mouse & touch devices.

The most robust - detect touch via JS and prepend CSS :hover rules

This method needs prepending all the hover rules with body.hasHover. (or a class name of your choice)

body.hasHover a:hover { color: blue; }

The hasHover class may be added using hasTouch() from the first example:

if (!hasTouch()) document.body.className += ' hasHover'

However, this whould have the same drawbacks with mixed touch devices as previous examples, which brings us to the ultimate solution. Enable hover effects whenever a mouse cursor is moved, disable hover effects whenever a touch is detected.

function watchForHover() {
  // lastTouchTime is used for ignoring emulated mousemove events
  let lastTouchTime = 0

  function enableHover() {
    if (new Date() - lastTouchTime < 500) return

  function disableHover() {

  function updateLastTouchTime() {
    lastTouchTime = new Date()

  document.addEventListener('touchstart', updateLastTouchTime, true)
  document.addEventListener('touchstart', disableHover, true)
  document.addEventListener('mousemove', enableHover, true)



This should work basically in any browser and enables/disables hover styles as needed.

Here's the full example - modern:
Legacy (for use with old browsers):

"Submit is not a function" error in JavaScript

If you have no opportunity to change name="submit" you can also submit form this way:

function submitForm(form) {
    const submitFormFunction = Object.getPrototypeOf(form).submit;;

Difference between multitasking, multithreading and multiprocessing?

MultiProgramming - In a multiprogramming system, there are more than one programs loaded in main memory which are ready to execute. Only one program at a time is able to get the CPU for executing its instructions while all others are waiting their turn. The main idea of multiprogramming is to maximize the use of CPU time. Suppose currently running process is performing an I/O task, then OS may interrupt that process and give the control to one of the other in - main memory programs that are ready to execute (i.e. process context switching). In this way, no CPU time is wasted by system waiting for the I/O task to be completed.

MultiProcessing - Multiprocessing is the ability of an operating system to execute more than one process simultaneously on a multi processor machine. In multiprocessing system, a computer uses more than one CPU at a tme.

Multitasking - Multitasking is the ability of an operating system to execute more than one task simultaneously on single processor machine, these multiple tasks share common resources such as CPU and memory. In multitasking system, CPU switches from one task to next task so quickly that appears as all tasks are executing at the same time.

There are differences between multitasking and multiprogramming. A task in a multitasking system is not whole application program but it can refres to a "thread of execution" when one process is divided into sub-tasks. Each smaller task does not hijack the CPU until it finishes, they share a small amount of the CPU time called Quantum. Multiprogramming and multitasking operating systems are time sharing systems.

Multithreading - Multithreading is the extension of multitasking. Multithreading is the ability of an operating system to subdivide the specific operation within a single application into individual threads. Each of these threads can run in parallel. The OS divides processing time not only among different applications but also among each thread within an application.

How can I save application settings in a Windows Forms application?

As far as I can tell, .NET does support persisting settings using the built-in application settings facility:

The Application Settings feature of Windows Forms makes it easy to create, store, and maintain custom application and user preferences on the client computer. With Windows Forms application settings, you can store not only application data such as database connection strings, but also user-specific data, such as user application preferences. Using Visual Studio or custom managed code, you can create new settings, read them from and write them to disk, bind them to properties on your forms, and validate settings data prior to loading and saving. -

Browserslist: caniuse-lite is outdated. Please run next command `npm update caniuse-lite browserslist`

I did downgrade the node version from 12 to 10


This error occurred with me because I was using node version 12. When I downgrade to version 10.16.5 this error stops. This error happened in my local env, but in prod and staging, it not happens. In prod and staging node version is 10.x so I just do this and I didn't need to update any package in my package.json

TypeError: 'undefined' is not an object

try out this if you want to assign value to object and it is showing this error in angular..

crate object in construtor

this.modelObj = new Model(); //<---------- after declaring object above

dbms_lob.getlength() vs. length() to find blob size in oracle

length and dbms_lob.getlength return the number of characters when applied to a CLOB (Character LOB). When applied to a BLOB (Binary LOB), dbms_lob.getlength will return the number of bytes, which may differ from the number of characters in a multi-byte character set.

As the documentation doesn't specify what happens when you apply length on a BLOB, I would advise against using it in that case. If you want the number of bytes in a BLOB, use dbms_lob.getlength.

Wrap text in <td> tag

I believe you've encountered the catch 22 of tables. Tables are great for wrapping up content in a tabular structure and they do a wonderful job of "stretching" to meet the needs of the content they contain.

By default the table cells will stretch to fit content... thus your text just makes it wider.

There's a few solutions.

1.) You can try setting a max-width on the TD.

<td style="max-width:150px;">

2.) You can try putting your text in a wrapping element (e.g. a span) and set constraints on it.

<td><span style="max-width:150px;">Hello World...</span></td>

Be aware though that older versions of IE don't support min/max-width.

Since IE doesn't support max-width natively you'll need to add a hack if you want to force it to. There's several ways to add a hack, this is just one.

On page load, for IE6 only, get the rendered width of the table (in pixels) then get 15% of that and apply that as the width to the first TD in that column (or TH if you have headers) again, in pixels.

Python: How to pip install opencv2 with specific version 2.4.9?

Below Python packages are to be downloaded and installed to their default locations.

1.1. Python-2.7.x.

1.2. Numpy.

1.3. Matplotlib (Matplotlib is optional, but recommended since we use it a lot in our tutorials).

Install all packages into their default locations. Python will be installed to C:/Python27/.

After installation, open Python IDLE. Enter import numpy and make sure Numpy is working fine.

Download latest OpenCV release from sourceforge site and double-click to extract it.

Goto opencv/build/python/2.7 folder.

Copy cv2.pyd to C:/Python27/lib/site-packeges.

Open Python IDLE and type following codes in Python terminal.

import cv2 print cv2.version If the results are printed out without any errors, congratulations !!! You have installed OpenCV-Python successfully.

NoClassDefFoundError on Maven dependency

I was able to work around it by running mvn install:install-file with -Dpackaging=class. Then adding entry to POM as described here:

Regex for parsing directory and filename

What about this?


Deterministic :


Strict :


How to test if a string contains one of the substrings in a list, in pandas?

You can use str.contains alone with a regex pattern using OR (|):


Or you could add the series to a dataframe then use str.contains:

df = pd.DataFrame(s)


0 cat
1 hat
2 dog
3 fog 

How to Concatenate Numbers and Strings to Format Numbers in T-SQL?

You need to CAST your numeric data to strings before you do string concatenation, so for example use CAST(@Actual_Dims_Lenght AS VARCHAR) instead of just @Actual_Dims_Lenght, &c.

How do I run a spring boot executable jar in a Production environment?

In a production environment you want your app to be started again on a machine restart etc, creating a /etc/init.d/ script and linking to the appropriate runlevel to start and stop it is the correct approach. Spring Boot will not extend to covering this as it is a operating system specific setup and the are tonnes of other options, do you want it running in a chroot jail, does it need to stop / start before some other software etc.

How to get all keys with their values in redis

check out my tool, rdd

rdd -v

will output you all keys with data

Parsing JSON objects for HTML table

I spent a lot of time developing various reports. So, now I have an idea - create a web framework for building web reports. I have started here:

Now it is an angular 4 module. You can pass your json data to TableLayoutComponent and get a HTML table as result. Table already has fixed header. Also you can fix some your columns by default or by click. More there, you can customize table properties like background-color, font-color, row-height etc.

If you are interested you can join me in this project and help.

Possible to iterate backwards through a foreach?

It is possible if you can change the collection code that implements IEnumerable or IEnumerable (e.g. your own implementation of IList).

Create an Iterator doing this job for you, for example like the following implementation through the IEnumerable interface (assuming 'items' is a List field in this sample):

public IEnumerator<TObject> GetEnumerator()
    for (var i = items.Count - 1; i >= 0; i--)
        yield return items[i];

IEnumerator IEnumerable.GetEnumerator()
    return GetEnumerator();

Because of this your List will iterate in reverse order through your list.

Just a hint: You should clearly state this special behaviour of your list within the documentation (even better by choosing a self-explaining class name like Stack or Queue, too).

Regex to replace multiple spaces with a single space

var str = "The      dog        has a long tail,      and it is RED!";
str = str.replace(/ {2,}/g,' ');

EDIT: If you wish to replace all kind of whitespace characters the most efficient way would be like that:

str = str.replace(/\s{2,}/g,' ');

Xcode couldn't find any provisioning profiles matching

I opened XCode -> Preferences -> Accounts and clicked on Download certificate. That fixed my problem

JavaScript Regular Expression Email Validation

I have been using this one....


It allows that + before @ ([email protected])

How can I clear event subscriptions in C#?

Remove all events, assume the event is an "Action" type:

Delegate[] dary = TermCheckScore.GetInvocationList();

if ( dary != null )
    foreach ( Delegate del in dary )
        TermCheckScore -= ( Action ) del;

find: missing argument to -exec

A -exec command must be terminated with a ; (so you usually need to type \; or ';' to avoid interpretion by the shell) or a +. The difference is that with ;, the command is called once per file, with +, it is called just as few times as possible (usually once, but there is a maximum length for a command line, so it might be split up) with all filenames. See this example:

$ cat /tmp/echoargs
echo $1 - $2 - $3
$ find /tmp/foo -exec /tmp/echoargs {} \;
/tmp/foo - -
/tmp/foo/one - -
/tmp/foo/two - -
$ find /tmp/foo -exec /tmp/echoargs {} +
/tmp/foo - /tmp/foo/one - /tmp/foo/two

Your command has two errors:

First, you use {};, but the ; must be a parameter of its own.

Second, the command ends at the &&. You specified “run find, and if that was successful, remove the file named {};.“. If you want to use shell stuff in the -exec command, you need to explicitly run it in a shell, such as -exec sh -c 'ffmpeg ... && rm'.

However you should not add the {} inside the bash command, it will produce problems when there are special characters. Instead, you can pass additional parameters to the shell after -c command_string (see man sh):

$ ls
$(echo damn.)
$ find * -exec sh -c 'echo "{}"' \;
$ find * -exec sh -c 'echo "$1"' - {} \;
$(echo damn.)

You see the $ thing is evaluated by the shell in the first example. Imagine there was a file called $(rm -rf /) :-)

(Side note: The - is not needed, but the first variable after the command is assigned to the variable $0, which is a special variable normally containing the name of the program being run and setting that to a parameter is a little unclean, though it won't cause any harm here probably, so we set that to just - and start with $1.)

So your command could be something like

find -exec bash -c 'ffmpeg -i "$1" -sameq "$1".mp3 && rm "$1".mp3' - {} \;

But there is a better way. find supports and and or, so you may do stuff like find -name foo -or -name bar. But that also works with -exec, which evaluates to true if the command exits successfully, and to false if not. See this example:

$ ls
false  true
$ find * -exec {} \; -and -print

It only runs the print if the command was successfully, which it did for true but not for false.

So you can use two exec statements chained with an -and, and it will only execute the latter if the former was run successfully.

Jenkins - Configure Jenkins to poll changes in SCM

That's an old question, I know. But, according to me, it is missing proper answer.

The actual / optimal workflow here would be to incorporate SVN's post-commit hook so it triggers Jenkins job after the actual commit is issued only, not in any other case. This way you avoid unneeded polls on your SCM system.

You may find the following links interesting:

In case of my setup in the corp's SVN server, I utilize the following (censored) script as a post-commit hook on the subversion server side:




MSG=$(svnlook pg --revprop $REPOS svn:log -r$REV)

echo post-commit $* >> $LOGFILE 2>&1

# trigger Jenkins job - xxx
svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -qP "branches/xxx/xxx/Source"
if test 0 -eq $? ; then
        echo $(date) - $REPOS - $REV: >> $LOGFILE
        svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -P "branches/xxx/xxx/Source" >> $LOGFILE 2>&1
        echo logmsg: $MSG >> $LOGFILE 2>&1
        echo curl -qs $JENK >> $LOGFILE 2>&1
        curl -qs $JENK >> $LOGFILE 2>&1
        echo -------- >> $LOGFILE

# trigger Jenkins job - xxxx
svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -qP "branches/xxx_TEST"
if test 0 -eq $? ; then
        echo $(date) - $REPOS - $REV: >> $LOGFILE
        svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -P "branches/xxx_TEST" >> $LOGFILE 2>&1
        echo logmsg: $MSG >> $LOGFILE 2>&1
        echo curl -qs $JENKtest >> $LOGFILE 2>&1
        curl -qs $JENKtest >> $LOGFILE 2>&1
        echo -------- >> $LOGFILE

exit 0

Structs data type in php?

A public class is one option, if you want something more encapsulated you can use an abstract/anonymous class combination. My favorite part is that autocomplete still works (for PhpStorm) for this but I don't have a public class sitting around.


final class MyParentClass
     * @return MyStruct[]
    public function getData(): array
        return array(
            $this->createMyObject("One", 1.0, new DateTime("now")),
            $this->createMyObject("Two", 2.0, new DateTime("tommorow"))

    private function createMyObject(string $description, float $magnitude, DateTime $timeStamp): MyStruct
        return new class(func_get_args()) extends MyStruct {
            protected function __construct(array $args)
                $this->description = $args[0];
                $this->magnitude = $args[1];
                $this->timeStamp = $args[2];

abstract class MyStruct
    public string $description;
    public float $magnitude;
    public DateTime $timeStamp;

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled

It seems to me that your Hibernate libraries are not found (NoClassDefFoundError: org/hibernate/boot/archive/scan/spi/ScanEnvironment as you can see above).

Try checking to see if Hibernate core is put in as dependency:


How to convert Base64 String to javascript file object like as from file input form?

const url = 'data:image/png;base6....';
  .then(res => res.blob())
  .then(blob => {
    const file = new File([blob], "File name",{ type: "image/png" })

Base64 String -> Blob -> File.

How to add custom html attributes in JSX

uniqueId is custom attribute.

<a {...{ "uniqueId": `${item.File.UniqueId}` }}  href={item.File.ServerRelativeUrl} target='_blank'>{item.File.Name}</a>

How do I handle ImeOptions' done button click?

Thanks to chikka.anddev and Alex Cohn in Kotlin it is:

text.setOnEditorActionListener { v, actionId, event ->
    if (actionId == EditorInfo.IME_ACTION_DONE ||
        event?.action == KeyEvent.ACTION_DOWN && event.keyCode == KeyEvent.KEYCODE_ENTER) {
    } else {

Here I check for Enter key, because it returns EditorInfo.IME_NULL instead of IME_ACTION_DONE.

See also Android imeOptions="actionDone" not working. Add android:singleLine="true" in the EditText.

Fixing broken UTF-8 encoding

If you utf8_encode() on a string that is already UTF-8 then it looks garbled when it is encoded multiple times.

I made a function toUTF8() that converts strings into UTF-8.

You don't need to specify what the encoding of your strings is. It can be Latin1 (iso 8859-1), Windows-1252 or UTF8, or a mix of these three.

I used this myself on a feed with mixed encodings in the same string.


$utf8_string = Encoding::toUTF8($mixed_string);

$latin1_string = Encoding::toLatin1($mixed_string);

My other function fixUTF8() fixes garbled UTF8 strings if they were encoded into UTF8 multiple times.


$utf8_string = Encoding::fixUTF8($garbled_utf8_string);


echo Encoding::fixUTF8("Fédération Camerounaise de Football");
echo Encoding::fixUTF8("Fédération Camerounaise de Football");
echo Encoding::fixUTF8("FÃÂédÃÂération Camerounaise de Football");
echo Encoding::fixUTF8("Fédération Camerounaise de Football");

will output:

Fédération Camerounaise de Football
Fédération Camerounaise de Football
Fédération Camerounaise de Football
Fédération Camerounaise de Football


store return value of a Python script in a bash script

In addition to what Tichodroma said, you might end up using this syntax:

outputString=$(python myPythonScript arg1 arg2 arg3)

CSS transition shorthand with multiple properties?

I made it work with this:

.element {
   transition: height 3s ease-out, width 5s ease-in;

python: how to send mail with TO, CC and BCC?

Email headers don't matter to the smtp server. Just add the CC and BCC recipients to the toaddrs when you send your email. For CC, add them to the CC header.

toaddr = '[email protected]'
cc = ['[email protected]','[email protected]']
bcc = ['[email protected]']
fromaddr = '[email protected]'
message_subject = "disturbance in sector 7"
message_text = "Three are dead in an attack in the sewers below sector 7."
message = "From: %s\r\n" % fromaddr
        + "To: %s\r\n" % toaddr
        + "CC: %s\r\n" % ",".join(cc)
        + "Subject: %s\r\n" % message_subject
        + "\r\n" 
        + message_text
toaddrs = [toaddr] + cc + bcc
server = smtplib.SMTP('')
server.sendmail(fromaddr, toaddrs, message)

Format decimal for percentage values?

Use the P format string. This will vary by culture:

String.Format("Value: {0:P2}.", 0.8526) // formats as 85.26 % (varies by culture)

PHP Email sending BCC

You were setting BCC but then overwriting the variable with the FROM

$to = "[email protected]";
     $subject .= "".$emailSubject."";
 $headers .= "Bcc: ".$emailList."\r\n";
 $headers .= "From: [email protected]\r\n" .
     "X-Mailer: php";
     $headers .= "MIME-Version: 1.0\r\n";
     $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
 $message = '<html><body>';

     if (mail($to, $subject, $message, $headers)) {
     $sent = "Your email was sent!";
     } else {
      $sent = ("Error sending email.");

How to get values from IGrouping

var groups = list.GroupBy(x => x.ID);

Can anybody suggest how to get the values (List) from an IGrouping<int, smth> in such a context?

"IGrouping<int, smth> group" is actually an IEnumerable with a key, so you either:

  • iterate on the group or
  • use group.ToList() to convert it to a List
foreach (IGrouping<int, smth> group in groups)
   var thisIsYourGroupKey = group.Key; 
   List<smth> list = group.ToList();     // or use directly group.foreach

Unable to start MySQL server

Keep dump/backup of all databases.This is not 100% reliable process. Manual backup: Go to datadir path (see in my.ini file) and copy all databases.sql files from data folder

This error will be thrown when unexpectedly MySql service is stopped or disabled and not able to restart in the Services.

First try restart PC and MySql Service couple of times ,if still getting same error then follow the steps.

Keep open the following wizards and folders:

  • C:\Program Files (x86)\MySQL\MySQL Server 5.5\bin

  • C:\Program Files (x86)\MySQL\MySQL Server 5.5

Services list ->select MySql Service.

  1. Go to installed folder MySql, double-click on instance config C:\Program Files (x86)\MySQL\MySQL Server 5.5\bin\MySqlInstanceConfig.exe

Then select remove instance and click on next to remove non-working MySql service instance. See in the Service list (refresh F5) where MySql service should not be found.

  1. Now go to C:\Program Files (x86)\MySQL\MySQL Server 5.5 open my.ini file check below

#Path to installation directory

basedir="C:/Program Files (x86)/MySQL/MySQL Server 5.5/"

#Path to data directory

datadir="C:/ProgramData/MySQL/MySQL Server 5.5/Data/"

  1. Choose data dir Go to "C:/ProgramData/MySQL/MySQL Server 5.5/Data/" It contains all tables data and log info, ib data, user.err, . Delete

    • log files,
    • ib data,
    • user.err,
    • files.

(why because to create new MySql instance or when reconfiguring MySql service by clicking on MySqlInstanceConfig.exe and selecting default configure, after enter choosing password and clicking on execute the wizard will try to create these log files or will try to append the text again to these log files and other files which will make the setup wizard as unresponding and finally end up with configuration not done).

  1. After deleted selected files from C:/ProgramData/MySQL/MySQL Server 5.5/Data/ go to C:\Program Files (x86)\MySQL\MySQL Server 5.5

Delete the selected files my.ini and and other .bak format files which cause for the instance config.exe un-responding.

  1. C:\Program Files (x86)\MySQL\MySQL Server 5.5\bin\MySqlInstanceConfig.exe Select MySqlInstanceConfig.exe and double-click on it and select default configuration or do the regular set up that we do when installing MySql server first time.

gcc/g++: "No such file or directory"

Your compiler just tried to compile the file named Upon hitting line number line, the compiler finds:

#include "bar"


#include <bar>

The compiler then tries to find that file. For this, it uses a set of directories to look into, but within this set, there is no file bar. For an explanation of the difference between the versions of the include statement look here.

How to tell the compiler where to find it

g++ has an option -I. It lets you add include search paths to the command line. Imagine that your file bar is in a folder named frobnicate, relative to (assume you are compiling from the directory where is located):

g++ -Ifrobnicate

You can add more include-paths; each you give is relative to the current directory. Microsoft's compiler has a correlating option /I that works in the same way, or in Visual Studio, the folders can be set in the Property Pages of the Project, under Configuration Properties->C/C++->General->Additional Include Directories.

Now imagine you have multiple version of bar in different folders, given:

// A/bar
std::string which() { return "A/bar"; }

// B/bar
std::string which() { return "B/bar"; }

// C/bar
std::string which() { return "C/bar"; }

#include "bar"
#include <iostream>

int main () {
    std::cout << which() << std::endl;

The priority with #include "bar" is leftmost:

$ g++ -IA -IB -IC
$ ./a.out

As you see, when the compiler started looking through A/, B/ and C/, it stopped at the first or leftmost hit.

This is true of both forms, include <> and incude "".

Difference between #include <bar> and #include "bar"

Usually, the #include <xxx> makes it look into system folders first, the #include "xxx" makes it look into the current or custom folders first.


Imagine you have the following files in your project folder:



#include "list"

For this, your compiler will #include the file list in your project folder, because it currently compiles and there is that file list in the current folder.

But with

#include <list>

and then g++, your compiler will look into the system folders first, and because <list> is a standard header, it will #include the file named list that comes with your C++ platform as part of the standard library.

This is all a bit simplified, but should give you the basic idea.

Details on <>/""-priorities and -I

According to the gcc-documentation, the priority for include <> is, on a "normal Unix system", as follows:


For C++ programs, it will also look in /usr/include/c++/version, first. In the above, target is the canonical name of the system GCC was configured to compile code for; [...].

The documentation also states:

You can add to this list with the -Idir command line option. All the directories named by -I are searched, in left-to-right order, before the default directories. The only exception is when dir is already searched by default. In this case, the option is ignored and the search order for system directories remains unchanged.

To continue our #include<list> / #include"list" example (same code):

g++ -I.


int main () { std::list<int> l; }

and indeed, the -I. prioritizes the folder . over the system includes and we get a compiler error.

Regarding Java switch statements - using return and omitting breaks in each case

Assigning a value to a local variable and then returning that at the end is considered a good practice. Methods having multiple exits are harder to debug and can be difficult to read.

That said, thats the only plus point left to this paradigm. It was originated when only low-level procedural languages were around. And it made much more sense at that time.

While we are on the topic you must check this out. Its an interesting read.

CardView background color always white

You can use




How do you read scanf until EOF in C?

You need to check the return value against EOF, not against 1.

Note that in your example, you also used two different variable names, words and word, only declared words, and didn't declare its length, which should be 16 to fit the 15 characters read in plus a NUL character.

Check a radio button with javascript

I was able to select (check) a radio input button by using this Javascript code in Firefox 72, within a Web Extension option page to LOAD the value:

var reloadItem ='reload_mode');
reloadItem.then((response) => {
    if (response["reload_mode"] == "Periodic") {
    } else if (response["reload_mode"] == "Page Bottom") {
        document.querySelector('input[name=reload_mode][value="Page Bottom"]').click();
    } else {

Where the associated code to SAVE the value was:

reload_mode: document.querySelector('input[name=reload_mode]:checked').value

Given HTML like the following:

    <input type="radio" id="periodic" name="reload_mode" value="Periodic">
    <label for="periodic">Periodic</label><br>
    <input type="radio" id="bottom" name="reload_mode" value="Page Bottom">
    <label for="bottom">Page Bottom</label><br>
    <input type="radio" id="both" name="reload_mode" value="Both">
    <label for="both">Both</label></br></br>

How do I use SELECT GROUP BY in DataTable.Select(Expression)?

This solution sort by Col1 and group by Col2. Then extract value of Col2 and display it in a mbox.

var grouped = from DataRow dr in dt.Rows orderby dr["Col1"] group dr by dr["Col2"];
string x = "";
foreach (var k in grouped) x += (string)(k.ElementAt(0)["Col2"]) + Environment.NewLine;

Copy entire contents of a directory to another using php

With Symfony this is very easy to accomplish:

$fileSystem = new Symfony\Component\Filesystem\Filesystem();
$fileSystem->mirror($from, $to);


Optional args in MATLAB functions

There are a few different options on how to do this. The most basic is to use varargin, and then use nargin, size etc. to determine whether the optional arguments have been passed to the function.

% Function that takes two arguments, X & Y, followed by a variable 
% number of additional arguments
function varlist(X,Y,varargin)
   fprintf('Total number of inputs = %d\n',nargin);

   nVarargs = length(varargin);
   fprintf('Inputs in varargin(%d):\n',nVarargs)
   for k = 1:nVarargs
      fprintf('   %d\n', varargin{k})

A little more elegant looking solution is to use the inputParser class to define all the arguments expected by your function, both required and optional. inputParser also lets you perform type checking on all arguments.

Are one-line 'if'/'for'-statements good Python style?

an example of a language feature that isn't just removing line breaks, although still not convinced this is clearer than the more verbose version

a = 1 if x > 15 else 2


Just note to anyone trying the REGEXP to use "LIKE IN" functionality.

IN allows you to do:

field IN (

In REGEXP this won't work


It has to be in one line like this:

REGEXP 'val1$|val2$|val3$'

Math functions in AngularJS bindings

This is a hairy one to answer, because you didn't give the full context of what you're doing. The accepted answer will work, but in some cases will cause poor performance. That, and it's going to be harder to test.

If you're doing this as part of a static form, fine. The accepted answer will work, even if it isn't easy to test, and it's hinky.

If you want to be "Angular" about this:

You'll want to keep any "business logic" (i.e. logic that alters data to be displayed) out of your views. This is so you can unit test your logic, and so you don't end up tightly coupling your controller and your view. Theoretically, you should be able to point your controller at another view and use the same values from the scopes. (if that makes sense).

You'll also want to consider that any function calls inside of a binding (such as {{}} or ng-bind or ng-bind-html) will have to be evaluated on every digest, because angular has no way of knowing if the value has changed or not like it would with a property on the scope.

The "angular" way to do this would be to cache the value in a property on the scope on change using an ng-change event or even a $watch.

For example with a static form:

angular.controller('MainCtrl', function($scope, $window) {
   $scope.count = 0;
   $ = 1;

   $scope.updatePercentage = function () {
      $scope.percentage = $window.Math.round((100 * $scope.count) / $;
<form name="calcForm">
   <label>Count <input name="count" ng-model="count" 
                  type="number" min="0" required/></label><br/>
   <label>Total <input name="total" ng-model="total"
                  type="number" min="1" required/></label><br/>
   Percentage: {{percentage}}

And now you can test it!

describe('Testing percentage controller', function() {
  var $scope = null;
  var ctrl = null;

  //you need to indicate your module in a test

  beforeEach(inject(function($rootScope, $controller) {
    $scope = $rootScope.$new();

    ctrl = $controller('MainCtrl', {
      $scope: $scope

  it('should calculate percentages properly', function() {
    $scope.count = 1;
    $ = 1;

    $scope.count = 1;
    $ = 2;

    $scope.count = 497;
    $ = 10000;
    expect($scope.percentage).toEqual(5); //4.97% rounded up.

    $scope.count = 231;
    $ = 10000;
    expect($scope.percentage).toEqual(2); //2.31% rounded down.

How do I run Java .class files?

You have to put java in lower case and you have to add .class!

java HelloWorld2.class


You can use .desc() function in your query just like this

query = (model.Session.query(model.Entry)

This will order by amount in descending order or

query = session.query(

Use of desc function of SQLAlchemy

from sqlalchemy import desc
query = session.query(

For official docs please use the link or check below snippet

sqlalchemy.sql.expression.desc(column) Produce a descending ORDER BY clause element.


from sqlalchemy import desc

stmt = select([users_table]).order_by(desc(

will produce SQL as:

SELECT id, name FROM user ORDER BY name DESC

The desc() function is a standalone version of the ColumnElement.desc() method available on all SQL expressions, e.g.:

stmt = select([users_table]).order_by(

Parameters column – A ColumnElement (e.g. scalar SQL expression) with which to apply the desc() operation.

See also





How can I create objects while adding them into a vector?

You cannot insert a class into a vector, you can insert an object (provided that it is of the proper type or convertible) of a class though.

If the type Player has a default constructor, you can create a temporary object by doing Player(), and that should work for your case:


Get remote registry value

You can try using .net:

$Reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $computer1)
$RegKey= $Reg.OpenSubKey("SOFTWARE\\Veritas\\NetBackup\\CurrentVersion")
$NetbackupVersion1 = $RegKey.GetValue("PackageVersion")

execJs: 'Could not find a JavaScript runtime' but execjs AND therubyracer are in Gemfile

In your gemfile add:

gem 'execjs'
gem 'therubyracer', :platforms => :ruby

For more details: ExecJS and could not find a JavaScript runtime

go to character in vim

:goto 21490 will take you to the 21490th byte in the buffer.

Convert JSONObject to Map

The best way to convert it to HashMap<String, Object> is this:

HashMap<String, Object> result = new ObjectMapper().readValue(jsonString, new TypeReference<Map<String, Object>>(){}));

How to convert DateTime to a number with a precision greater than days in T-SQL?

If the purpose of this is to create a unique value from the date, here is what I would do

SET @ts = CAST(getdate() AS TIMESTAMP)

This gets the date and declares it as a simple timestamp

Is it possible to modify a string of char in C?

All are good answers explaining why you cannot modify string literals because they are placed in read-only memory. However, when push comes to shove, there is a way to do this. Check out this example:

#include <sys/mman.h>
#include <unistd.h>
#include <stddef.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

int take_me_back_to_DOS_times(const void *ptr, size_t len);

int main()
    const *data = "Bender is always sober.";
    printf("Before: %s\n", data);
    if (take_me_back_to_DOS_times(data, sizeof(data)) != 0)
        perror("Time machine appears to be broken!");
    memcpy((char *)data + 17, "drunk!", 6);
    printf("After: %s\n", data);

    return 0;

int take_me_back_to_DOS_times(const void *ptr, size_t len)
    int pagesize;
    unsigned long long pg_off;
    void *page;

    pagesize = sysconf(_SC_PAGE_SIZE);
    if (pagesize < 0)
        return -1;
    pg_off = (unsigned long long)ptr % (unsigned long long)pagesize;
    page = ((char *)ptr - pg_off);
    if (mprotect(page, len + pg_off, PROT_READ | PROT_WRITE | PROT_EXEC) == -1)
        return -1;
    return 0;

I have written this as part of my somewhat deeper thoughts on const-correctness, which you might find interesting (I hope :)).

Hope it helps. Good Luck!

How can I find out what version of git I'm running?

$ git --version
git version

git help and man git both hint at the available arguments you can pass to the command-line tool

How to force 'cp' to overwrite directory instead of creating another one inside?

Try to use this composed of two steps command:

rm -rf bar && cp -r foo bar

How can two strings be concatenated?

Given the matrix, tmp, that you created:

paste(tmp[1,], collapse = ",")

I assume there is some reason why you're creating a matrix using cbind, as opposed to simply:

tmp <- "GAD,AB"

In Python, what does dict.pop(a,b) mean?

The pop method of dicts (like, i.e. {'a':'aaa','b':'bbb','c':'ccc'}, here) takes two arguments -- see the docs

The second argument, default, is what pop returns if the first argument, key, is absent. (If you call pop with just one argument, key, it raises an exception if that key's absent).

In your example, print b.pop('a',{'b':'bbb'}), this is irrelevant because 'a' is a key in But if you repeat that line...:

print b.pop('a',{'b':'bbb'})
print b.pop('a',{'b':'bbb'})

you'll see it makes a difference: the first pop removes the 'a' key, so in the second pop the default argument is actually returned (since 'a' is now absent from

Error using eclipse for Android - No resource found that matches the given name

Project ---> Clean does the trick in most of the cases. It did in mine.

mysql_config not found when installing mysqldb python interface

For Alpine Linux:

$ apk add mariadb-dev mariadb-client mariadb-libs

MariaDB is a drop-in replacement for MySQL and became the new standard as of Alpine 3.2. See

How to uninstall a Windows Service when there is no executable for it left on the system?

found here

I just tried on windows XP, it worked

local computer: sc \\. delete [service-name]

  Deleting services in Windows Server 2003

  We can use sc.exe in the Windows Server 2003 to control services, create services and delete services. Since some people thought they must directly modify the registry to delete a service, I would like to share how to use sc.exe to delete a service without directly modifying the registry so that decreased the possibility for system failures.

  To delete a service: 

  Click “start“ - “run“, and then enter “cmd“ to open Microsoft Command Console.

  Enter command:

  sc servername delete servicename

  For instance, sc \\dc delete myservice

  (Note: In this example, dc is my Domain Controller Server name, which is not the local machine, myservice is the name of the service I want to delete on the DC server.)

  Below is the official help of all sc functions:

    SC is a command line program used for communicating with the
    NT Service Controller and services. 

Can I pass an array as arguments to a method with variable arguments in Java?

It's ok to pass an array - in fact it amounts to the same thing

String.format("%s %s", "hello", "world!");

is the same as

String.format("%s %s", new Object[] { "hello", "world!"});

It's just syntactic sugar - the compiler converts the first one into the second, since the underlying method is expecting an array for the vararg parameter.


How to properly express JPQL "join fetch" with "where" clause as JPA 2 CriteriaQuery?

I will show visually the problem, using the great example from James answer and adding the alternative solution.

When you do the follow query, without the FETCH:

Select e from Employee e 
join e.phones p 
where p.areaCode = '613'

You will have the follow results from Employee as you expected:

EmployeeId EmployeeName PhoneId PhoneAreaCode
1 James 5 613
1 James 6 416

But when you add the FETCH word on JOIN, this is what happens:

EmployeeId EmployeeName PhoneId PhoneAreaCode
1 James 5 613

The generated SQL is the same for the two queries, but the Hibernate removes on memory the 416 register when you use WHERE on the FETCH join.

So, to bring all phones and apply the WHERE correctly, you need to have two JOINs: one for the WHERE and another for the FETCH. Like:

Select e from Employee e 
join e.phones p 
join fetch e.phones      //no alias, to not commit the mistake
where p.areaCode = '613'

How do I find which process is leaking memory?

I suggest the use of htop, as a better alternative to top.

How to show Snackbar when Activity starts?

Just point to any View inside the Activity's XML. You can give an id to the root viewGroup, for example, and use:

protected void onCreate(Bundle savedInstanceState) {
   View parentLayout = findViewById(;
   Snackbar.make(parentLayout, "This is main activity", Snackbar.LENGTH_LONG) 
        .setAction("CLOSE", new View.OnClickListener() {
            public void onClick(View view) {

        .setActionTextColor(getResources().getColor(android.R.color.holo_red_light ))
   //Other stuff in OnCreate();

FileNotFoundException while getting the InputStream object from HttpURLConnection

Please change

con = (HttpURLConnection) new URL("http://localhost:8080/myapp/service/generate").openConnection();


con = (HttpURLConnection) new URL("http://YOUR_IP:8080/myapp/service/generate").openConnection();

Upgrading PHP on CentOS 6.5 (Final)

I managed to install php54w according to Simon's suggestion, but then my sites stopped working perhaps because of an incompatibility with php-mysql or some other module. Even frantically restoring the old situation was not amusing: for anyone in my own situation the sequence is:

sudo yum remove php54w
sudo yum remove php54w-common
sudo yum install php-common
sudo yum install php-mysql
sudo yum install php

It would be nice if someone submitted the full procedure to update all the php packet. That was my production server and my heart is still rapidly beating.

ProcessStartInfo hanging on "WaitForExit"? Why?

After reading all the posts here, i settled on the consolidated solution of Marko Avlijaš. However, it did not solve all of my issues.

In our environment we have a Windows Service which is scheduled to run hundreds of different .bat .cmd .exe,... etc. files which have accumulated over the years and were written by many different people and in different styles. We have no control over the writing of the programs & scripts, we are just responsible for scheduling, running, and reporting on success/failure.

So i tried pretty much all of the suggestions here with different levels of success. Marko's answer was almost perfect, but when run as a service, it didnt always capture stdout. I never got to the bottom of why not.

The only solution we found that works in ALL our cases is this :

Can you split a stream into two streams?

not exactly, but you may be able to accomplish what you need by invoking Collectors.groupingBy(). you create a new Collection, and can then instantiate streams on that new collection.

How to check if an array is empty?

you may use yourArray.length to findout number of elements in an array.

Make sure yourArray is not null before doing yourArray.length, otherwise you will end up with NullPointerException.

Configure Log4net to write to multiple files

These answers were helpful, but I wanted to share my answer with both the app.config part and the c# code part, so there is less guessing for the next person.

  <appender name="SomeName" type="log4net.Appender.RollingFileAppender">
    <file value="c:/Console.txt" />
    <appendToFile value="true" />
    <rollingStyle value="Composite" />
    <datePattern value="yyyyMMdd" />
    <maxSizeRollBackups value="10" />
    <maximumFileSize value="1MB" />
  <appender name="Summary" type="log4net.Appender.FileAppender">
    <file value="SummaryFile.log" />
    <appendToFile value="true" />
    <level value="ALL" />
    <appender-ref ref="SomeName" />
  <logger additivity="false" name="Summary">
    <level value="DEBUG"/>
    <appender-ref ref="Summary" />

Then in code:

ILog Log = LogManager.GetLogger("SomeName");
ILog SummaryLog = LogManager.GetLogger("Summary");

Here c:/Console.txt will contain "Processing" ... and \SummaryFile.log will contain "Processing2"

Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details

In my case I got the error simply because I had changed the Listen 80 to listen 443 in the file


Since I had installed mod_ssl using the yum commands

yum -y install mod_ssl  

there was a duplicate listen 443 directive in the file ssl.conf created during mod_ssl installation.

You can verify this if you have duplicate listen 80 or 443 by running the below command in linux centos (My linux)

grep  '443' /etc/httpd/conf.d/*

below is sample output

/etc/httpd/conf.d/ssl.conf:Listen 443 https
/etc/httpd/conf.d/ssl.conf:<VirtualHost _default_:443>

Simply reverting the listen 443 in httd.conf to listen 80 fixed my issue.

How to make a JSON call to a url?

You make a bog standard HTTP GET Request. You get a bog standard HTTP Response with an application/json content type and a JSON document as the body. You then parse this.

Since you have tagged this 'JavaScript' (I assume you mean "from a web page in a browser"), and I assume this is a third party service, you're stuck. You can't fetch data from remote URI in JavaScript unless explicit workarounds (such as JSONP) are put in place.

Oh wait, reading the documentation you linked to - JSONP is available, but you must say 'js' not 'json' and specify a callback: format=js&callback=foo

Then you can just define the callback function:

function foo(myData) { 
    // do stuff with myData

And then load the data:

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = theUrlForTheApi;

How can I make a list of lists in R?

The example creates a list of named lists in a loop.

  MyList <- list()
  for (aName in c("name1", "name2")){
    MyList[[aName]] <- list(aName)

To add another list named "name3" do write:

  MyList$name3 <- list(1, 2, 3)

How to perform case-insensitive sorting in JavaScript?

This may help if you have struggled to understand:

var array = ["sort", "Me", "alphabetically", "But", "Ignore", "case"];
console.log('Unordered array ---', array, '------------');

array.sort(function(a,b) {
    a = a.toLowerCase();
    b = b.toLowerCase();
    console.log("Compare '" + a + "' and '" + b + "'");

    if( a == b) {
        console.log('Comparison result, 0 --- leave as is ');
        return 0;
    if( a > b) {
        console.log('Comparison result, 1 --- move '+b+' to before '+a+' ');
        return 1;
    console.log('Comparison result, -1 --- move '+a+' to before '+b+' ');
    return -1;


console.log('Ordered array ---', array, '------------');

// return logic

If compareFunction(a, b) is less than 0, sort a to a lower index than b, i.e. a comes first.
If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.
If compareFunction(a, b) is greater than 0, sort b to a lower index than a.

Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries

If you are using foreignkey then you have to use "on_delete=models.CASCADE" as it will eliminate the complexity developed after deleting the original element from the parent table. As simple as that.

categorie = models.ForeignKey('Categorie', on_delete=models.CASCADE)

jQuery click function doesn't work after ajax call?

I tested a simple solution that works for me! My javascript was in a js separate file. What I did is that I placed the javascript for the new element into the html that was loaded with ajax, and it works fine for me! This is for those having big files of javascript!!

indexOf and lastIndexOf in PHP?

// sample array
$fruits3 = [

// Let's say we are looking for the item "ascorbic", in the above array

//a PHP function matching indexOf() from JS
echo(array_search("ascorbic", $fruits3, true)); //returns "2"

// a PHP function matching lastIndexOf() from JS world
function lastIndexOf($needle, $arr)
    return array_search($needle, array_reverse($arr, true), true);

echo(lastIndexOf("ascorbic", $fruits3)); //returns "4"

// so these (above) are the two ways to run a function similar to indexOf and lastIndexOf()

Disable text input history

<input type="text" autocomplete="off" />

How to set Android camera orientation properly?

From other member and my problem:

Camera Rotation issue depend on different Devices and certain Version.

Version 1.6: to fix the Rotation Issue, and it is good for most of devices

if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
            p.set("orientation", "portrait");
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
            p.set("orientation", "landscape");          
            p.set("rotation", 90);

Version 2.1: depend on kind of devices, for example, Cannt fix the issue with XPeria X10, but it is good for X8, and Mini

Camera.Parameters parameters = camera.getParameters();
parameters.set("orientation", "portrait");

Version 2.2: not for all devices


How to prevent a background process from being stopped after closing SSH client in Linux

daemonize? nohup? SCREEN? (tmux ftw, screen is junk ;-)

Just do what every other app has done since the beginning -- double fork.

# ((exec sleep 30)&)
# grep PPid /proc/`pgrep sleep`/status
PPid:   1
# jobs
# disown
bash: disown: current: no such job

Bang! Done :-) I've used this countless times on all types of apps and many old machines. You can combine with redirects and whatnot to open a private channel between you and the process.

Create as



run_in_coproc () {
    echo "coproc[$1] -> main"
    read -r; echo $REPLY

# dynamic-coprocess-generator. nice.
_coproc () {
    local i o e n=${1//[^A-Za-z0-9_]}; shift
    exec {i}<> <(:) {o}<> >(:) {e}<> >(:)
. /dev/stdin <<COPROC "${@}"
    (("\$@")&) <&$i >&$o 2>&$e
    $n=( $o $i $e )

# pi-rads-of-awesome?
for x in {0..5}; do
    _coproc COPROC$x run_in_coproc $x
    declare -p COPROC$x

for x in COPROC{0..5}; do
. /dev/stdin <<RUN
    read -r -u \${$x[0]}; echo \$REPLY
    echo "$x <- main" >&\${$x[1]}
    read -r -u \${$x[0]}; echo \$REPLY

and then

# ./ 
declare -a COPROC0='([0]="21" [1]="16" [2]="23")'
declare -a COPROC1='([0]="24" [1]="19" [2]="26")'
declare -a COPROC2='([0]="27" [1]="22" [2]="29")'
declare -a COPROC3='([0]="30" [1]="25" [2]="32")'
declare -a COPROC4='([0]="33" [1]="28" [2]="35")'
declare -a COPROC5='([0]="36" [1]="31" [2]="38")'
coproc[0] -> main
COPROC0 <- main
coproc[1] -> main
COPROC1 <- main
coproc[2] -> main
COPROC2 <- main
coproc[3] -> main
COPROC3 <- main
coproc[4] -> main
COPROC4 <- main
coproc[5] -> main
COPROC5 <- main

And there you go, spawn whatever. the <(:) opens an anonymous pipe via process substitution, which dies, but the pipe sticks around because you have a handle to it. I usually do a sleep 1 instead of : because its slightly racy, and I'd get a "file busy" error -- never happens if a real command is ran (eg, command true)

"heredoc sourcing":

. /dev/stdin <<EOF

This works on every single shell I've ever tried, including busybox/etc (initramfs). I've never seen it done before, I independently discovered it while prodding, who knew source could accept args? But it often serves as a much more manageable form of eval, if there is such a thing.

SQL Statement with multiple SETs and WHEREs

Use a query terminator string and set this in the options of your SQL client application. I use ; as the query terminator.

Your SQL would look like this;

UPDATE table SET ID = 111111259 WHERE ID = 2555;
UPDATE table SET ID = 111111261 WHERE ID = 2724;
UPDATE table SET ID = 111111263 WHERE ID = 2021;
UPDATE table SET ID = 111111264 WHERE ID = 2017;

This will allow you to do a Ctrl + A and run all the lines at once.

The string terminator tells the SQL client that the update statement is finished and to go to the next line and process the next statement.

Hope that helps

How can I get the full/absolute URL (with domain) in Django?

As mentioned in other answers, request.build_absolute_uri() is perfect if you have access to request, and sites framework is great as long as different URLs point to different databases.

However, my use case was slightly different. My staging server and the production server access the same database, but get_current_site both returned the first site in the database. To resolve this, you have to use some kind of environment variable. You can either use 1) an environment variable (something like os.environ.get('SITE_URL', 'localhost:8000')) or 2) different SITE_IDs for different servers AND different

Hopefully someone will find this useful!

What is a loop invariant?

Invariant in this case means a condition that must be true at a certain point in every loop iteration.

In contract programming, an invariant is a condition that must be true (by contract) before and after any public method is called.

C++ auto keyword. Why is it magic?

The auto keyword specifies that the type of the variable that is being declared will be automatically deducted from its initializer. In case of functions, if their return type is auto then that will be evaluated by return type expression at runtime.

It can be very useful when we have to use the iterator. For e.g. for below code we can simply use the "auto" instead of writing the whole iterator syntax .

int main() 

// Initialize set 
set<int> s; 


// iterator pointing to 
// position where 2 is 
auto pos = s.find(3); 

// prints the set elements 
cout << "The set elements after 3 are: "; 
for (auto it = pos; it != s.end(); it++) 
    cout << *it << " "; 

return 0; 

This is how we can use "auto" keyword

How do I calculate the normal vector of a line segment?

m1 = (y2 - y1) / (x2 - x1)

if perpendicular two lines:

m1*m2 = -1


m2 = -1 / m1 //if (m1 == 0, then your line should have an equation like x = b)

y = m2*x + b //b is offset of new perpendicular line.. 

b is something if you want to pass it from a point you defined

How do I address unchecked cast warnings?

Here's one way I handle this when I override the equals() operation.

public abstract class Section<T extends Section> extends Element<Section<T>> {
    Object attr1;

    * Compare one section object to another.
    * @param obj the object being compared with this section object
    * @return true if this section and the other section are of the same
    * sub-class of section and their component fields are the same, false
    * otherwise
    public boolean equals(Object obj) {
        if (obj == null) {
            // this exists, but obj doesn't, so they can't be equal!
            return false;

        // prepare to cast...
        Section<?> other;

        if (getClass() != obj.getClass()) {
            // looks like we're comparing apples to oranges
            return false;
        } else {
            // it must be safe to make that cast!
            other = (Section<?>) obj;

        // and then I compare attributes between this and other
        return this.attr1.equals(other.attr1);

This seems to work in Java 8 (even compiled with -Xlint:unchecked)

How to override trait function and call it from the overridden function?

Another variation: Define two functions in the trait, a protected one that performs the actual task, and a public one which in turn calls the protected one.

This just saves classes from having to mess with the 'use' statement if they want to override the function, since they can still call the protected function internally.

trait A {
    protected function traitcalc($v) {
        return $v+1;

    function calc($v) {
        return $this->traitcalc($v);

class MyClass {
    use A;

    function calc($v) {
        return $this->traitcalc($v);

class MyOtherClass {
    use A;

print (new MyClass())->calc(2); // will print 4

print (new MyOtherClass())->calc(2); // will print 3

How do I set a program to launch at startup

Thanks to everyone for responding so fast. Joel, I used your option 2 and added a registry key to the "Run" folder of the current user. Here's the code I used for anyone else who's interested.

    using Microsoft.Win32;
    private void SetStartup()
        RegistryKey rk = Registry.CurrentUser.OpenSubKey
            ("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);

        if (chkStartUp.Checked)
            rk.SetValue(AppName, Application.ExecutablePath);


adb uninstall failed

I assume that you enable developer mode on your android device and you are connected to your device and you have shell access (adb shell).

Once this is done you can uninstall application with this command pm uninstall --user 0 <>. Where 0 is ID of main user in Android system. This way you don't need to root your device.

Here is an example how I did on my Huawei p10 lite device.

# gain shell access
$ adb shell

# check who you are
$ whoami

# obtain user id
$ id
uid=2000(shell) gid=2000(shell)

# list packages
$ pm list packages | grep google                                                                                                                                                

# uninstall gmail app
pm uninstall --user 0

How do I set response headers in Flask?

Use make_response of Flask something like

def home():
    resp = make_response("hello") #here you could use make_response(render_template(...)) too
    resp.headers['Access-Control-Allow-Origin'] = '*'
    return resp

From flask docs,


Sometimes it is necessary to set additional headers in a view. Because views do not have to return response objects but can return a value that is converted into a response object by Flask itself, it becomes tricky to add headers to it. This function can be called instead of using a return and you will get a response object which you can use to attach headers.

How can I uninstall Ruby on ubuntu?

Why you are removing old version of the ruby?

rvm install 2.4.2 // version of ruby u need to insatll rvm use 2.4.2 --default // set ruby version you want use by default

Using rvm you can install multiple ruby version in the system

Please follow below steps install ruby using rvm

sudo apt-get install libgdbm-dev libncurses5-dev automake libtool bison libffi-dev
gpg --keyserver hkp:// --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 
curl -sSL | bash -s stable 
source ~/.rvm/scripts/rvm
rvm install 2.4.2 
rvm use 2.4.2 --default 
ruby -v

The installation step will change for different Ubuntu version

For more info,

Javascript: convert 24-hour time-of-day string to 12-hour time with AM/PM and no timezone

Nothing built in, my solution would be as follows :

function tConvert (time) {
  // Check correct time format and split into components
  time = time.toString ().match (/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time];

  if (time.length > 1) { // If time format correct
    time = time.slice (1);  // Remove full string match value
    time[5] = +time[0] < 12 ? 'AM' : 'PM'; // Set AM/PM
    time[0] = +time[0] % 12 || 12; // Adjust hours
  return time.join (''); // return adjusted time or original string

tConvert ('18:00:00');

This function uses a regular expression to validate the time string and to split it into its component parts. Note also that the seconds in the time may optionally be omitted. If a valid time was presented, it is adjusted by adding the AM/PM indication and adjusting the hours.

The return value is the adjusted time if a valid time was presented or the original string.

Working example

(function() {_x000D_
  function tConvert(time) {_x000D_
    // Check correct time format and split into components_x000D_
    time = time.toString().match(/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time];_x000D_
    if (time.length > 1) { // If time format correct_x000D_
      time = time.slice(1); // Remove full string match value_x000D_
      time[5] = +time[0] < 12 ? 'AM' : 'PM'; // Set AM/PM_x000D_
      time[0] = +time[0] % 12 || 12; // Adjust hours_x000D_
    return time.join(''); // return adjusted time or original string_x000D_
  var tel = document.getElementById('tests');_x000D_
  tel.innerHTML = tel.innerHTML.split(/\r*\n|\n\r*|\r/).map(function(v) {_x000D_
    return v ? v + ' => "' + tConvert(v.trim()) + '"' : v;_x000D_
<h3>tConvert tests : </h3>_x000D_
<pre id="tests">_x000D_

CSS to make table 100% of max-width

I have a very well working solution for tables of max-width: 100%. Just use word-break: break-all; for the table cells (except heading cells) to break all long text into several lines:

<!DOCTYPE html>

table {
  max-width: 100%; 
table td {
  word-break: break-all;


<table border="1">
    <td>some text</td>


This will render like this (when the screen width is limited):

How can a Jenkins user authentication details be "passed" to a script which uses Jenkins API to create jobs?

If you want to write a script to automate creation of jobs using the Jenkins API, you can use one of the API clients to do that. A ruby client for Jenkins is available at

gem install jenkins_api_client

require "rubygems"
require "jenkins_api_client"

# Initialize the client by passing in the server information
# and credentials to communicate with the server
client =
  :server_ip => "",
  :username => "awesomeuser",
  :password => "awesomepassword"

# The following block will create 10 jobs in Jenkins
# test_job_0, test_job_1, test_job_2, ...
10.times do |num|
  client.job.create_freestyle(:name => "test_job_#{num}")

# The jobs in Jenkins can be listed using

The API client can be used to perform a lot of operations.

Converting string to integer

The function you need is CInt.

ie CInt(PrinterLabel)

See Type Conversion Functions (Visual Basic) on MSDN

Edit: Be aware that CInt and its relatives behave differently in and VBScript. For example, in, CInt casts to a 32-bit integer, but in VBScript, CInt casts to a 16-bit integer. Be on the lookout for potential overflows!

adb shell command to make Android package uninstall dialog appear

In my case, I do an adb shell pm list packages to see first what are the packages/apps installed in my Android device or emulator, then upon locating the desired package/app, I do an adb shell pm uninstall -k

Remove padding from columns in Bootstrap 3

Bootstrap 4 has a native class to do this : add the class .no-gutters to the parent .row

Android RatingBar change star colors

1) declare this xml




2) in style.xml

<style name="coloredRatingBarStyleSmall">
        <item name="indicator">false</item>
        <item name="type">small</item>


import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

public class CustomRatingBar extends View{

    private static final String TAG="ColoredRatingBar";
    private static final int NORMAL = 0;
    private static final int SMALL = 1;

    Bitmap[] drawables;
    Bitmap progressBackground;
    Context mContext;
    private int mNumStars =9;
    private float mRating =0;
    private boolean mIndicator;
    private float slidePosition;
    private int mType;

     * A callback that notifies clients when the rating has been changed. This
     * includes changes that were initiated by the user through a touch gesture
     * or arrow key/trackball as well as changes that were initiated
     * programmatically.
    public interface OnRatingBarChangeListener {

         * Notification that the rating has changed. Clients can use the
         * fromUser parameter to distinguish user-initiated changes from those
         * that occurred programmatically. This will not be called continuously
         * while the user is dragging, only when the user finalizes a rating by
         * lifting the touch.
         * @param ratingBar The RatingBar whose rating has changed.
         * @param rating The current rating. This will be in the range
         *            0..numStars.
         * @param fromUser True if the rating change was initiated by a user's
         *            touch gesture or arrow key/horizontal trackbell movement.
        void onRatingChanged(CustomRatingBar ratingBar, float rating, boolean fromUser);


    private OnRatingBarChangeListener mOnRatingBarChangeListener;

    public CustomRatingBar(Context context) {
        this(context, null);
    public CustomRatingBar(Context context, AttributeSet attrs) {
        this(context, attrs,0);//R.attr.coloredRatingBarStyle

    public CustomRatingBar(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomRatingBar,defStyle, 0);
        final boolean indicator = a.getBoolean(R.styleable.CustomRatingBar_indicator, false);
        final float rating = a.getFloat(R.styleable.CustomRatingBar_setrating, -1);
        final int type = a.getInt(R.styleable.CustomRatingBar_type, 0);


    public int getType() {
        return mType;

    public void setType(int type) {
        this.mType = type;

    private void init(Context context) {
        mContext = context;
        Resources res = getResources();
            drawables = new Bitmap[]{BitmapFactory.decodeResource(res, R.drawable.rating_inactive),BitmapFactory.decodeResource(res, R.drawable.rating_active)};
            progressBackground = BitmapFactory.decodeResource(res, R.drawable.rating_inactive);
            drawables = new Bitmap[]{BitmapFactory.decodeResource(res, R.drawable.rating_inactive),BitmapFactory.decodeResource(res, R.drawable.rating_active)};
            progressBackground = BitmapFactory.decodeResource(res, R.drawable.rating_inactive);


    protected void onDraw(Canvas canvas) {
        //draw empty stars bg
        for(int i=0;i< mNumStars;i++){


    private void drawStar(Canvas canvas, int position) {
        float fraction = mRating -(position);
        Bitmap ratedStar1 = getRatedStar();
        Paint paint=getPaint(position);
        int division=getSize();
        Bitmap ratedStar=null;
        Bitmap emptyStar=null;
        ratedStar=Bitmap.createScaledBitmap(ratedStar1, division, division, false);
        emptyStar=Bitmap.createScaledBitmap(progressBackground, division, division, false);
        if((position)< mRating){
           canvas.drawBitmap(ratedStar,(position* division),0,paint);

        } else{



    private int getSize(){
        return (getWidth()/mNumStars);

    private Bitmap getRatedStar() {

            return drawables[0];
            return drawables[1];

    private Paint getPaint(int position){
        int value=(255*(position+1))/mNumStars;
        String hexString=Integer.toHexString(value).equals("0")?"00":Integer.toHexString(value);
        String hexvalue="#"+hexString+"000000";//FEE98E
        //Log.e("TAG", position+"/"+value+"/"+hexvalue);

        Paint paint=new Paint();


        return paint;

    public int getNumStars() {
        return mNumStars;

    public void setNumStars(int numStars) {
        this.mNumStars = numStars;

    public float getRating() {
        return mRating;

    public void setRating(float rating) {

    void setRating(float rating,boolean fromUser) {
            this.mRating = mNumStars;
        this.mRating = rating;

    public boolean isIndicator() {
        return mIndicator;

    public void setIndicator(boolean indicator) {
        this.mIndicator = indicator;

    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (progressBackground != null) {

            final int width = progressBackground.getWidth() * mNumStars;
            final int height = progressBackground.getHeight();

            int widthSize = MeasureSpec.getSize(widthMeasureSpec);
            Bitmap emptyStar=Bitmap.createScaledBitmap(progressBackground, widthSize/mNumStars, widthSize/mNumStars, false);
            int heightSize = emptyStar.getHeight();

            setMeasuredDimension(resolveSizeAndState(widthSize, widthMeasureSpec, 0),
                    resolveSizeAndState(heightSize, heightMeasureSpec, 0));
              int desiredWidth = 100;
            int desiredHeight = 50;

            int widthMode = MeasureSpec.getMode(widthMeasureSpec);
            int widthSize = MeasureSpec.getSize(widthMeasureSpec);
            int heightMode = MeasureSpec.getMode(heightMeasureSpec);
            int heightSize = MeasureSpec.getSize(heightMeasureSpec);

            int width;
            int height;

            //Measure Width
            if (widthMode == MeasureSpec.EXACTLY) {
                //Must be this size
                width = widthSize;
            } else if (widthMode == MeasureSpec.AT_MOST) {
                //Can't be bigger than...
                width = Math.min(desiredWidth, widthSize);
            } else {
                //Be whatever you want
                width = desiredWidth;

            //Measure Height
            if (heightMode == MeasureSpec.EXACTLY) {
                //Must be this size
                height = heightSize;
            } else if (heightMode == MeasureSpec.AT_MOST) {
                //Can't be bigger than...
                height = Math.min(desiredHeight, heightSize);
            } else {
                //Be whatever you want
                height = desiredHeight;

            //MUST CALL THIS
          setMeasuredDimension(resolveSizeAndState(width, widthMeasureSpec, 0),resolveSizeAndState(height, heightMeasureSpec, 0));

    public boolean onTouchEvent(MotionEvent event) {
            return false;

        int action = event.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_MOVE:
            case MotionEvent.ACTION_UP:
                slidePosition = getRelativePosition(event.getX());

                int newRating = (int)(slidePosition>0?slidePosition+1:0) ;

             //   Log.e("TAG", ""+newRating);
                if (newRating != mRating) {
            case MotionEvent.ACTION_CANCEL:

        return true;

    private float getRelativePosition(float x) {
        Bitmap emptyStar=Bitmap.createScaledBitmap(progressBackground, getWidth()/mNumStars, getWidth()/mNumStars, false);
        int widthSize = emptyStar.getWidth();
      //  Log.e("TAG", widthSize+"/"+x);
         float position = x / widthSize;
       position = Math.max(position, 0);
       return Math.min(position, mNumStars);

     * Sets the listener to be called when the rating changes.
     * @param listener The listener.
    public void setOnRatingBarChangeListener(OnRatingBarChangeListener listener) {
        mOnRatingBarChangeListener = listener;

     * @return The listener (may be null) that is listening for rating change
     *         events.
    public OnRatingBarChangeListener getOnRatingBarChangeListener() {
        return mOnRatingBarChangeListener;

    void dispatchRatingChange(boolean fromUser) {
        if (mOnRatingBarChangeListener != null) {
            mOnRatingBarChangeListener.onRatingChanged(this, getRating(),

5) then in calling activity---

CustomRatingBar coloredRatingBar5=(CustomRatingBar)findViewById(;
        coloredRatingBar5.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {

            public void onRatingChanged(CustomRatingBar ratingBar, float rating,boolean fromUser) {
                // TODO Auto-generated method stub
                Log.e("RATING", ""+rating);


6) rating active---take any image with dark color coz it will be used as color transparency for different rating

rating_inactive--take any image of same size of above image with light will used when no rating is selected

Remove background drawable programmatically in Android

Try this

RelativeLayout relative = (RelativeLayout) findViewById(;

Check the setBackground functions in the RelativeLayout documentation

What is the correct way to declare a boolean variable in Java?

Not only there is no need to declare it as false first, I would add few other improvements:

  • use boolean instead of Boolean (which can also be null for no reason)

  • assign during declaration:

    boolean isMatch = email1.equals(email2);
  • ...and use final keyword if you can:

    final boolean isMatch = email1.equals(email2);

Last but not least:

if (isMatch == true)

can be expressed as:

if (isMatch)

which renders the isMatch flag not that useful, inlining it might not hurt readability. I suggest looking for some better courses/tutorials out there...

Communicating between a fragment and an activity - best practices

There are severals ways to communicate between activities, fragments, services etc. The obvious one is to communicate using interfaces. However, it is not a productive way to communicate. You have to implement the listeners etc.

My suggestion is to use an event bus. Event bus is a publish/subscribe pattern implementation.

You can subscribe to events in your activity and then you can post that events in your fragments etc.

Here on my blog post you can find more detail about this pattern and also an example project to show the usage.

JavaScript/jQuery - How to check if a string contain specific words

You're looking for the indexOf function:

if (str.indexOf("are") >= 0){//Do stuff}

Is there any 'out-of-the-box' 2D/3D plotting library for C++?

MathGL have many plot types, C/Fortran interface and basic data analysis

how to install gcc on windows 7 machine?

EDIT Since not so recently by now, MinGW-w64 has "absorbed" one of the toolchain building projects. The downloads can be found here. The installer should work, and allow you to pick a version that you need.

Note the Qt SDK comes with the same toolchain. So if you are developing in Qt and using the SDK, just use the toolchain it comes with.

Another alternative that has up to date toolchains comes from... harhar... a Microsoft developer, none other than STL (Stephan T. Lavavej, isn't that a spot-on name for the maintainer of MSVC++ Standard Library!). You can find it here. It includes Boost.

Another option which is highly useful if you care for prebuilt dependencies is MSYS2, which provides a Unix shell (a Cygwin fork modified to work better with Windows pathnames and such), also provides a GCC. It usually lags a bit behind, but that is compensated for by its good package management system and stability. They also provide a functional Clang with libc++ if you care for such thing.

I leave the below for reference, but I strongly suggest against using, due to limitations detailed below. TDM-GCC (the MinGW-w64 version) provides some hacks that you may find useful in your specific situation, although I recommend using vanilla GCC at all times for maximum compatibility.

GCC for Windows is provided by two projects currently. They both provide a very own implementation of the Windows SDK (headers and libraries) which is necessary because GCC does not work with Visual Studio files.

  1. The older, which @Mat already pointed you to. They provide only a 32-bit compiler. See here for the downloads you need:

    • Binutils is the linker and resource compiler etc.
    • GCC is the compiler, and is split in core and language packages
    • GDB is the debugger.
    • runtime library is required only for
    • You might need to download mingw32-make seperately.
    • For support, you can try (don't expect friendly replies) [email protected]

    Alternatively, download mingw-get and use that.

  2. The newer mingw-w64, which as the name predicts, also provides a 64-bit variant, and in the future hopefully some ARM support. I use it and built toolchains with their CRT. Personal and auto builds are found under "Toolchains targetting Win32/64" here. They also provide Linux to Windows cross-compilers. I suggest you try a personal build first, they are more complete. Try mine (rubenvb) for GCC 4.6 to 4.8, or use sezero's for GCC 4.4 and 4.5. Both of us provide 32-bit and 64-bit native toolchains. These packages include everything listed above. I currently recommend the "MinGW-Builds" builds, as these are currently sanctioned as "official builds", and come with an installer (see above).

    For support, send an email to [email protected] or post on the forum via

Both projects have their files listed on sourceforge, and all you have to do is either run the installer (in case of or download a suitable zipped package and extract it (in the case of mingw-w64).

There are a lot of "non-official" toolchain builders, one of the most popular is TDM-GCC. They may use patches that break binary compatibility with official/unpatched toolchains, so be careful using them. It's best to use the official releases.

how to set default method argument values?

You can accomplish this via method overloading.

public int doSomething(int arg1, int arg2)
        return 0;

public int doSomething()
        return doSomething(defaultValue0, defaultValue1);

By creating this parameterless method you are allowing the user to call the parameterfull method with the default arguments you supply within the implementation of the parameterless method. This is known as overloading the method.

Pandas Merge - How to avoid duplicating columns

I use the suffixes option in .merge():

dfNew = df.merge(df2, left_index=True, right_index=True,
                 how='outer', suffixes=('', '_y'))
dfNew.drop(dfNew.filter(regex='_y$').columns.tolist(),axis=1, inplace=True)

Thanks @ijoseph

How do I clone into a non-empty directory?

Maybe I misunderstood your question, but wouldn't it be simpler if you copy/move the files from A to the git repo B and add the needed ones with git add?

UPDATE: From the git doc:

Cloning into an existing directory is only allowed if the directory is empty.


Ruby on Rails: Clear a cached page

This line in development.rb ensures that caching is not happening.

config.action_controller.perform_caching             = false

You can clear the Rails cache with


That said - I am not convinced this is a caching issue. Are you making changes to the page and not seeing them reflected? You aren't perhaps looking at the live version of that page? I have done that once (blush).


You can call that command from in the console. Are you sure you are running the application in development?

The only alternative is that the page that you are trying to render isn't the page that is being rendered.

If you watch the server output you should be able to see the render command when the page is rendered similar to this:

Rendered shared_partials/_latest_featured_video (31.9ms)
Rendered shared_partials/_s_invite_friends (2.9ms)
Rendered layouts/_sidebar (2002.1ms)
Rendered layouts/_footer (2.8ms)
Rendered layouts/_busy_indicator (0.6ms)

Why is my JavaScript function sometimes "not defined"?

I had this function not being recognized as defined in latest Firefox for Linux, though Chromium was dealing fine with it.

What happened in my case was that I had a former SCRIPT block, before the block that defined the function with problem, stated in the following way:

<SCRIPT src="mycode.js"/>

(That is, without the closing tag.)

I had to redeclare this block in the following way.

<SCRIPT src="mycode.js"></SCRIPT>

And then what followed worked fine... weird huh?

sql: check if entry in table A exists in table B

If you are set on using EXISTS you can use the below in SQL Server:

SELECT * FROM TableB as b
   SELECT * FROM TableA as a
   WHERE =

How to get the selected item of a combo box to a string variable in c#

Try this:

string selected = this.ComboBox.GetItemText(this.ComboBox.SelectedItem);

Trying to get Laravel 5 email to work

the problem will be solved by clearing cache

php artisan config:cache

static constructors in C++? I need to initialize private static objects

To get the equivalent of a static constructor, you need to write a separate ordinary class to hold the static data and then make a static instance of that ordinary class.

class StaticStuff
     std::vector<char> letters_;

         for (char c = 'a'; c <= 'z'; c++)

     // provide some way to get at letters_

class Elsewhere
    static StaticStuff staticStuff; // constructor runs once, single instance


How do I choose the URL for my Spring Boot webapp?

The server.contextPath or server.context-path works if

in pom.xml

  1. packing should be war not jar
  2. Add following dependencies

    <!-- Tomcat/TC server -->

    In eclipse, right click on project --> Run as --> Spring Boot App.

Javascript/DOM: How to remove all events of a DOM object?

May be the browser will do it for you if you do something like:

Copy the div and its attributes and insert it before the old one, then move the content from the old to the new and delete the old?

How to 'foreach' a column in a DataTable using C#?

In LINQ you could do something like:

foreach (var data in from DataRow row in dataTable.Rows
                     from DataColumn col in dataTable.Columns
                              row[col] != null
                          select row[col])
    // do something with data

Numpy, multiply array with scalar

You can multiply numpy arrays by scalars and it just works.

>>> import numpy as np
>>> np.array([1, 2, 3]) * 2
array([2, 4, 6])
>>> np.array([[1, 2, 3], [4, 5, 6]]) * 2
array([[ 2,  4,  6],
       [ 8, 10, 12]])

This is also a very fast and efficient operation. With your example:

>>> a_1 = np.array([1.0, 2.0, 3.0])
>>> a_2 = np.array([[1., 2.], [3., 4.]])
>>> b = 2.0
>>> a_1 * b
array([2., 4., 6.])
>>> a_2 * b
array([[2., 4.],
       [6., 8.]])

How to get Bitmap from an Uri?

  InputStream imageStream = null;
    try {
        imageStream = getContext().getContentResolver().openInputStream(uri);
    } catch (FileNotFoundException e) {
    final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);

Jquery selector input[type=text]')

$('input[type=text],select', '.sys');

for looping:

$('input[type=text],select', '.sys').each(function() {
   // code

Is Fortran easier to optimize than C for heavy calculations?

I think the key point in favor of Fortran is that it is a language slightly more suited for expressing vector- and array-based math. The pointer analysis issue pointed out above is real in practice, since portable code cannot really assume that you can tell a compiler something. There is ALWAYS an advantage to expression computaitons in a manner closer to how the domain looks. C does not really have arrays at all, if you look closely, just something that kind of behaves like it. Fortran has real arrawys. Which makes it easier to compile for certain types of algorithms especially for parallel machines.

Deep down in things like run-time system and calling conventions, C and modern Fortran are sufficiently similar that it is hard to see what would make a difference. Note that C here is really base C: C++ is a totally different issue with very different performance characteristics.

C library function to perform sort

There are several C sorting functions available in stdlib.h. You can do man 3 qsort on a unix machine to get a listing of them but they include:

  • heapsort
  • quicksort
  • mergesort

How can you flush a write using a file descriptor?

Have you tried disabling buffering?

setvbuf(fd, NULL, _IONBF, 0);

ImportError: No Module Named bs4 (BeautifulSoup)

The easiest is using easy_install.

easy_install bs4 

It will work if pip fails.

Prevent jQuery UI dialog from setting focus to first textbox

I had similar problem. On my page first input is text box with jQuery UI calendar. Second element is button. As date already have value, I set focus on button, but first add trigger for blur on text box. This solve problem in all browsers and probably in all version of jQuery. Tested in version 1.8.2.

<div style="padding-bottom: 30px; height: 40px; width: 100%;">
@using (Html.BeginForm("Statistics", "Admin", FormMethod.Post, new { id = "FormStatistics" }))
    <label style="float: left;">@Translation.StatisticsChooseDate</label>
    @Html.TextBoxFor(m => m.SelectDate, new { @class = "js-date-time",  @tabindex=1 })
    <input class="button gray-button button-large button-left-margin text-bold" style="position:relative; top:-5px;" type="submit" id="ButtonStatisticsSearchTrips" value="@Translation.StatisticsSearchTrips"  tabindex="2"/>

<script type="text/javascript">
$(document).ready(function () {        
    $("#SelectDate").blur(function () {


Check if string contains only whitespace

You want to use the isspace() method


Return true if there are only whitespace characters in the string and there is at least one character, false otherwise.

That's defined on every string object. Here it is an usage example for your specific use case:

if aStr and (not aStr.isspace()):
    print aStr

Abstract methods in Python

You can use six and abc to construct a class for both python2 and python3 efficiently as follows:

import six
import abc

class MyClass(object):

    def initialize(self, para=None):
        raise NotImplementedError

This is an awesome document of it.

How to add the text "ON" and "OFF" to toggle button

Square version of the toggle can be added by modifying the border radius

.switch {
  position: relative;
  display: inline-block;
  width: 90px;
  height: 36px;

.switch input {display:none;}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ca2222;
  -webkit-transition: .4s;
  transition: .4s;
  border-radius: 6px;

.slider:before {
  position: absolute;
  content: "";
  height: 34px;
  width: 32px;
  top: 1px;
  left: 1px;
  right: 1px;
  bottom: 1px;
  background-color: white;
  transition: 0.4s;
  border-radius: 6px;

input:checked + .slider {
  background-color: #2ab934;

input:focus + .slider {
  box-shadow: 0 0 1px #2196F3;

input:checked + .slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(55px);

.slider:after {
  color: white;
  display: block;
  position: absolute;
  transform: translate(-50%,-50%);
  top: 50%;
  left: 50%;
  font-size: 10px;
  font-family: Verdana, sans-serif;
input:checked + .slider:after {
<label class="switch">
  <input type="checkbox" id="togBtn">
  <div class="slider"></div>

enter image description here

LINQ - Left Join, Group By, and Count

Consider using a subquery:

from p in context.ParentTable 
let cCount =
  from c in context.ChildTable
  where p.ParentId == c.ChildParentId
  select c
select new { ParentId = p.Key, Count = cCount } ;

If the query types are connected by an association, this simplifies to:

from p in context.ParentTable 
let cCount = p.Children.Count()
select new { ParentId = p.Key, Count = cCount } ;

How to avoid HTTP error 429 (Too Many Requests) python

Another workaround would be to spoof your IP using some sort of Public VPN or Tor network. This would be assuming the rate-limiting on the server at IP level.

There is a brief blog post demonstrating a way to use tor along with urllib2:

How can I merge two commits into one if I already started rebase?

Assuming you were in your own topic branch. If you want to merge the last 2 commits into one and look like a hero, branch off the commit just before you made the last two commits (specified with the relative commit name HEAD~2).

git checkout -b temp_branch HEAD~2

Then squash commit the other branch in this new branch:

git merge branch_with_two_commits --squash

That will bring in the changes but not commit them. So just commit them and you're done.

git commit -m "my message"

Now you can merge this new topic branch back into your main branch.

What is the difference between "px", "dip", "dp" and "sp"?

I've come across a good article about designing Android apps UI for different screen resolutions, and I'd like to leave it here just for somebody searching in this area. Yes, I know that it's somehow described in Google docs (and mentioned in the posts above), I read that but it was not good for me (yeah, I may be too stupid)). It remained unclear for me how to design layouts capable to handle different screen size. I hate DP concept and so on, when I need to implement a "flexible" UI layout for different screens. (Hey iOS developers - yes, you're right it's Storyboard concept).

Android has not bad UI concept, but lacks iOS Storyboard features, unfortunately. Designing flexible UI in Android is not easy thing (at the best).

Here goes the article that helped me to understand what to do in Android to make layouts for different screen sizes:

JMSTUDIO Blog :- Decide Android App Screen Size

How to Design UI for Android Apps for Different Screen Size

To design an app UI for different screen sizes, our initial design has to meet a minimum required space for each screen size. Android defines a minimum size (in dp) for each generalized screen type. Here is an Android screen size guideline. Minimum Screen Size for Android in dp When we get the screen size in dp, it is not enough for us to design the Android app UI. For each screen size, we need to prepare graphics and bitmap images for each density. Here is an Android screen density guideline. Android Density Guideline (dpi)

For easy calculation, we can follow the 3:4:6:8 scaling ratio between the four generalized densities. If we create a 36×36 pixel picture for ldpi device, the rest densities pictures size will be 48×48 for mdpi, 72×72 for hdpi, and 96×96 for xhdpi.

How to Design Android Apps UI in Photoshop

Many designers have problems for designing Android app UI in photoshop or other pixel based graphic design tools because of density-independent unit, dp. Designers don’t know how to map dp to pixel. Google also doesn’t give a clear Android UI design guide for them, though they give a basic formula for dp and pixel translation.

As Android’s definition, 1pd equal to 1px under 160 dpi device (mdpi). So we want to design an Android app for xlarge Android device with mdpi density, we can define our UI size in pixel as 960 pixel in width and 720px in height; Follow the same mapping rule, we can get following Android App screen size UI design guideline:

Android App Screen Size in Pixel Guideline

ADDED: If you interested in "flexible" UI too, have a look at this library: An Android SDK that provides a new size unit - sdp (scalable dp). This size unit scales with the screen size (this also mentioned in an answer here, about SDP library)

ADDED2 Google has finally understood usefulness of iOS Storeboard UI concept, and here goes ConstraintLayout for Android world: Build a Responsive UI with ConstraintLayout

How to install a Mac application using Terminal

Probably not exactly your issue..

Do you have any spaces in your package path? You should wrap it up in double quotes to be safe, otherwise it can be taken as two separate arguments

sudo installer -store -pkg "/User/MyName/Desktop/helloWorld.pkg" -target /

What is "not assignable to parameter of type never" error in typescript?

All you have to do is define your result as a string array, like the following:

const result : string[] = [];

Without defining the array type, it by default will be never. So when you tried to add a string to it, it was a type mismatch, and so it threw the error you saw.

Switch between python 2.7 and python 3.5 on Mac OS X

OSX's Python binary (version 2) is located at /usr/bin/python

if you use which python it will tell you where the python command is being resolved to. Typically, what happens is third parties redefine things in /usr/local/bin (which takes precedence, by default over /usr/bin). To fix, you can either run /usr/bin/python directly to use 2.x or find the errant redefinition (probably in /usr/local/bin or somewhere else in your PATH)

Get local IP address

I also was struggling with obtaining the correct IP.

I tried a variety of the solutions here but none provided me the desired affect. Almost all of the conditional tests that was provided caused no address to be used.

This is what worked for me, hope it helps...

var firstAddress = (from address in NetworkInterface.GetAllNetworkInterfaces().Select(x => x.GetIPProperties()).SelectMany(x => x.UnicastAddresses).Select(x => x.Address)
                    where !IPAddress.IsLoopback(address) && address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork
                    select address).FirstOrDefault();


Where is SQL Server Management Studio 2012?

For separate modules (x86 and x64), if you want a customized installation without downloading loads of crap, see Servers Microsoft® SQL Server® 2012 Express.

Can you have multiline HTML5 placeholder text in a <textarea>?

If you're using AngularJS, you can simply use braces to place whatever you'd like in it: Here's a fiddle.

<textarea rows="6" cols="45" placeholder="{{'Address Line1\nAddress Line2\nCity State, Zip\nCountry'}}"></textarea>

How to recover just deleted rows in mysql?

I'm sorry, bu it's not posible, unless you made a backup file earlier.

EDIT: Actually it is possible, but it gets very tricky and you shouldn't think about it if data wasn't really, really important. You see: when data get's deleted from a computer it still remains in the same place on the disk, only its sectors are marked as empty. So data remains intact, except if it gets overwritten by new data. There are several programs designed for this purpose and there are companies who specialize in data recovery, though they are rather expensive.

Determine command line working directory when running node bin script

  • process.cwd() returns directory where command has been executed (not directory of the node package) if it's has not been changed by 'process.chdir' inside of application.
  • __filename returns absolute path to file where it is placed.
  • __dirname returns absolute path to directory of __filename.

If you need to load files from your module directory you need to use relative paths.


instead of

var lib  = path.join(path.dirname(fs.realpathSync(__filename)), '../lib');

require(lib + '/test');

It's always relative to file where it called from and don't depend on current work dir.

Convert Iterator to ArrayList

In Java 8, you can use the new forEachRemaining method that's been added to the Iterator interface:

List<Element> list = new ArrayList<>();

Javascript loading CSV file into an array

The original code works fine for reading and separating the csv file data but you need to change the data type from csv to text.

How to move text up using CSS when nothing is working

used the following snippet and it worked fine..

.smallText .bmv-disclaimer {
   height: 40px;

Uploading Files in without using the FileUpload server control

The Request.Files collection contains any files uploaded with your form, regardless of whether they came from a FileUpload control or a manually written <input type="file">.

So you can just write a plain old file input tag in the middle of your WebForm, and then read the file uploaded from the Request.Files collection.

Reading in a JSON File Using Swift

This worked for me with XCode 8.3.3

func fetchPersons(){

    if let pathURL = Bundle.main.url(forResource: "Person", withExtension: "json"){

        do {

            let jsonData = try Data(contentsOf: pathURL, options: .mappedIfSafe)

            let jsonResult = try JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) as! [String: Any]
            if let persons = jsonResult["person"] as? [Any]{


        }catch(let error){
            print (error.localizedDescription)

How to import RecyclerView for Android L-preview

If anyone still has this issue - you don't have to change compileSdkVersion, this just defeats the whole purpose of support libraries.

Instead, use these in your file:

compile ''
compile ''
compile ''`

What is the equivalent of Java's final in C#?

The final keyword has several usages in Java. It corresponds to both the sealed and readonly keywords in C#, depending on the context in which it is used.


To prevent subclassing (inheritance from the defined class):


public final class MyFinalClass {...}


public sealed class MyFinalClass {...}


Prevent overriding of a virtual method.


public class MyClass
    public final void myFinalMethod() {...}


public class MyClass : MyBaseClass
    public sealed override void MyFinalMethod() {...}

As Joachim Sauer points out, a notable difference between the two languages here is that Java by default marks all non-static methods as virtual, whereas C# marks them as sealed. Hence, you only need to use the sealed keyword in C# if you want to stop further overriding of a method that has been explicitly marked virtual in the base class.


To only allow a variable to be assigned once:


public final double pi = 3.14; // essentially a constant


public readonly double pi = 3.14; // essentially a constant

As a side note, the effect of the readonly keyword differs from that of the const keyword in that the readonly expression is evaluated at runtime rather than compile-time, hence allowing arbitrary expressions.

Check if an element contains a class in JavaScript?

Using the classList is also ideal


<div id="box" class="myClass"></div>


const element = document.querySelector("#box");


chrome undo the action of "prevent this page from creating additional dialogs"

open a new window or tab with the same link.. the PREVENT option lasts per session only..

How to make Excel VBA variables available to multiple macros?

You may consider declaring the variables with moudule level scope. Module-level variable is available to all of the procedures in that module, but it is not available to procedures in other modules

For details on Scope of variables refer this link

Please copy the below code into any module, save the workbook and then run the code.

Here is what code does

  • The sample subroutine sets the folder path & later the file path. Kindly set them accordingly before you run the code.

  • I have added a function IsWorkBookOpen to check if workbook is already then set the workbook variable the workbook name else open the workbook which will be assigned to workbook variable accordingly.

Dim wbA As Workbook
Dim wbB As Workbook

Sub MySubRoutine()
    Dim folderPath As String, fileNm1 As String, fileNm2 As String, filePath1 As String, filePath2 As String

    folderPath = ThisWorkbook.Path & "\"
    fileNm1 = "file1.xlsx"
    fileNm2 = "file2.xlsx"

    filePath1 = folderPath & fileNm1
    filePath2 = folderPath & fileNm2

    If IsWorkBookOpen(filePath1) Then
        Set wbA = Workbooks(fileNm1)
        Set wbA = Workbooks.Open(filePath1)
    End If

    If IsWorkBookOpen(filePath2) Then
        Set wbB = Workbooks.Open(fileNm2)
        Set wbB = Workbooks.Open(filePath2)
    End If

    ' your code here
End Sub

Function IsWorkBookOpen(FileName As String)
    Dim ff As Long, ErrNo As Long

    On Error Resume Next
    ff = FreeFile()
    Open FileName For Input Lock Read As #ff
    Close ff
    ErrNo = Err
    On Error GoTo 0

    Select Case ErrNo
    Case 0: IsWorkBookOpen = False
    Case 70: IsWorkBookOpen = True
    Case Else: Error ErrNo
    End Select
End Function

Using Prompt to select the file use below code.

Dim wbA As Workbook
Dim wbB As Workbook

Sub MySubRoutine()
    Dim folderPath As String, fileNm1 As String, fileNm2 As String, filePath1 As String, filePath2 As String

    Dim filePath As String
    cmdBrowse_Click filePath, 1

    filePath1 = filePath

    'reset the variable
    filePath = vbNullString

    cmdBrowse_Click filePath, 2
    filePath2 = filePath

   fileNm1 = GetFileName(filePath1, "\")
   fileNm2 = GetFileName(filePath2, "\")

    If IsWorkBookOpen(filePath1) Then
        Set wbA = Workbooks(fileNm1)
        Set wbA = Workbooks.Open(filePath1)
    End If

    If IsWorkBookOpen(filePath2) Then
        Set wbB = Workbooks.Open(fileNm2)
        Set wbB = Workbooks.Open(filePath2)
    End If

    ' your code here
End Sub

Function IsWorkBookOpen(FileName As String)
    Dim ff As Long, ErrNo As Long

    On Error Resume Next
    ff = FreeFile()
    Open FileName For Input Lock Read As #ff
    Close ff
    ErrNo = Err
    On Error GoTo 0

    Select Case ErrNo
    Case 0: IsWorkBookOpen = False
    Case 70: IsWorkBookOpen = True
    Case Else: Error ErrNo
    End Select
End Function

Private Sub cmdBrowse_Click(ByRef filePath As String, num As Integer)

    Dim fd As FileDialog
    Set fd = Application.FileDialog(msoFileDialogFilePicker)
    fd.AllowMultiSelect = False
    fd.Title = "Select workbook " & num
    fd.InitialView = msoFileDialogViewSmallIcons

    Dim FileChosen As Integer

    FileChosen = fd.Show

    fd.Filters.Add "Excel macros", "*.xlsx"

    fd.FilterIndex = 1

    If FileChosen <> -1 Then
        MsgBox "You chose cancel"
        filePath = ""
        filePath = fd.SelectedItems(1)
    End If

End Sub

Function GetFileName(fullName As String, pathSeparator As String) As String

    Dim i As Integer
    Dim iFNLenght As Integer
    iFNLenght = Len(fullName)

    For i = iFNLenght To 1 Step -1
        If Mid(fullName, i, 1) = pathSeparator Then Exit For

    GetFileName = Right(fullName, iFNLenght - i)

End Function

PL/SQL print out ref cursor returned by a stored procedure

If you want to print all the columns in your select clause you can go with the autoprint command.

CREATE OR REPLACE PROCEDURE sps_detail_dtest(v_refcur OUT sys_refcursor)
  OPEN v_refcur FOR 'select * from dummy_table';

SET autoprint on;

--calling the procedure
VAR vcur refcursor;

Hope this gives you an alternate solution