Programs & Examples On #Hoptoad

A html space is showing as %2520 instead of %20

The following code snippet resolved my issue. Thought this might be useful to others.

var strEnc = this.$.txtSearch.value.replace(/\s/g, "-");_x000D_
strEnc = strEnc.replace(/-/g, " ");

Rather using default encodeURIComponent my first line of code is converting all spaces into hyphens using regex pattern /\s\g and the following line just does the reverse, i.e. converts all hyphens back to spaces using another regex pattern /-/g. Here /g is actually responsible for finding all matching characters.

When I am sending this value to my Ajax call, it traverses as normal spaces or simply %20 and thus gets rid of double-encoding.

Can I have multiple background images using CSS?

CSS3 allows this sort of thing and it looks like this:

body {
    background-image: url(images/bgtop.png), url(images/bg.png);
    background-repeat: repeat-x, repeat;

The current versions of all the major browsers now support it, however if you need to support IE8 or below, then the best way you can work around it is to have extra divs:

    <div id="bgTopDiv">
        content here
    background-image: url(images/bg.png);
    background-image: url(images/bgTop.png);
    background-repeat: repeat-x;

Function not defined javascript

important: in this kind of error you should look for simple mistakes in most cases

besides syntax error, I should say once I had same problem and it was because of bad name I have chosen for function. I have never searched for the reason but I remember that I copied another function and change it to use. I add "1" after the name to changed the function name and I got this error.

When running UPDATE ... datetime = NOW(); will all rows updated have the same date/time?

The sqlite answer is

update TABLE set mydatetime = datetime('now');

in case someone else was looking for it.

Extend a java class from one file in another java file

You don't.

If you want to extend Person with Student, just do:

public class Student extends Person

And make sure, when you compile both classes, one can find the other one.

What IDE are you using?

Is it possible to set ENV variables for rails development environment in my code?


While the solution under "old answer" will work for general problems, this section is to answer your specific question after clarification from your comment.

You should be able to set environment variables exactly like you specify in your question. As an example, I have a Heroku app that uses HTTP basic authentication.

# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  before_filter :authenticate

  def authenticate
    authenticate_or_request_with_http_basic do |username, password|
      username == ENV['HTTP_USER'] && password == ENV['HTTP_PASS']

# config/initializers/dev_environment.rb
unless Rails.env.production?
  ENV['HTTP_USER'] = 'testuser'
  ENV['HTTP_PASS'] = 'testpass'

So in your case you would use

unless Rails.env.production?
  ENV['admin_password'] = "secret"

Don't forget to restart the server so the configuration is reloaded!

[Old Answer]

For app-wide configuration, you might consider a solution like the following:

Create a file config/application.yml with a hash of options you want to be able to access:

admin_password: something_secret
allow_registration: true
  app_id: application_id_here
  app_secret: application_secret_here
  api_key: api_key_here

Now, create the file config/initializers/app_config.rb and include the following:

require 'yaml'

yaml_data = YAML::load(, 'config', 'application.yml'))).result)

Now, anywhere in your application, you can access APP_CONFIG[:admin_password], along with all your other data. (Note that since the initializer includes, your YAML file can contain ERB markup.)

Get filename from file pointer

You can get the path via Example:

>>> f = open('foo/bar.txt')

You might need os.path.basename if you want only the file name:

>>> import os
>>> f = open('foo/bar.txt')
>>> os.path.basename(

File object docs (for Python 2) here.

Difference between array_map, array_walk and array_filter

From the documentation,

bool array_walk ( array &$array , callback $funcname [, mixed $userdata ] ) <-return bool

array_walk takes an array and a function F and modifies it by replacing every element x with F(x).

array array_map ( callback $callback , array $arr1 [, array $... ] )<-return array

array_map does the exact same thing except that instead of modifying in-place it will return a new array with the transformed elements.

array array_filter ( array $input [, callback $callback ] )<-return array

array_filter with function F, instead of transforming the elements, will remove any elements for which F(x) is not true

How to make jQuery UI nav menu horizontal?

To get a horizontal nav bar with vertical dropdowns, use a combination of a table and unordered lists.

The level 1 items are represented by table cells, subsequent levels are represented by unordered lists.

The positioning of the child menus was a problem. The default is to have them appear directly alongside, but when on a top level item, that was obscuring the subsequent items in the horizontal nav bar. Having them appear below was ok for a single dropdown menu, but if there was a second level beneath, then that 2nd level would obscure the rest of the first. The solution is to have the menu open below and somewhat to the right, see the "position" option in the menu invocation.

<style type="text/css">
  #trJMenu td { white-space: nowrap; width: auto; }
  #trJMenu li { white-space: nowrap; width: auto; }

<script language="javascript" type="text/javascript">
    $("#trJMenu").menu( { position: { my: "left top", at: "center bottom" } } );          

  <tr id='trJMenu'>
      <a href='#'>Timesheets</a>
        <li><a href='#'>Labour</a></li>
        <li><a href='#'>Chargeout Report</a></li>
      <a href='#'>Activity Management</a>
        <li><a href='#'>Activities</a></li>
        <li><a href='#'>Proposals</a></li>

The project description file (.project) for my project is missing

I am using Eclipse 3.5.1 on Ubuntu. After rebooting my machine my projects in PHP Explorer view were giving the warning that the .project file was missing. The problem was that the external directory where my projects are hosted was not mounted on reboot. So I did a mount -a from the command line and the Eclipse recognized the files.

Sublime Text 2 multiple line edit

I was facing the same problem on Linux, what I did was to select all the content (ctrl-A) and then press ctrl+shift+L, It gives you a cursor on each line and then you can add similar content to each column.

Also you can perform other operations like cut, copy and paste column wise.

PS :- If you want to select a rectangular set of data from text, you can also press shift and hold Right Mouse button and then select data in a rectangular fashion. Then press CTRL+SHIFT+L to get the cursor on each line.

How to output HTML from JSP <%! ... %> block?

All you need to do is pass the JspWriter object into your method as a parameter i.e.

void someOutput(JspWriter stream)

Then call it via:

<% someOutput(out) %>

The writer object is a local variable inside _jspService so you need to pass it into your utility method. The same would apply for all the other built in references (e.g. request, response, session).

A great way to see whats going on is to use Tomcat as your server and drill down into the 'work' directory for the '.java' file generated from your 'jsp' page. Alternatively in weblogic you can use the 'weblogic.jspc' page compiler to view the Java that will be generated when the page is requested.

Is there an equivalent of CSS max-width that works in HTML emails?

Bit late to the party, but this will get it done. I left the example at 600, as that is what most people will use:

Similar to Shay's example except this also includes max-width to work on the rest of the clients that do have support, as well as a second method to prevent the expansion (media query) which is needed for Outlook '11.

In the head:

  <style type="text/css">
    @media only screen and (min-width: 600px) { .maxW { width:600px !important; } }

In the body:

<!--[if (gte mso 9)|(IE)]><table width="600" align="center" cellpadding="0" cellspacing="0" border="0"><tr><td><![endif]-->
<div class="maxW" style="max-width:600px;">

<table width="100%" border="0" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF">
main content here

<!--[if (gte mso 9)|(IE)]></td></tr></table><![endif]-->

Here is another example of this in use: Responsive order confirmation emails for mobile devices?

How to split string using delimiter char using T-SQL?

You simply need to do a SUBSTR on the string in col3....

    Select col1, col2, REPLACE(substr(col3, instr(col3, 'Client Name'), 
    (instr(col3, '|', instr(col3, 'Client Name')  -
    instr(col3, 'Client Name'))
'Client Name = ',
    from Table01 

And yes, that is a bad DB design for the reasons stated in the original issue

How can I completely uninstall nodejs, npm and node in Ubuntu

Those who installed node.js via the package manager can just run:

sudo apt-get purge nodejs

Optionally if you have installed it by adding the official NodeSource repository as stated in Installing Node.js via package manager, do:

sudo rm /etc/apt/sources.list.d/nodesource.list

If you want to clean up npm cache as well:

rm -rf ~/.npm

It is bad practice to try to remove things manually, as it can mess up the package manager, and the operating system itself. This answer is completely safe to follow

Adding elements to an xml file in C#

I've used XDocument.Root.Add to add elements. Root returns XElement which has an Add function for additional XElements

Send file via cURL from form POST in PHP

Here is my solution, i have been reading a lot of post and they was really helpfull, finaly i build a code for small files, with cUrl and Php, that i think its really usefull.

public function postFile()

        $file_url = "test.txt";  //here is the file route, in this case is on same directory but you can set URL too like ""
        $eol = "\r\n"; //default line-break for mime type
        $BOUNDARY = md5(time()); //random boundaryid, is a separator for each param on my post curl function
        $BODY=""; //init my curl body
        $BODY.= '--'.$BOUNDARY. $eol; //start param header
        $BODY .= 'Content-Disposition: form-data; name="sometext"' . $eol . $eol; // last Content with 2 $eol, in this case is only 1 content.
        $BODY .= "Some Data" . $eol;//param data in this case is a simple post data and 1 $eol for the end of the data
        $BODY.= '--'.$BOUNDARY. $eol; // start 2nd param,
        $BODY.= 'Content-Disposition: form-data; name="somefile"; filename="test.txt"'. $eol ; //first Content data for post file, remember you only put 1 when you are going to add more Contents, and 2 on the last, to close the Content Instance
        $BODY.= 'Content-Type: application/octet-stream' . $eol; //Same before row
        $BODY.= 'Content-Transfer-Encoding: base64' . $eol . $eol; // we put the last Content and 2 $eol,
        $BODY.= chunk_split(base64_encode(file_get_contents($file_url))) . $eol; // we write the Base64 File Content and the $eol to finish the data,
        $BODY.= '--'.$BOUNDARY .'--' . $eol. $eol; // we close the param and the post width "--" and 2 $eol at the end of our boundary header.

        $ch = curl_init(); //init curl
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                         'X_PARAM_TOKEN : 71e2cb8b-42b7-4bf0-b2e8-53fbd2f578f9' //custom header for my api validation you can get it from $_SERVER["HTTP_X_PARAM_TOKEN"] variable
                         ,"Content-Type: multipart/form-data; boundary=".$BOUNDARY) //setting our mime type for make it work on $_FILE variable
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/1.0 (Windows NT 6.1; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0'); //setting our user agent
        curl_setopt($ch, CURLOPT_URL, ""); //setting our api post url
        curl_setopt($ch, CURLOPT_COOKIEJAR, $BOUNDARY.'.txt'); //saving cookies just in case we want
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); // call return content
        curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1); navigate the endpoint
        curl_setopt($ch, CURLOPT_POST, true); //set as post
        curl_setopt($ch, CURLOPT_POSTFIELDS, $BODY); // set our $BODY 

        $response = curl_exec($ch); // start curl navigation

     print_r($response); //print response


With this we shoud be get on the "" the following vars posted You can easly test with this script, and you should be recive this debugs on the function postFile() at the last row

print_r($response); //print response

public function getPostFile()

    echo "\n\n_SERVER\n";
    echo "<pre>";
    echo "/<pre>";
    echo "_POST\n";
    echo "<pre>";
    echo "/<pre>";
    echo "_FILES\n";
    echo "<pre>";
    echo "/<pre>";

Here you are it should be work good, could be better solutions but this works and is really helpfull to understand how the Boundary and multipart/from-data mime works on php and curl library,

My Best Reggards,

my apologies about my english but isnt my native language.

Python pandas: how to specify data types when reading an Excel file?

The read_excel() function has a converters argument, where you can apply functions to input in certain columns. You can use this to keep them as strings. Documentation:

Dict of functions for converting values in certain columns. Keys can either be integers or column labels, values are functions that take one input argument, the Excel cell content, and return the transformed content.

Example code:

pandas.read_excel(my_file, converters = {my_str_column: str})

How can you test if an object has a specific property?

I recently switch to set strict-mode -version 2.0 and my null tests failed.

I added a function:

#use in strict mode to validate property exists before using
function exists {
  try {
    if ($null -ne $obj[$prop]) {return $true}
    return $false
  } catch {
    return $false
  return $false

Now I code

if (exists $run main) { ...

rather than

if ($run.main -ne $null) { ...

and we are on our way. Seems to work on objects and hashtables

As an unintended benefit it is less typing.

How do I install g++ for Fedora?

I had the same problem. At least I could solve it with this:

sudo yum install gcc gcc-c++

Hope it solves your problem too.

Python Write bytes to file

If you want to write bytes then you should open the file in binary mode.

f = open('/tmp/output', 'wb')

android.os.FileUriExposedException: file:///storage/emulated/0/test.txt exposed beyond app through Intent.getData()

If targetSdkVersion is higher than 24, then FileProvider is used to grant access.

Create an xml file(Path: res\xml) provider_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="">
    <external-path name="external_files" path="."/>

Add a Provider in AndroidManifest.xml


If you are using androidx, the FileProvider path should be:


and replace

Uri uri = Uri.fromFile(fileImagePath);


Uri uri = FileProvider.getUriForFile(MainActivity.this, BuildConfig.APPLICATION_ID + ".provider",fileImagePath);

Edit: While you're including the URI with an Intent make sure to add below line:


and you are good to go. Hope it helps.

Can't push image to Amazon ECR - fails with "no basic auth credentials"

Make sure you use the correct region in aws ecr get-login, it must match the region in which your repository is created.

More elegant way of declaring multiple variables at the same time

In your case, I would use YAML .

That is an elegant and professional standard for dealing with multiple parameters. The values are loaded from a separate file. You can see some info in this link:

But it is easier to Google it, as it is a standard, there are hundreds of info about it, you can find what best fits to your understanding. ;)

Best regards.

Permanently hide Navigation Bar in an activity

AFAIK, this is not possible without root access. It would be a security issue to be able to have an app that cannot be exited with system buttons.

Edit, see here: Hide System Bar in Tablets

How do I create variable variables?

Use globals()

You can actually assign variables to global scope dynamically, for instance, if you want 10 variables that can be accessed on a global scope i_1, i_2 ... i_10:

for i in range(10):
    globals()['i_{}'.format(i)] = 'a'

This will assign 'a' to all of these 10 variables, of course you can change the value dynamically as well. All of these variables can be accessed now like other globally declared variable:

>>> i_5

How to identify and switch to the frame in selenium webdriver when frame does not have id

I struggled with this for a while; a particularly frustrating website had several nested frames throughout the site. I couldn't find any way to identify the frames- no name, id, xpath, css selector- nothing.

Eventually I realised that frames are numbered with the top level being frame(0) the second frame(1) etc.

As I still didn't know which frame the element I needed was sitting in, I wrote a for loop to start from 0 and cycle to 50 continually moving to the next frame and attempting to access my required element; if it failed I got it to print a message and continue.

Spent too much time on this problem for such a simple solution -_-

for x in range(50):
        print("It's not: ", x)

Apply jQuery datepicker to multiple instances

When adding datepicker at runtime generated input textboxes you have to check if it already contains datepicker then first remove class hasDatepicker then apply datePicker to it.

function convertTxtToDate() {
        $('.dateTxt').each(function () {
            if ($(this).hasClass('hasDatepicker')) {

Section vs Article HTML5

also, for syndicated content "Authors are encouraged to use the article element instead of the section element when it would make sense to syndicate the contents of the element."

Python SQL query string formatting

Using 'sqlparse' library we can format the sqls.

>>> import sqlparse
>>> raw = 'select * from foo; select * from bar;'
>>> print(sqlparse.format(raw, reindent=True, keyword_case='upper'))
FROM foo;

FROM bar;


RecyclerView inside ScrollView is not working

You can use this way either :

Add this line to your recyclerView xml view :


try it ,recyclerview will be smoothly scrolled with flexible height

hope this helped .

Use dynamic variable names in JavaScript

This is an alternative for those who need to export a dynamically named variable

export {
  [someVariable]: 'some value',
  [anotherVariable]: 'another value',

// then.... import from another file like this:
import * as vars from './some-file'

Another alternative is to simply create an object whose keys are named dynamically

const vars = { [someVariable]: 1, [otherVariable]: 2 };

// consume it like this

How to count the number of set bits in a 32-bit integer?

This will also work fine :

int ans = 0;
 ans += (num &1);
 num = num >>1;
return ans;

Is there a way to reduce the size of the git folder?

yes yes, git gc is the solution, naturally,

and locally - you can just delete the local repository and clone it again,

but there is something more important here...

the seconds you wait for that huge git & externals to process are collected to long minutes in which are collected to hours of inefficient time spent,

Create a new (entirely, not just a branch) repository from scratch, including the only recent version of files, naturally you'll loose all the history,

but when in code-world it is not time to get sentimental, there is no point dragging along the entire 5 years of code every commit or diff, you can still store the old git & externals somewhere, if you get nostalgic :]

but, at some point you really have to move along :]

your team will thank you!

How do I install Eclipse with C++ in Ubuntu 12.10 (Quantal Quetzal)? ^Give that a try

I have not used the CDT for eclipse but I do use Eclipse Java for Ubuntu 12.04 and it works wonders.

git index.lock File exists when I try to commit, but cannot delete the file

On Linux, Unix, Git Bash, or Cygwin, try:

rm -f .git/index.lock

On Windows Command Prompt, try:

del .git\index.lock

For Windows:

  • From a PowerShell console opened as administrator, try

    rm -Force ./.git/index.lock
  • If that does not work, you must kill all git.exe processes

    taskkill /F /IM git.exe

    SUCCESS: The process "git.exe" with PID 20448 has been terminated.
    SUCCESS: The process "git.exe" with PID 11312 has been terminated.
    SUCCESS: The process "git.exe" with PID 23868 has been terminated.
    SUCCESS: The process "git.exe" with PID 27496 has been terminated.
    SUCCESS: The process "git.exe" with PID 33480 has been terminated.
    SUCCESS: The process "git.exe" with PID 28036 has been terminated. \

    rm -Force ./.git/index.lock

Passing vector by reference

If you define your function to take argument of std::vector<int>& arr and integer value, then you can use push_back inside that function:

void do_something(int el, std::vector<int>& arr)


std::vector<int> arr;
do_something(1, arr); 

.Net System.Mail.Message adding multiple "To" addresses

Put in addresses this code:

objMessage.To.Add(***addresses:=***"[email protected] , [email protected] , [email protected]")

phpMyAdmin - Error > Incorrect format parameter?

This error is caused by the fact that the maximum upload size is (Max: 2,048KiB). If your file is bigger than this, you will get an error. Zip the file and upload it again, you will not get the error.

Microsoft Advertising SDK doesn't deliverer ads

I only use MicrosoftAdvertising.Mobile and Microsoft.Advertising.Mobile.UI and I am served ads. The SDK should only add the DLLs not reference itself.

Note: You need to explicitly set width and height Make sure the phone dialer, and web browser capabilities are enabled

Followup note: Make sure that after you've removed the SDK DLL, that the xmlns references are not still pointing to it. The best route to take here is

  1. Remove the XAML for the ad
  2. Remove the xmlns declaration (usually at the top of the page, but sometimes will be declared in the ad itself)
  3. Remove the bad DLL (the one ending in .SDK )
  4. Do a Clean and then Build (clean out anything remaining from the DLL)
  5. Add the xmlns reference (actual reference is below)
  6. Add the ad to the page (example below)

Here is the xmlns reference:


Then the ad itself:

<AdNamespace:AdControl x:Name="myAd" Height="80" Width="480"                    AdUnitId="yourAdUnitIdHere" ApplicationId="yourIdHere"/> 

Printing string variable in Java

You're getting the toString() value returned by the Scanner object itself which is not what you want and not how you use a Scanner object. What you want instead is the data obtained by the Scanner object. For example,

Scanner input = new Scanner(;
String data = input.nextLine();

Please read the tutorial on how to use it as it will explain all.

Please look here: Scanner tutorial

Also have a look at the Scanner API which will explain some of the finer points of Scanner's methods and properties.

Go / golang time.Now().UnixNano() convert to milliseconds?

At randall77 suggested


which exploits the fact that Go's time.Duration already have Milliseconds method.

Installing TensorFlow on Windows (Python 3.6.x)

Tensor flow has only support for python 2.7 3.4 3.5 Other python versions are not supported So you please install the supported python version and try it again. The official link is It provides how to install it with anaconda . This will help you

PostgreSQL - query from bash script as database user 'postgres'

Try this one:

psql -U postgres -d database_name -c "SELECT c_defaults  FROM user_info WHERE c_uid = 'testuser'"

Or using su:

su -c "psql -d database_name -c \"SELECT c_defaults  FROM user_info WHERE c_uid = 'testuser'\"" postgres

And also sudo:

sudo -u postgres -H -- psql -d database_name -c "SELECT c_defaults  FROM user_info WHERE c_uid = 'testuser'"

Directory-tree listing in Python

For Python 2


import os

def scan_dir(path):
    print map(os.path.abspath, os.listdir(pwd))

For Python 3

For filter and map, you need wrap them with list()


import os

def scan_dir(path):
    print(list(map(os.path.abspath, os.listdir(pwd))))

The recommendation now is that you replace your usage of map and filter with generators expressions or list comprehensions:


import os

def scan_dir(path):
    print([os.path.abspath(f) for f in os.listdir(path)])

How to print register values in GDB?

If you're trying to print a specific register in GDB, you have to omit the % sign. For example,

info registers eip

If your executable is 64 bit, the registers start with r. Starting them with e is not valid.

info registers rip

Those can be abbreviated to:

i r rip

How do I get the last character of a string using an Excel function?


is quite sufficient (where the string is contained in A1).

Similar in nature to LEFT, Excel's RIGHT function extracts a substring from a string starting from the right-most character:


RIGHT( text, [number_of_characters] )

Parameters or Arguments


The string that you wish to extract from.


Optional. It indicates the number of characters that you wish to extract starting from the right-most character. If this parameter is omitted, only 1 character is returned.

Applies To

Excel 2016, Excel 2013, Excel 2011 for Mac, Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000

Since number_of_characters is optional and defaults to 1 it is not required in this case.

However, there have been many issues with trailing spaces and if this is a risk for the last visible character (in general):


might be preferred.

Specify system property to Maven project

Is there a way ( I mean how do I ) set a system property in a maven project? I want to access a property from my test [...]

You can set system properties in the Maven Surefire Plugin configuration (this makes sense since tests are forked by default). From Using System Properties:


and my webapp ( running locally )

Not sure what you mean here but I'll assume the webapp container is started by Maven. You can pass system properties on the command line using:

mvn -DargLine="-DpropertyName=propertyValue"

Update: Ok, got it now. For Jetty, you should also be able to set system properties in the Maven Jetty Plugin configuration. From Setting System Properties:


Angular CLI SASS options

Quoted from Officials github repo here -

To use one just install for example

npm install node-sass

and rename .css files in your project to .scss or .sass. They will be compiled automatically. The Angular2App's options argument has sassCompiler, lessCompiler, stylusCompiler and compassCompiler options that are passed directly to their respective CSS preprocessors.

See here

use current date as default value for a column

I have also come across this need for my database project. I decided to share my findings here.

1) There is no way to a NOT NULL field without a default when data already exists (Can I add a not null column without DEFAULT value)

2) This topic has been addressed for a long time. Here is a 2008 question (Add a column with a default value to an existing table in SQL Server)

3) The DEFAULT constraint is used to provide a default value for a column. The default value will be added to all new records IF no other value is specified. (

4) The Visual Studio Database Project that I use for development is really good about generating change scripts for you. This is the change script created for my DB promotion:

PRINT N'Altering [dbo].[PROD_WHSE_ACTUAL]...';



Here are the steps I took to update my database using Visual Studio for development.

1) Add default value (Visual Studio SSDT: DB Project: table designer) enter image description here

2) Use the Schema Comparison tool to generate the change script.

code already provided above

3) View the data BEFORE applying the change. enter image description here

4) View the data AFTER applying the change. enter image description here

Java: Insert multiple rows into MySQL with PreparedStatement

we can be submit multiple updates together in JDBC to submit batch updates.

we can use Statement, PreparedStatement, and CallableStatement objects for bacth update with disable autocommit

addBatch() and executeBatch() functions are available with all statement objects to have BatchUpdate

here addBatch() method adds a set of statements or parameters to the current batch.

Disable time in bootstrap date time picker

Disable time in boostrap datetime picker...

   $(document).ready(function () {
            format: "dd-mm-yy",

Disable date in boostrap datetime picker...

   $(document).ready(function () {
            format: "HH:mm A",

DataSet panel (Report Data) in SSRS designer is gone

First you have to click on the report, Then View -> Report Data

Trying to get property of non-object - CodeIgniter

To get the value:

$query = $this->db->query("YOUR QUERY");

Then, for single row from(in controller):

$query1 = $query->row();
$data['product'] = $query1;

In view, you can use your own code (above code)

Can I install/update WordPress plugins without providing FTP access?

setting up a ftp or even an SFTP connection or chmod 777 are bad ways to go for anything other than a local environment. Opening even an SFTP method introduces more security risks that are not needed.

what is needed is a writeable permission to /wp-content/uploads & /wp-content/plugins/ by the owner of those directories. (linux ls -la will show you ownership).

Default apache user that runs is www-data.

chmod 777 allows any user on the machine to edit those file, not just the apache/php thread user.

SFTP if you are not already using it, will introduce another point of possible failure from an external source. Whereas you only need access by the local user running the apache/php process to complete the objective.

Didn't see anyone making these points, so I thought I would offer this info to help with our constant WP security issues online.

How to include() all PHP files from a directory?

//Loading all php files into of functions/ folder 

$folder =   "./functions/"; 
$files = glob($folder."*.php"); // return array files

 foreach($files as $phpFile){   

offsetTop vs. jQuery.offset().top

You can use parseInt(jQuery.offset().top) to always use the Integer (primitive - int) value across all browsers.

Abstract Class vs Interface in C++

Pure Virtual Functions are mostly used to define:

a) abstract classes

These are base classes where you have to derive from them and then implement the pure virtual functions.

b) interfaces

These are 'empty' classes where all functions are pure virtual and hence you have to derive and then implement all of the functions.

Pure virtual functions are actually functions which have no implementation in base class and have to be implemented in derived class.

Android Fragment no view found for ID?

In our case we have purged/corrupted class.dex file along with gradle compiled outputs. Due to cache recompile weren't tried hence no error, but apk was not having the required file causing this confusing error. A gradle resync and fresh build cleared us from all errors.

// Happy coding

Build error: "The process cannot access the file because it is being used by another process"

Deleting Obj, retail and debug folder of the .NET project and re-building again worked for me.

How do I point Crystal Reports at a new database

Choose Database | Set Datasource Location... Select the database node (yellow-ish cylinder) of the current connection, then select the database node of the desired connection (you may need to authenticate), then click Update.

You will need to do this for the 'Subreports' nodes as well.

FYI, you can also do individual tables by selecting each individually, then choosing Update.

urlencode vs rawurlencode?

urlencode: This differs from the » RFC 1738 encoding (see rawurlencode()) in that for historical reasons, spaces are encoded as plus (+) signs.

Check if a class is derived from a generic class

It might be overkill but I use extension methods like the following. They check interfaces as well as subclasses. It can also return the type that has the specified generic definition.

E.g. for the example in the question it can test against generic interface as well as generic class. The returned type can be used with GetGenericArguments to determine that the generic argument type is "SomeType".

/// <summary>
/// Checks whether this type has the specified definition in its ancestry.
/// </summary>   
public static bool HasGenericDefinition(this Type type, Type definition)
    return GetTypeWithGenericDefinition(type, definition) != null;

/// <summary>
/// Returns the actual type implementing the specified definition from the
/// ancestry of the type, if available. Else, null.
/// </summary>
public static Type GetTypeWithGenericDefinition(this Type type, Type definition)
    if (type == null)
        throw new ArgumentNullException("type");
    if (definition == null)
        throw new ArgumentNullException("definition");
    if (!definition.IsGenericTypeDefinition)
        throw new ArgumentException(
            "The definition needs to be a GenericTypeDefinition", "definition");

    if (definition.IsInterface)
        foreach (var interfaceType in type.GetInterfaces())
            if (interfaceType.IsGenericType
                && interfaceType.GetGenericTypeDefinition() == definition)
                return interfaceType;

    for (Type t = type; t != null; t = t.BaseType)
        if (t.IsGenericType && t.GetGenericTypeDefinition() == definition)
            return t;

    return null;

how to print a string to console in c++

"Visual Studio does not support std::cout as debug tool for non-console applications"
- from Marius Amado-Alves' answer to "How can I see cout output in a non-console application?"

Which means if you use it, Visual Studio shows nothing in the "output" window (in my case VS2008)

sudo in php exec()

I think you can bring specific access to user and command with visudo something like this:

nobody ALL = NOPASSWD: /path/to/osascript myscript.scpt

and with php:

@exec("sudo /path/to/osascript myscript.scpt ");

supposing nobody user is running apache.

Using Git with Visual Studio

I find that Git, working on whole trees as it does, benefits less from IDE integration than source control tools that are either file based or follow a checkout-edit-commit pattern. Of course there are instances when it can be nice to click on a button to do some history examination, but I don't miss that very much.

The real must-do is to get your .gitignore file full of the things that shouldn't be in a shared repository. Mine generally contain (amongst other stuff) the following:


but this is heavily C++ biased with little or no use of any class wizard style functionality.

My usage pattern is something like the following.

  1. Code, code, code in Visual Studio.

  2. When happy (sensible intermediate point to commit code, switch to Git, stage changes and review diffs. If anything's obviously wrong switch back to Visual Studio and fix, otherwise commit.

Any merge, branch, rebase or other fancy SCM stuff is easy to do in Git from the command prompt. Visual Studio is normally fairly happy with things changing under it, although it can sometimes need to reload some projects if you've altered the project files significantly.

I find that the usefulness of Git outweighs any minor inconvenience of not having full IDE integration but it is, to some extent, a matter of taste.

File.Move Does Not Work - File Already Exists

According to the docs for File.Move there is no "overwrite if exists" parameter. You tried to specify the destination folder, but you have to give the full file specification.

Reading the docs again ("providing the option to specify a new file name"), I think, adding a backslash to the destination folder spec may work.

Calling a particular PHP function on form submit

Write this code

        echo 'Hello World';

         <form method="post">
             <input type="text" name="studentname">
             <input type="submit" name="submit" value="click">

How can I exclude a directory from Visual Studio Code "Explore" tab?

There's this Explorer Exclude extension that exactly does this.

It adds an option to hide current folder/file to the right click menu. It also adds a vertical tab Hidden Items to explorer menu where you can see currently hidden files & folders and can toggle them easily.

enter image description here

How to initialize an array of objects in Java

Player[] players = Stream.iterate(0, x-> x+1 ).limit(PlayerCount).map(i -> new Player(i)).toArray(Player[]::new);

round() doesn't seem to be rounding properly

If you use the Decimal module you can approximate without the use of the 'round' function. Here is what I've been using for rounding especially when writing monetary applications:

Decimal(str(16.2)).quantize(Decimal('.01'), rounding=ROUND_UP)

This will return a Decimal Number which is 16.20.

How to call a shell script from python code?

import os
import sys

Assuming is the shell script that you would want to execute


How to post data using HttpClient?

You need to use:

await client.PostAsync(uri, content);

Something like that:

var comment = "hello world";
var questionId = 1;

var formContent = new FormUrlEncodedContent(new[]
    new KeyValuePair<string, string>("comment", comment), 
    new KeyValuePair<string, string>("questionId", questionId) 

var myHttpClient = new HttpClient();
var response = await myHttpClient.PostAsync(uri.ToString(), formContent);

And if you need to get the response after post, you should use:

var stringContent = await response.Content.ReadAsStringAsync();

Hope it helps ;)

cell format round and display 2 decimal places

Input: 0 0.1 1000


Output: 0.00 0.10 1,000.00


Output: 0.00 0.10 1000.00

Note: As you can see FIXED add a coma after a thousand, where TEXT does not.

Threading pool similar to the multiprocessing Pool?

Yes, there is a threading pool similar to the multiprocessing Pool, however, it is hidden somewhat and not properly documented. You can import it by following way:-

from multiprocessing.pool import ThreadPool

Just I show you simple example

def test_multithread_stringio_read_csv(self):
        # see gh-11786
        max_row_range = 10000
        num_files = 100

        bytes_to_df = [
                ['%d,%d,%d' % (i, i, i) for i in range(max_row_range)]
            ).encode() for j in range(num_files)]
        files = [BytesIO(b) for b in bytes_to_df]

        # read all files in many threads
        pool = ThreadPool(8)
        results =, files)
        first_result = results[0]

        for result in results:
            tm.assert_frame_equal(first_result, result) 

DateTimeFormat in TypeScript

This should work...

var displayDate = new Date().toLocaleDateString();


But I suspect you are trying it on something else, for example:

var displayDate =; // No!


Logger slf4j advantages of formatting with {} instead of string concatenation

It is about string concatenation performance. It's potentially significant if your have dense logging statements.

(Prior to SLF4J 1.7) But only two parameters are possible

Because the vast majority of logging statements have 2 or fewer parameters, so SLF4J API up to version 1.6 covers (only) the majority of use cases. The API designers have provided overloaded methods with varargs parameters since API version 1.7.

For those cases where you need more than 2 and you're stuck with pre-1.7 SLF4J, then just use either string concatenation or new Object[] { param1, param2, param3, ... }. There should be few enough of them that the performance is not as important.

How to prevent default event handling in an onclick method?

Let your callback return false and pass that on to the onclick handler:

<a href="#" onclick="return callmymethod(24)">Call</a>

function callmymethod(myVal){
    //doing custom things with myVal
    //here I want to prevent default
    return false;

To create maintainable code, however, you should abstain from using "inline Javascript" (i.e.: code that's directly within an element's tag) and modify an element's behavior via an included Javascript source file (it's called unobtrusive Javascript).

The mark-up:

<a href="#" id="myAnchor">Call</a>

The code (separate file):

// Code example using Prototype JS API
$('myAnchor').observe('click', function(event) {
    Event.stop(event); // suppress default click behavior, cancel the event
    /* your onclick code goes here */

Setting default values for columns in JPA

This isn't possible in JPA.

Here's what you can do with the Column annotation:

Remove characters except digits from string using Python?

along the lines of bayer's answer:

''.join(i for i in s if i.isdigit())

Error: TypeError: $(...).dialog is not a function

Here are the complete list of scripts required to get rid of this problem. (Make sure the file exists at the given file path)

   <script src="@Url.Content("~/Scripts/jquery-1.8.2.js")" type="text/javascript">
    <script src="@Url.Content("~/Scripts/jquery-ui-1.8.24.js")" type="text/javascript">
    <script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript">
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript">
    <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript">

and also include the below css link in _Layout.cshtml for a stylish popup.

<link rel="stylesheet" type="text/css" href="../../Content/themes/base/jquery-ui.css" />

Loop through all elements in XML using NodeList

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document dom = db.parse("file.xml");
    Element docEle = dom.getDocumentElement();
    NodeList nl = docEle.getChildNodes();
    int length = nl.getLength();
    for (int i = 0; i < length; i++) {
        if (nl.item(i).getNodeType() == Node.ELEMENT_NODE) {
            Element el = (Element) nl.item(i);
            if (el.getNodeName().contains("staff")) {
                String name = el.getElementsByTagName("name").item(0).getTextContent();
                String phone = el.getElementsByTagName("phone").item(0).getTextContent();
                String email = el.getElementsByTagName("email").item(0).getTextContent();
                String area = el.getElementsByTagName("area").item(0).getTextContent();
                String city = el.getElementsByTagName("city").item(0).getTextContent();

Iterate over all children and nl.item(i).getNodeType() == Node.ELEMENT_NODE is used to filter text nodes out. If there is nothing else in XML what remains are staff nodes.

For each node under stuff (name, phone, email, area, city)


el.getElementsByTagName("name") will extract the "name" nodes under stuff, .item(0) will get you the first node and .getTextContent() will get the text content inside.

Edit: Since we have jackson I would do this in a different way. Define a pojo for the object:

public class Staff {
    private String name;
    private String phone;
    private String email;
    private String area;
    private String city;
...getters setters

Then using jackson:

    JsonNode root = new XmlMapper().readTree(xml.getBytes());
    ObjectMapper mapper = new ObjectMapper();
    root.forEach(node -> consume(node, mapper));

private void consume(JsonNode node, ObjectMapper mapper) {
    try {
        Staff staff = mapper.treeToValue(node, Staff.class);
        //TODO your job with staff
    } catch (JsonProcessingException e) {

Turn off warnings and errors on PHP and MySQL

PHP error_reporting reference:

// Turn off all error reporting

// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);

// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// Report all errors except E_NOTICE
// This is the default value set in php.ini
error_reporting(E_ALL ^ E_NOTICE);

// Report all PHP errors (see changelog)

// Report all PHP errors

// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);

AngularJS access parent scope from child controller

Perhaps this is lame but you can also just point them both at some external object:

var cities = [];

function ParentCtrl() {
    var vm = this;
    vm.cities = cities;
    vm.cities[0] = 'Oakland';

function ChildCtrl($scope) {
    var vm = this;
    vm.cities = cities;

The benefit here is that edits in ChildCtrl now propogate back to the data in the parent.

AFNetworking Post Request

For AFNetworking 3.0 and Swift. Maybe we can use like this:

let configutation = NSURLSessionConfiguration.defaultSessionConfiguration()
manager = AFHTTPSessionManager(sessionConfiguration: configutation)

let urlString = "url"
manager.POST(urlString, parameters: [params here], progress: nil, success: { (dataTask: NSURLSessionDataTask, response: AnyObject?) -> Void in
        }) { (dataTask: NSURLSessionDataTask?, error: NSError) -> Void in

Hope this will help other find answer like me!

How to convert milliseconds to "hh:mm:ss" format?

The answer marked as correct has a little mistake,

String myTime = String.format("%02d:%02d:%02d",
            TimeUnit.MILLISECONDS.toMinutes(millis) -
                    TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)), // The change is in this line
            TimeUnit.MILLISECONDS.toSeconds(millis) -

for example this is an example of the value that i get:


This is the solution to get the right format is:

String myTime =  String.format("%02d:%02d:%02d",
                TimeUnit.MILLISECONDS.toHours(millis) -
                TimeUnit.MILLISECONDS.toMinutes(millis) -
                TimeUnit.MILLISECONDS.toSeconds(millis) -

getting as a result a correct format:


other option to get the format hh:mm:ss is just :

   Date myDate = new Date(timeinMillis);
   SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
   String myTime = formatter.format(myDate);

Accessing the logged-in user in a template

{{ app.user.username|default('') }}

Just present login username for example, filter function default('') should be nice when user is NOT login by just avoid annoying error message.

ORA-29283: invalid file operation ORA-06512: at "SYS.UTL_FILE", line 536

On Windows also check whether the file is not encrypted using EFS. I had the same problem untill I decrypted the file manualy.

What is the difference/usage of homebrew, macports or other package installation tools?

MacPorts is the way to go.

  1. Like @user475443 pointed, MacPorts has many many more packages. With brew you'll find yourself trapped soon because the formula you need doesn't exist.

  2. MacPorts is a native application: C + TCL. You don't need Ruby at all. To install Ruby on Mac OS X you might need MacPorts, so just go with MacPorts and you'll be happy.

  3. MacPorts is really stable, in 8 years I never had a problem with it, and my entire Unix ecosystem relay on it.

  4. If you are a PHP developer you can install the last version of Apache (Mac OS X uses 2.2), PHP and all the extensions you need, then upgrade all with one command. Forget to do the same with Homebrew.

  5. MacPorts support groups.

    foo@macpro:~/ port select --summary
    Name        Selected      Options
    ====        ========      =======
    db          none          db46 none
    gcc         none          gcc42 llvm-gcc42 mp-gcc48 none
    llvm        none          mp-llvm-3.3 none
    mysql       mysql56       mysql56 none
    php         php55         php55 php56 none
    postgresql  postgresql94  postgresql93 postgresql94 none
    python      none          python24 python25-apple python26-apple python27 python27-apple none

    If you have both PHP55 and PHP56 installed (with many different extensions), you can swap between them with just one command. All the relative extensions are part of the group and they will be activated within the chosen group: php55 or php56. I'm not sure Homebrew has this feature.

  6. Rubists like to rewrite everything in Ruby, because the only thing they are at ease is Ruby itself.

how does unix handle full path name with space and arguments?

I would also like to point out that in case you are using command line arguments as part of a shell script (.sh file), then within the script, you would need to enclose the argument in quotes. So if your command looks like

> arg1 arg2

And arg1 is your path that has spaces, then within the shell script, you would need to refer to it as "$arg1" instead of $arg1

Here are the details

Select single item from a list

Use the FirstOrDefault selector.

var list = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

var firstEven = list.FirstOrDefault(n => n % 2 == 0);

if (firstEven == 0)
    Console.WriteLine("no even number");
    Console.WriteLine("first even number is {0}", firstEven);

Just pass in a predicate to the First or FirstOrDefault method and it'll happily go round' the list and picks the first match for you.

If there isn't a match, FirstOrDefault will returns the default value of whatever datatype the list items is.

Hope this helps :-)

Hiding the scroll bar on an HTML page

In addition to Peter's answer:

#element::-webkit-scrollbar {
    display: none;

This will work the same for Internet Explorer 10:

 #element {
      -ms-overflow-style: none;

Calculate Age in MySQL (InnoDb)

Since the question is being tagged for mysql, I have the following implementation that works for me and I hope similar alternatives would be there for other RDBMS's. Here's the sql:

select YEAR(now()) - YEAR(dob) - ( DAYOFYEAR(now()) < DAYOFYEAR(dob) ) as age 
from table 
where ...

What are the JavaScript KeyCodes?

One possible answer will be given when you run this snippet.

for (var i = 0; i < 250; i++) {_x000D_
  document.write('<tr><td>' + i + '</td><td>' + String.fromCharCode(i) + '</td></tr>')_x000D_
td {_x000D_
  border: solid 1px;_x000D_
  padding: 1px 12px;_x000D_
  text-align: right;_x000D_
table {_x000D_
  border-collapse: collapse;_x000D_
* {_x000D_
  font-family: monospace;_x000D_
  font-size: 1.1em;_x000D_

How do I use the CONCAT function in SQL Server 2008 R2?

NULL safe drop in replacement approximations for SQL Server 2012 CONCAT function

SQL Server 2012:

SELECT CONCAT(data1, data2)

PRE SQL 2012 (Two Solutions):

SELECT {fn CONCAT(ISNULL(data1, ''), ISNULL(data2, ''))}

SELECT ISNULL(CAST(data1 AS varchar(MAX)), '') + ISNULL(CAST(data2 AS varchar(MAX)), '')

These two solutions collate several excellent answers and caveats raised by other posters including @Martin Smith, @Svish and @vasin1987.

These options add NULL to '' (empty string) casting for safe NULL handling while accounting for the varying behaviour of the + operator pertaining to specific operands.

Note the ODBC Scaler Function solution is limited to 2 arguments whereas the + operator approach is scalable to many arguments as needed.

Note also the potential issue identified by @Swifty regarding the default varchar size here remedied by varchar(MAX).

Fastest way to tell if two files have the same contents in Unix/Linux?

Try also to use the cksum command:

chk1=`cksum <file1> | awk -F" " '{print $1}'`
chk2=`cksum <file2> | awk -F" " '{print $1}'`

if [ $chk1 -eq $chk2 ]
  echo "File is identical"
  echo "File is not identical"

The cksum command will output the byte count of a file. See 'man cksum'.

ASP.NET Identity reset password

In case of password reset, it is recommended to reset it through sending password reset token to registered user email and ask user to provide new password. If have created a easily usable .NET library over Identity framework with default configuration settins. You can find details at blog link and source code at github.

Get Android shared preferences value in activity/normal class

This is the procedure that seems simplest to me:

SharedPreferences sp = getSharedPreferences("MySharedPrefs", MODE_PRIVATE);
SharedPreferences.Editor e = sp.edit();

    if (sp.getString("sharedString", null).equals("true")
            || sp.getString("sharedString", null) == null) {
        e.putString("sharedString", "false").commit();
        // Do something
    } else {
        // Do something else

How do I get my solution in Visual Studio back online in TFS?

Go to File > Source Control > Go Online, select the files you changed, and finish the process.

Use Conditional formatting to turn a cell Red, yellow or green depending on 3 values in another sheet

  1. Highlight the range in question.
  2. On the Home tab, in the Styles Group, Click "Conditional Formatting".
  3. Click "Highlight cell rules"

For the first rule,

Click "greater than", then in the value option box, click on the cell criteria you want it to be less than, than use the format drop-down to select your color.

For the second,

Click "less than", then in the value option box, type "=.9*" and then click the cell criteria, then use the formatting just like step 1.

For the third,

Same as the second, except your formula is =".8*" rather than .9.

Spring-Boot: How do I set JDBC pool properties like maximum number of connections?

Based on your application type/size/load/no. of users ..etc - u can keep following as your production properties


PHP: Split string into array, like explode with no delimiter

str_split can do the trick. Note that strings in PHP can be accessed just like a chars array, in most cases, you won't need to split your string into a "new" array.

How do I format a string using a dictionary in python-3.x?

Is this good for you?

geopoint = {'latitude':41.123,'longitude':71.091}
print('{latitude} {longitude}'.format(**geopoint))

Angular 4/5/6 Global Variables

You can use the Window object and access it everwhere. example window.defaultTitle = "my title"; then you can access window.defaultTitle without importing anything.

How to properly export an ES6 class in Node 4?

With ECMAScript 2015 you can export and import multiple classes like this

class Person
        this.type = "Person";

class Animal{
        this.type = "Animal";

module.exports = {

then where you use them:

const { Animal, Person } = require("classes");

const animal = new Animal();
const person = new Person();

In case of name collisions, or you prefer other names you can rename them like this:

const { Animal : OtherAnimal, Person : OtherPerson} = require("./classes");

const animal = new OtherAnimal();
const person = new OtherPerson();

jQuery or Javascript - how to disable window scroll without overflow:hidden;

Try to handler 'mousewheel' event on all nodes except one

    'mousewheel': function(e) {
        if ( == 'el') return;


Get index of selected option with jQuery

try this


'gulp' is not recognized as an internal or external command

I was having the same exception with node v12.13.1,

Downgraded node to v10.15.3 and it works fine now.

How to create a WPF Window without a border that can be resized via a grip only?

Sample here:

<Style TargetType="Window" x:Key="DialogWindow">
        <Setter Property="AllowsTransparency" Value="True"/>
        <Setter Property="WindowStyle" Value="None"/>
        <Setter Property="ResizeMode" Value="CanResizeWithGrip"/>
        <Setter Property="Template">
                <ControlTemplate TargetType="{x:Type Window}">
                    <Border BorderBrush="Black" BorderThickness="3" CornerRadius="10" Height="{TemplateBinding Height}"
                            Width="{TemplateBinding Width}" Background="Gray">
                            <Grid DockPanel.Dock="Top">
                                    <ColumnDefinition Width="50"/>
                                <Label Height="35" Grid.ColumnSpan="2"
                                <Button Width="15" Height="15" Content="x" Grid.Column="1" x:Name="PART_CloseButton"/>
                            <Border HorizontalAlignment="Stretch" VerticalAlignment="Stretch" 
                                        Background="LightBlue" CornerRadius="0,0,10,10" 
                                        <ColumnDefinition Width="20"/>
                                        <RowDefinition Height="*"/>
                                        <RowDefinition Height="20"></RowDefinition>
                                    <ResizeGrip Width="10" Height="10" Grid.Column="1" VerticalAlignment="Bottom" Grid.Row="1"/>

How do I copy an entire directory of files into an existing directory using Python?

Here's a solution that's part of the standard library:

from distutils.dir_util import copy_tree
copy_tree("/a/b/c", "/x/y/z")

See this similar question.

Copy directory contents into a directory with python

Link to all Visual Studio $ variables

Nikita's answer is nice for the macros that Visual Studio sets up in its environment, but this is far from comprehensive. (Environment variables become MSBuild macros, but not vis-a-versa.)

Slight tweak to ojdo's answer: Go to the "Pre-build event command line" in "Build Events" of the IDE for any project (where you find this in the IDE may depend on the language, i.e. C#, c++, etc. See other answers for location.) Post the code below into the "Pre-build event command line", then build that project. After the build starts, you will have a "macros.txt" file in your TEMP directory with a nice list of all the macros and their values. I based the list entirely on the list contained within ojdo's answer. I have no idea if it is comprehensive, but it's a good start!

echo AllowLocalNetworkLoopback=$(AllowLocalNetworkLoopback) >>$(TEMP)\macros.txt
echo AndroidTargetsPath=$(AndroidTargetsPath) >>$(TEMP)\macros.txt
echo APPDATA=$(APPDATA) >>$(TEMP)\macros.txt
echo AppxManifestMetadataClHostArchDir=$(AppxManifestMetadataClHostArchDir) >>$(TEMP)\macros.txt
echo AppxManifestMetadataCITargetArchDir=$(AppxManifestMetadataCITargetArchDir) >>$(TEMP)\macros.txt
echo Attach=$(Attach) >>$(TEMP)\macros.txt
echo BaseIntermediateOutputPath=$(BaseIntermediateOutputPath) >>$(TEMP)\macros.txt
echo BuildingInsideVisualStudio=$(BuildingInsideVisualStudio) >>$(TEMP)\macros.txt
echo CharacterSet=$(CharacterSet) >>$(TEMP)\macros.txt
echo CLRSupport=$(CLRSupport) >>$(TEMP)\macros.txt
echo CommonProgramFiles=$(CommonProgramFiles) >>$(TEMP)\macros.txt
echo CommonProgramW6432=$(CommonProgramW6432) >>$(TEMP)\macros.txt
echo ComSpec=$(ComSpec) >>$(TEMP)\macros.txt
echo Configuration=$(Configuration) >>$(TEMP)\macros.txt
echo ConfigurationType=$(ConfigurationType) >>$(TEMP)\macros.txt
echo CppWinRT_IncludePath=$(CppWinRT_IncludePath) >>$(TEMP)\macros.txt
echo CrtSDKReferencelnclude=$(CrtSDKReferencelnclude) >>$(TEMP)\macros.txt
echo CrtSDKReferenceVersion=$(CrtSDKReferenceVersion) >>$(TEMP)\macros.txt
echo CustomAfterMicrosoftCommonProps=$(CustomAfterMicrosoftCommonProps) >>$(TEMP)\macros.txt
echo CustomBeforeMicrosoftCommonProps=$(CustomBeforeMicrosoftCommonProps) >>$(TEMP)\macros.txt
echo DebugCppRuntimeFilesPath=$(DebugCppRuntimeFilesPath) >>$(TEMP)\macros.txt
echo DebuggerFlavor=$(DebuggerFlavor) >>$(TEMP)\macros.txt
echo DebuggerLaunchApplication=$(DebuggerLaunchApplication) >>$(TEMP)\macros.txt
echo DebuggerRequireAuthentication=$(DebuggerRequireAuthentication) >>$(TEMP)\macros.txt
echo DebuggerType=$(DebuggerType) >>$(TEMP)\macros.txt
echo DefaultLanguageSourceExtension=$(DefaultLanguageSourceExtension) >>$(TEMP)\macros.txt
echo DefaultPlatformToolset=$(DefaultPlatformToolset) >>$(TEMP)\macros.txt
echo DefaultWindowsSDKVersion=$(DefaultWindowsSDKVersion) >>$(TEMP)\macros.txt
echo DefineExplicitDefaults=$(DefineExplicitDefaults) >>$(TEMP)\macros.txt
echo DelayImplib=$(DelayImplib) >>$(TEMP)\macros.txt
echo DesignTimeBuild=$(DesignTimeBuild) >>$(TEMP)\macros.txt
echo DevEnvDir=$(DevEnvDir) >>$(TEMP)\macros.txt
echo DocumentLibraryDependencies=$(DocumentLibraryDependencies) >>$(TEMP)\macros.txt
echo DotNetSdk_IncludePath=$(DotNetSdk_IncludePath) >>$(TEMP)\macros.txt
echo DotNetSdk_LibraryPath=$(DotNetSdk_LibraryPath) >>$(TEMP)\macros.txt
echo DotNetSdk_LibraryPath_arm=$(DotNetSdk_LibraryPath_arm) >>$(TEMP)\macros.txt
echo DotNetSdk_LibraryPath_arm64=$(DotNetSdk_LibraryPath_arm64) >>$(TEMP)\macros.txt
echo DotNetSdk_LibraryPath_x64=$(DotNetSdk_LibraryPath_x64) >>$(TEMP)\macros.txt
echo DotNetSdk_LibraryPath_x86=$(DotNetSdk_LibraryPath_x86) >>$(TEMP)\macros.txt
echo DotNetSdkRoot=$(DotNetSdkRoot) >>$(TEMP)\macros.txt
echo DriverData=$(DriverData) >>$(TEMP)\macros.txt
echo EmbedManifest=$(EmbedManifest) >>$(TEMP)\macros.txt
echo EnableManagedIncrementalBuild=$(EnableManagedIncrementalBuild) >>$(TEMP)\macros.txt
echo EspXtensions=$(EspXtensions) >>$(TEMP)\macros.txt
echo ExcludePath=$(ExcludePath) >>$(TEMP)\macros.txt
echo ExecutablePath=$(ExecutablePath) >>$(TEMP)\macros.txt
echo ExtensionsToDeleteOnClean=$(ExtensionsToDeleteOnClean) >>$(TEMP)\macros.txt
echo FrameworkDir=$(FrameworkDir) >>$(TEMP)\macros.txt
echo FrameworkDir_110=$(FrameworkDir_110) >>$(TEMP)\macros.txt
echo FrameworkSdkDir=$(FrameworkSdkDir) >>$(TEMP)\macros.txt
echo FrameworkSDKRoot=$(FrameworkSDKRoot) >>$(TEMP)\macros.txt
echo FrameworkVersion=$(FrameworkVersion) >>$(TEMP)\macros.txt
echo GenerateManifest=$(GenerateManifest) >>$(TEMP)\macros.txt
echo GPURefDebuggerBreakOnAllThreads=$(GPURefDebuggerBreakOnAllThreads) >>$(TEMP)\macros.txt
echo HOMEDRIVE=$(HOMEDRIVE) >>$(TEMP)\macros.txt
echo HOMEPATH=$(HOMEPATH) >>$(TEMP)\macros.txt
echo IgnorelmportLibrary=$(IgnorelmportLibrary) >>$(TEMP)\macros.txt
echo ImportByWildcardAfterMicrosoftCommonProps=$(ImportByWildcardAfterMicrosoftCommonProps) >>$(TEMP)\macros.txt
echo ImportByWildcardBeforeMicrosoftCommonProps=$(ImportByWildcardBeforeMicrosoftCommonProps) >>$(TEMP)\macros.txt
echo ImportDirectoryBuildProps=$(ImportDirectoryBuildProps) >>$(TEMP)\macros.txt
echo ImportProjectExtensionProps=$(ImportProjectExtensionProps) >>$(TEMP)\macros.txt
echo ImportUserLocationsByWildcardAfterMicrosoftCommonProps=$(ImportUserLocationsByWildcardAfterMicrosoftCommonProps) >>$(TEMP)\macros.txt
echo ImportUserLocationsByWildcardBeforeMicrosoftCommonProps=$(ImportUserLocationsByWildcardBeforeMicrosoftCommonProps) >>$(TEMP)\macros.txt
echo IncludePath=$(IncludePath) >>$(TEMP)\macros.txt
echo IncludeVersionInInteropName=$(IncludeVersionInInteropName) >>$(TEMP)\macros.txt
echo IntDir=$(IntDir) >>$(TEMP)\macros.txt
echo InteropOutputPath=$(InteropOutputPath) >>$(TEMP)\macros.txt
echo iOSTargetsPath=$(iOSTargetsPath) >>$(TEMP)\macros.txt
echo Keyword=$(Keyword) >>$(TEMP)\macros.txt
echo KIT_SHARED_IncludePath=$(KIT_SHARED_IncludePath) >>$(TEMP)\macros.txt
echo LangID=$(LangID) >>$(TEMP)\macros.txt
echo LangName=$(LangName) >>$(TEMP)\macros.txt
echo Language=$(Language) >>$(TEMP)\macros.txt
echo LibraryPath=$(LibraryPath) >>$(TEMP)\macros.txt
echo LibraryWPath=$(LibraryWPath) >>$(TEMP)\macros.txt
echo LinkCompiled=$(LinkCompiled) >>$(TEMP)\macros.txt
echo LinkIncremental=$(LinkIncremental) >>$(TEMP)\macros.txt
echo LocalDebuggerAttach=$(LocalDebuggerAttach) >>$(TEMP)\macros.txt
echo LocalDebuggerDebuggerlType=$(LocalDebuggerDebuggerlType) >>$(TEMP)\macros.txt
echo LocalDebuggerMergeEnvironment=$(LocalDebuggerMergeEnvironment) >>$(TEMP)\macros.txt
echo LocalDebuggerSQLDebugging=$(LocalDebuggerSQLDebugging) >>$(TEMP)\macros.txt
echo LocalDebuggerWorkingDirectory=$(LocalDebuggerWorkingDirectory) >>$(TEMP)\macros.txt
echo LocalGPUDebuggerTargetType=$(LocalGPUDebuggerTargetType) >>$(TEMP)\macros.txt
echo LOGONSERVER=$(LOGONSERVER) >>$(TEMP)\macros.txt
echo MicrosoftCommonPropsHasBeenImported=$(MicrosoftCommonPropsHasBeenImported) >>$(TEMP)\macros.txt
echo MpiDebuggerCleanupDeployment=$(MpiDebuggerCleanupDeployment) >>$(TEMP)\macros.txt
echo MpiDebuggerDebuggerType=$(MpiDebuggerDebuggerType) >>$(TEMP)\macros.txt
echo MpiDebuggerDeployCommonRuntime=$(MpiDebuggerDeployCommonRuntime) >>$(TEMP)\macros.txt
echo MpiDebuggerNetworkSecurityMode=$(MpiDebuggerNetworkSecurityMode) >>$(TEMP)\macros.txt
echo MpiDebuggerSchedulerNode=$(MpiDebuggerSchedulerNode) >>$(TEMP)\macros.txt
echo MpiDebuggerSchedulerTimeout=$(MpiDebuggerSchedulerTimeout) >>$(TEMP)\macros.txt
echo MSBuild_ExecutablePath=$(MSBuild_ExecutablePath) >>$(TEMP)\macros.txt
echo MSBuildAllProjects=$(MSBuildAllProjects) >>$(TEMP)\macros.txt
echo MSBuildAssemblyVersion=$(MSBuildAssemblyVersion) >>$(TEMP)\macros.txt
echo MSBuildBinPath=$(MSBuildBinPath) >>$(TEMP)\macros.txt
echo MSBuildExtensionsPath=$(MSBuildExtensionsPath) >>$(TEMP)\macros.txt
echo MSBuildExtensionsPath32=$(MSBuildExtensionsPath32) >>$(TEMP)\macros.txt
echo MSBuildExtensionsPath64=$(MSBuildExtensionsPath64) >>$(TEMP)\macros.txt
echo MSBuildFrameworkToolsPath=$(MSBuildFrameworkToolsPath) >>$(TEMP)\macros.txt
echo MSBuildFrameworkToolsPath32=$(MSBuildFrameworkToolsPath32) >>$(TEMP)\macros.txt
echo MSBuildFrameworkToolsPath64=$(MSBuildFrameworkToolsPath64) >>$(TEMP)\macros.txt
echo MSBuildFrameworkToolsRoot=$(MSBuildFrameworkToolsRoot) >>$(TEMP)\macros.txt
echo MSBuildLoadMicrosoftTargetsReadOnly=$(MSBuildLoadMicrosoftTargetsReadOnly) >>$(TEMP)\macros.txt
echo MSBuildNodeCount=$(MSBuildNodeCount) >>$(TEMP)\macros.txt
echo MSBuildProgramFiles32=$(MSBuildProgramFiles32) >>$(TEMP)\macros.txt
echo MSBuildProjectDefaultTargets=$(MSBuildProjectDefaultTargets) >>$(TEMP)\macros.txt
echo MSBuildProjectDirectory=$(MSBuildProjectDirectory) >>$(TEMP)\macros.txt
echo MSBuildProjectDirectoryNoRoot=$(MSBuildProjectDirectoryNoRoot) >>$(TEMP)\macros.txt
echo MSBuildProjectExtension=$(MSBuildProjectExtension) >>$(TEMP)\macros.txt
echo MSBuildProjectExtensionsPath=$(MSBuildProjectExtensionsPath) >>$(TEMP)\macros.txt
echo MSBuildProjectFile=$(MSBuildProjectFile) >>$(TEMP)\macros.txt
echo MSBuildProjectFullPath=$(MSBuildProjectFullPath) >>$(TEMP)\macros.txt
echo MSBuildProjectName=$(MSBuildProjectName) >>$(TEMP)\macros.txt
echo MSBuildRuntimeType=$(MSBuildRuntimeType) >>$(TEMP)\macros.txt
echo MSBuildRuntimeVersion=$(MSBuildRuntimeVersion) >>$(TEMP)\macros.txt
echo MSBuildSDKsPath=$(MSBuildSDKsPath) >>$(TEMP)\macros.txt
echo MSBuildStartupDirectory=$(MSBuildStartupDirectory) >>$(TEMP)\macros.txt
echo MSBuildToolsPath=$(MSBuildToolsPath) >>$(TEMP)\macros.txt
echo MSBuildToolsPath32=$(MSBuildToolsPath32) >>$(TEMP)\macros.txt
echo MSBuildToolsPath64=$(MSBuildToolsPath64) >>$(TEMP)\macros.txt
echo MSBuildToolsRoot=$(MSBuildToolsRoot) >>$(TEMP)\macros.txt
echo MSBuildToolsVersion=$(MSBuildToolsVersion) >>$(TEMP)\macros.txt
echo MSBuildUserExtensionsPath=$(MSBuildUserExtensionsPath) >>$(TEMP)\macros.txt
echo MSBuildVersion=$(MSBuildVersion) >>$(TEMP)\macros.txt
echo MultiToolTask=$(MultiToolTask) >>$(TEMP)\macros.txt
echo NETFXKitsDir=$(NETFXKitsDir) >>$(TEMP)\macros.txt
echo NETFXSDKDir=$(NETFXSDKDir) >>$(TEMP)\macros.txt
echo NuGetProps=$(NuGetProps) >>$(TEMP)\macros.txt
echo OneDrive=$(OneDrive) >>$(TEMP)\macros.txt
echo OneDriveCommercial=$(OneDriveCommercial) >>$(TEMP)\macros.txt
echo OS=$(OS) >>$(TEMP)\macros.txt
echo OutDir=$(OutDir) >>$(TEMP)\macros.txt
echo OutDirWasSpecified=$(OutDirWasSpecified) >>$(TEMP)\macros.txt
echo OutputType=$(OutputType) >>$(TEMP)\macros.txt
echo Path=$(Path) >>$(TEMP)\macros.txt
echo PATHEXT=$(PATHEXT) >>$(TEMP)\macros.txt
echo PkgDefApplicationConfigFile=$(PkgDefApplicationConfigFile) >>$(TEMP)\macros.txt
echo Platform=$(Platform) >>$(TEMP)\macros.txt
echo Platform_Actual=$(Platform_Actual) >>$(TEMP)\macros.txt
echo PlatformArchitecture=$(PlatformArchitecture) >>$(TEMP)\macros.txt
echo PlatformName=$(PlatformName) >>$(TEMP)\macros.txt
echo PlatformPropsFound=$(PlatformPropsFound) >>$(TEMP)\macros.txt
echo PlatformShortName=$(PlatformShortName) >>$(TEMP)\macros.txt
echo PlatformTarget=$(PlatformTarget) >>$(TEMP)\macros.txt
echo PlatformTargetsFound=$(PlatformTargetsFound) >>$(TEMP)\macros.txt
echo PlatformToolset=$(PlatformToolset) >>$(TEMP)\macros.txt
echo PlatformToolsetVersion=$(PlatformToolsetVersion) >>$(TEMP)\macros.txt
echo PostBuildEventUseInBuild=$(PostBuildEventUseInBuild) >>$(TEMP)\macros.txt
echo PreBuildEventUseInBuild=$(PreBuildEventUseInBuild) >>$(TEMP)\macros.txt
echo PreferredToolArchitecture=$(PreferredToolArchitecture) >>$(TEMP)\macros.txt
echo PreLinkEventUselnBuild=$(PreLinkEventUselnBuild) >>$(TEMP)\macros.txt
echo ProgramData=$(ProgramData) >>$(TEMP)\macros.txt
echo ProgramFiles=$(ProgramFiles) >>$(TEMP)\macros.txt
echo ProgramW6432=$(ProgramW6432) >>$(TEMP)\macros.txt
echo ProjectDir=$(ProjectDir) >>$(TEMP)\macros.txt
echo ProjectExt=$(ProjectExt) >>$(TEMP)\macros.txt
echo ProjectFileName=$(ProjectFileName) >>$(TEMP)\macros.txt
echo ProjectGuid=$(ProjectGuid) >>$(TEMP)\macros.txt
echo ProjectName=$(ProjectName) >>$(TEMP)\macros.txt
echo ProjectPath=$(ProjectPath) >>$(TEMP)\macros.txt
echo PSExecutionPolicyPreference=$(PSExecutionPolicyPreference) >>$(TEMP)\macros.txt
echo PSModulePath=$(PSModulePath) >>$(TEMP)\macros.txt
echo PUBLIC=$(PUBLIC) >>$(TEMP)\macros.txt
echo ReferencePath=$(ReferencePath) >>$(TEMP)\macros.txt
echo RemoteDebuggerAttach=$(RemoteDebuggerAttach) >>$(TEMP)\macros.txt
echo RemoteDebuggerConnection=$(RemoteDebuggerConnection) >>$(TEMP)\macros.txt
echo RemoteDebuggerDebuggerlype=$(RemoteDebuggerDebuggerlype) >>$(TEMP)\macros.txt
echo RemoteDebuggerDeployDebugCppRuntime=$(RemoteDebuggerDeployDebugCppRuntime) >>$(TEMP)\macros.txt
echo RemoteDebuggerServerName=$(RemoteDebuggerServerName) >>$(TEMP)\macros.txt
echo RemoteDebuggerSQLDebugging=$(RemoteDebuggerSQLDebugging) >>$(TEMP)\macros.txt
echo RemoteDebuggerWorkingDirectory=$(RemoteDebuggerWorkingDirectory) >>$(TEMP)\macros.txt
echo RemoteGPUDebuggerTargetType=$(RemoteGPUDebuggerTargetType) >>$(TEMP)\macros.txt
echo RetargetAlwaysSupported=$(RetargetAlwaysSupported) >>$(TEMP)\macros.txt
echo RootNamespace=$(RootNamespace) >>$(TEMP)\macros.txt
echo RoslynTargetsPath=$(RoslynTargetsPath) >>$(TEMP)\macros.txt
echo SDK35ToolsPath=$(SDK35ToolsPath) >>$(TEMP)\macros.txt
echo SDK40ToolsPath=$(SDK40ToolsPath) >>$(TEMP)\macros.txt
echo SDKDisplayName=$(SDKDisplayName) >>$(TEMP)\macros.txt
echo SDKIdentifier=$(SDKIdentifier) >>$(TEMP)\macros.txt
echo SDKVersion=$(SDKVersion) >>$(TEMP)\macros.txt
echo SESSIONNAME=$(SESSIONNAME) >>$(TEMP)\macros.txt
echo SolutionDir=$(SolutionDir) >>$(TEMP)\macros.txt
echo SolutionExt=$(SolutionExt) >>$(TEMP)\macros.txt
echo SolutionFileName=$(SolutionFileName) >>$(TEMP)\macros.txt
echo SolutionName=$(SolutionName) >>$(TEMP)\macros.txt
echo SolutionPath=$(SolutionPath) >>$(TEMP)\macros.txt
echo SourcePath=$(SourcePath) >>$(TEMP)\macros.txt
echo SpectreMitigation=$(SpectreMitigation) >>$(TEMP)\macros.txt
echo SQLDebugging=$(SQLDebugging) >>$(TEMP)\macros.txt
echo SystemDrive=$(SystemDrive) >>$(TEMP)\macros.txt
echo SystemRoot=$(SystemRoot) >>$(TEMP)\macros.txt
echo TargetExt=$(TargetExt) >>$(TEMP)\macros.txt
echo TargetFrameworkVersion=$(TargetFrameworkVersion) >>$(TEMP)\macros.txt
echo TargetName=$(TargetName) >>$(TEMP)\macros.txt
echo TargetPlatformMinVersion=$(TargetPlatformMinVersion) >>$(TEMP)\macros.txt
echo TargetPlatformVersion=$(TargetPlatformVersion) >>$(TEMP)\macros.txt
echo TargetPlatformWinMDLocation=$(TargetPlatformWinMDLocation) >>$(TEMP)\macros.txt
echo TargetUniversalCRTVersion=$(TargetUniversalCRTVersion) >>$(TEMP)\macros.txt
echo TEMP=$(TEMP) >>$(TEMP)\macros.txt
echo TMP=$(TMP) >>$(TEMP)\macros.txt
echo ToolsetPropsFound=$(ToolsetPropsFound) >>$(TEMP)\macros.txt
echo ToolsetTargetsFound=$(ToolsetTargetsFound) >>$(TEMP)\macros.txt
echo UCRTContentRoot=$(UCRTContentRoot) >>$(TEMP)\macros.txt
echo UM_IncludePath=$(UM_IncludePath) >>$(TEMP)\macros.txt
echo UniversalCRT_IncludePath=$(UniversalCRT_IncludePath) >>$(TEMP)\macros.txt
echo UniversalCRT_LibraryPath_arm=$(UniversalCRT_LibraryPath_arm) >>$(TEMP)\macros.txt
echo UniversalCRT_LibraryPath_arm64=$(UniversalCRT_LibraryPath_arm64) >>$(TEMP)\macros.txt
echo UniversalCRT_LibraryPath_x64=$(UniversalCRT_LibraryPath_x64) >>$(TEMP)\macros.txt
echo UniversalCRT_LibraryPath_x86=$(UniversalCRT_LibraryPath_x86) >>$(TEMP)\macros.txt
echo UniversalCRT_PropsPath=$(UniversalCRT_PropsPath) >>$(TEMP)\macros.txt
echo UniversalCRT_SourcePath=$(UniversalCRT_SourcePath) >>$(TEMP)\macros.txt
echo UniversalCRTSdkDir=$(UniversalCRTSdkDir) >>$(TEMP)\macros.txt
echo UniversalCRTSdkDir_10=$(UniversalCRTSdkDir_10) >>$(TEMP)\macros.txt
echo UseDebugLibraries=$(UseDebugLibraries) >>$(TEMP)\macros.txt
echo UseLegacyManagedDebugger=$(UseLegacyManagedDebugger) >>$(TEMP)\macros.txt
echo UseOfATL=$(UseOfATL) >>$(TEMP)\macros.txt
echo UseOfMfc=$(UseOfMfc) >>$(TEMP)\macros.txt
echo USERDOMAIN=$(USERDOMAIN) >>$(TEMP)\macros.txt
echo USERNAME=$(USERNAME) >>$(TEMP)\macros.txt
echo USERPROFILE=$(USERPROFILE) >>$(TEMP)\macros.txt
echo UserRootDir=$(UserRootDir) >>$(TEMP)\macros.txt
echo VC_ATLMFC_IncludePath=$(VC_ATLMFC_IncludePath) >>$(TEMP)\macros.txt
echo VC_ATLMFC_SourcePath=$(VC_ATLMFC_SourcePath) >>$(TEMP)\macros.txt
echo VC_CRT_SourcePath=$(VC_CRT_SourcePath) >>$(TEMP)\macros.txt
echo VC_ExecutablePath_ARM=$(VC_ExecutablePath_ARM) >>$(TEMP)\macros.txt
echo VC_ExecutablePath_ARM64=$(VC_ExecutablePath_ARM64) >>$(TEMP)\macros.txt
echo VC_ExecutablePath_x64=$(VC_ExecutablePath_x64) >>$(TEMP)\macros.txt
echo VC_ExecutablePath_x64_ARM=$(VC_ExecutablePath_x64_ARM) >>$(TEMP)\macros.txt
echo VC_ExecutablePath_x64_ARM64=$(VC_ExecutablePath_x64_ARM64) >>$(TEMP)\macros.txt
echo VC_ExecutablePath_x64_x64=$(VC_ExecutablePath_x64_x64) >>$(TEMP)\macros.txt
echo VC_ExecutablePath_x64_x86=$(VC_ExecutablePath_x64_x86) >>$(TEMP)\macros.txt
echo VC_ExecutablePath_x86=$(VC_ExecutablePath_x86) >>$(TEMP)\macros.txt
echo VC_ExecutablePath_x86_ARM=$(VC_ExecutablePath_x86_ARM) >>$(TEMP)\macros.txt
echo VC_ExecutablePath_x86_ARM64=$(VC_ExecutablePath_x86_ARM64) >>$(TEMP)\macros.txt
echo VC_ExecutablePath_x86_x64=$(VC_ExecutablePath_x86_x64) >>$(TEMP)\macros.txt
echo VC_ExecutablePath_x86_x86=$(VC_ExecutablePath_x86_x86) >>$(TEMP)\macros.txt
echo VC_IFCPath=$(VC_IFCPath) >>$(TEMP)\macros.txt
echo VC_IncludePath=$(VC_IncludePath) >>$(TEMP)\macros.txt
echo VC_LibraryPath_ARM=$(VC_LibraryPath_ARM) >>$(TEMP)\macros.txt
echo VC_LibraryPath_ARM64=$(VC_LibraryPath_ARM64) >>$(TEMP)\macros.txt
echo VC_LibraryPath_ATL_ARM=$(VC_LibraryPath_ATL_ARM) >>$(TEMP)\macros.txt
echo VC_LibraryPath_ATL_ARM64=$(VC_LibraryPath_ATL_ARM64) >>$(TEMP)\macros.txt
echo VC_LibraryPath_ATL_x64=$(VC_LibraryPath_ATL_x64) >>$(TEMP)\macros.txt
echo VC_LibraryPath_ATL_x86=$(VC_LibraryPath_ATL_x86) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_ARM=$(VC_LibraryPath_VC_ARM) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_ARM_Desktop=$(VC_LibraryPath_VC_ARM_Desktop) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_ARM_OneCore=$(VC_LibraryPath_VC_ARM_OneCore) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_ARM_Store=$(VC_LibraryPath_VC_ARM_Store) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_ARM64=$(VC_LibraryPath_VC_ARM64) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_ARM64_Desktop=$(VC_LibraryPath_VC_ARM64_Desktop) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_ARM64_OneCore=$(VC_LibraryPath_VC_ARM64_OneCore) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_ARM64_Store=$(VC_LibraryPath_VC_ARM64_Store) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_x64=$(VC_LibraryPath_VC_x64) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_x64_Desktop=$(VC_LibraryPath_VC_x64_Desktop) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_x64_OneCore=$(VC_LibraryPath_VC_x64_OneCore) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_x64_Store=$(VC_LibraryPath_VC_x64_Store) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_x86=$(VC_LibraryPath_VC_x86) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_x86_Desktop=$(VC_LibraryPath_VC_x86_Desktop) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_x86_OneCore=$(VC_LibraryPath_VC_x86_OneCore) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_x86_Store=$(VC_LibraryPath_VC_x86_Store) >>$(TEMP)\macros.txt
echo VC_LibraryPath_x64=$(VC_LibraryPath_x64) >>$(TEMP)\macros.txt
echo VC_LibraryPath_x86=$(VC_LibraryPath_x86) >>$(TEMP)\macros.txt
echo VC_PGO_RunTime_Dir=$(VC_PGO_RunTime_Dir) >>$(TEMP)\macros.txt
echo VC_ReferencesPath_ARM=$(VC_ReferencesPath_ARM) >>$(TEMP)\macros.txt
echo VC_ReferencesPath_ARM64=$(VC_ReferencesPath_ARM64) >>$(TEMP)\macros.txt
echo VC_ReferencesPath_ATL_ARM=$(VC_ReferencesPath_ATL_ARM) >>$(TEMP)\macros.txt
echo VC_ReferencesPath_ATL_ARM64=$(VC_ReferencesPath_ATL_ARM64) >>$(TEMP)\macros.txt
echo VC_ReferencesPath_ATL_x64=$(VC_ReferencesPath_ATL_x64) >>$(TEMP)\macros.txt
echo VC_ReferencesPath_ATL_x86=$(VC_ReferencesPath_ATL_x86) >>$(TEMP)\macros.txt
echo VC_ReferencesPath_VC_ARM=$(VC_ReferencesPath_VC_ARM) >>$(TEMP)\macros.txt
echo VC_ReferencesPath_VC_ARM64=$(VC_ReferencesPath_VC_ARM64) >>$(TEMP)\macros.txt
echo VC_ReferencesPath_VC_x64=$(VC_ReferencesPath_VC_x64) >>$(TEMP)\macros.txt
echo VC_ReferencesPath_VC_x86=$(VC_ReferencesPath_VC_x86) >>$(TEMP)\macros.txt
echo VC_ReferencesPath_x64=$(VC_ReferencesPath_x64) >>$(TEMP)\macros.txt
echo VC_ReferencesPath_x86=$(VC_ReferencesPath_x86) >>$(TEMP)\macros.txt
echo VC_SourcePath=$(VC_SourcePath) >>$(TEMP)\macros.txt
echo VC_VC_IncludePath=$(VC_VC_IncludePath) >>$(TEMP)\macros.txt
echo VC_VS_IncludePath=$(VC_VS_IncludePath) >>$(TEMP)\macros.txt
echo VC_VS_LibraryPath_VC_VS_ARM=$(VC_VS_LibraryPath_VC_VS_ARM) >>$(TEMP)\macros.txt
echo VC_VS_LibraryPath_VC_VS_x64=$(VC_VS_LibraryPath_VC_VS_x64) >>$(TEMP)\macros.txt
echo VC_VS_LibraryPath_VC_VS_x86=$(VC_VS_LibraryPath_VC_VS_x86) >>$(TEMP)\macros.txt
echo VC_VS_SourcePath=$(VC_VS_SourcePath) >>$(TEMP)\macros.txt
echo VCIDEInstallDir=$(VCIDEInstallDir) >>$(TEMP)\macros.txt
echo VCIDEInstallDir_150=$(VCIDEInstallDir_150) >>$(TEMP)\macros.txt
echo VCInstallDir=$(VCInstallDir) >>$(TEMP)\macros.txt
echo VCInstallDir_150=$(VCInstallDir_150) >>$(TEMP)\macros.txt
echo VCLibPackagePath=$(VCLibPackagePath) >>$(TEMP)\macros.txt
echo VCProjectVersion=$(VCProjectVersion) >>$(TEMP)\macros.txt
echo VCTargetsPath=$(VCTargetsPath) >>$(TEMP)\macros.txt
echo VCTargetsPath10=$(VCTargetsPath10) >>$(TEMP)\macros.txt
echo VCTargetsPath11=$(VCTargetsPath11) >>$(TEMP)\macros.txt
echo VCTargetsPath12=$(VCTargetsPath12) >>$(TEMP)\macros.txt
echo VCTargetsPath14=$(VCTargetsPath14) >>$(TEMP)\macros.txt
echo VCTargetsPath15=$(VCTargetsPath15) >>$(TEMP)\macros.txt
echo VCTargetsPathActual=$(VCTargetsPathActual) >>$(TEMP)\macros.txt
echo VCTargetsPathEffective=$(VCTargetsPathEffective) >>$(TEMP)\macros.txt
echo VCToolArchitecture=$(VCToolArchitecture) >>$(TEMP)\macros.txt
echo VCToolsInstallDir=$(VCToolsInstallDir) >>$(TEMP)\macros.txt
echo VCToolsInstallDir_150=$(VCToolsInstallDir_150) >>$(TEMP)\macros.txt
echo VCToolsVersion=$(VCToolsVersion) >>$(TEMP)\macros.txt
echo VisualStudioDir=$(VisualStudioDir) >>$(TEMP)\macros.txt
echo VisualStudioEdition=$(VisualStudioEdition) >>$(TEMP)\macros.txt
echo VisualStudioVersion=$(VisualStudioVersion) >>$(TEMP)\macros.txt
echo VS_ExecutablePath=$(VS_ExecutablePath) >>$(TEMP)\macros.txt
echo VS140COMNTOOLS=$(VS140COMNTOOLS) >>$(TEMP)\macros.txt
echo VSAPPIDDIR=$(VSAPPIDDIR) >>$(TEMP)\macros.txt
echo VSAPPIDNAME=$(VSAPPIDNAME) >>$(TEMP)\macros.txt
echo VSInstallDir=$(VSInstallDir) >>$(TEMP)\macros.txt
echo VSInstallDir_150=$(VSInstallDir_150) >>$(TEMP)\macros.txt
echo VsInstallRoot=$(VsInstallRoot) >>$(TEMP)\macros.txt
echo VSLANG=$(VSLANG) >>$(TEMP)\macros.txt
echo VSVersion=$(VSVersion) >>$(TEMP)\macros.txt
echo WDKBinRoot=$(WDKBinRoot) >>$(TEMP)\macros.txt
echo WebBrowserDebuggerDebuggerlype=$(WebBrowserDebuggerDebuggerlype) >>$(TEMP)\macros.txt
echo WebServiceDebuggerDebuggerlype=$(WebServiceDebuggerDebuggerlype) >>$(TEMP)\macros.txt
echo WebServiceDebuggerSQLDebugging=$(WebServiceDebuggerSQLDebugging) >>$(TEMP)\macros.txt
echo WholeProgramOptimization=$(WholeProgramOptimization) >>$(TEMP)\macros.txt
echo WholeProgramOptimizationAvailabilityInstrument=$(WholeProgramOptimizationAvailabilityInstrument) >>$(TEMP)\macros.txt
echo WholeProgramOptimizationAvailabilityOptimize=$(WholeProgramOptimizationAvailabilityOptimize) >>$(TEMP)\macros.txt
echo WholeProgramOptimizationAvailabilityTrue=$(WholeProgramOptimizationAvailabilityTrue) >>$(TEMP)\macros.txt
echo WholeProgramOptimizationAvailabilityUpdate=$(WholeProgramOptimizationAvailabilityUpdate) >>$(TEMP)\macros.txt
echo windir=$(windir) >>$(TEMP)\macros.txt
echo Windows81SdkInstalled=$(Windows81SdkInstalled) >>$(TEMP)\macros.txt
echo WindowsAppContainer=$(WindowsAppContainer) >>$(TEMP)\macros.txt
echo WindowsSDK_ExecutablePath=$(WindowsSDK_ExecutablePath) >>$(TEMP)\macros.txt
echo WindowsSDK_ExecutablePath_arm=$(WindowsSDK_ExecutablePath_arm) >>$(TEMP)\macros.txt
echo WindowsSDK_ExecutablePath_arm64=$(WindowsSDK_ExecutablePath_arm64) >>$(TEMP)\macros.txt
echo WindowsSDK_ExecutablePath_x64=$(WindowsSDK_ExecutablePath_x64) >>$(TEMP)\macros.txt
echo WindowsSDK_LibraryPath_x86=$(WindowsSDK_LibraryPath_x86) >>$(TEMP)\macros.txt
echo WindowsSDK_MetadataFoundationPath=$(WindowsSDK_MetadataFoundationPath) >>$(TEMP)\macros.txt
echo WindowsSDK_MetadataPath=$(WindowsSDK_MetadataPath) >>$(TEMP)\macros.txt
echo WindowsSDK_MetadataPathVersioned=$(WindowsSDK_MetadataPathVersioned) >>$(TEMP)\macros.txt
echo WindowsSDK_PlatformPath=$(WindowsSDK_PlatformPath) >>$(TEMP)\macros.txt
echo WindowsSDK_SupportedAPIs_arm=$(WindowsSDK_SupportedAPIs_arm) >>$(TEMP)\macros.txt
echo WindowsSDK_SupportedAPIs_x64=$(WindowsSDK_SupportedAPIs_x64) >>$(TEMP)\macros.txt
echo WindowsSDK_SupportedAPIs_x86=$(WindowsSDK_SupportedAPIs_x86) >>$(TEMP)\macros.txt
echo WindowsSDK_UnionMetadataPath=$(WindowsSDK_UnionMetadataPath) >>$(TEMP)\macros.txt
echo WindowsSDK80Path=$(WindowsSDK80Path) >>$(TEMP)\macros.txt
echo WindowsSdkDir=$(WindowsSdkDir) >>$(TEMP)\macros.txt
echo WindowsSdkDir_10=$(WindowsSdkDir_10) >>$(TEMP)\macros.txt
echo WindowsSdkDir_81=$(WindowsSdkDir_81) >>$(TEMP)\macros.txt
echo WindowsSdkDir_81A=$(WindowsSdkDir_81A) >>$(TEMP)\macros.txt
echo WindowsSDKToolArchitecture=$(WindowsSDKToolArchitecture) >>$(TEMP)\macros.txt
echo WindowsTargetPlatformVersion=$(WindowsTargetPlatformVersion) >>$(TEMP)\macros.txt
echo WinRT_IncludePath=$(WinRT_IncludePath) >>$(TEMP)\macros.txt
echo WMSISProject=$(WMSISProject) >>$(TEMP)\macros.txt
echo WMSISProjectDirectory=$(WMSISProjectDirectory) >>$(TEMP)\macros.txt

'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine

The way I solved it on different computers:

I have a Windows 7 32bit machine with Visual Studio 2012 which did not have the Access Database because I do not have the Office 2010. I copied the same source I had in my Windows 7 64bit machine.

So, I installed the AccessDatabaseEngine into this Windows 7 32 bit machine after downloading it per above suggestions from others here and everything worked fine.

I still had the problem on my Windows 7 64 bit machine which already has Office 2010 that already includes Access 2010. The way I solved on this computer was by going into the PROJECT, selected Properties, and at Platform target had Any CPU I checked Prefer 32-bit. Recompiled/Build and the Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine message was gone.

How to compile python script to binary executable

Or use PyInstaller as an alternative to py2exe. Here is a good starting point. PyInstaller also lets you create executables for linux and mac...

Here is how one could fairly easily use PyInstaller to solve the issue at hand:


From the tool's documentation:

PyInstaller analyzes and:

  • Writes myscript.spec in the same folder as the script.
  • Creates a folder build in the same folder as the script if it does not exist.
  • Writes some log files and working files in the build folder.
  • Creates a folder dist in the same folder as the script if it does not exist.
  • Writes the myscript executable folder in the dist folder.

In the dist folder you find the bundled app you distribute to your users.

FormData.append("key", "value") is not working

form data doesn't appear in web browser console

for (var data of formData) {

try this way it will show

Getting return value from stored procedure in C#

For .net core 3.0 and dapper:

If your stored procedure returns this:

select ID, FILE_NAME from dbo.FileStorage where ID = (select max(ID) from dbo.FileStorage);

Then in c#:

 var data = (_dbConnection.Query<FileUploadQueryResponse>
              ("dbo.insertFile", whateverParameters, commandType: CommandType.StoredProcedure)).ToList();
 var storedFileName = data[0].FILE_NAME;
 var id = data[0].ID;

As you can see, you can define a simple class to help with retrieving the actual values from dapper's default return structure (which I found impossible to work with):

public class FileUploadQueryResponse
    public string ID { get; set; }
    public string FILE_NAME { get; set; }

Converting String to Double in Android

    cost=(TextView )findViewById(;

            btn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) { cst =  Double.valueOf(kw.getText().toString());
            cst = cst*0.551;

logger configuration to log to file and print to stdout

Logging to stdout and rotating file with different levels and formats:

import logging
import logging.handlers
import sys

if __name__ == "__main__":

    # Change root logger level from WARNING (default) to NOTSET in order for all messages to be delegated.

    # Add stdout handler, with level INFO
    console = logging.StreamHandler(sys.stdout)
    formater = logging.Formatter('%(name)-13s: %(levelname)-8s %(message)s')

    # Add file rotating handler, with level DEBUG
    rotatingHandler = logging.handlers.RotatingFileHandler(filename='rotating.log', maxBytes=1000, backupCount=5)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

    log = logging.getLogger("app." + __name__)

    log.debug('Debug message, should only appear in the file.')'Info message, should appear in file and stdout.')
    log.warning('Warning message, should appear in file and stdout.')
    log.error('Error message, should appear in file and stdout.')

return string with first match Regex

If you only need the first match, then use instead of re.findall:

>>> m ='\d+', 'aa33bbb44')
>>> m ='\d+', 'aazzzbbb')
Traceback (most recent call last):
  File "<pyshell#281>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'

Then you can use m as a checking condition as:

>>> m ='\d+', 'aa33bbb44')
>>> if m:
        print('First number found = {}'.format(
        print('Not Found')

First number found = 33

jQuery AJAX Call to PHP Script with JSON Return

try to send content type header from server use this just before echoing

header('Content-Type: application/json');

Check if a temporary table exists and delete if it exists before creating a temporary table

When you change a column in a temp table, you must drop the table before running the query again. (Yes, it is annoying. Just what you have to do.)

I have always assumed this is because the "invalid column" check is done by parser before the query is run, so it is based on the columns in the table before it is dropped..... and that is what pnbs also said.

Plotting histograms from grouped data in a pandas DataFrame

I'm on a roll, just found an even simpler way to do it using the by keyword in the hist method:


That's a very handy little shortcut for quickly scanning your grouped data!

For future visitors, the product of this call is the following chart: enter image description here

Casting a variable using a Type variable

Other answers do not mention "dynamic" type. So to add one more answer, you can use "dynamic" type to store your resulting object without having to cast converted object with a static type.

dynamic changedObj = Convert.ChangeType(obj, typeVar);

Keep in mind that with the use of "dynamic" the compiler is bypassing static type checking which could introduce possible runtime errors if you are not careful.

Also, it is assumed that the obj is an instance of Type typeVar or is convertible to that type.

How to create range in Swift?

I find it surprising that, even in Swift 4, there's still no simple native way to express a String range using Int. The only String methods that let you supply an Int as a way of obtaining a substring by range are prefix and suffix.

It is useful to have on hand some conversion utilities, so that we can talk like NSRange when speaking to a String. Here's a utility that takes a location and length, just like NSRange, and returns a Range<String.Index>:

func range(_ start:Int, _ length:Int) -> Range<String.Index> {
    let i = self.index(start >= 0 ? self.startIndex : self.endIndex,
        offsetBy: start)
    let j = self.index(i, offsetBy: length)
    return i..<j

For example, "hello".range(0,1)" is the Range<String.Index> embracing the first character of "hello". As a bonus, I've allowed negative locations: "hello".range(-1,1)" is the Range<String.Index> embracing the last character of "hello".

It is useful also to convert a Range<String.Index> to an NSRange, for those moments when you have to talk to Cocoa (for example, in dealing with NSAttributedString attribute ranges). Swift 4 provides a native way to do that:

let nsrange = NSRange(range, in:s) // where s is the string

We can thus write another utility where we go directly from a String location and length to an NSRange:

extension String {
    func nsRange(_ start:Int, _ length:Int) -> NSRange {
        return NSRange(self.range(start,length), in:self)

What is the best way to add a value to an array in state

For now, this is the best way.

this.setState(previousState => ({
    myArray: [...previousState.myArray, 'new value']

How to set background image in Java?

function SetBack(dir) {

UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function

If you use Python 3.6 (possibly 3.5 or later), it doesn't give that error to me anymore. I had a similar issue, because I was using v3.4, but it went away after I uninstalled and reinstalled.

Git Cherry-pick vs Merge Workflow

In my opinion cherry-picking should be reserved for rare situations where it is required, for example if you did some fix on directly on 'master' branch (trunk, main development branch) and then realized that it should be applied also to 'maint'. You should base workflow either on merge, or on rebase (or "git pull --rebase").

Please remember that cherry-picked or rebased commit is different from the point of view of Git (has different SHA-1 identifier) than the original, so it is different than the commit in remote repository. (Rebase can usually deal with this, as it checks patch id i.e. the changes, not a commit id).

Also in git you can merge many branches at once: so called octopus merge. Note that octopus merge has to succeed without conflicts. Nevertheless it might be useful.


How to find a value in an array and remove it by using PHP array functions?

This is how I would do it:

$terms = array('BMW', 'Audi', 'Porsche', 'Honda');
// -- purge 'make' Porsche from terms --
if (!empty($terms)) {
    $pos = '';
    $pos = array_search('Porsche', $terms);
    if ($pos !== false) unset($terms[$pos]);

Commands out of sync; you can't run this command now

To clear the referencing memory, and run the next MYSQL fetch

If you either use Buffered or Unbuffered result set for fetching data, first you must simply clear the fetched data from the memory, once you have fetched all the data. As you can't execute another MYSQL procedure on the same connection until you clear the fetched memory.

Add this below function right end of your script, so it will solve the problem

$numRecords->close(); or $numRecords->free(); // This clears the referencing memory, and will be ready for the next MYSQL fetch

Reference from the PHP documentation

What is the difference between active and passive FTP?

Active and passive are the two modes that FTP can run in.

For background, FTP actually uses two channels between client and server, the command and data channels, which are actually separate TCP connections.

The command channel is for commands and responses while the data channel is for actually transferring files.

This separation of command information and data into separate channels a nifty way of being able to send commands to the server without having to wait for the current data transfer to finish. As per the RFC, this is only mandated for a subset of commands, such as quitting, aborting the current transfer, and getting the status.

In active mode, the client establishes the command channel but the server is responsible for establishing the data channel. This can actually be a problem if, for example, the client machine is protected by firewalls and will not allow unauthorised session requests from external parties.

In passive mode, the client establishes both channels. We already know it establishes the command channel in active mode and it does the same here.

However, it then requests the server (on the command channel) to start listening on a port (at the servers discretion) rather than trying to establish a connection back to the client.

As part of this, the server also returns to the client the port number it has selected to listen on, so that the client knows how to connect to it.

Once the client knows that, it can then successfully create the data channel and continue.

More details are available in the RFC:

Selecting multiple columns with linq query and lambda expression

Not sure what you table structure is like but see below.

public NamePriceModel[] AllProducts()
        using (UserDataDataContext db = new UserDataDataContext())
            return db.mrobProducts
                .Where(x => x.Status == 1)
                .Select(x => new NamePriceModel { 
                    Name = x.Name, 
                    Id = x.Id, 
                    Price = x.Price
                .OrderBy(x => x.Id)
         return null;

This would return an array of type anonymous with the members you require.


Create a new class.

public class NamePriceModel 
    public string Name {get; set;}
    public decimal? Price {get; set;}
    public int Id {get; set;}

I've modified the query above to return this as well and you should change your method from returning string[] to returning NamePriceModel[].

Windows batch command(s) to read first line from text file

Thanks to thetalkingwalnut with answer Windows batch command(s) to read first line from text file I came up with the following solution:

@echo off
for /f "delims=" %%a in ('type sample.txt') do (
echo %%a
exit /b

"Logging out" of phpMyAdmin?

The second button from the left. The one on the right of the house in the image you posted is your logout button.

For your error message try this link in the documentation:

Make certain you have a phpadmin control user account created. This is covered in the second paragraph in on the documentation page in the link.

How do I find the length (or dimensions, size) of a numpy matrix in python?

shape is a property of both numpy ndarray's and matrices.


will return a tuple (m, n), where m is the number of rows, and n is the number of columns.

In fact, the numpy matrix object is built on top of the ndarray object, one of numpy's two fundamental objects (along with a universal function object), so it inherits from ndarray

Is there a free GUI management tool for Oracle Database Express?

There are a few options:

  • is a windows GUI to connect to many different types of databases, oracle included.
  • Oracle SQL Developer is a free tool from Oracle.
  • SQuirreL SQL is a java based client that can connect to any database that uses JDBC drivers.

I'm sure there are others out there that you could use too...

C# create simple xml file

You could use XDocument:

new XDocument(
    new XElement("root", 
        new XElement("someNode", "someValue")    

If the file you want to create is very big and cannot fit into memory you might use XmlWriter.

Is it possible to access an SQLite database from JavaScript?

IMHO, the best way is to call Python using POST via AJAX and do everything you need to do with the DB within Python, then return the result to the javascript. json and sqlite support in Python is awesome and it's 100% built-in within even slightly recent versions of Python, so there is no "install this, install that" pain. In Python:

import sqlite3
import json

...that's all you need. It's part of every Python distribution.

@Sedrick Jefferson asked for examples, so (somewhat tardily) I have written up a stand-alone back-and-forth between Javascript and Python here.

Laravel - Form Input - Multiple select for a one to many relationship

A multiple select is really just a select with a multiple attribute. With that in mind, it should be as easy as...

Form::select('sports[]', $sports, null, array('multiple'))

The first parameter is just the name, but post-fixing it with the [] will return it as an array when you use Input::get('sports').

The second parameter is an array of selectable options.

The third parameter is an array of options you want pre-selected.

The fourth parameter is actually setting this up as a multiple select dropdown by adding the multiple property to the actual select element..

Uncaught TypeError: undefined is not a function while using jQuery UI

You may see if you are not loading jQuery twice somehow. Especially after your plugin JavaScript file loaded.

I has the same error and found that one of my external PHP files was loading jQuery again.

What's the difference between ClusterIP, NodePort and LoadBalancer service types in Kubernetes?

And do not forget the "new" service type (from the k8s docu):

ExternalName: Maps the Service to the contents of the externalName field (e.g., by returning a CNAME record with its value. No proxying of any kind is set up.

Note: You need either kube-dns version 1.7 or CoreDNS version 0.0.8 or higher to use the ExternalName type.

split python source code into multiple files?


#file  -- --
myvar = 42
def test_func():

Now, this file ("") is in python terminology a "module". We can import it (as long as it can be found in our PYTHONPATH) Note that the current directory is always in PYTHONPATH, so if use_test is being run from the same directory where lives, you're all set:

#file -- --
import test
test.test_func()  #prints "Hello!"
print (test.myvar)  #prints 42

from test import test_func #Only import the function directly into current namespace
test_func() #prints "Hello"
print (myvar)     #Exception (NameError)

from test import *
test_func() #prints "Hello"
print(myvar)      #prints 42

There's a lot more you can do than just that through the use of special files which allow you to treat multiple files as a single module), but this answers your question and I suppose we'll leave the rest for another time.

How to use sed/grep to extract text between two words?

GNU grep can also support positive & negative look-ahead & look-back: For your case, the command would be:

echo "Here is a string" | grep -o -P '(?<=Here).*(?=string)'

If there are multiple occurrences of Here and string, you can choose whether you want to match from the first Here and last string or match them individually. In terms of regex, it is called as greedy match (first case) or non-greedy match (second case)

$ echo 'Here is a string, and Here is another string.' | grep -oP '(?<=Here).*(?=string)' # Greedy match
 is a string, and Here is another 
$ echo 'Here is a string, and Here is another string.' | grep -oP '(?<=Here).*?(?=string)' # Non-greedy match (Notice the '?' after '*' in .*)
 is a 
 is another 

How to set value of input text using jQuery

Using jQuery, we can use the following code:

Select by input name:

$('input[name="textboxname"]').val('some value')

Select by input class:

$('input[type=text].textboxclass').val('some value')

Select by input id:

$('#textboxid').val('some value')

Environment variables in Jenkins

The quick and dirty way, you can view the available environment variables from the below link.


Just replace localhost with your Jenkins hostname, if its different

Angular ng-click with call to a controller function not working

You should probably use the ngHref directive along with the ngClick:

 <a ng-href='#here' ng-click='go()' >click me</a>

Here is an example:

<body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>
    <a ng-href='#here' ng-click='go()' >click me</a>
    <div style='height:1000px'>

      <a id='here'></a>


var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $ = 'World';

  $scope.go = function() {

    $scope.msg = 'clicked';

I don't know if this will work with the library you are using but it will at least let you link and use the ngClick function.

** Update **

Here is a demo of the set and get working fine with a service.

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope, sharedProperties) {
  $ = 'World';

  $scope.go = function(item) {


  $scope.getItem = function() {

    $scope.msg = sharedProperties.getListName();

app.service('sharedProperties', function () {
    var list_name = '';

    return {

        getListName: function() {
            return list_name;
        setListName: function(name) {
            list_name = name;


* Edit *

Please review which talks about how to use lungo and angular. Also note that if your page is completely reloading when browsing to another link, you will need to persist your shared properties into localstorage and/or a cookie.

Indentation shortcuts in Visual Studio

If you would like nicely auto-formatted code. Try CTRL + A + K + F. While holding down CTRL hit a, then k, then f.

Can't run Curl command inside my Docker Container

You don't need to install curl to download the file into Docker container, use ADD command, e.g.

ADD /tmp
RUN ruby -e /tmp/install

Note: Add above lines to your Dockerfile file.

Another example which installs Azure CLI:

ADD /tmp
RUN bash /tmp/InstallAzureCLIDeb

Find the host name and port using PSQL commands

go to the "Terminal" and just type

service postgres status

In the results you can get the port detailsRunning postgres details

In my case it's running on port "5432" (default).
I'm using CentOS 7.Hope this helps.

Setting focus to a textbox control

Using Focus method

  Private Sub frmTest_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    End Sub

Update ViewPager dynamically?

I've gone through all the answers above and a number of others posts but still couldn't find something that worked for me (with different fragment types along with dynamically adding and removing tabs). FWIW following approach is what worked for me (in case anyone else has same issues).

public class MyFragmentStatePageAdapter extends FragmentStatePagerAdapter {
    private static final String TAB1_TITLE = "Tab 1";
    private static final String TAB2_TITLE = "Tab 2";
    private static final String TAB3_TITLE = "Tab 3";

    private ArrayList<String> titles = new ArrayList<>();
    private Map<Fragment, Integer> fragmentPositions = new HashMap<>();

    public MyFragmentStatePageAdapter(FragmentManager fm) {

    public void update(boolean showTab1, boolean showTab2, boolean showTab3) {

        if (showTab1) {
        if (showTab2) {
        if (showTab3) {

    public int getCount() {
        return titles.size();

    public Fragment getItem(int position) {
        Fragment fragment = null;

        String tabName = titles.get(position);
        if (tabName.equals(TAB1_TITLE)) { 
            fragment =  Tab1Fragment.newInstance();
        } else if (tabName.equals(TAB2_TITLE)) {
            fragment =  Tab2Fragment.newInstance();
        } else if (tabName.equals(TAB3_TITLE)) {
            fragment =  Tab3Fragmen.newInstance();

        fragmentPositions.put(fragment, position);
        return fragment;

    public CharSequence getPageTitle(int position) {
        return titles.get(position);

    public int getItemPosition(Object item) {
        BaseFragment fragment = (BaseFragment)item;
        String title = fragment.getTitle();
        int position = titles.indexOf(title);

        Integer fragmentPosition = fragmentPositions.get(item);
        if (fragmentPosition != null && position == fragmentPosition) {
            return POSITION_UNCHANGED;
        } else {
            return POSITION_NONE;

    public void destroyItem(ViewGroup container, int position, Object object) {
        super.destroyItem(container, position, object);

make: Nothing to be done for `all'

I think you missed a tab in 9th line. The line following all:hello must be a blank tab. Make sure that you have a blank tab in 9th line. It will make the interpreter understand that you want to use default recipe for makefile.

jquery ajax function not working

I think you have putted e.preventDefault(); before ajax call that's why its prevent calling of that function and your Ajax call will not call.

So try to remove that e.prevent Default() before Ajax call and add it to the after Ajax call.

OAuth: how to test with local URLs?

Google doesn't allow test auth api on localhost using or .loc and .etc and google short link that shortened your local url( also :). Google accepts only url which starts http://localhost/...

if you want to test google auth api you should follow these steps ...

set new alias

if you use openserver go to settings panel and click on aliases tab and click on dropdown then find localhost and choose it.

now you should choose your local web project root folder by clicking the next dropdown that is next to first dropdown.

and click on a button called add and restart opensever.

now your local project available on this link http://localhost/ also you can paste this local url to google auth api to redirect url field...

Can I install the "app store" in an IOS simulator?

No, according to Apple here:

Note: You cannot install apps from the App Store in simulation environments.

How to compile the finished C# project and then run outside Visual Studio?

On your project folder, open up the bin\Debug subfolder and you'll see the compiled result.

Create multiple threads and wait all of them to complete

I think you need WaitHandler.WaitAll. Here is an example:

public static void Main(string[] args)
    int numOfThreads = 10;
    WaitHandle[] waitHandles = new WaitHandle[numOfThreads];

    for (int i = 0; i < numOfThreads; i++)
        var j = i;
        // Or you can use AutoResetEvent/ManualResetEvent
        var handle = new EventWaitHandle(false, EventResetMode.ManualReset);
        var thread = new Thread(() =>
                                    Thread.Sleep(j * 1000);
                                    Console.WriteLine("Thread{0} exits", j);
        waitHandles[j] = handle;
    Console.WriteLine("Main thread exits");

FCL has a few more convenient functions.

(1) Task.WaitAll, as well as its overloads, when you want to do some tasks in parallel (and with no return values).

var tasks = new[]
    Task.Factory.StartNew(() => DoSomething1()),
    Task.Factory.StartNew(() => DoSomething2()),
    Task.Factory.StartNew(() => DoSomething3())

(2) Task.WhenAll when you want to do some tasks with return values. It performs the operations and puts the results in an array. It's thread-safe, and you don't need to using a thread-safe container and implement the add operation yourself.

var tasks = new[]
    Task.Factory.StartNew(() => GetSomething1()),
    Task.Factory.StartNew(() => GetSomething2()),
    Task.Factory.StartNew(() => GetSomething3())
var things = Task.WhenAll(tasks);

"OverflowError: Python int too large to convert to C long" on windows but not mac

Could anyone help explain why

In Python 2 a python "int" was equivalent to a C long. In Python 3 an "int" is an arbitrary precision type but numpy still uses "int" it to represent the C type "long" when creating arrays.

The size of a C long is platform dependent. On windows it is always 32-bit. On unix-like systems it is normally 32 bit on 32 bit systems and 64 bit on 64 bit systems.

or give a solution for the code on windows? Thanks so much!

Choose a data type whose size is not platform dependent. You can find the list at the most sensible choice would probably be np.int64

AngularJS - ng-if check string empty value

Probably your is undefined if you don't have a photo attribute on item in the first place and thus undefined != ''. But if you'd put some code to show how you provide values to item, it would help.

PS: Sorry to post this as an answer (I rather think it's more of a comment), but I don't have enough reputation yet.

Difference between applicationContext.xml and spring-servlet.xml in Spring Framework

In simple words,

applicationContext.xml defines the beans that are shared among all the servlets. If your application have more than one servlet, then defining the common resources in the applicationContext.xml would make more sense.

spring-servlet.xml defines the beans that are related only to that servlet. Here it is the dispatcher servlet. So, your Spring MVC controllers must be defined in this file.

There is nothing wrong in defining all the beans in the spring-servlet.xml if you are running only one servlet in your web application.

JavaScript DOM remove element

Using Node.removeChild() does the job for you, simply use something like this:

var leftSection = document.getElementById('left-section');

In DOM 4, the remove method applied, but there is a poor browser support according to W3C:

The method node.remove() is implemented in the DOM 4 specification. But because of poor browser support, you should not use it.

But you can use remove method if you using jQuery...

$('#left-section').remove(); //using remove method in jQuery

Also in new frameworks like you can use conditions to remove an element, for example *ngIf in Angular and in React, rendering different views, depends on the conditions...

How to start Apache and MySQL automatically when Windows 8 comes up

You can do it via cmd.

For Apache

Open cmd in administrator mode. Change directory to C:/xampp/apache/bin. Run the command as httpd.exe -k install. Your Apache server service will be installed. You can start it from services.


Change directory to C:/xampp/mysql/bin. Run the command as mysqld --install. Your MySQL service will be installed. You can start it from services.

Note: Make sure the selected Apache and MySQL services are set to start automatically.

You're done. There isn't any need to launch the XAMPP control panel

How can I access iframe elements with Javascript?

Using jQuery you can use contents(). For example:

var inside = $('#one').contents();

Simple function to sort an array of objects

My solution for similar sort problem using ECMA 6

var library = [_x000D_
        {name: 'Steve', course:'WAP', courseID: 'cs452'}, _x000D_
        {name: 'Rakesh', course:'WAA', courseID: 'cs545'},_x000D_
        {name: 'Asad', course:'SWE', courseID: 'cs542'},_x000D_
const sorted_by_name = library.sort( (a,b) => > );_x000D_
for(let k in sorted_by_name){_x000D_

Bitbucket fails to authenticate on git pull

You can update your Bitbucket credentials from the OSX Keychain.

Updating your cached credentials via the command line:

$ git credential-osxkeychain erase
[press return]

If it's successful, nothing will print out. To test that it works, try and clone a repository from Bitbucket. If you are prompted for a password, the keychain entry was deleted.

javascript functions to show and hide divs

check this:

click here
<div id="benefits" style="display:none;">some input in here plus the close button
       <div id="upbutton"><a onclick="close(); return false;"></a></div>

GIT commit as different user without email / or only email

Open Git Bash.

Set a Git username:

$ git config --global "name family" Confirm that you have set the Git username correctly:

$ git config --global

name family

Set a Git email:

$ git config --global [email protected] Confirm that you have set the Git email correctly:

$ git config --global

[email protected]

CodeIgniter PHP Model Access "Unable to locate the model you have specified"

Just adding my problem i had:


and the .php shouldnt be there, so it should have been:


hope this helps someone

How to create an alert message in jsp page after submit process is complete

So let's say after getMasterData servlet will response.sendRedirect to to test.jsp.

In test.jsp

Create a javascript

<script type="text/javascript">
function alertName(){
alert("Form has been submitted");

and than at the bottom

<script type="text/javascript"> window.onload = alertName; </script>

Note:im not sure how to type the code in stackoverflow!. Edit: I just learned how to

Edit 2: TO the question:This works perfectly. Another question. How would I get rid of the initial alert when I first start up the JSP? "Form has been submitted" is present the second I execute. It shows up after the load is done to which is perfect.

To do that i would highly recommendation to use session!

So what you want to do is in your servlet:

session.setAttribute("getAlert", "Yes");//Just initialize a random variable.

than in the test.jsp


 <script type="text/javascript">
var Msg ='<%=session.getAttribute("getAlert")%>';
    if (Msg != "null") {
 function alertName(){
 alert("Form has been submitted");

and than at the bottom

<script type="text/javascript"> window.onload = alertName; </script>

So everytime you submit that form a session will be pass on! If session is not null the function will run!

How can I auto-elevate my batch file, so that it requests from UAC administrator rights if required?

If you don’t need to pass arguments through then here’s a compact UAC prompting script that’s a single line long. This does a similar thing as the elevation script in the top voted answer but doesn’t pass arguments through since there’s no foolproof way to do that that handles every possible combination of poison characters.

net sess>nul 2>&1||(echo(CreateObject("Shell.Application"^).ShellExecute"%~0",,,"RunAs",1:CreateObject("Scripting.FileSystemObject"^).DeleteFile(wsh.ScriptFullName^)>"%temp%\%~nx0.vbs"&start wscript.exe "%temp%\%~nx0.vbs"&exit)

Place this just below the @echo off line in your batch script.


The net sess>nul 2>&1 part is what checks for elevation. net sess is just shorthand for net session which is a command that returns an error code when the script doesn’t have elevated rights. I got this idea from this SO answer. Most of the answers here use net file instead though which works the same.

The error level is then checked with the || operator. If the check succeeds then it creates and executes a WScript which re-runs the original batch file but with elevated rights before deleting itself.

The WScript file is the best approach being fast and reliable, although it uses a temporary file. Here are some other variations and their dis/advantages.


net sess>nul 2>&1||(powershell saps '%0'-Verb RunAs&exit)


  • Very short.
  • No temporary files.


  • Slow. PowerShell can be very slow to start up.
  • Spews red text when the user declines the UAC prompt. The PowerShell command could be wrapped in a try..catch to prevent this though.

Mshta WSH script

net sess>nul 2>&1||(start mshta.exe vbscript:code(close(Execute("CreateObject(""Shell.Application"").ShellExecute""%~0"",,,""RunAs"",1"^)^)^)&exit)


  • Fast.
  • No temporary files.


  • Not reliable. Some Windows 10 machines will block the script from running as Windows Defender intercepts it as a potential trojan.

disable all form elements inside div

For jquery 1.6+, use .prop() instead of .attr(),

$("#parent-selector :input").prop("disabled", true);


$("#parent-selector :input").attr("disabled", "disabled");

ubuntu "No space left on device" but there is tons of space

It's possible that you've run out of memory or some space elsewhere and it prompted the system to mount an overflow filesystem, and for whatever reason, it's not going away.

Try unmounting the overflow partition:

umount /tmp


umount overflow

Mocking a method to throw an exception (moq), but otherwise act like the mocked object?

I think this is what you want, I already tested this code and works

The tools used are: (all these tools can be downloaded as Nuget packages)

var fixture = new Fixture().Customize(new AutoMoqCustomization());
var myInterface = fixture.Freeze<Mock<IFileConnection>>();

var sut = fixture.CreateAnonymous<Transfer>();

myInterface.Setup(x => x.Get(It.IsAny<string>(), It.IsAny<string>()))

sut.Invoking(x => 


Let me explain:

When you write a test, you must know exactly what you want to test, this is called: "subject under test (SUT)", if my understanding is correctly, in this case your SUT is: Transfer

So with this in mind, you should not mock your SUT, if you substitute your SUT, then you wouldn't be actually testing the real code

When your SUT has external dependencies (very common) then you need to substitute them in order to test in isolation your SUT. When I say substitute I'm referring to use a mock, dummy, mock, etc depending on your needs

In this case your external dependency is IFileConnection so you need to create mock for this dependency and configure it to throw the exception, then just call your SUT real method and assert your method handles the exception as expected

  • var fixture = new Fixture().Customize(new AutoMoqCustomization());: This linie initializes a new Fixture object (Autofixture library), this object is used to create SUT's without having to explicitly have to worry about the constructor parameters, since they are created automatically or mocked, in this case using Moq

  • var myInterface = fixture.Freeze<Mock<IFileConnection>>();: This freezes the IFileConnection dependency. Freeze means that Autofixture will use always this dependency when asked, like a singleton for simplicity. But the interesting part is that we are creating a Mock of this dependency, you can use all the Moq methods, since this is a simple Moq object

  • var sut = fixture.CreateAnonymous<Transfer>();: Here AutoFixture is creating the SUT for us

  • myInterface.Setup(x => x.Get(It.IsAny<string>(), It.IsAny<string>())).Throws<System.IO.IOException>(); Here you are configuring the dependency to throw an exception whenever the Get method is called, the rest of the methods from this interface are not being configured, therefore if you try to access them you will get an unexpected exception

  • sut.Invoking(x => x.TransferFiles(myInterface.Object, It.IsAny<string>(), It.IsAny<string>())).ShouldThrow<System.IO.IOException>();: And finally, the time to test your SUT, this line uses the FluenAssertions library, and it just calls the TransferFiles real method from the SUT and as parameters it receives the mocked IFileConnection so whenever you call the IFileConnection.Get in the normal flow of your SUT TransferFiles method, the mocked object will be invoking throwing the configured exception and this is the time to assert that your SUT is handling correctly the exception, in this case, I am just assuring that the exception was thrown by using the ShouldThrow<System.IO.IOException>() (from the FluentAssertions library)

References recommended:

How to use sed to remove all double quotes within a file

Try prepending the doublequote with a backslash in your expresssion:

sed 's/\"//g' [file name]

Java TreeMap Comparator

The comparator should be only for the key, not for the whole entry. It sorts the entries based on the keys.

You should change it to something as follows

SortedMap<String, Double> myMap = 
    new TreeMap<String, Double>(new Comparator<String>()
        public int compare(String o1, String o2)
            return o1.compareTo(o2);


You can do something as follows (create a list of entries in the map and sort the list base on value, but note this not going to sort the map itself) -

List<Map.Entry<String, Double>> entryList = new ArrayList<Map.Entry<String, Double>>(myMap.entrySet());
    Collections.sort(entryList, new Comparator<Map.Entry<String, Double>>() {
        public int compare(Entry<String, Double> o1, Entry<String, Double> o2) {
            return o1.getValue().compareTo(o2.getValue());

How to prevent rm from reporting that a file was not found?

I had same issue for cshell. The only solution I had was to create a dummy file that matched pattern before "rm" in my script.

jquery ui Dialog: cannot call methods on dialog prior to initialization

If you cannot upgrade jQuery and you are getting:

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

You can work around it like so:


Or if you control the view and know no other dialogs should be in use at all on the entire page, you could do:


I would only recommend doing this if using closest causes a performance issue. There are likely other ways to work around it without doing a global close on all dialogs.

How to delete multiple pandas (python) dataframes from memory to save RAM?

In python automatic garbage collection deallocates the variable (pandas DataFrame are also just another object in terms of python). There are different garbage collection strategies that can be tweaked (requires significant learning).

You can manually trigger the garbage collection using

import gc

But frequent calls to garbage collection is discouraged as it is a costly operation and may affect performance.


what is <meta charset="utf-8">?

That meta tag basically specifies which character set a website is written with.

Here is a definition of UTF-8:

UTF-8 (U from Universal Character Set + Transformation Format—8-bit) is a character encoding capable of encoding all possible characters (called code points) in Unicode. The encoding is variable-length and uses 8-bit code units.

How to override trait function and call it from the overridden function?

An alternative approach if interested - with an extra intermediate class to use the normal OOO way. This simplifies the usage with parent::methodname

trait A {
    function calc($v) {
        return $v+1;

// an intermediate class that just uses the trait
class IntClass {
    use A;

// an extended class from IntClass
class MyClass extends IntClass {
    function calc($v) {
        return parent::calc($v);

Cannot resolve symbol AppCompatActivity - Support v7 libraries aren't recognized?

After invalidating Cache, changing from




worked for me.

Using multiple .cpp files in c++ program?

You can simply place a forward declaration of your second() function in your main.cpp above main(). If your second.cpp has more than one function and you want all of it in main(), put all the forward declarations of your functions in second.cpp into a header file and #include it in main.cpp.

Like this-


void second();
int third();
double fourth();


#include <iostream>
#include "second.h"
int main()
    return 0;


void second()

int third()
    return foo;

double fourth()
    return f;

Note that: it is not necessary to #include "second.h" in second.cpp. All your compiler need is forward declarations and your linker will do the job of searching the definitions of those declarations in the other files.

Process to convert simple Python script into Windows executable

You can create executable from python script using NSIS (Nullsoft scriptable install system). Follow the below steps to convert your python files to executable.

  • Download and install NSIS in your system.

  • Compress the folder in the .zip file that you want to export into the executable.

  • Start NSIS and select Installer based on ZIP file. Find and provide a path to your compressed file.

  • Provide your Installer Name and Default Folder path and click on Generate to generate your exe file.

  • Once its done you can click on Test to test executable or Close to complete the process.

  • The executable generated can be installed on the system and can be distributed to use this application without even worrying about installing the required python and its packages.

For a video tutorial follow: How to Convert any Python File to .EXE

remove first element from array and return the array minus the first element

This can be done in one line with lodash _.tail:

var arr = ["item 1", "item 2", "item 3", "item 4"];_x000D_
<script src=""></script>

How to ping ubuntu guest on VirtualBox

Using NAT (the default) this is not possible. Bridged Networking should allow it. If bridged does not work for you (this may be the case when your network adminstration does not allow multiple IP addresses on one physical interface), you could try 'Host-only networking' instead.

For configuration of Host-only here is a quote from the vbox manual(which is pretty good).

For host-only networking, like with internal networking, you may find the DHCP server useful that is built into VirtualBox. This can be enabled to then manage the IP addresses in the host-only network since otherwise you would need to configure all IP addresses statically.

In the VirtualBox graphical user interface, you can configure all these items in the global settings via "File" -> "Settings" -> "Network", which lists all host-only networks which are presently in use. Click on the network name and then on the "Edit" button to the right, and you can modify the adapter and DHCP settings.

Pad a string with leading zeros so it's 3 characters long in SQL Server 2008

For a more dynamic approach try this.

declare @val varchar(5)
declare @maxSpaces int
set @maxSpaces = 3
set @val = '3'
select concat(REPLICATE('0',@maxSpaces-len(@val)),@val)

Hibernate dialect for Oracle Database 11g?

Use the Oracle 10g dialect. Also Hibernate 3.3.2+ is required for recent JDBC drivers (the internal class structure changed - symptoms will be whining about an abstract class).

Dialect of Oracle 11g is same as Oracle 10g (org.hibernate.dialect.Oracle10gDialect). Source:

Run java jar file on a server as background process

Systemd which now runs in the majority of distros

Step 1:

Find your user defined services mine was at /usr/lib/systemd/system/

Step 2:

Create a text file with your favorite text editor name it whatever_you_want.service

Step 3:

Put following Template to the file whatever_you_want.service

Description=webserver Daemon

ExecStart=/usr/bin/java -jar /web/server.jar


Step 4:

Run your service
as super user

$ systemctl start whatever_you_want.service # starts the service
$ systemctl enable whatever_you_want.service # auto starts the service
$ systemctl disable whatever_you_want.service # stops autostart
$ systemctl stop whatever_you_want.service # stops the service
$ systemctl restart whatever_you_want.service # restarts the service

Responsive Google Map?

My Responsive [Solution] Google Map in Foundation 4 Modal


Create an external JavaScript file (i.e. mymap.js) with the following code

google.maps.visualRefresh = true; //Optional

var respMap;

function mymapini() {
    var mapPos = new google.maps.LatLng(-0.172175,1.5); //Set the coordinates
    var mapOpts = {
    zoom: 10, //You can change this according your needs
    disableDefaultUI: true, //Disabling UI Controls (Optional)
    center: mapPos, //Center the map according coordinates
    mapTypeId: google.maps.MapTypeId.ROADMAP

    respMap = new google.maps.Map(document.getElementById('mymap'),

    var mapMarker = new google.maps.Marker({
          position: mapPos,
          map: respMap,
          title: 'You can put any title'

    //This centers automatically to the marker even if you resize your window
    google.maps.event.addListener(respMap, 'idle', function() {
    window.setTimeout(function() {
    }, 250);    

google.maps.event.addDomListener(window, 'load', mymapini);

$("#modalOpen").click(function(){ //Use it like <a href="#" id="modalOpen"...
    $("#myModal").show(); //ID from the Modal <div id="myModal">...
    google.maps.event.trigger(respMap, 'resize');


Add the following code before the tag:

<script src=""></script>
<script src="js/mymap.js"></script>

Add this to the modal code:

<div id="mymap"></div>


Add this to your stylesheet:

#mymap { margin: 0; padding: 0; width:100%; height: 400px;}

iOS 7 status bar overlapping UI

If your developing for iOS 7 I wouldn't recommend wrapping the status bar in a black rectangle old iOS style. Just integrate it to the design for a more iOS 7 "fullscreen" look.

You can use this plugin to adjust the ink colour of the status bar, or hide it or show it in any instance of your app.

The js methods are:


IMPORTANT: Also in your app plist file set UIViewControllerBasedStatusBarAppearance to NO.

How to get the input from the Tkinter Text Widget?

I think this is a better way-

variable1=StringVar() # Value saved here

def search():
  return ''

ttk.Entry(mainframe, width=7, textvariable=variable1).grid(column=2, row=1)

ttk.Label(mainframe, text="label").grid(column=1, row=1)

ttk.Button(mainframe, text="Search", command=search).grid(column=2, row=13)

On pressing the button, the value in the text field would get printed. But make sure You import the ttk separately.

The full code for a basic application is-

from tkinter import *
from tkinter import ttk

mainframe = ttk.Frame(root, padding="10 10 12 12")
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)

variable1=StringVar() # Value saved here

def search():
  return ''

ttk.Entry(mainframe, width=7, textvariable=variable1).grid(column=2, row=1)

ttk.Label(mainframe, text="label").grid(column=1, row=1)

ttk.Button(mainframe, text="Search", command=search).grid(column=2, row=13)


PHP - get base64 img string decode and save as jpg (resulting empty image )

Decode and save image as PNG

header('content-type: image/png');


        $ret = fopen($fullurl, 'r', true, $context);
        $contents = stream_get_contents($ret);
        $base64 = 'data:image/PNG;base64,' . base64_encode($contents);
        echo "<img src=$base64 />" ;


How can I set the initial value of Select2 when using AJAX?

after spending a few hours searching for a solution, I decided to create my own. He it is:

 function CustomInitSelect2(element, options) {
            if (options.url) {
                    type: 'GET',
                    url: options.url,
                    dataType: 'json'
                }).then(function (data) {
                        data: data
                    if (options.initialValue) {

And you can initialize the selects using this function:

$('.select2').each(function (index, element) {
            var item = $(element);
            if ('url')) {
                CustomInitSelect2(item, {
            else {

And of course, here is the html:

<select class="form-control select2" id="test1" data-url="mysite/load" data-value="123"></select>

How to disable keypad popup when on edittext?

Thanks @A.B for good solution


this case if you will disable keyboard in edit text , just add android:focusableInTouchMode="false" in edittext tagline.

work for me in Android Studio 3.0.1 minsdk 16 , maxsdk26

laravel collection to array

you can do something like this

$collection = collect(['name' => 'Desk', 'price' => 200]);

Reference is

Originally from Laracasts website

How can I simulate an array variable in MySQL?

I would try something like this for multiple collections. I'm a MySQL beginner. Sorry about the function names, couldn't decide on what names would be best.

delimiter //

drop  procedure init_
create procedure init_()
    realm  varchar(30) 
    ,  id  varchar(30) 
    ,  val   varchar(255) 
    ,  primary key ( realm , id )

drop function if exists get_
create function get_( p_realm varchar(30) , p_id varchar(30) )
  returns varchar(255)
  reads sql data
  declare ret_val varchar(255);
  declare continue handler for 1146 set ret_val = null;
  select val into ret_val from val_store where id = p_id;
  return ret_val;

drop procedure if exists set_
create procedure set_( p_realm varchar(30) , p_id varchar(30) , p_val varchar(255) )
  call init_(); 
  insert into val_store (realm,id,val) values (p_realm , p_id , p_val) on duplicate key update val = p_val;

drop   procedure if exists remove_
create procedure remove_( p_realm varchar(30) , p_id varchar(30) )
  call init_();
  delete from val_store where realm = p_realm and id = p_id;

drop   procedure if exists erase_
create procedure erase_( p_realm varchar(30) ) 
  call init_();
  delete from val_store where realm = p_realm;

call set_('my_array_table_name','my_key','my_value');

select get_('my_array_table_name','my_key');

Android - setOnClickListener vs OnClickListener vs View.OnClickListener

  1. First of all, there is no difference between View.OnClickListener and OnClickListener. If you just use View.OnClickListener directly, then you don't need to write-

    import android.view.View.OnClickListener

  2. You set an OnClickListener instance (e.g. myListener named object)as the listener to a view via setOnclickListener(). When a click event is fired, that myListener gets notified and it's onClick(View view) method is called. Thats where we do our own task. Hope this helps you.