Programs & Examples On #Mptt

mptt refers to "Modified Preorder Tree Traversal" algorithm for storing hierarchical data

Cancel a vanilla ECMAScript 6 Promise chain

Here's our implementation https://github.com/permettez-moi-de-construire/cancellable-promise

Used like

const {
  cancellablePromise,
  CancelToken,
  CancelError
} = require('@permettezmoideconstruire/cancellable-promise')

const cancelToken = new CancelToken()

const initialPromise = SOMETHING_ASYNC()
const wrappedPromise = cancellablePromise(initialPromise, cancelToken)


// Somewhere, cancel the promise...
cancelToken.cancel()


//Then catch it
wrappedPromise
.then((res) => {
  //Actual, usual fulfill
})
.catch((err) => {
  if(err instanceOf CancelError) {
    //Handle cancel error
  }

  //Handle actual, usual error
})

which :

  • Doesn't touch Promise API
  • Let us make further cancellation inside catch call
  • Rely on cancellation being rejected instead of resolved unlike any other proposal or implementation

Pulls and comments welcome

Django: OperationalError No Such Table

I'm using Django CMS 3.4 with Django 1.8. I stepped through the root cause in the Django CMS code. Root cause is the Django CMS is not changing directory to the directory with file containing the SQLite3 database before making database calls. The error message is spurious. The underlying problem is that a SQLite database call is made in the wrong directory.

The workaround is to ensure all your Django applications change directory back to the Django Project root directory when changing to working directories.

MySQL the right syntax to use near '' at line 1 error

the problem is because you have got the query over multiple lines using the " " that PHP is actually sending all the white spaces in to MySQL which is causing it to error out.

Either put it on one line or append on each line :o)

Sqlyog must be trimming white spaces on each line which explains why its working.

Example:

$qr2="INSERT INTO wp_bp_activity
      (
            user_id,
 (this stuff)component,
     (is)      `type`,
    (a)        `action`,
  (problem)  content,
             primary_link,
             item_id,....

Could not execute menu item (internal error)[Exception] - When changing PHP version from 5.3.1 to 5.2.9

To anyone who is reading this -> don't use php 5.3 anymore, switch to newer versions of php, because php 5.3 is using deprecated functions.

The following is a list of deprecated INI directives. Use of any of these INI directives will cause an E_DEPRECATED error to be thrown at startup, so I advise you to use newer version to develop.

define_syslog_variables
register_globals
register_long_arrays
safe_mode
magic_quotes_gpc
magic_quotes_runtime
magic_quotes_sybase
Comments starting with '#' are now deprecated in .INI files.

Deprecated functions:

call_user_method() (use call_user_func() instead)
call_user_method_array() (use call_user_func_array() instead)
define_syslog_variables()
dl()
ereg() (use preg_match() instead)
ereg_replace() (use preg_replace() instead)
eregi() (use preg_match() with the 'i' modifier instead)
eregi_replace() (use preg_replace() with the 'i' modifier instead)
set_magic_quotes_runtime() and its alias, magic_quotes_runtime()
session_register() (use the $_SESSION superglobal instead)
session_unregister() (use the $_SESSION superglobal instead)
session_is_registered() (use the $_SESSION superglobal instead)
set_socket_blocking() (use stream_set_blocking() instead)
split() (use preg_split() instead)
spliti() (use preg_split() with the 'i' modifier instead)
sql_regcase()
mysql_db_query() (use mysql_select_db() and mysql_query() instead)
mysql_escape_string() (use mysql_real_escape_string() instead)
Passing locale category names as strings is now deprecated. Use the LC_* family of constants instead.
The is_dst parameter to mktime(). Use the new timezone handling functions instead.

Deprecated features:

Assigning the return value of new by reference is now deprecated.
Call-time pass-by-reference is now deprecated.

Iterating through a list in reverse order in java

This is an old question, but it's lacking a java8-friendly answer. Here are some ways of reverse-iterating the list, with the help of the Streaming API:

List<Integer> list = new ArrayList<Integer>(Arrays.asList(1, 3, 3, 7, 5));
list.stream().forEach(System.out::println); // 1 3 3 7 5

int size = list.size();

ListIterator<Integer> it = list.listIterator(size);
Stream.generate(it::previous).limit(size)
    .forEach(System.out::println); // 5 7 3 3 1

ListIterator<Integer> it2 = list.listIterator(size);
Stream.iterate(it2.previous(), i -> it2.previous()).limit(size)
    .forEach(System.out::println); // 5 7 3 3 1

// If list is RandomAccess (i.e. an ArrayList)
IntStream.range(0, size).map(i -> size - i - 1).map(list::get)
    .forEach(System.out::println); // 5 7 3 3 1

// If list is RandomAccess (i.e. an ArrayList), less efficient due to sorting
IntStream.range(0, size).boxed().sorted(Comparator.reverseOrder())
    .map(list::get).forEach(System.out::println); // 5 7 3 3 1

replacing NA's with 0's in R dataframe

dataset <- matrix(sample(c(NA, 1:5), 25, replace = TRUE), 5);
data <- as.data.frame(dataset)
[,1] [,2] [,3] [,4] [,5] 
[1,]    2    3    5    5    4
[2,]    2    4    3    2    4
[3,]    2   NA   NA   NA    2
[4,]    2    3   NA    5    5
[5,]    2    3    2    2    3
data[is.na(data)] <- 0

MySQL delete multiple rows in one query conditions unique to each row

Took a lot of googling but here is what I do in Python for MySql when I want to delete multiple items from a single table using a list of values.

#create some empty list
values = []
#continue to append the values you want to delete to it
#BUT you must ensure instead of a string it's a single value tuple
values.append(([Your Variable],))
#Then once your array is loaded perform an execute many
cursor.executemany("DELETE FROM YourTable WHERE ID = %s", values)

MVC4 HTTP Error 403.14 - Forbidden

Before applying

runAllManagedModulesForAllRequests="true"/>

consider the link below that suggests a less drastic alternative. In the post the author offers the following alteration to the local web.config:

  <system.webServer>
    <modules>
    <remove name="UrlRoutingModule-4.0" />
    <add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />
    </modules>

http://www.britishdeveloper.co.uk/2010/06/dont-use-modules-runallmanagedmodulesfo.html

Insert current date into a date column using T-SQL?

To insert a new row into a given table (tblTable) :

INSERT INTO tblTable (DateColumn) VALUES (GETDATE())

To update an existing row :

UPDATE tblTable SET DateColumn = GETDATE()
 WHERE ID = RequiredUpdateID

Note that when INSERTing a new row you will need to observe any constraints which are on the table - most likely the NOT NULL constraint - so you may need to provide values for other columns eg...

 INSERT INTO tblTable (Name, Type, DateColumn) VALUES ('John', 7, GETDATE())

npm throws error without sudo

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

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

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

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

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

Ionic 2: Cordova is not available. Make sure to include cordova.js or run in a device/simulator (running in emulator)

In case anyone stumbles with this problem again, the accepted solution did work for older versions of ionic and app scripts, I had used it many times in the past, but last week, after I updated some stuff, it got broken again, and this fix wasn't working anymore as this was already solved on the current version of app-scripts, most of the info is referred on this post https://forum.ionicframework.com/t/ionic-cordova-run-android-livereload-cordova-not-available/116790/18 but I'll make it short here:

First make sure you have this versions on your system

cli packages: (xxxx\npm\node_modules)

@ionic/cli-utils  : 1.19.2
ionic (Ionic CLI) : 3.20.0

global packages:

cordova (Cordova CLI) : not installed

local packages:

@ionic/app-scripts : 3.1.9
Cordova Platforms  : android 7.0.0
Ionic Framework    : ionic-angular 3.9.2

System:

Node : v10.1.0
npm  : 5.6.0

An this on your package.json

"@angular/cli": "^6.0.3", "@ionic/app-scripts": "^3.1.9", "typescript": "~2.4.2"

Now remove your platform with ionic cordova platform rm what-ever Then DELETE the node_modules and plugins folder and MAKE SURE the platform was deleted inside the platforms folder.

Finally, run

npm install ionic cordova platform add what-ever ionic cordova run

And everything should be working again

How to get just one file from another branch

If you want the file from a particular commit (any branch) , say 06f8251f

git checkout 06f8251f path_to_file

for example , in windows:

git checkout 06f8251f C:\A\B\C\D\file.h

VSCode: How to Split Editor Vertically

The key bindings has been changed with version 1.20:

SHIFT+ALT+0 for Linux.

Presumably the same works for Windows also and CMD+OPT+0 for Mac.

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

GET requests can have "Accept" headers, which say which types of content the client understands. The server can then use that to decide which content type to send back.

They're optional though.

http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1

When I catch an exception, how do I get the type, file, and line number?

Simplest form that worked for me.

import traceback

try:
    print(4/0)
except ZeroDivisionError:
    print(traceback.format_exc())

Output

Traceback (most recent call last):
  File "/path/to/file.py", line 51, in <module>
    print(4/0)
ZeroDivisionError: division by zero

Process finished with exit code 0

How to delete the first row of a dataframe in R?

No one probably really wants to remove row one. So if you are looking for something meaningful, that is conditional selection

#remove rows that have long length and "0" value for vector E

>> setNew<-set[!(set$length=="long" & set$E==0),]

PHP: Best way to check if input is a valid number?

filter_var()

$options = array(
    'options' => array('min_range' => 0)
);

if (filter_var($int, FILTER_VALIDATE_INT, $options) !== FALSE) {
 // you're good
}

Run cURL commands from Windows console

Simplest answer:

(1) Download the curl binary here: https://curl.haxx.se/download.html (see the binary for your OS). Example:

Choose 64 bit or 32 bit after click

(2) Create a folder "C:\curl" then unzip all there

See the .crt file, it is, the SSL certificate that already comes with curl package

(3) Edit the system variable called "Path" by adding ";C:\curl\bin" in the end. Finished.

enter image description here

Obs.: I've seen some guys telling to add ";C:\curl" but this way it's not possible to access curl.exe.

How might I schedule a C# Windows Service to perform a task daily?

Check out Quartz.NET. You can use it within a Windows service. It allows you to run a job based on a configured schedule, and it even supports a simple "cron job" syntax. I've had a lot of success with it.

Here's a quick example of its usage:

// Instantiate the Quartz.NET scheduler
var schedulerFactory = new StdSchedulerFactory();
var scheduler = schedulerFactory.GetScheduler();

// Instantiate the JobDetail object passing in the type of your
// custom job class. Your class merely needs to implement a simple
// interface with a single method called "Execute".
var job = new JobDetail("job1", "group1", typeof(MyJobClass));

// Instantiate a trigger using the basic cron syntax.
// This tells it to run at 1AM every Monday - Friday.
var trigger = new CronTrigger(
    "trigger1", "group1", "job1", "group1", "0 0 1 ? * MON-FRI");

// Add the job to the scheduler
scheduler.AddJob(job, true);
scheduler.ScheduleJob(trigger);

How to get visitor's location (i.e. country) using geolocation?

You can use my service, http://ipinfo.io, for this. It will give you the client IP, hostname, geolocation information (city, region, country, area code, zip code etc) and network owner. Here's a simple example that logs the city and country:

$.get("https://ipinfo.io", function(response) {
    console.log(response.city, response.country);
}, "jsonp");

Here's a more detailed JSFiddle example that also prints out the full response information, so you can see all of the available details: http://jsfiddle.net/zK5FN/2/

The location will generally be less accurate than the native geolocation details, but it doesn't require any user permission.

Initial size for the ArrayList

Right now there are no elements in your list so you cannot add to index 5 of the list when it does not exist. You are confusing the capacity of the list with its current size.

Just call:

arr.add(10)

to add the Integer to your ArrayList

Check if null Boolean is true results in exception

Or with the power of Java 8 Optional, you also can do such trick:

Optional.ofNullable(boolValue).orElse(false)

:)

Set selected option of select box

$(function() {
$("#demo").val('hello');
});

error: Unable to find vcvarsall.bat

I tried all the above answers, and found all of them not to work, this was perhaps I was using Windows 8 and had installed Visual Studio 2012. In this case, this is what you do.

The vcvarsall.bat file is located here: C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC

Simply select the file, and copy it.

Then go to this directory: C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\Tools

and paste the file. And then, all should be well.

How to get full REST request body using Jersey?

Turns out you don't have to do much at all.

See below - the parameter x will contain the full HTTP body (which is XML in our case).

@POST
public Response go(String x) throws IOException {
    ...
}

Get POST data in C#/ASP.NET

Try using:

string ap = c.Request["AP"];

That reads from the cookies, form, query string or server variables.

Alternatively:

string ap = c.Request.Form["AP"];

to just read from the form's data.

How to get the difference between two arrays in JavaScript?

var compare = array1.length > array2.length ? array1 : array2;
var compareWith = array1.length > array2.length ? array2 : array1;
var uniqueValues = compareWith.filter(function(value){
                    if(compare.indexOf(vakye) == -1)
                       return true;
                   });

This will both check which one is the larger one among the arrays and then will do the comparison.

Jquery get input array field

use map method we can get input values that stored in array.

var values = $("input[name='pages_title[]']").map(function(){return $(this).val();}).get();

What does $1 mean in Perl?

These are called "match variables". As previously mentioned they contain the text from your last regular expression match.

More information is in Essential Perl. (Ctrl + F for 'Match Variables' to find the corresponding section.)

how to bind img src in angular 2 in ngFor?

Angular 2 and Angular 4 

In a ngFor loop it must be look like this:

<div class="column" *ngFor="let u of events ">
                <div class="thumb">
                    <img src="assets/uploads/{{u.image}}">
                    <h4>{{u.name}}</h4>
                </div>
                <div class="info">
                    <img src="assets/uploads/{{u.image}}">
                    <h4>{{u.name}}</h4>
                    <p>{{u.text}}</p>
                </div>
            </div>

JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value

Spring Boot 2.2.2 / Gradle:

Gradle (build.gradle):

implementation("com.fasterxml.jackson.datatype:jackson-datatype-jsr310")

Entity (User.class):

LocalDate dateOfBirth;

Code:

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
User user = mapper.readValue(json, User.class);

git status shows fatal: bad object HEAD

I managed to fix a similar problem to this when some of git's files were corrupted:

https://stackoverflow.com/a/30871926/1737957

In my answer on that question, look for the part where I had the same error message as here:

fatal: bad object HEAD.

You could try following what I did from that point on. Make sure to back up the whole folder first.

Of course, your repository might be corrupted in a completely different way, and what I did won't solve your problem. But it might give you some ideas! Git internals seem like magic, but it's really just a bunch of files which can be edited, moved, deleted the same as any others. Once you have a good idea of what they do and how they fit together you have a good chance of success.

HTML select form with option to enter custom value

HTML5 has a built-in combo box. You create a text input and a datalist. Then you add a list attribute to the input, with a value of the id of the datalist.

Update: As of March 2019 all major browsers (now including Safari 12.1 and iOS Safari 12.3) support datalist to the level needed for this functionality. See caniuse for detailed browser support.

It looks like this:

_x000D_
_x000D_
<input type="text" list="cars" />_x000D_
<datalist id="cars">_x000D_
  <option>Volvo</option>_x000D_
  <option>Saab</option>_x000D_
  <option>Mercedes</option>_x000D_
  <option>Audi</option>_x000D_
</datalist>
_x000D_
_x000D_
_x000D_

Android ADB doesn't see device

On Windows it is most probably that the device drivers are not installed properly.

First, install Google USB Driver from Android SDK Manager.

Then, go to Start, right-click on My Computer, select Properties and go to Device Manager on the left. Locate you device under Other Devices (Unknown devices, USB Devices). Right-click on it and select Properties. Navigate to Driver tab. Select Update Driver and then Browse my computer for driver software. Choose %ANDROID_SDK_HOME%\extras\google\usb_driver directory. Windows should find and install drivers there. Then run adb kill-server. Next time you do adb devices the device should be in the list.

How to bring a window to the front?

I had the same problem with bringing a JFrame to the front under Ubuntu (Java 1.6.0_10). And the only way I could resolve it is by providing a WindowListener. Specifically, I had to set my JFrame to always stay on top whenever toFront() is invoked, and provide windowDeactivated event handler to setAlwaysOnTop(false).


So, here is the code that could be placed into a base JFrame, which is used to derive all application frames.

@Override
public void setVisible(final boolean visible) {
  // make sure that frame is marked as not disposed if it is asked to be visible
  if (visible) {
      setDisposed(false);
  }
  // let's handle visibility...
  if (!visible || !isVisible()) { // have to check this condition simply because super.setVisible(true) invokes toFront if frame was already visible
      super.setVisible(visible);
  }
  // ...and bring frame to the front.. in a strange and weird way
  if (visible) {
      toFront();
  }
}

@Override
public void toFront() {
  super.setVisible(true);
  int state = super.getExtendedState();
  state &= ~JFrame.ICONIFIED;
  super.setExtendedState(state);
  super.setAlwaysOnTop(true);
  super.toFront();
  super.requestFocus();
  super.setAlwaysOnTop(false);
}

Whenever your frame should be displayed or brought to front call frame.setVisible(true).

Since I moved to Ubuntu 9.04 there seems to be no need in having a WindowListener for invoking super.setAlwaysOnTop(false) -- as can be observed; this code was moved to the methods toFront() and setVisible().

Please note that method setVisible() should always be invoked on EDT.

How to make links in a TextView clickable?

This question is very old but none answered the obvious one. This code is taken from one of my hobby projects:

package com.stackoverflow.java.android;

import android.content.Context;
import android.text.method.LinkMovementMethod;
import android.text.method.MovementMethod;
import android.util.AttributeSet;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;

public class HyperlinkTextView extends AppCompatTextView {
    public HyperlinkTextView(Context context) {
        super(context);
    }

    public HyperlinkTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public HyperlinkTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    /**
     * Set default movement method to {@link LinkMovementMethod}
     * @return Link movement method as the default movement method
     */
    @Override
    protected MovementMethod getDefaultMovementMethod() {
        return LinkMovementMethod.getInstance();
    }
}

Now, simply using com.stackoverflow.java.android.HyperlinkTextView instead of TextView in your layout files will solve your problem.

MongoDB: update every document on one field

I have been using MongoDB .NET driver for a little over a month now. If I were to do it using .NET driver, I would use Update method on the collection object. First, I will construct a query that will get me all the documents I am interested in and do an Update on the fields I want to change. Update in Mongo only affects the first document and to update all documents resulting from the query one needs to use 'Multi' update flag. Sample code follows...

var collection = db.GetCollection("Foo");
var query = Query.GTE("No", 1); // need to construct in such a way that it will give all 20K //docs.
var update = Update.Set("timestamp", datetime.UtcNow);
collection.Update(query, update, UpdateFlags.Multi);

What is Python buffer type for?

I think buffers are e.g. useful when interfacing python to native libraries. (Guido van Rossum explains buffer in this mailinglist post).

For example, numpy seems to use buffer for efficient data storage:

import numpy
a = numpy.ndarray(1000000)

the a.data is a:

<read-write buffer for 0x1d7b410, size 8000000, offset 0 at 0x1e353b0>

Is there a JavaScript / jQuery DOM change listener?

In addition to the "raw" tools provided by MutationObserver API, there exist "convenience" libraries to work with DOM mutations.

Consider: MutationObserver represents each DOM change in terms of subtrees. So if you're, for instance, waiting for a certain element to be inserted, it may be deep inside the children of mutations.mutation[i].addedNodes[j].

Another problem is when your own code, in reaction to mutations, changes DOM - you often want to filter it out.

A good convenience library that solves such problems is mutation-summary (disclaimer: I'm not the author, just a satisfied user), which enables you to specify queries of what you're interested in, and get exactly that.

Basic usage example from the docs:

var observer = new MutationSummary({
  callback: updateWidgets,
  queries: [{
    element: '[data-widget]'
  }]
});

function updateWidgets(summaries) {
  var widgetSummary = summaries[0];
  widgetSummary.added.forEach(buildNewWidget);
  widgetSummary.removed.forEach(cleanupExistingWidget);
}

What is an NP-complete in computer science?

We need to separate algorithms and problems. We write algorithms to solve problems, and they scale in a certain way. Although this is a simplification, let's label an algorithm with a 'P' if the scaling is good enough, and 'NP' if it isn't.

It's helpful to know things about the problems we're trying to solve, rather than the algorithms we use to solve them. So we'll say that all the problems which have a well-scaling algorithm are "in P". And the ones which have a poor-scaling algorithm are "in NP".

That means that lots of simple problems are "in NP" too, because we can write bad algorithms to solve easy problems. It would be good to know which problems in NP are the really tricky ones, but we don't just want to say "it's the ones we haven't found a good algorithm for". After all, I could come up with a problem (call it X) that I think needs a super-amazing algorithm. I tell the world that the best algorithm I could come up with to solve X scales badly, and so I think that X is a really tough problem. But tomorrow, maybe somebody cleverer than me invents an algorithm which solves X and is in P. So this isn't a very good definition of hard problems.

All the same, there are lots of problems in NP that nobody knows a good algorithm for. So if I could prove that X is a certain sort of problem: one where a good algorithm to solve X could also be used, in some roundabout way, to give a good algorithm for every other problem in NP. Well now people might be a bit more convinced that X is a genuinely tricky problem. And in this case we call X NP-Complete.

Rotate and translate

There is no need for that, as you can use css 'writing-mode' with values 'vertical-lr' or 'vertical-rl' as desired.

.item {
  writing-mode: vertical-rl;
}

CSS:writing-mode

How to split a large text file into smaller files with equal number of lines?

use split

Split a file into fixed-size pieces, creates output files containing consecutive sections of INPUT (standard input if none is given or INPUT is `-')

Syntax split [options] [INPUT [PREFIX]]

http://ss64.com/bash/split.html

How do I remove a single breakpoint with GDB?

Use:

clear fileName:lineNum   // Removes all breakpoints at the specified line.
delete breakpoint number // Delete one breakpoint whose number is 'number'

RestTemplate: How to send URL and query parameters together

One-liner using TestRestTemplate.exchange function with parameters map.

restTemplate.exchange("/someUrl?id={id}", HttpMethod.GET, reqEntity, respType, ["id": id])

The params map initialized like this is a groovy initializer*

How do I get the localhost name in PowerShell?

All above questions are correct but if you want the hostname and domain name try this:

 [System.Net.DNS]::GetHostByName('').HostName

Understanding INADDR_ANY for socket programming

To bind socket with localhost, before you invoke the bind function, sin_addr.s_addr field of the sockaddr_in structure should be set properly. The proper value can be obtained either by

my_sockaddress.sin_addr.s_addr = inet_addr("127.0.0.1")

or by

my_sockaddress.sin_addr.s_addr=htonl(INADDR_LOOPBACK);

What does PermGen actually stand for?

Permgen stands for Permanent Generation. It is one of the JVM memory areas. It's part of Heap with fixed size by using a flag called MaxPermSize.

Why the name "PermGen" ?

This permgen was named in early days of Java. Permgen mains keeps all the meta data of loaded classes. But the problem is that once a class is loaded it'll remain in the JVM till JVM shutdown. So name permgen is opt for that. But later, dynamic loading of classes came into picture but name was not changed. But with Java 8, they have addressed that issue as well. Now permagen was renamed as MetaSpace with dynamic memory size.

how to reset <input type = "file">

You need to wrap <input type = “file”> in to <form> tags and then you can reset input by resetting your form:

onClick="this.form.reset()"

How to disassemble a binary executable in Linux to get the assembly code?

You might find ODA useful. It's a web-based disassembler that supports tons of architectures.

http://onlinedisassembler.com/

Git: How configure KDiff3 as merge tool and diff tool

These sites were very helpful, almost, mergetool and difftool. I used the global configuration, but can be used by repository without problems. You just need to execute the following commands:

git config --global merge.tool kdiff3
git config --global mergetool.kdiff3.path "C:/Program Files/KDiff3/bin/kdiff3.exe"
git config --global mergetool.kdiff3.trustExitCode false

git config --global diff.guitool kdiff3
git config --global difftool.kdiff3.path "C:/Program Files/KDiff3/bin/kdiff3.exe"
git config --global difftool.kdiff3.trustExitCode false

Note that the latest version kdiff3 moved the executable from the root of the application folder C:/Program Files/KDiff3 into the bin/ folder inside the application folder. If you're using an older version, remove "bin/" from the paths above.

The use of the trustExitCode option depends on what you want to do when diff tool returns. From documentation:

git-difftool invokes a diff tool individually on each file. Errors reported by the diff tool are ignored by default. Use --trust-exit-code to make git-difftool exit when an invoked diff tool returns a non-zero exit code.

Adding to the classpath on OSX

Normally there's no need for that. First of all

echo $CLASSPATH

If there's something in there, you probably want to check Applications -> Utilites -> Java.

How do you use script variables in psql?

FWIW, the real problem was that I had included a semicolon at the end of my \set command:

\set owner_password 'thepassword';

The semicolon was interpreted as an actual character in the variable:

\echo :owner_password thepassword;

So when I tried to use it:

CREATE ROLE myrole LOGIN UNENCRYPTED PASSWORD :owner_password NOINHERIT CREATEDB CREATEROLE VALID UNTIL 'infinity';

...I got this:

CREATE ROLE myrole LOGIN UNENCRYPTED PASSWORD thepassword; NOINHERIT CREATEDB CREATEROLE VALID UNTIL 'infinity';

That not only failed to set the quotes around the literal, but split the command into 2 parts (the second of which was invalid as it started with "NOINHERIT").

The moral of this story: PostgreSQL "variables" are really macros used in text expansion, not true values. I'm sure that comes in handy, but it's tricky at first.

Android get Current UTC time

see my answer here:

How can I get the current date and time in UTC or GMT in Java?

I've fully tested it by changing the timezones on the emulator

How to get an isoformat datetime string including the default timezone?

Something like the following example. Note I'm in Eastern Australia (UTC + 10 hours at the moment).

>>> import datetime
>>> dtnow = datetime.datetime.now();dtutcnow = datetime.datetime.utcnow()
>>> dtnow
datetime.datetime(2010, 8, 4, 9, 33, 9, 890000)
>>> dtutcnow
datetime.datetime(2010, 8, 3, 23, 33, 9, 890000)
>>> delta = dtnow - dtutcnow
>>> delta
datetime.timedelta(0, 36000)
>>> hh,mm = divmod((delta.days * 24*60*60 + delta.seconds + 30) // 60, 60)
>>> hh,mm
(10, 0)
>>> "%s%+02d:%02d" % (dtnow.isoformat(), hh, mm)
'2010-08-04T09:33:09.890000+10:00'
>>>

I get "Http failure response for (unknown url): 0 Unknown Error" instead of actual error message in Angular

Add This Codes in your connection file

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT,GET,POST,DELETE");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

Jackson and generic type reference

I modified rushidesai1's answer to include a working example.

JsonMarshaller.java

import java.io.*;
import java.util.*;

public class JsonMarshaller<T> {
    private static ClassLoader loader = JsonMarshaller.class.getClassLoader();

    public static void main(String[] args) {
        try {
            JsonMarshallerUnmarshaller<Station> marshaller = new JsonMarshallerUnmarshaller<>(Station.class);
            String jsonString = read(loader.getResourceAsStream("data.json"));
            List<Station> stations = marshaller.unmarshal(jsonString);
            stations.forEach(System.out::println);
            System.out.println(marshaller.marshal(stations));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @SuppressWarnings("resource")
    public static String read(InputStream ios) {
        return new Scanner(ios).useDelimiter("\\A").next(); // Read the entire file
    }
}

Output

Station [id=123, title=my title, name=my name]
Station [id=456, title=my title 2, name=my name 2]
[{"id":123,"title":"my title","name":"my name"},{"id":456,"title":"my title 2","name":"my name 2"}]

JsonMarshallerUnmarshaller.java

import java.io.*;
import java.util.List;

import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;

public class JsonMarshallerUnmarshaller<T> {
    private ObjectMapper mapper;
    private Class<T> targetClass;

    public JsonMarshallerUnmarshaller(Class<T> targetClass) {
        AnnotationIntrospector introspector = new JacksonAnnotationIntrospector();

        mapper = new ObjectMapper();
        mapper.getDeserializationConfig().with(introspector);
        mapper.getSerializationConfig().with(introspector);

        this.targetClass = targetClass;
    }

    public List<T> unmarshal(String jsonString) throws JsonParseException, JsonMappingException, IOException {
        return parseList(jsonString, mapper, targetClass);
    }

    public String marshal(List<T> list) throws JsonProcessingException {
        return mapper.writeValueAsString(list);
    }

    public static <E> List<E> parseList(String str, ObjectMapper mapper, Class<E> clazz)
            throws JsonParseException, JsonMappingException, IOException {
        return mapper.readValue(str, listType(mapper, clazz));
    }

    public static <E> List<E> parseList(InputStream is, ObjectMapper mapper, Class<E> clazz)
            throws JsonParseException, JsonMappingException, IOException {
        return mapper.readValue(is, listType(mapper, clazz));
    }

    public static <E> JavaType listType(ObjectMapper mapper, Class<E> clazz) {
        return mapper.getTypeFactory().constructCollectionType(List.class, clazz);
    }
}

Station.java

public class Station {
    private long id;
    private String title;
    private String name;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return String.format("Station [id=%s, title=%s, name=%s]", id, title, name);
    }
}

data.json

[{
  "id": 123,
  "title": "my title",
  "name": "my name"
}, {
  "id": 456,
  "title": "my title 2",
  "name": "my name 2"
}]

How do I make a redirect in PHP?

Use the header() function to send an HTTP Location header:

header('Location: '.$newURL);

Contrary to what some think, die() has nothing to do with redirection. Use it only if you want to redirect instead of normal execution.

File example.php:

<?php
    header('Location: static.html');
    $fh = fopen('/tmp/track.txt', 'a');
    fwrite($fh, $_SERVER['REMOTE_ADDR'] . ' ' . date('c') . "\n");
    fclose($fh);
?>

Result of three executions:

bart@hal9k:~> cat /tmp/track.txt
127.0.0.1 2009-04-21T09:50:02+02:00
127.0.0.1 2009-04-21T09:50:05+02:00
127.0.0.1 2009-04-21T09:50:08+02:00

Resuming — obligatory die()/exit() is some urban legend that has nothing to do with actual PHP. It has nothing to do with client "respecting" the Location: header. Sending a header does not stop PHP execution, regardless of the client used.

Core Data: Quickest way to delete all instances of an entity

in iOS 11.3 and Swift 4.1

let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
        let batchDeleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest )
        batchDeleteRequest.resultType = .resultTypeCount
        do {
            let batchDeleteResult = try dataController.viewContext.execute(batchDeleteRequest) as! NSBatchDeleteResult
            print("The batch delete request has deleted \(batchDeleteResult.result!) records.")
            dataController.viewContext.reset() // reset managed object context (need it for working)
        } catch {
            let updateError = error as NSError
            print("\(updateError), \(updateError.userInfo)")
        }

you have to call reset after you do execute. If not, it will not update on the table view.

What are the rules about using an underscore in a C++ identifier?

As for the other part of the question, it's common to put the underscore at the end of the variable name to not clash with anything internal.

I do this even inside classes and namespaces because I then only have to remember one rule (compared to "at the end of the name in global scope, and the beginning of the name everywhere else").

Print list without brackets in a single row

This is what you need

", ".join(names)

Execution time of C program

You functionally want this:

#include <sys/time.h>

struct timeval  tv1, tv2;
gettimeofday(&tv1, NULL);
/* stuff to do! */
gettimeofday(&tv2, NULL);

printf ("Total time = %f seconds\n",
         (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 +
         (double) (tv2.tv_sec - tv1.tv_sec));

Note that this measures in microseconds, not just seconds.

How to check status of PostgreSQL server Mac OS X

It depends on where your postgresql server is installed. You use the pg_ctl to manually start the server like below.

pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start

How does one create an InputStream from a String?

You could do this:

InputStream in = new ByteArrayInputStream(string.getBytes("UTF-8"));

Note the UTF-8 encoding. You should specify the character set that you want the bytes encoded into. It's common to choose UTF-8 if you don't specifically need anything else. Otherwise if you select nothing you'll get the default encoding that can vary between systems. From the JavaDoc:

The behavior of this method when this string cannot be encoded in the default charset is unspecified. The CharsetEncoder class should be used when more control over the encoding process is required.

Cannot make Project Lombok work on Eclipse

You not only have to add lombok.jar to the libraries, but also install it by either double-clicking the lombok jar, or from the command line run java -jar lombok.jar. That will show you a nice installer screen. Select your Eclipse installation and install.

Afterwards, you can check if the installer has correctly modified your eclipse.ini:

-vmargs
...
-javaagent:lombok.jar
-Xbootclasspath/a:lombok.jar

If your Eclipse was already running, you have to Exit Eclipse and start it again. (File/Restart is not enough)

If you are starting Eclipse using a shortcut, make sure that either there are no command line arguments filled in, or manually add -javaagent:lombok.jar -Xbootclasspath/a:lombok.jar somewhere after -vmargs.

Recent editions of Lombok also add a line to the About Eclipse screen. If Lombok is active you can find a line like 'Lombok v0.11.6 "Dashing Kakapo" is installed. http://projectlombok.org/' just above the line of buttons.

If for some reason, usually related to customized eclipse builds, you need to use the full path, you can instruct the installer on the command line to do so:

java -Dlombok.installer.fullpath -jar lombok.jar

Constructing pandas DataFrame from values in variables gives "ValueError: If using all scalar values, you must pass an index"

Pandas magic at work. All logic is out.

The error message "ValueError: If using all scalar values, you must pass an index" Says you must pass an index.

This does not necessarily mean passing an index makes pandas do what you want it to do

When you pass an index, pandas will treat your dictionary keys as column names and the values as what the column should contain for each of the values in the index.

a = 2
b = 3
df2 = pd.DataFrame({'A':a,'B':b}, index=[1])

    A   B
1   2   3

Passing a larger index:

df2 = pd.DataFrame({'A':a,'B':b}, index=[1, 2, 3, 4])

    A   B
1   2   3
2   2   3
3   2   3
4   2   3

An index is usually automatically generated by a dataframe when none is given. However, pandas does not know how many rows of 2 and 3 you want. You can however be more explicit about it

df2 = pd.DataFrame({'A':[a]*4,'B':[b]*4})
df2

    A   B
0   2   3
1   2   3
2   2   3
3   2   3

The default index is 0 based though.

I would recommend always passing a dictionary of lists to the dataframe constructor when creating dataframes. It's easier to read for other developers. Pandas has a lot of caveats, don't make other developers have to experts in all of them in order to read your code.

Git remote branch deleted, but still it appears in 'branch -a'

git remote prune origin, as suggested in the other answer, will remove all such stale branches. That's probably what you'd want in most cases, but if you want to just remove that particular remote-tracking branch, you should do:

git branch -d -r origin/coolbranch

(The -r is easy to forget...)

-r in this case will "List or delete (if used with -d) the remote-tracking branches." according to the Git documentation found here: https://git-scm.com/docs/git-branch

How to read input from console in a batch file?

In addition to the existing answer it is possible to set a default option as follows:

echo off
ECHO A current build of Test Harness exists.
set delBuild=n
set /p delBuild=Delete preexisting build [y/n] (default - %delBuild%)?:

This allows users to simply hit "Enter" if they want to enter the default.

LINQ to SQL - Left Outer Join with multiple join conditions

this works too, ...if you have multiple column joins

from p in context.Periods
join f in context.Facts 
on new {
    id = p.periodid,
    p.otherid
} equals new {
    f.id,
    f.otherid
} into fg
from fgi in fg.DefaultIfEmpty()
where p.companyid == 100
select f.value

Showing/Hiding Table Rows with Javascript - can do with ID - how to do with Class?

document.getElementsByClassName returns a NodeList, not a single element, I'd recommend either using jQuery, since you'd only have to use something like $('.new').toggle()

or if you want plain JS try :

function toggle_by_class(cls, on) {
    var lst = document.getElementsByClassName(cls);
    for(var i = 0; i < lst.length; ++i) {
        lst[i].style.display = on ? '' : 'none';
    }
}

Renaming the current file in Vim

If you use git and already have the tpope's plugin fugitive.vim then simply:

:Gmove newname

This will:

  1. Rename your file on disk.
  2. Rename the file in git repo.
  3. Reload the file into the current buffer.
  4. Preserve undo history.

If your file was not yet added to a git repo then first add it:

:Gwrite

Importing variables from another file?

script1.py

title="Hello world"

script2.py is where we using script1 variable

Method 1:

import script1
print(script1.title)

Method 2:

from script1 import title
print(title)

Extract a substring from a string in Ruby using a regular expression

String1.scan(/<([^>]*)>/).last.first

scan creates an array which, for each <item> in String1 contains the text between the < and the > in a one-element array (because when used with a regex containing capturing groups, scan creates an array containing the captures for each match). last gives you the last of those arrays and first then gives you the string in it.

PHP compare time

To see of the curent time is greater or equal to 14:08:10 do this:

if (time() >= strtotime("14:08:10")) {
  echo "ok";
}

Depending on your input sources, make sure to account for timezone.

See PHP time() and PHP strtotime()

Call Jquery function

To call the function on click of some html element (control).

$('#controlID').click(myFunction);

You will need to ensure you bind the event when your html element is ready on which you binding the event. You can put the code in document.ready

$(document).ready(function(){
    $('#controlID').click(myFunction);
});

You can use anonymous function to bind the event to the html element.

$(document).ready(function(){
    $('#controlID').click(function(){
         $.messager.show({  
            title:'My Title',  
            msg:'The message content',  
            showType:'fade',  
            style:{  
                right:'',  
                bottom:''  
            }  
        });  
    });
});

If you want to bind click with many elements you can use class selector

$('.someclass').click(myFunction);

Edit based on comments by OP, If you want to call function under some condition

You can use if for conditional execution, for example,

if(a == 3)
     myFunction();

Make sure that the controller has a parameterless public constructor error

Sometimes because you are resolving your interface in ContainerBootstraper.cs it's very difficult to catch the error. In my case there was an error in resolving the implementation of the interface I've injected to the api controller. I couldn't find the error because I have resolve the interface in my bootstraperContainer like this: container.RegisterType<IInterfaceApi, MyInterfaceImplementaionHelper>(new ContainerControlledLifetimeManager());
then I've adde the following line in my bootstrap container : container.RegisterType<MyController>(); so when I compile the project , compiler complained and stopped in above line and showed the error.

How to create localhost database using mysql?

See here for starting the service and here for how to make it permanent. In short to test it, open a "DOS" terminal with administrator privileges and write:

shell> "C:\Program Files\MySQL\[YOUR MYSQL VERSION PATH]\bin\mysqld"

Left function in c#

use substring function:

yourString.Substring(0, length);

Can vue-router open a link in a new tab?

If you are interested ONLY on relative paths like: /dashboard, /about etc, See other answers.

If you want to open an absolute path like: https://www.google.com to a new tab, you have to know that Vue Router is NOT meant to handle those.

However, they seems to consider that as a feature-request. #1280. But until they do that,



Here is a little trick you can do to handle external links with vue-router.

  • Go to the router configuration (probably router.js) and add this code:
/* Vue Router is not meant to handle absolute urls. */
/* So whenever we want to deal with those, we can use this.$router.absUrl(url) */
Router.prototype.absUrl = function(url, newTab = true) {
  const link = document.createElement('a')
  link.href = url
  link.target = newTab ? '_blank' : ''
  if (newTab) link.rel = 'noopener noreferrer' // IMPORTANT to add this
  link.click()
}

Now, whenever we deal with absolute URLs we have a solution. For example to open google to a new tab

this.$router.absUrl('https://www.google.com)

Remember that whenever we open another page to a new tab we MUST use noopener noreferrer.

Read more here

or Here

How do I force my .NET application to run as administrator?

In Visual Studio 2010 right click your project name. Hit "View Windows Settings", this generates and opens a file called "app.manifest". Within this file replace "asInvoker" with "requireAdministrator" as explained in the commented sections within the file.

How to catch and print the full exception traceback without halting/exiting the program?

traceback.format_exc() or sys.exc_info() will yield more info if that's what you want.

import traceback
import sys

try:
    do_stuff()
except Exception:
    print(traceback.format_exc())
    # or
    print(sys.exc_info()[2])

How does String substring work in Swift

I had the same initial reaction. I too was frustrated at how syntax and objects change so drastically in every major release.

However, I realized from experience how I always eventually suffer the consequences of trying to fight "change" like dealing with multi-byte characters which is inevitable if you're looking at a global audience.

So I decided to recognize and respect the efforts exerted by Apple engineers and do my part by understanding their mindset when they came up with this "horrific" approach.

Instead of creating extensions which is just a workaround to make your life easier (I'm not saying they're wrong or expensive), why not figure out how Strings are now designed to work.

For instance, I had this code which was working on Swift 2.2:

let rString = cString.substringToIndex(2)
let gString = (cString.substringFromIndex(2) as NSString).substringToIndex(2)
let bString = (cString.substringFromIndex(4) as NSString).substringToIndex(2)

and after giving up trying to get the same approach working e.g. using Substrings, I finally understood the concept of treating Strings as a bidirectional collection for which I ended up with this version of the same code:

let rString = String(cString.characters.prefix(2))
cString = String(cString.characters.dropFirst(2))
let gString = String(cString.characters.prefix(2))
cString = String(cString.characters.dropFirst(2))
let bString = String(cString.characters.prefix(2))

I hope this contributes...

sum two columns in R

You can do this :

    df <- data.frame("a" = c(1,2,3,4), "b" = c(4,3,2,1), "x_ind" = c(1,0,1,1), "y_ind" = c(0,0,1,1), "z_ind" = c(0,1,1,1) )
df %>% mutate( bi  = ifelse((df$x_ind + df$y_ind +df$z_ind)== 3, 1,0 ))

How do I convert a number to a letter in Java?

Just make use of the ASCII representation.

private String getCharForNumber(int i) {
    return i > 0 && i < 27 ? String.valueOf((char)(i + 64)) : null;
}

Note: This assumes that i is between 1 and 26 inclusive.

You'll have to change the condition to i > -1 && i < 26 and the increment to 65 if you want i to be zero-based.

Here is the full ASCII table, in case you need to refer to:


enter image description here


Edit:

As some folks suggested here, it's much more readable to directly use the character 'A' instead of its ASCII code.

private String getCharForNumber(int i) {
    return i > 0 && i < 27 ? String.valueOf((char)(i + 'A' - 1)) : null;
}

How to parse a String containing XML in Java and retrieve the value of the root node?

One of the above answer states to convert XML String to bytes which is not needed. Instead you can can use InputSource and supply it with StringReader.

String xmlStr = "<message>HELLO!</message>";
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = db.parse(new InputSource(new StringReader(xmlStr)));
System.out.println(doc.getFirstChild().getNodeValue());

size of uint8, uint16 and uint32?

It's quite unclear how you are computing the size ("the size in debug mode"?").

Use printf():

printf("the size of c is %u\n", (unsigned int) sizeof c);

Normally you'd print a size_t value (which is the type sizeof returns) with %zu, but if you're using a pre-C99 compiler like Visual Studio that won't work.

You need to find the typedef statements in your code that define the custom names like uint8 and so on; those are not standard so nobody here can know how they're defined in your code.

New C code should use <stdint.h> which gives you uint8_t and so on.

How do I get values from a SQL database into textboxes using C#?

Make a connection and open it.

con = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=<database_name>)));User Id =<userid>; Password =<password>");
con.Open();

Write the select query:

string sql = "select * from Pending_Tasks";

Create a command object:

OracleCommand cmd = new OracleCommand(sql, con);

Execute the command and put the result in a object to read it.

OracleDataReader r = cmd.ExecuteReader();

now start reading from it.

while (read.Read())
{
 CustID.Text = (read["Customer_ID"].ToString());
 CustName.Text = (read["Customer_Name"].ToString());
 Add1.Text = (read["Address_1"].ToString());
 Add2.Text = (read["Address_2"].ToString());
 PostBox.Text = (read["Postcode"].ToString());
 PassBox.Text = (read["Password"].ToString());
 DatBox.Text = (read["Data_Important"].ToString());
 LanNumb.Text = (read["Landline"].ToString());
 MobNumber.Text = (read["Mobile"].ToString());
 FaultRep.Text = (read["Fault_Report"].ToString());
}
read.Close();

Add this too using Oracle.ManagedDataAccess.Client;

What is The Rule of Three?

Introduction

C++ treats variables of user-defined types with value semantics. This means that objects are implicitly copied in various contexts, and we should understand what "copying an object" actually means.

Let us consider a simple example:

class person
{
    std::string name;
    int age;

public:

    person(const std::string& name, int age) : name(name), age(age)
    {
    }
};

int main()
{
    person a("Bjarne Stroustrup", 60);
    person b(a);   // What happens here?
    b = a;         // And here?
}

(If you are puzzled by the name(name), age(age) part, this is called a member initializer list.)

Special member functions

What does it mean to copy a person object? The main function shows two distinct copying scenarios. The initialization person b(a); is performed by the copy constructor. Its job is to construct a fresh object based on the state of an existing object. The assignment b = a is performed by the copy assignment operator. Its job is generally a little more complicated, because the target object is already in some valid state that needs to be dealt with.

Since we declared neither the copy constructor nor the assignment operator (nor the destructor) ourselves, these are implicitly defined for us. Quote from the standard:

The [...] copy constructor and copy assignment operator, [...] and destructor are special member functions. [ Note: The implementation will implicitly declare these member functions for some class types when the program does not explicitly declare them. The implementation will implicitly define them if they are used. [...] end note ] [n3126.pdf section 12 §1]

By default, copying an object means copying its members:

The implicitly-defined copy constructor for a non-union class X performs a memberwise copy of its subobjects. [n3126.pdf section 12.8 §16]

The implicitly-defined copy assignment operator for a non-union class X performs memberwise copy assignment of its subobjects. [n3126.pdf section 12.8 §30]

Implicit definitions

The implicitly-defined special member functions for person look like this:

// 1. copy constructor
person(const person& that) : name(that.name), age(that.age)
{
}

// 2. copy assignment operator
person& operator=(const person& that)
{
    name = that.name;
    age = that.age;
    return *this;
}

// 3. destructor
~person()
{
}

Memberwise copying is exactly what we want in this case: name and age are copied, so we get a self-contained, independent person object. The implicitly-defined destructor is always empty. This is also fine in this case since we did not acquire any resources in the constructor. The members' destructors are implicitly called after the person destructor is finished:

After executing the body of the destructor and destroying any automatic objects allocated within the body, a destructor for class X calls the destructors for X's direct [...] members [n3126.pdf 12.4 §6]

Managing resources

So when should we declare those special member functions explicitly? When our class manages a resource, that is, when an object of the class is responsible for that resource. That usually means the resource is acquired in the constructor (or passed into the constructor) and released in the destructor.

Let us go back in time to pre-standard C++. There was no such thing as std::string, and programmers were in love with pointers. The person class might have looked like this:

class person
{
    char* name;
    int age;

public:

    // the constructor acquires a resource:
    // in this case, dynamic memory obtained via new[]
    person(const char* the_name, int the_age)
    {
        name = new char[strlen(the_name) + 1];
        strcpy(name, the_name);
        age = the_age;
    }

    // the destructor must release this resource via delete[]
    ~person()
    {
        delete[] name;
    }
};

Even today, people still write classes in this style and get into trouble: "I pushed a person into a vector and now I get crazy memory errors!" Remember that by default, copying an object means copying its members, but copying the name member merely copies a pointer, not the character array it points to! This has several unpleasant effects:

  1. Changes via a can be observed via b.
  2. Once b is destroyed, a.name is a dangling pointer.
  3. If a is destroyed, deleting the dangling pointer yields undefined behavior.
  4. Since the assignment does not take into account what name pointed to before the assignment, sooner or later you will get memory leaks all over the place.

Explicit definitions

Since memberwise copying does not have the desired effect, we must define the copy constructor and the copy assignment operator explicitly to make deep copies of the character array:

// 1. copy constructor
person(const person& that)
{
    name = new char[strlen(that.name) + 1];
    strcpy(name, that.name);
    age = that.age;
}

// 2. copy assignment operator
person& operator=(const person& that)
{
    if (this != &that)
    {
        delete[] name;
        // This is a dangerous point in the flow of execution!
        // We have temporarily invalidated the class invariants,
        // and the next statement might throw an exception,
        // leaving the object in an invalid state :(
        name = new char[strlen(that.name) + 1];
        strcpy(name, that.name);
        age = that.age;
    }
    return *this;
}

Note the difference between initialization and assignment: we must tear down the old state before assigning to name to prevent memory leaks. Also, we have to protect against self-assignment of the form x = x. Without that check, delete[] name would delete the array containing the source string, because when you write x = x, both this->name and that.name contain the same pointer.

Exception safety

Unfortunately, this solution will fail if new char[...] throws an exception due to memory exhaustion. One possible solution is to introduce a local variable and reorder the statements:

// 2. copy assignment operator
person& operator=(const person& that)
{
    char* local_name = new char[strlen(that.name) + 1];
    // If the above statement throws,
    // the object is still in the same state as before.
    // None of the following statements will throw an exception :)
    strcpy(local_name, that.name);
    delete[] name;
    name = local_name;
    age = that.age;
    return *this;
}

This also takes care of self-assignment without an explicit check. An even more robust solution to this problem is the copy-and-swap idiom, but I will not go into the details of exception safety here. I only mentioned exceptions to make the following point: Writing classes that manage resources is hard.

Noncopyable resources

Some resources cannot or should not be copied, such as file handles or mutexes. In that case, simply declare the copy constructor and copy assignment operator as private without giving a definition:

private:

    person(const person& that);
    person& operator=(const person& that);

Alternatively, you can inherit from boost::noncopyable or declare them as deleted (in C++11 and above):

person(const person& that) = delete;
person& operator=(const person& that) = delete;

The rule of three

Sometimes you need to implement a class that manages a resource. (Never manage multiple resources in a single class, this will only lead to pain.) In that case, remember the rule of three:

If you need to explicitly declare either the destructor, copy constructor or copy assignment operator yourself, you probably need to explicitly declare all three of them.

(Unfortunately, this "rule" is not enforced by the C++ standard or any compiler I am aware of.)

The rule of five

From C++11 on, an object has 2 extra special member functions: the move constructor and move assignment. The rule of five states to implement these functions as well.

An example with the signatures:

class person
{
    std::string name;
    int age;

public:
    person(const std::string& name, int age);        // Ctor
    person(const person &) = default;                // 1/5: Copy Ctor
    person(person &&) noexcept = default;            // 4/5: Move Ctor
    person& operator=(const person &) = default;     // 2/5: Copy Assignment
    person& operator=(person &&) noexcept = default; // 5/5: Move Assignment
    ~person() noexcept = default;                    // 3/5: Dtor
};

The rule of zero

The rule of 3/5 is also referred to as the rule of 0/3/5. The zero part of the rule states that you are allowed to not write any of the special member functions when creating your class.

Advice

Most of the time, you do not need to manage a resource yourself, because an existing class such as std::string already does it for you. Just compare the simple code using a std::string member to the convoluted and error-prone alternative using a char* and you should be convinced. As long as you stay away from raw pointer members, the rule of three is unlikely to concern your own code.

Custom HTTP headers : naming conventions

The recommendation is was to start their name with "X-". E.g. X-Forwarded-For, X-Requested-With. This is also mentioned in a.o. section 5 of RFC 2047.


Update 1: On June 2011, the first IETF draft was posted to deprecate the recommendation of using the "X-" prefix for non-standard headers. The reason is that when non-standard headers prefixed with "X-" become standard, removing the "X-" prefix breaks backwards compatibility, forcing application protocols to support both names (E.g, x-gzip & gzip are now equivalent). So, the official recommendation is to just name them sensibly without the "X-" prefix.


Update 2: On June 2012, the deprecation of recommendation to use the "X-" prefix has become official as RFC 6648. Below are cites of relevance:

3. Recommendations for Creators of New Parameters

...

  1. SHOULD NOT prefix their parameter names with "X-" or similar constructs.

4. Recommendations for Protocol Designers

...

  1. SHOULD NOT prohibit parameters with an "X-" prefix or similar constructs from being registered.

  2. MUST NOT stipulate that a parameter with an "X-" prefix or similar constructs needs to be understood as unstandardized.

  3. MUST NOT stipulate that a parameter without an "X-" prefix or similar constructs needs to be understood as standardized.

Note that "SHOULD NOT" ("discouraged") is not the same as "MUST NOT" ("forbidden"), see also RFC 2119 for another spec on those keywords. In other words, you can keep using "X-" prefixed headers, but it's not officially recommended anymore and you may definitely not document them as if they are public standard.


Summary:

  • the official recommendation is to just name them sensibly without the "X-" prefix
  • you can keep using "X-" prefixed headers, but it's not officially recommended anymore and you may definitely not document them as if they are public standard

"Continue" (to next iteration) on VBScript

We can use a separate function for performing a continue statement work. suppose you have following problem:

for i=1 to 10

if(condition) then   'for loop body'
contionue
End If

Next

Here we will use a function call for for loop body:

for i=1 to 10
Call loopbody()
next

function loopbody()

if(condition) then   'for loop body'
Exit Function
End If

End Function

loop will continue for function exit statement....

Get time in milliseconds using C#

The DateTime.Ticks property gets the number of ticks that represent the date and time.

10,000 Ticks is a millisecond (10,000,000 ticks per second).

How to detect when a youtube video finishes playing?

What you may want to do is include a script on all pages that does the following ... 1. find the youtube-iframe : searching for it by width and height by title or by finding www.youtube.com in its source. You can do that by ... - looping through the window.frames by a for-in loop and then filter out by the properties

  1. inject jscript in the iframe of the current page adding the onYoutubePlayerReady must-include-function http://shazwazza.com/post/Injecting-JavaScript-into-other-frames.aspx

  2. Add the event listeners etc..

Hope this helps

How to insert Records in Database using C# language?

You should form the command with the contents of the textboxes:

sql = "insert into Main (Firt Name, Last Name) values(" + textbox2.Text + "," + textbox3.Text+ ")";

This, of course, provided that you manage to open the connection correctly.

It would be helpful to know what's happening with your current code. If you are getting some error displayed in that message box, it would be great to know what it's saying.

You should also validate the inputs before actually running the command (i.e. make sure they don't contain malicious code...).

Vbscript list all PDF files in folder and subfolders

Set objFSO = CreateObject("Scripting.FileSystemObject")
objStartFolder = "C:\Users\NOLA BOOTHE\My Documents\operating system"

Set objFolder = objFSO.GetFolder(objStartFolder)

Set colFiles = objFolder.Files
For Each objFile in colFiles
    Wscript.Echo objFile.Name
Next

How to find the path of Flutter SDK

If you suppose unzipped the flutter zip file in folder called "Flutter". Your Flutter SDK Path will be <path_of_unzipped_file>\Flutter\flutter

Modulo operator with negative values

a % b

in c++ default:

(-7/3) => -2
-2 * 3 => -6
so a%b => -1

(7/-3) => -2
-2 * -3 => 6
so a%b => 1

in python:

-7 % 3 => 2
7 % -3 => -2

in c++ to python:

(b + (a%b)) % b

Insert line after first match using sed

Note the standard sed syntax (as in POSIX, so supported by all conforming sed implementations around (GNU, OS/X, BSD, Solaris...)):

sed '/CLIENTSCRIPT=/a\
CLIENTSCRIPT2="hello"' file

Or on one line:

sed -e '/CLIENTSCRIPT=/a\' -e 'CLIENTSCRIPT2="hello"' file

(-expressions (and the contents of -files) are joined with newlines to make up the sed script sed interprets).

The -i option for in-place editing is also a GNU extension, some other implementations (like FreeBSD's) support -i '' for that.

Alternatively, for portability, you can use perl instead:

perl -pi -e '$_ .= qq(CLIENTSCRIPT2="hello"\n) if /CLIENTSCRIPT=/' file

Or you could use ed or ex:

printf '%s\n' /CLIENTSCRIPT=/a 'CLIENTSCRIPT2="hello"' . w q | ex -s file

How to turn off caching on Firefox?

The Web Developer Toolbar has an option to disable caching which makes it very easy to turn it on and off when you need it.

How can I tell if a DOM element is visible in the current viewport?

I think this is a more functional way to do it. Dan's answer do not work in a recursive context.

This function solves the problem when your element is inside others scrollable divs by testing any levels recursively up to the HTML tag, and stops at the first false.

/**
 * fullVisible=true only returns true if the all object rect is visible
 */
function isReallyVisible(el, fullVisible) {
    if ( el.tagName == "HTML" )
            return true;
    var parentRect=el.parentNode.getBoundingClientRect();
    var rect = arguments[2] || el.getBoundingClientRect();
    return (
            ( fullVisible ? rect.top    >= parentRect.top    : rect.bottom > parentRect.top ) &&
            ( fullVisible ? rect.left   >= parentRect.left   : rect.right  > parentRect.left ) &&
            ( fullVisible ? rect.bottom <= parentRect.bottom : rect.top    < parentRect.bottom ) &&
            ( fullVisible ? rect.right  <= parentRect.right  : rect.left   < parentRect.right ) &&
            isReallyVisible(el.parentNode, fullVisible, rect)
    );
};

Select option padding not working in chrome

This simple hack will indent the text. Works well.

select {
  text-indent: 5px;
}

Pass parameter to controller from @Html.ActionLink MVC 4

You are using a wrong overload of the Html.ActionLink helper. What you think is routeValues is actually htmlAttributes! Just look at the generated HTML, you will see that this anchor's href property doesn't look as you expect it to look.

Here's what you are using:

@Html.ActionLink(
    "Reply",                                                  // linkText
    "BlogReplyCommentAdd",                                    // actionName
    "Blog",                                                   // routeValues
    new {                                                     // htmlAttributes
        blogPostId = blogPostId, 
        replyblogPostmodel = Model, 
        captchaValid = Model.AddNewComment.DisplayCaptcha 
    }
)

and here's what you should use:

@Html.ActionLink(
    "Reply",                                                  // linkText
    "BlogReplyCommentAdd",                                    // actionName
    "Blog",                                                   // controllerName
    new {                                                     // routeValues
        blogPostId = blogPostId, 
        replyblogPostmodel = Model, 
        captchaValid = Model.AddNewComment.DisplayCaptcha 
    },
    null                                                      // htmlAttributes
)

Also there's another very serious issue with your code. The following routeValue:

replyblogPostmodel = Model

You cannot possibly pass complex objects like this in an ActionLink. So get rid of it and also remove the BlogPostModel parameter from your controller action. You should use the blogPostId parameter to retrieve the model from wherever this model is persisted, or if you prefer from wherever you retrieved the model in the GET action:

public ActionResult BlogReplyCommentAdd(int blogPostId, bool captchaValid)
{
    BlogPostModel model = repository.Get(blogPostId);
    ...
}

As far as your initial problem is concerned with the wrong overload I would recommend you writing your helpers using named parameters:

@Html.ActionLink(
    linkText: "Reply",
    actionName: "BlogReplyCommentAdd",
    controllerName: "Blog",
    routeValues: new {
        blogPostId = blogPostId, 
        captchaValid = Model.AddNewComment.DisplayCaptcha
    },
    htmlAttributes: null
)

Now not only that your code is more readable but you will never have confusion between the gazillions of overloads that Microsoft made for those helpers.

How to execute .sql file using powershell?

Here is a function that I have in my PowerShell profile for loading SQL snapins:

function Load-SQL-Server-Snap-Ins
{
    try 
    {
        $sqlpsreg="HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.SqlServer.Management.PowerShell.sqlps"

        if (!(Test-Path $sqlpsreg -ErrorAction "SilentlyContinue"))
        {
            throw "SQL Server Powershell is not installed yet (part of SQLServer installation)."
        }

        $item = Get-ItemProperty $sqlpsreg
        $sqlpsPath = [System.IO.Path]::GetDirectoryName($item.Path)

        $assemblyList = @(
            "Microsoft.SqlServer.Smo",
            "Microsoft.SqlServer.SmoExtended",
            "Microsoft.SqlServer.Dmf",
            "Microsoft.SqlServer.WmiEnum",
            "Microsoft.SqlServer.SqlWmiManagement",
            "Microsoft.SqlServer.ConnectionInfo ",
            "Microsoft.SqlServer.Management.RegisteredServers",
            "Microsoft.SqlServer.Management.Sdk.Sfc",
            "Microsoft.SqlServer.SqlEnum",
            "Microsoft.SqlServer.RegSvrEnum",
            "Microsoft.SqlServer.ServiceBrokerEnum",
            "Microsoft.SqlServer.ConnectionInfoExtended",
            "Microsoft.SqlServer.Management.Collector",
            "Microsoft.SqlServer.Management.CollectorEnum"
        )

        foreach ($assembly in $assemblyList)
        { 
            $assembly = [System.Reflection.Assembly]::LoadWithPartialName($assembly) 
            if ($assembly -eq $null)
                { Write-Host "`t`t($MyInvocation.InvocationName): Could not load $assembly" }
        }

        Set-Variable -scope Global -name SqlServerMaximumChildItems -Value 0
        Set-Variable -scope Global -name SqlServerConnectionTimeout -Value 30
        Set-Variable -scope Global -name SqlServerIncludeSystemObjects -Value $false
        Set-Variable -scope Global -name SqlServerMaximumTabCompletion -Value 1000

        Push-Location

         if ((Get-PSSnapin -Name SqlServerProviderSnapin100 -ErrorAction SilentlyContinue) -eq $null) 
        { 
            cd $sqlpsPath

            Add-PsSnapin SqlServerProviderSnapin100 -ErrorAction Stop
            Add-PsSnapin SqlServerCmdletSnapin100 -ErrorAction Stop
            Update-TypeData -PrependPath SQLProvider.Types.ps1xml
            Update-FormatData -PrependPath SQLProvider.Format.ps1xml
        }
    } 

    catch 
    {
        Write-Host "`t`t$($MyInvocation.InvocationName): $_" 
    }

    finally
    {
        Pop-Location
    }
}

Pretty-Print JSON in Java

Most of the existing answers either depend on some external library, or requiring a special Java version. Here is a simple code to pretty print a JSON string, only using general Java APIs (available in Java 7 for higher; haven't tried older version although).

The basic idea is to tigger the formatting based on special characters in JSON. For example, if a '{' or '[' is observed, the code will create a new line and increase the indent level.

Disclaimer: I only tested this for some simple JSON cases (basic key-value pair, list, nested JSON) so it may need some work for more general JSON text, like string value with quotes inside, or special characters (\n, \t etc.).

/**
 * A simple implementation to pretty-print JSON file.
 *
 * @param unformattedJsonString
 * @return
 */
public static String prettyPrintJSON(String unformattedJsonString) {
  StringBuilder prettyJSONBuilder = new StringBuilder();
  int indentLevel = 0;
  boolean inQuote = false;
  for(char charFromUnformattedJson : unformattedJsonString.toCharArray()) {
    switch(charFromUnformattedJson) {
      case '"':
        // switch the quoting status
        inQuote = !inQuote;
        prettyJSONBuilder.append(charFromUnformattedJson);
        break;
      case ' ':
        // For space: ignore the space if it is not being quoted.
        if(inQuote) {
          prettyJSONBuilder.append(charFromUnformattedJson);
        }
        break;
      case '{':
      case '[':
        // Starting a new block: increase the indent level
        prettyJSONBuilder.append(charFromUnformattedJson);
        indentLevel++;
        appendIndentedNewLine(indentLevel, prettyJSONBuilder);
        break;
      case '}':
      case ']':
        // Ending a new block; decrese the indent level
        indentLevel--;
        appendIndentedNewLine(indentLevel, prettyJSONBuilder);
        prettyJSONBuilder.append(charFromUnformattedJson);
        break;
      case ',':
        // Ending a json item; create a new line after
        prettyJSONBuilder.append(charFromUnformattedJson);
        if(!inQuote) {
          appendIndentedNewLine(indentLevel, prettyJSONBuilder);
        }
        break;
      default:
        prettyJSONBuilder.append(charFromUnformattedJson);
    }
  }
  return prettyJSONBuilder.toString();
}

/**
 * Print a new line with indention at the beginning of the new line.
 * @param indentLevel
 * @param stringBuilder
 */
private static void appendIndentedNewLine(int indentLevel, StringBuilder stringBuilder) {
  stringBuilder.append("\n");
  for(int i = 0; i < indentLevel; i++) {
    // Assuming indention using 2 spaces
    stringBuilder.append("  ");
  }
}

Angular 2 - Using 'this' inside setTimeout

You need to use Arrow function ()=> ES6 feature to preserve this context within setTimeout.

// var that = this;                             // no need of this line
this.messageSuccess = true;

setTimeout(()=>{                           //<<<---using ()=> syntax
      this.messageSuccess = false;
 }, 3000);

Media Queries - In between two widths

You need to switch your values:

/* No greater than 900px, no less than 400px */
@media (max-width:900px) and (min-width:400px) {
    .foo {
        display:none;
    }
}?

Demo: http://jsfiddle.net/xf6gA/ (using background color, so it's easier to confirm)

Java: Best way to iterate through a Collection (here ArrayList)

There is additionally collections’ stream() util with Java 8

collection.forEach((temp) -> {
            System.out.println(temp);
});

or

collection.forEach(System.out::println);

More information about Java 8 stream and collections for wonderers link

Html code as IFRAME source rather than a URL

According to W3Schools, HTML 5 lets you do this using a new "srcdoc" attribute, but the browser support seems very limited.

What is DOM element?

When a web page is loaded, the browser creates a Document Object Model of the page.

The HTML DOM model is constructed as a tree of Objects:

With the object model, JavaScript gets all the power it needs to create dynamic HTML:

  • JavaScript can change all the HTML elements in the page
  • JavaScript can change all the HTML attributes in the page
  • JavaScript can change all the CSS styles in the page
  • JavaScript can remove existing HTML elements and attributes
  • JavaScript can add new HTML elements and attributes
  • JavaScript can react to all existing HTML events in the page
  • JavaScript can create new HTML events on the page

source

how to download image from any web page in java

If you want to save the image and you know its URL you can do this:

try(InputStream in = new URL("http://example.com/image.jpg").openStream()){
    Files.copy(in, Paths.get("C:/File/To/Save/To/image.jpg"));
}

You will also need to handle the IOExceptions which may be thrown.

Create whole path automatically when writing to a new file

Use FileUtils to handle all these headaches.

Edit: For example, use below code to write to a file, this method will 'checking and creating the parent directory if it does not exist'.

openOutputStream(File file [, boolean append]) 

How do I change the default port (9000) that Play uses when I execute the "run" command?

For Play 2.2.x on Windows with a distributable tar file I created a file in the distributable root directory called: {PROJECT_NAME}_config.txt and added:

-Dhttp.port=8080

Where {PROJECT_NAME} should be replaced with the name of your project. Then started the {PROJECT_NAME}.bat script as usual in the bin\ directory.

Merging dataframes on index with pandas

You should be able to use join, which joins on the index as default. Given your desired result, you must use outer as the join type.

>>> df1.join(df2, how='outer')
            V1  V2
A 1/1/2012  12  15
  2/1/2012  14 NaN
  3/1/2012 NaN  21
B 1/1/2012  15  24
  2/1/2012   8   9
C 1/1/2012  17 NaN
  2/1/2012   9 NaN
D 1/1/2012 NaN   7
  2/1/2012 NaN  16

Signature: _.join(other, on=None, how='left', lsuffix='', rsuffix='', sort=False) Docstring: Join columns with other DataFrame either on index or on a key column. Efficiently Join multiple DataFrame objects by index at once by passing a list.

Which SchemaType in Mongoose is Best for Timestamp?

new mongoose.Schema({ description: { type: String, required: true, trim: true }, completed: { type: Boolean, default: false }, owner: { type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User' } }, { timestamps: true });

Show a div as a modal pop up

A simple modal pop up div or dialog box can be done by CSS properties and little bit of jQuery.The basic idea is simple:

  • 1. Create a div with semi transparent background & show it on top of your content page on click.
  • 2. Show your pop up div or alert div on top of the semi transparent dimming/hiding div.
  • So we need three divs:

  • content(main content of the site).
  • hider(To dim the content).
  • popup_box(the modal div to display).

    First let us define the CSS:

        #hider
        {
            position:absolute;
            top: 0%;
            left: 0%;
            width:1600px;
            height:2000px;
            margin-top: -800px; /*set to a negative number 1/2 of your height*/
            margin-left: -500px; /*set to a negative number 1/2 of your width*/
            /*
            z- index must be lower than pop up box
           */
            z-index: 99;
           background-color:Black;
           //for transparency
           opacity:0.6;
        }
    
        #popup_box  
        {
    
        position:absolute;
            top: 50%;
            left: 50%;
            width:10em;
            height:10em;
            margin-top: -5em; /*set to a negative number 1/2 of your height*/
            margin-left: -5em; /*set to a negative number 1/2 of your width*/
            border: 1px solid #ccc;
            border:  2px solid black;
            z-index:100; 
    
        }
    

    It is important that we set our hider div's z-index lower than pop_up box as we want to show popup_box on top.
    Here comes the java Script:

            $(document).ready(function () {
            //hide hider and popup_box
            $("#hider").hide();
            $("#popup_box").hide();
    
            //on click show the hider div and the message
            $("#showpopup").click(function () {
                $("#hider").fadeIn("slow");
                $('#popup_box').fadeIn("slow");
            });
            //on click hide the message and the
            $("#buttonClose").click(function () {
    
                $("#hider").fadeOut("slow");
                $('#popup_box').fadeOut("slow");
            });
    
            });
    

    And finally the HTML:

    <div id="hider"></div>
    <div id="popup_box">
        Message<br />
        <a id="buttonClose">Close</a>
    </div>    
    <div id="content">
        Page's main content.<br />
        <a id="showpopup">ClickMe</a>
    </div>
    

    I have used jquery-1.4.1.min.js www.jquery.com/download and tested the code in Firefox. Hope this helps.

  • How to disable mouse right click on a web page?

    <body oncontextmenu="return false;"> works for me in Google Chrome. Not sure about other browsers.

    Note, all someone has to do is disable JavaScript in order to see the right-click menu anyway.

    'router-outlet' is not a known element

    In your app.module.ts file

    import { RouterModule, Routes } from '@angular/router';
    
    const appRoutes: Routes = [
    {
        path: '',
        redirectTo: '/dashboard',
        pathMatch: 'full',
        component: DashboardComponent
    },  
    {
        path: 'dashboard',
        component: DashboardComponent
    }
    ];
    
    @NgModule({
    imports: [
        BrowserModule,
        RouterModule.forRoot(appRoutes),
        FormsModule               
    ],
    declarations: [
        AppComponent,  
        DashboardComponent      
    ],
    bootstrap: [AppComponent]
    })
    export class AppModule {
    
    }
    

    Add this code. Happy Coding.

    Is it possible to put a ConstraintLayout inside a ScrollView?

    Anyone who has set below property to

    ScrollView:: android:fillViewport="true"

    constraint layout: android:layout_height="wrap_content"

    And it's still not working then make sure then you have not set the Inner scrollable layout (RecycleView) bottom constraint to bottom of the parent.

    Add below lines of code:

    android:nestedScrollingEnabled="false"
    android:layout_height="wrap_content"
    

    Make sure to remove below constraint:

    app:layout_constraintBottom_toBottomOf="parent"
    

    Full code

       <androidx.core.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true">
    
    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/selectHubLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        tools:context=".ui.hubs.SelectHubFragment">
    
        <include
            android:id="@+id/include"
            layout="@layout/signup_hub_selection_details"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/rv_HubSelection"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:nestedScrollingEnabled="false"
            app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="1.0"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/include" />
    </androidx.constraintlayout.widget.ConstraintLayout>
    

    Cannot construct instance of - Jackson

    In your concrete example the problem is that you don't use this construct correctly:

    @JsonSubTypes({ @JsonSubTypes.Type(value = MyAbstractClass.class, name = "MyAbstractClass") })
    

    @JsonSubTypes.Type should contain the actual non-abstract subtypes of your abstract class.

    Therefore if you have:

    abstract class Parent and the concrete subclasses

    Ch1 extends Parent and Ch2 extends Parent

    Then your annotation should look like:

    @JsonSubTypes({ 
              @JsonSubTypes.Type(value = Ch1.class, name = "ch1"),
              @JsonSubTypes.Type(value = Ch2.class, name = "ch2")
    })
    

    Here name should match the value of your 'discriminator':

    @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, 
    include = JsonTypeInfo.As.WRAPPER_OBJECT, 
    property = "type")
    

    in the property field, here it is equal to type. So type will be the key and the value you set in name will be the value.

    Therefore, when the json string comes if it has this form:

    {
     "type": "ch1",
     "other":"fields"
    }
    

    Jackson will automatically convert this to a Ch1 class.

    If you send this:

    {
     "type": "ch2",
     "other":"fields"
    }
    

    You would get a Ch2 instance.

    How to toggle boolean state of react component?

    Set: const [state, setState] = useState(1);

    Toggle: setState(state*-1);

    Use: state > 0 ? 'on' : 'off';

    jQuery: Test if checkbox is NOT checked

    I know this has already been answered, but still, this is a good way to do it:

    if ($("#checkbox").is(":checked")==false) {
        //Do stuff here like: $(".span").html("<span>Lorem</span>");
    }
    

    Proper way to exit command line program?

    if you do ctrl-z and then type exit it will close background applications.

    Ctrl+Q is another good way to kill the application.

    How do I view the SSIS packages in SQL Server Management Studio?

    1. you could find it under intergration services option in object explorer.
    2. you could find the packages under integration services catalog where all packages are deployed.

    Sort rows in data.table in decreasing order on string key `order(-x,v)` gives error on data.table 1.9.4 or earlier

    Update

    data.table v1.9.6+ now supports OP's original attempt and the following answer is no longer necessary.


    You can use DT[order(-rank(x), y)].

       x y v
    1: c 1 7
    2: c 3 8
    3: c 6 9
    4: b 1 1
    5: b 3 2
    6: b 6 3
    7: a 1 4
    8: a 3 5
    9: a 6 6
    

    Count occurrences of a char in a string using Bash

    you can for example remove all other chars and count the whats remains, like:

    var="text,text,text,text"
    res="${var//[^,]}"
    echo "$res"
    echo "${#res}"
    

    will print

    ,,,
    3
    

    or

    tr -dc ',' <<<"$var" | awk '{ print length; }'
    

    or

    tr -dc ',' <<<"$var" | wc -c    #works, but i don't like wc.. ;)
    

    or

    awk -F, '{print NF-1}' <<<"$var"
    

    or

    grep -o ',' <<<"$var" | grep -c .
    

    or

    perl -nle 'print s/,//g' <<<"$var"
    

    What are named pipes?

    Named pipes is a windows system for inter-process communication. In the case of SQL server, if the server is on the same machine as the client, then it is possible to use named pipes to tranfer the data, as opposed to TCP/IP.

    Notepad++: Multiple words search in a file (may be in different lines)?

    You need a new version of notepad++. Looks like old versions don't support |.

    Note: egrep "CAT|TOWN" will search for lines containing CATOWN. (CAT)|(TOWN) is the proper or extension (matching 1,3,4). Strangely you wrote and which is btw (CAT.*TOWN)|(TOWN.*CAT)

    Make the size of a heatmap bigger with seaborn

    You could alter the figsize by passing a tuple showing the width, height parameters you would like to keep.

    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots(figsize=(10,10))         # Sample figsize in inches
    sns.heatmap(df1.iloc[:, 1:6:], annot=True, linewidths=.5, ax=ax)
    

    EDIT

    I remember answering a similar question of yours where you had to set the index as TIMESTAMP. So, you could then do something like below:

    df = df.set_index('TIMESTAMP')
    df.resample('30min').mean()
    fig, ax = plt.subplots()
    ax = sns.heatmap(df.iloc[:, 1:6:], annot=True, linewidths=.5)
    ax.set_yticklabels([i.strftime("%Y-%m-%d %H:%M:%S") for i in df.index], rotation=0)
    

    For the head of the dataframe you posted, the plot would look like:

    enter image description here

    Java File - Open A File And Write To It

    Please Search Google given to the world by Larry Page and Sergey Brin.

    BufferedWriter out = null;
    
    try {
        FileWriter fstream = new FileWriter("out.txt", true); //true tells to append data.
        out = new BufferedWriter(fstream);
        out.write("\nsue");
    }
    
    catch (IOException e) {
        System.err.println("Error: " + e.getMessage());
    }
    
    finally {
        if(out != null) {
            out.close();
        }
    }
    

    Find all elements on a page whose element ID contains a certain text using jQuery

    $('*[id*=mytext]:visible').each(function() {
        $(this).doStuff();
    });
    

    Note the asterisk '*' at the beginning of the selector matches all elements.

    See the Attribute Contains Selectors, as well as the :visible and :hidden selectors.

    Removing highcharts.com credits link

    credits : null
    

    also works to disable the credits

    mysqli_connect(): (HY000/2002): No connection could be made because the target machine actively refused it

    For those who came here looking for the answer and didnt type 3306 wrong...If like myself, you have wasted hours with no luck searching for this answer, then possibly this may help.

    If you are seeing this: (HY000/2002): No connection could be made because the target machine actively refused it

    Then my understanding is that it cant connect for one of the following below. Now which..

    1) is your wamp, mamp, etc icon GREEN? Either way, right-click the icon --> click tools --> test both the port used for Apache (typically 80) and for Mariadb (3307?). Should say 'It is correct' for both.

    2) Error comes from a .php file. So, check your dbconnect.php.

    <?php
    $servername = "localhost";
    $username = "your_username";
    $password = "your_pw";
    $dbname = "your_dbname";
    $port = "3307";
    ?>
    

    Is your setup correct? Does your user exist? Do they have rights? Does port match the tested port in 1)? Doesn't have to be 3307 and user can be root. You can also left click the green icon --> click MariaDB and view used port as shown in the image below. All good? Positive? ok!

    enter image description here

    3) Error comes when you login to phpmyadmin. So, check your my.ini.

    enter image description here

    Open my.ini by left clicking the green icon --> click MariaDB -->

    ; The following options will be passed to all MariaDB clients
    [client]
    ;password = your_password
    port = 3307
    socket = /tmp/mariadb.sock
    
    ; Here follows entries for some specific programs
    
    ; The MariaDB server
    [wampmariadb64]
    ;skip-grant-tables
    port = 3307
    socket = /tmp/mariadb.sock
    

    Make sure the ports match the port MariaDB is being testing on. Then finally..

    [mysqld]
    port = 3307
    

    At the bottom of my.ini, make sure this port matches as well.

    4) 1-3 done? restart your WAMP and cross your fingers!

    Any way to make a WPF textblock selectable?

    All the answers here are just using a TextBox or trying to implement text selection manually, which leads to poor performance or non-native behaviour (blinking caret in TextBox, no keyboard support in manual implementations etc.)

    After hours of digging around and reading the WPF source code, I instead discovered a way of enabling the native WPF text selection for TextBlock controls (or really any other controls). Most of the functionality around text selection is implemented in System.Windows.Documents.TextEditor system class.

    To enable text selection for your control you need to do two things:

    1. Call TextEditor.RegisterCommandHandlers() once to register class event handlers

    2. Create an instance of TextEditor for each instance of your class and pass the underlying instance of your System.Windows.Documents.ITextContainer to it

    There's also a requirement that your control's Focusable property is set to True.

    This is it! Sounds easy, but unfortunately TextEditor class is marked as internal. So I had to write a reflection wrapper around it:

    class TextEditorWrapper
    {
        private static readonly Type TextEditorType = Type.GetType("System.Windows.Documents.TextEditor, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
        private static readonly PropertyInfo IsReadOnlyProp = TextEditorType.GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
        private static readonly PropertyInfo TextViewProp = TextEditorType.GetProperty("TextView", BindingFlags.Instance | BindingFlags.NonPublic);
        private static readonly MethodInfo RegisterMethod = TextEditorType.GetMethod("RegisterCommandHandlers", 
            BindingFlags.Static | BindingFlags.NonPublic, null, new[] { typeof(Type), typeof(bool), typeof(bool), typeof(bool) }, null);
    
        private static readonly Type TextContainerType = Type.GetType("System.Windows.Documents.ITextContainer, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
        private static readonly PropertyInfo TextContainerTextViewProp = TextContainerType.GetProperty("TextView");
    
        private static readonly PropertyInfo TextContainerProp = typeof(TextBlock).GetProperty("TextContainer", BindingFlags.Instance | BindingFlags.NonPublic);
    
        public static void RegisterCommandHandlers(Type controlType, bool acceptsRichContent, bool readOnly, bool registerEventListeners)
        {
            RegisterMethod.Invoke(null, new object[] { controlType, acceptsRichContent, readOnly, registerEventListeners });
        }
    
        public static TextEditorWrapper CreateFor(TextBlock tb)
        {
            var textContainer = TextContainerProp.GetValue(tb);
    
            var editor = new TextEditorWrapper(textContainer, tb, false);
            IsReadOnlyProp.SetValue(editor._editor, true);
            TextViewProp.SetValue(editor._editor, TextContainerTextViewProp.GetValue(textContainer));
    
            return editor;
        }
    
        private readonly object _editor;
    
        public TextEditorWrapper(object textContainer, FrameworkElement uiScope, bool isUndoEnabled)
        {
            _editor = Activator.CreateInstance(TextEditorType, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.CreateInstance, 
                null, new[] { textContainer, uiScope, isUndoEnabled }, null);
        }
    }
    

    I also created a SelectableTextBlock derived from TextBlock that takes the steps noted above:

    public class SelectableTextBlock : TextBlock
    {
        static SelectableTextBlock()
        {
            FocusableProperty.OverrideMetadata(typeof(SelectableTextBlock), new FrameworkPropertyMetadata(true));
            TextEditorWrapper.RegisterCommandHandlers(typeof(SelectableTextBlock), true, true, true);
    
            // remove the focus rectangle around the control
            FocusVisualStyleProperty.OverrideMetadata(typeof(SelectableTextBlock), new FrameworkPropertyMetadata((object)null));
        }
    
        private readonly TextEditorWrapper _editor;
    
        public SelectableTextBlock()
        {
            _editor = TextEditorWrapper.CreateFor(this);
        }
    }
    

    Another option would be to create an attached property for TextBlock to enable text selection on demand. In this case, to disable the selection again, one needs to detach a TextEditor by using the reflection equivalent of this code:

    _editor.TextContainer.TextView = null;
    _editor.OnDetach();
    _editor = null;
    

    Spring @Autowired and @Qualifier

    The @Qualifier annotation is used to resolve the autowiring conflict, when there are multiple beans of same type.

    The @Qualifier annotation can be used on any class annotated with @Component or on methods annotated with @Bean. This annotation can also be applied on constructor arguments or method parameters.

    Ex:-

    public interface Vehicle {
         public void start();
         public void stop();
    }
    

    There are two beans, Car and Bike implements Vehicle interface

    @Component(value="car")
    public class Car implements Vehicle {
    
         @Override
         public void start() {
               System.out.println("Car started");
         }
    
         @Override
         public void stop() {
               System.out.println("Car stopped");
         }
     }
    
    @Component(value="bike")
    public class Bike implements Vehicle {
    
         @Override
         public void start() {
              System.out.println("Bike started");
         }
    
         @Override
         public void stop() {
              System.out.println("Bike stopped");
         }
    }
    

    Injecting Bike bean in VehicleService using @Autowired with @Qualifier annotation. If you didn't use @Qualifier, it will throw NoUniqueBeanDefinitionException.

    @Component
    public class VehicleService {
    
        @Autowired
        @Qualifier("bike")
        private Vehicle vehicle;
    
        public void service() {
             vehicle.start();
             vehicle.stop();
        }
    }
    

    Reference:- @Qualifier annotation example

    Check if at least two out of three booleans are true

    Currenty with Java 8, I really prefer something like this:

    boolean atLeastTwo(boolean a, boolean b, boolean c) {
        return Stream.of(a, b, c).filter(active -> active).count() >= 2;
    }
    

    JavaScript - populate drop down list with array

    You'll need to loop through your array elements, create a new DOM node for each and append it to your object.

    var select = document.getElementById("selectNumber"); 
    var options = ["1", "2", "3", "4", "5"]; 
    
    for(var i = 0; i < options.length; i++) {
        var opt = options[i];
        var el = document.createElement("option");
        el.textContent = opt;
        el.value = opt;
        select.appendChild(el);
    }?
    

    Live example

    ERROR 2013 (HY000): Lost connection to MySQL server at 'reading authorization packet', system error: 0

    My case was that the server didn't accept the connection from this IP. The server is a SQL server from Google Apps Engine, and you have to configure allowed remote hosts that can connect to the server.

    Adding the (new) host to the GAE admin page solved the issue.

    How to create a laravel hashed password

    ok, this is a extract from the make function in hash.php

        $work = str_pad(8, 2, '0', STR_PAD_LEFT);
    
        // Bcrypt expects the salt to be 22 base64 encoded characters including
        // dots and slashes. We will get rid of the plus signs included in the
        // base64 data and replace them with dots.
        if (function_exists('openssl_random_pseudo_bytes'))
        {
            $salt = openssl_random_pseudo_bytes(16);
        }
        else
        {
            $salt = Str::random(40);
        }
    
        $salt = substr(strtr(base64_encode($salt), '+', '.'), 0 , 22);
    
        echo crypt('yourpassword', '$2a$'.$work.'$'.$salt);
    

    Just copy/paste it into a php file and run it.

    Programmatically set image to UIImageView with Xcode 6.1/Swift

    With swift syntax this worked for me :

        let leftImageView = UIImageView()
        leftImageView.image = UIImage(named: "email")
    
        let leftView = UIView()
        leftView.addSubview(leftImageView)
    
        leftView.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
        leftImageView.frame = CGRect(x: 10, y: 10, width: 20, height: 20)
        userNameTextField.leftViewMode = .always
        userNameTextField.leftView = leftView
    

    Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\wordpress\wp-includes\class-http.php on line 1610

    1. Find file:

      [XAMPP Installation Directory]\php\php.ini
      
    2. open php.ini.
    3. Find max_execution_time and increase the value of it as you required
    4. Restart XAMPP control panel

    Angular 2 - NgFor using numbers instead collections

    A simplest way that i have tried

    You can also create an array in your component file and you can call it with *ngFor directive by returning as an array .

    Something like this ....

    import { Component, OnInit } from '@angular/core';
    
    @Component({
      selector: 'app-morning',
      templateUrl: './morning.component.html',
      styleUrls: ['./morning.component.css']
    })
    export class MorningComponent implements OnInit {
    
      arr = [];
      i: number = 0;
      arra() {
        for (this.i = 0; this.i < 20; this.i++) {
          this.arr[this.i]=this.i;
        }
        return this.arr;
      }
    
      constructor() { }
    
      ngOnInit() {
      }
    
    }
    

    And this function can be used in your html template file

    <p *ngFor="let a of arra(); let i= index">
    value:{{a}} position:{{i}}
    </p>
    

    SQL Select between dates

    Or you can cast your string to Date format with date function. Even the date is stored as TEXT in the DB. Like this (the most workable variant):

    SELECT * FROM test WHERE date(date) 
    BETWEEN date('2011-01-11') AND date('2011-8-11')
    

    nullable object must have a value

    Assign the members directly without the .Value part:

    DateTimeExtended(DateTimeExtended myNewDT)
    {
       this.MyDateTime = myNewDT.MyDateTime;
       this.otherdata = myNewDT.otherdata;
    }
    

    How to merge lists into a list of tuples?

    In python 3.0 zip returns a zip object. You can get a list out of it by calling list(zip(a, b)).

    How do you write multiline strings in Go?

    You can put content with `` around it, like

    var hi = `I am here,
    hello,
    `
    

    How to test the type of a thrown exception in Jest

    Try:

    expect(t).rejects.toThrow()
    

    Running CMake on Windows

    The default generator for Windows seems to be set to NMAKE. Try to use:

    cmake -G "MinGW Makefiles"
    

    Or use the GUI, and select MinGW Makefiles when prompted for a generator. Don't forget to cleanup the directory where you tried to run CMake, or delete the cache in the GUI. Otherwise, it will try again with NMAKE.

    jQuery rotate/transform

    Simply remove the line that rotates it one degree at a time and calls the script forever.

    // Animate rotation with a recursive call
    setTimeout(function() { rotate(++degree); },65);
    

    Then pass the desired value into the function... in this example 45 for 45 degrees.

    $(function() {
    
        var $elie = $("#bkgimg");
        rotate(45);
    
            function rotate(degree) {
          // For webkit browsers: e.g. Chrome
               $elie.css({ WebkitTransform: 'rotate(' + degree + 'deg)'});
          // For Mozilla browser: e.g. Firefox
               $elie.css({ '-moz-transform': 'rotate(' + degree + 'deg)'});
            }
    
    });
    

    Change .css() to .animate() in order to animate the rotation with jQuery. We also need to add a duration for the animation, 5000 for 5 seconds. And updating your original function to remove some redundancy and support more browsers...

    $(function() {
    
        var $elie = $("#bkgimg");
        rotate(45);
    
            function rotate(degree) {
                $elie.animate({
                            '-webkit-transform': 'rotate(' + degree + 'deg)',
                            '-moz-transform': 'rotate(' + degree + 'deg)',
                            '-ms-transform': 'rotate(' + degree + 'deg)',
                            '-o-transform': 'rotate(' + degree + 'deg)',
                            'transform': 'rotate(' + degree + 'deg)',
                            'zoom': 1
                }, 5000);
            }
    });
    

    EDIT: The standard jQuery CSS animation code above is not working because apparently, jQuery .animate() does not yet support the CSS3 transforms.

    This jQuery plugin is supposed to animate the rotation:

    http://plugins.jquery.com/project/QTransform

    How to validate white spaces/empty spaces? [Angular 2]

    Maybe this article can help you http://blog.angular-university.io/introduction-to-angular-2-forms-template-driven-vs-model-driven/

    In this approach, you have to use FormControl then watch for value changes and then apply your mask to the value. An example should be:

    ...
    form: FormGroup;
    ...
    
    
    ngOnInit(){
        this.form.valueChanges
                .map((value) => {
                    // Here you can manipulate your value
                    value.firstName = value.firstName.trim();
                    return value;
                })
                .filter((value) => this.form.valid)
                .subscribe((value) => {
                   console.log("Model Driven Form valid value: vm = ",JSON.stringify(value));
                });
    
    }
    

    get UTC timestamp in python with datetime

    I feel like the main answer is still not so clear, and it's worth taking the time to understand time and timezones.

    The most important thing to understand when dealing with time is that time is relative!

    • 2017-08-30 13:23:00: (a naive datetime), represents a local time somewhere in the world, but note that 2017-08-30 13:23:00 in London is NOT THE SAME TIME as 2017-08-30 13:23:00 in San Francisco.

    Because the same time string can be interpreted as different points-in-time depending on where you are in the world, there is a need for an absolute notion of time.

    A UTC timestamp is a number in seconds (or milliseconds) from Epoch (defined as 1 January 1970 00:00:00 at GMT timezone +00:00 offset).

    Epoch is anchored on the GMT timezone and therefore is an absolute point in time. A UTC timestamp being an offset from an absolute time therefore defines an absolute point in time.

    This makes it possible to order events in time.

    Without timezone information, time is relative, and cannot be converted to an absolute notion of time without providing some indication of what timezone the naive datetime should be anchored to.

    What are the types of time used in computer system?

    • naive datetime: usually for display, in local time (i.e. in the browser) where the OS can provide timezone information to the program.

    • UTC timestamps: A UTC timestamp is an absolute point in time, as mentioned above, but it is anchored in a given timezone, so a UTC timestamp can be converted to a datetime in any timezone, however it does not contain timezone information. What does that mean? That means that 1504119325 corresponds to 2017-08-30T18:55:24Z, or 2017-08-30T17:55:24-0100 or also 2017-08-30T10:55:24-0800. It doesn't tell you where the datetime recorded is from. It's usually used on the server side to record events (logs, etc...) or used to convert a timezone aware datetime to an absolute point in time and compute time differences.

    • ISO-8601 datetime string: The ISO-8601 is a standardized format to record datetime with timezone. (It's in fact several formats, read on here: https://en.wikipedia.org/wiki/ISO_8601) It is used to communicate timezone aware datetime information in a serializable manner between systems.

    When to use which? or rather when do you need to care about timezones?

    • If you need in any way to care about time-of-day, you need timezone information. A calendar or alarm needs time-of-day to set a meeting at the correct time of the day for any user in the world. If this data is saved on a server, the server needs to know what timezone the datetime corresponds to.

    • To compute time differences between events coming from different places in the world, UTC timestamp is enough, but you lose the ability to analyze at what time of day events occured (ie. for web analytics, you may want to know when users come to your site in their local time: do you see more users in the morning or the evening? You can't figure that out without time of day information.

    Timezone offset in a date string:

    Another point that is important, is that timezone offset in a date string is not fixed. That means that because 2017-08-30T10:55:24-0800 says the offset -0800 or 8 hours back, doesn't mean that it will always be!

    In the summer it may well be in daylight saving time, and it would be -0700

    What that means is that timezone offset (+0100) is not the same as timezone name (Europe/France) or even timezone designation (CET)

    America/Los_Angeles timezone is a place in the world, but it turns into PST (Pacific Standard Time) timezone offset notation in the winter, and PDT (Pacific Daylight Time) in the summer.

    So, on top of getting the timezone offset from the datestring, you should also get the timezone name to be accurate.

    Most packages will be able to convert numeric offsets from daylight saving time to standard time on their own, but that is not necessarily trivial with just offset. For example WAT timezone designation in West Africa, is UTC+0100 just like CET timezone in France, but France observes daylight saving time, while West Africa does not (because they're close to the equator)

    So, in short, it's complicated. VERY complicated, and that's why you should not do this yourself, but trust a package that does it for you, and KEEP IT UP TO DATE!

    Failed to load resource: the server responded with a status of 500 (Internal Server Error) in Bind function

    The 500 code would normally indicate an error on the server, not anything with your code. Some thoughts

    • Talk to the server developer for more info. You can't get more info directly.
    • Verify your arguments into the call (values). Look for anything you might think could cause a problem for the server process. The process should not die and should return you a better code, but bugs happen there also.
    • Could be intermittent, like if the server database goes down. May be worth trying at another time.

    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 -_-

    driver.switch_to.default_content()
    for x in range(50):
        try:
            driver.switch_to.frame(x)
            driver.find_element_by_xpath("//*[@id='23']").click()
            driver.find_element_by_xpath("/html/body/form/table/tbody/tr[1]/td/ul/li[49]/a").click()
        except:
            print("It's not: ", x)
            continue
    

    How do I convert a Swift Array to a String?

    Nowadays, in iOS 13+ and macOS 10.15+, we might use ListFormatter:

    let formatter = ListFormatter()
    
    let names = ["Moe", "Larry", "Curly"]
    if let string = formatter.string(from: names) {
        print(string)
    }
    

    That will produce a nice, natural language string representation of the list. A US user will see:

    Moe, Larry, and Curly

    It will support any languages for which (a) your app has been localized; and (b) the user’s device is configured. For example, a German user with an app supporting German localization, would see:

    Moe, Larry und Curly

    Is there something like Codecademy for Java

    Check out javapassion, they have a number of courses that encompass web programming, and were free (until circumstances conspired to make the website need to support itself).

    Even with the nominal fee, you get a lot for an entire year. It's a bargain compared to the amount of time you'll be investing.

    The other options are to look to Oracle's online tutorials, they lack the glitz of Codeacademy, but are surprisingly good. I haven't read the one on web programming, that might be embedded in the Java EE tutorial(s), which is not tuned for a new beginner to Java.

    How to initialize an array of objects in Java

    thePlayers[i] = new Player(i); I just deleted the i inside Player(i); and it worked.

    so the code line should be:

    thePlayers[i] = new Player9();
    

    Setting Authorization Header of HttpClient

    This is how i have done it:

    using (HttpClient httpClient = new HttpClient())
    {
       Dictionary<string, string> tokenDetails = null;
       var messageDetails = new Message { Id = 4, Message1 = des };
       HttpClient client = new HttpClient();
       client.BaseAddress = new Uri("http://localhost:3774/");
       var login = new Dictionary<string, string>
           {
               {"grant_type", "password"},
               {"username", "[email protected]"},
               {"password", "lopzwsx@23"},
           };
       var response = client.PostAsync("Token", new FormUrlEncodedContent(login)).Result;
       if (response.IsSuccessStatusCode)
       {
          tokenDetails = JsonConvert.DeserializeObject<Dictionary<string, string>>(response.Content.ReadAsStringAsync().Result);
          if (tokenDetails != null && tokenDetails.Any())
          {
             var tokenNo = tokenDetails.FirstOrDefault().Value;
             client.DefaultRequestHeaders.Add("Authorization", "Bearer " + tokenNo);
             client.PostAsJsonAsync("api/menu", messageDetails)
                 .ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode());
          }
       }
    }
    

    This you-tube video help me out a lot. Please check it out. https://www.youtube.com/watch?v=qCwnU06NV5Q

    Duplicate line in Visual Studio Code

    It's possible to create keybindings that are only active when Vim for VSCode is on and in a certain mode (i.e., "Normal", "Insert", or "Visual").

    To do so, use Ctrl + Shift + P to open up VSCode's Command Palette, then search for "Preferences: Open Keyboard Shortcuts (JSON)"--selecting this option will open up keybindings.json. Here, custom bindings can be added.

    For example, here are the classic VSCode commands to move/duplicate lines tweaked for ease of use in Vim..

        [
          {
            "key": "alt+j",
            "command": "editor.action.moveLinesDownAction",
            "when": "editorTextFocus && vim.active && vim.mode == 'Normal'"
          },
          {
            "key": "alt+shift+j",
            "command": "editor.action.copyLinesDownAction",
            "when": "editorTextFocus && vim.active && vim.mode == 'Normal'"
          },
          {
            "key": "alt+k",
            "command": "editor.action.moveLinesUpAction",
            "when": "editorTextFocus && vim.active && vim.mode == 'Normal'"
          },
          {
            "key": "alt+shift+k",
            "command": "editor.action.copyLinesUpAction",
            "when": "editorTextFocus && vim.active && vim.mode == 'Normal'"
          },
        ]
    

    Now we can use these Vim-friendly commands in VSCode!

    • Alt + J to move a line down
    • Alt + K to move a line up
    • Shift + Alt + J to duplicate a line down
    • Shift + Alt + K to duplicate a line up

    Java - escape string to prevent SQL injection

    Using a regular expression to remove text which could cause a SQL injection sounds like the SQL statement is being sent to the database via a Statement rather than a PreparedStatement.

    One of the easiest ways to prevent an SQL injection in the first place is to use a PreparedStatement, which accepts data to substitute into a SQL statement using placeholders, which does not rely on string concatenations to create an SQL statement to send to the database.

    For more information, Using Prepared Statements from The Java Tutorials would be a good place to start.

    READ_EXTERNAL_STORAGE permission for Android

    Has your problem been resolved? What is your target SDK? Try adding android;maxSDKVersion="21" to <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    Error: EPERM: operation not permitted, unlink 'D:\Sources\**\node_modules\fsevents\node_modules\abbrev\package.json'

    My problem was executing the command (npm audit fix all). I solved it when closing VSCODE and re-executed the command without problems.

    Deny access to one specific folder in .htaccess

    We will set the directory to be very secure, denying access for all file types. Below is the code you want to insert into the .htaccess file.

    Order Allow,Deny 
    Deny from all 
    

    Since we have now set the security, we now want to allow access to our desired file types. To do that, add the code below to the .htaccess file under the security code you just inserted.

    <FilesMatch "\.(jpg|gif|png|php)$">
    Order Deny,Allow
       Allow from all
    </FilesMatch>
    

    your final .htaccess file will look like

    Order Allow,Deny 
    Deny from all 
    
    <FilesMatch "\.(jpg|gif|png|php)$">
    Order Deny,Allow
       Allow from all
    </FilesMatch>
    

    Source from Allow access to specific file types in a protected directory

    Detecting request type in PHP (GET, POST, PUT or DELETE)

    REST in PHP can be done pretty simple. Create http://example.com/test.php (outlined below). Use this for REST calls, e.g. http://example.com/test.php/testing/123/hello. This works with Apache and Lighttpd out of the box, and no rewrite rules are needed.

    <?php
    $method = $_SERVER['REQUEST_METHOD'];
    $request = explode("/", substr(@$_SERVER['PATH_INFO'], 1));
    
    switch ($method) {
      case 'PUT':
        do_something_with_put($request);  
        break;
      case 'POST':
        do_something_with_post($request);  
        break;
      case 'GET':
        do_something_with_get($request);  
        break;
      default:
        handle_error($request);  
        break;
    }
    

    How do I use hexadecimal color strings in Flutter?

    utils.dart

    ///
    /// Convert a color hex-string to a Color object.
    ///
    Color getColorFromHex(String hexColor) {
      hexColor = hexColor.toUpperCase().replaceAll('#', '');
    
      if (hexColor.length == 6) {
        hexColor = 'FF' + hexColor;
      }
    
      return Color(int.parse(hexColor, radix: 16));
    }
    

    example usage

    Text(
      'hello world',
      style: TextStyle(
        color: getColorFromHex('#aabbcc'),
        fontWeight: FontWeight.bold,
      )
    )
    

    npm WARN package.json: No repository field

    If you are getting this from your own package.json, just add the repository field to it. (use the link to your actual repository):

    "repository" : { 
       "type" : "git",
       "url" : "https://github.com/npm/npm.git"
     }
    

    Remove plot axis values

    Change the axis_colour to match the background and if you are modifying the background dynamically you will need to update the axis_colour simultaneously. * The shared picture shows the graph/plot example using mock data ()

    ### Main Plotting Function ###
    plotXY <- function(time, value){
    
        ### Plot Style Settings ###
    
        ### default bg is white, set it the same as the axis-colour 
        background <- "white"
    
        ### default col.axis is black, set it the same as the background to match
        axis_colour <- "white"
    
        plot_title <- "Graph it!"
        xlabel <- "Time"
        ylabel <- "Value"
        label_colour <- "black"
        label_scale <- 2
        axis_scale <- 2
        symbol_scale <- 2
        title_scale <- 2
        subtitle_scale <- 2
        # point style 16 is a black dot
        point <- 16 
        # p - points, l - line, b - both
        plot_type <- "b"
    
        plot(time, value, main=plot_title, cex=symbol_scale, cex.lab=label_scale, cex.axis=axis_scale, cex.main=title_scale, cex.sub=subtitle_scale, xlab=xlabel, ylab=ylabel, col.lab=label_colour, col.axis=axis_colour, bg=background, pch=point, type=plot_type)
    }
    
    plotXY(time, value)
    

    enter image description here

    ' << ' operator in verilog

    << is the left-shift operator, as it is in many other languages.

    Here RAM_DEPTH will be 1 left-shifted by 8 bits, which is equivalent to 2^8, or 256.

    Simple function to sort an array of objects

    var data = [ 1, 2, 5, 3, 1]; data.sort(function(a,b) { return a-b });

    With a small compartor and using sort, we can do it

    How to check certificate name and alias in keystore files?

    You can run from Java code.

    try {
    
            File file = new File(keystore location);
            InputStream is = new FileInputStream(file);
            KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            String password = "password";
            keystore.load(is, password.toCharArray());
    
    
            Enumeration<String> enumeration = keystore.aliases();
            while(enumeration.hasMoreElements()) {
                String alias = enumeration.nextElement();
                System.out.println("alias name: " + alias);
                Certificate certificate = keystore.getCertificate(alias);
                System.out.println(certificate.toString());
    
            }
    
        } catch (java.security.cert.CertificateException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(null != is)
                try {
                    is.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        }
    

    Certificate class holds all information about the keystore.

    UPDATE- OBTAIN PRIVATE KEY

    Key key = keyStore.getKey(alias, password.toCharArray());
    String encodedKey = new Base64Encoder().encode(key.getEncoded());
    System.out.println("key ? " + encodedKey);
    

    @prateek Hope this is what you looking for!

    Convert a string to datetime in PowerShell

    You need to specify the format it already has, in order to parse it:

    $InvoiceDate = [datetime]::ParseExact($invoice, "dd-MMM-yy", $null)
    

    Now you can output it in the format you need:

    $InvoiceDate.ToString('yyyy-MM-dd')
    

    or

    '{0:yyyy-MM-dd}' -f $InvoiceDate
    

    C++ string to double conversion

    #include <iostream>
    #include <string>
    using namespace std;
    
    int main()
    {
        cout << stod("  99.999  ") << endl;
    }
    

    Output: 99.999 (which is double, whitespace was automatically stripped)

    Since C++11 converting string to floating-point values (like double) is available with functions:
    stof - convert str to a float
    stod - convert str to a double
    stold - convert str to a long double

    As conversion of string to int was also mentioned in the question, there are the following functions in C++11:
    stoi - convert str to an int
    stol - convert str to a long
    stoul - convert str to an unsigned long
    stoll - convert str to a long long
    stoull - convert str to an unsigned long long

    How to read PDF files using Java?

    PDFBox contains tools for text extraction.

    iText has more low-level support for text manipulation, but you'd have to write a considerable amount of code to get text extraction.

    iText in Action contains a good overview of the limitations of text extraction from PDF, regardless of the library used (Section 18.2: Extracting and editing text), and a convincing explanation why the library does not have text extraction support. In short, it's relatively easy to write a code that will handle simple cases, but it's basically impossible to extract text from PDF in general.

    Check existence of input argument in a Bash shell script

    If you'd like to check if the argument exists, you can check if the # of arguments is greater than or equal to your target argument number.

    The following script demonstrates how this works

    test.sh

    #!/usr/bin/env bash
    
    if [ $# -ge 3 ]
    then
      echo script has at least 3 arguments
    fi
    

    produces the following output

    $ ./test.sh
    ~
    $ ./test.sh 1
    ~
    $ ./test.sh 1 2
    ~
    $ ./test.sh 1 2 3
    script has at least 3 arguments
    $ ./test.sh 1 2 3 4
    script has at least 3 arguments
    

    How to maximize a plt.show() window using Python

    Ok so this is what worked for me. I did the whole showMaximize() option and it does resize your window in proportion to the size of the figure, but it does not expand and 'fit' the canvas. I solved this by:

    mng = plt.get_current_fig_manager()                                         
    mng.window.showMaximized()
    plt.tight_layout()    
    plt.savefig('Images/SAVES_PIC_AS_PDF.pdf') 
    
    plt.show()
    

    How to I say Is Not Null in VBA

    you can do like follows. Remember, IsNull is a function which returns TRUE if the parameter passed to it is null, and false otherwise.

    Not IsNull(Fields!W_O_Count.Value)
    

    How to replace a char in string with an Empty character in C#.NET

    If you are in a loop, let's say that you loop through a list of punctuation characters that you want to remove, you can do something like this:

          private const string PunctuationChars = ".,!?$";
              foreach (var word in words)
                    {
                        var word_modified = word;
    
                        var modified = false;
    
                        foreach (var punctuationChar in PunctuationChars)
                        {
                            if (word.IndexOf(punctuationChar) > 0)
                            {
                                modified = true;
                                word_modified = word_modified.Replace("" + punctuationChar, "");
    
    
                            }
                        }
                   //////////MORE CODE
                   }
    

    The trick being the following:

    word_modified.Replace("" + punctuationChar, "");
    

    How do I detect if I am in release or debug mode?

    Yes, you will have no problems using:

    if (BuildConfig.DEBUG) {
       //It's not a release version.
    }
    

    Unless you are importing the wrong BuildConfig class. Make sure you are referencing your project's BuildConfig class, not from any of your dependency libraries.

    enter image description here

    TreeMap sort by value

    polygenelubricants answer is almost perfect. It has one important bug though. It will not handle map entries where the values are the same.

    This code:...

    Map<String, Integer> nonSortedMap = new HashMap<String, Integer>();
    nonSortedMap.put("ape", 1);
    nonSortedMap.put("pig", 3);
    nonSortedMap.put("cow", 1);
    nonSortedMap.put("frog", 2);
    
    for (Entry<String, Integer> entry  : entriesSortedByValues(nonSortedMap)) {
        System.out.println(entry.getKey()+":"+entry.getValue());
    }
    

    Would output:

    ape:1
    frog:2
    pig:3
    

    Note how our cow dissapeared as it shared the value "1" with our ape :O!

    This modification of the code solves that issue:

    static <K,V extends Comparable<? super V>> SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map) {
            SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
                new Comparator<Map.Entry<K,V>>() {
                    @Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
                        int res = e1.getValue().compareTo(e2.getValue());
                        return res != 0 ? res : 1; // Special fix to preserve items with equal values
                    }
                }
            );
            sortedEntries.addAll(map.entrySet());
            return sortedEntries;
        }
    

    How to use Greek symbols in ggplot2?

    You do not need the latex2exp package to do what you wanted to do. The following code would do the trick.

    ggplot(smr, aes(Fuel.Rate, Eng.Speed.Ave., color=Eng.Speed.Max.)) + 
      geom_point() + 
      labs(title=expression("Fuel Efficiency"~(alpha*Omega)), 
    color=expression(alpha*Omega), x=expression(Delta~price))
    

    enter image description here

    Also, some comments (unanswered as of this point) asked about putting an asterisk (*) after a Greek letter. expression(alpha~"*") works, so I suggest giving it a try.

    More comments asked about getting ? Price and I find the most straightforward way to achieve that is expression(Delta~price)). If you need to add something before the Greek letter, you can also do this: expression(Indicative~Delta~price) which gets you:

    enter image description here

    Web API optional parameters

    I figured it out. I was using a bad example I found in the past of how to map query string to the method parameters.

    In case anyone else needs it, in order to have optional parameters in a query string such as:

    • ~/api/products/filter?apc=AA&xpc=BB
    • ~/api/products/filter?sku=7199123

    you would use:

    [Route("products/filter/{apc?}/{xpc?}/{sku?}")]
    public IHttpActionResult Get(string apc = null, string xpc = null, int? sku = null)
    { ... }
    

    It seems odd to have to define default values for the method parameters when these types already have a default.

    When are you supposed to use escape instead of encodeURI / encodeURIComponent?

    escape()

    Don't use it! escape() is defined in section B.2.1.2 escape and the introduction text of Annex B says:

    ... All of the language features and behaviours specified in this annex have one or more undesirable characteristics and in the absence of legacy usage would be removed from this specification. ...
    ... Programmers should not use or assume the existence of these features and behaviours when writing new ECMAScript code....

    Behaviour:

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape

    Special characters are encoded with the exception of: @*_+-./

    The hexadecimal form for characters, whose code unit value is 0xFF or less, is a two-digit escape sequence: %xx.

    For characters with a greater code unit, the four-digit format %uxxxx is used. This is not allowed within a query string (as defined in RFC3986):

    query       = *( pchar / "/" / "?" )
    pchar         = unreserved / pct-encoded / sub-delims / ":" / "@"
    unreserved    = ALPHA / DIGIT / "-" / "." / "_" / "~"
    pct-encoded   = "%" HEXDIG HEXDIG
    sub-delims    = "!" / "$" / "&" / "'" / "(" / ")"
                  / "*" / "+" / "," / ";" / "="
    

    A percent sign is only allowed if it is directly followed by two hexdigits, percent followed by u is not allowed.

    encodeURI()

    Use encodeURI when you want a working URL. Make this call:

    encodeURI("http://www.example.org/a file with spaces.html")
    

    to get:

    http://www.example.org/a%20file%20with%20spaces.html
    

    Don't call encodeURIComponent since it would destroy the URL and return

    http%3A%2F%2Fwww.example.org%2Fa%20file%20with%20spaces.html
    

    Note that encodeURI, like encodeURIComponent, does not escape the ' character.

    encodeURIComponent()

    Use encodeURIComponent when you want to encode the value of a URL parameter.

    var p1 = encodeURIComponent("http://example.org/?a=12&b=55")
    

    Then you may create the URL you need:

    var url = "http://example.net/?param1=" + p1 + "&param2=99";
    

    And you will get this complete URL:

    http://example.net/?param1=http%3A%2F%2Fexample.org%2F%Ffa%3D12%26b%3D55&param2=99

    Note that encodeURIComponent does not escape the ' character. A common bug is to use it to create html attributes such as href='MyUrl', which could suffer an injection bug. If you are constructing html from strings, either use " instead of ' for attribute quotes, or add an extra layer of encoding (' can be encoded as %27).

    For more information on this type of encoding you can check: http://en.wikipedia.org/wiki/Percent-encoding

    Is it possible to install both 32bit and 64bit Java on Windows 7?

    To install 32-bit Java on Windows 7 (64-bit OS + Machine). You can do:

    1) Download JDK: http://javadl.sun.com/webapps/download/AutoDL?BundleId=58124
    2) Download JRE: http://www.java.com/en/download/installed.jsp?jre_version=1.6.0_22&vendor=Sun+Microsystems+Inc.&os=Linux&os_version=2.6.41.4-1.fc15.i686
    
    3) System variable create: C:\program files (x86)\java\jre6\bin\
    
    4) Anywhere you type java -version
    

    it use 32-bit on (64-bit). I have to use this because lots of third party libraries do not work with 64-bit. Java wake up from the hell, give us peach :P. Go-language is killer.

    Get google map link with latitude/longitude

    Use View mode returns a map with no markers or directions.

    The example below uses the optional maptype parameter to display a satellite view of the map.

    https://www.google.com/maps/embed/v1/view
      ?key=YOUR_API_KEY
      &center=-33.8569,151.2152
      &zoom=18
      &maptype=satellite
    

    Google Maps setCenter()

     function resize() {
            var map_obj = document.getElementById("map_canvas");
    
          /*  map_obj.style.width = "500px";
            map_obj.style.height = "225px";*/
            if (map) {
                map.checkResize();
                map.panTo(new GLatLng(lat,lon));
            }
        }
    
    <body onload="initialize()" onunload="GUnload()" onresize="resize()">
    <div id="map_canvas" style="width: 100%; height: 100%">
    </div>
    

    How do I pause my shell script for a second before continuing?

    On Mac OSX, sleep does not take minutes/etc, only seconds. So for two minutes,

    sleep 120
    

    What is the best way to create a string array in python?

    But what is a reason to use fixed size? There is no actual need in python to use fixed size arrays(lists) so you always have ability to increase it's size using append, extend or decrease using pop, or at least you can use slicing.

    x = [''  for x in xrange(10)]
    

    Print number of keys in Redis

    Go to redis-cli and use below command

    info keyspace
    

    It may help someone

    ORA-12154 could not resolve the connect identifier specified

    In my case, the reason for this error was that I was missing the tnsnames.ora file under client_32\NETWORK\ADMIN

    How to print out all the elements of a List in Java?

    Use String.join() for example:

    System.out.print(String.join("\n", list));
    

    Mocking static methods with Mockito

    Observation : When you call static method within a static entity, you need to change the class in @PrepareForTest.

    For e.g. :

    securityAlgo = MessageDigest.getInstance(SECURITY_ALGORITHM);
    

    For the above code if you need to mock MessageDigest class, use

    @PrepareForTest(MessageDigest.class)
    

    While if you have something like below :

    public class CustomObjectRule {
    
        object = DatatypeConverter.printHexBinary(MessageDigest.getInstance(SECURITY_ALGORITHM)
                 .digest(message.getBytes(ENCODING)));
    
    }
    

    then, you'd need to prepare the class this code resides in.

    @PrepareForTest(CustomObjectRule.class)
    

    And then mock the method :

    PowerMockito.mockStatic(MessageDigest.class);
    PowerMockito.when(MessageDigest.getInstance(Mockito.anyString()))
          .thenThrow(new RuntimeException());
    

    Writing sqlplus output to a file

    just to save my own deductions from all this is (for saving DBMS_OUTPUT output on the client, using sqlplus):

    • no matter if i use Toad/with polling or sqlplus, for a long running script with occasional dbms_output.put_line commands, i will get the output in the end of the script execution
    • set serveroutput on; and dbms_output.enable(); should be present in the script
    • to save the output SPOOL command was not enough to get the DBMS_OUTPUT lines printed to a file - had to use the usual > windows CMD redirection. the passwords etc. can be given to the empty prompt, after invoking sqlplus. also the "/" directives and the "exit;" command should be put either inside the script, or given interactively as the password above (unless it is specified during the invocation of sqlplus)

    How to get json response using system.net.webrequest in c#?

    You need to explicitly ask for the content type.

    Add this line:

     request.ContentType = "application/json; charset=utf-8";
    At the appropriate place

    Passive Link in Angular 2 - <a href=""> equivalent

    I have 4 solutions for dummy anchor tag.

        1. <a style="cursor: pointer;"></a>
        2. <a href="javascript:void(0)" ></a>
        3. <a href="current_screen_path"></a>
    

    4.If you are using bootstrap:

    <button class="btn btn-link p-0" type="button" style="cursor: pointer"(click)="doSomething()">MY Link</button>
    

    How to make a browser display a "save as dialog" so the user can save the content of a string to a file on his system?

    There is a javascript library for this, see FileSaver.js on Github

    However the saveAs() function won't send pure string to the browser, you need to convert it to blob:

    function data2blob(data, isBase64) {
      var chars = "";
    
      if (isBase64)
        chars = atob(data);
      else
        chars = data;
    
      var bytes = new Array(chars.length);
      for (var i = 0; i < chars.length; i++) {
        bytes[i] = chars.charCodeAt(i);
      }
    
      var blob = new Blob([new Uint8Array(bytes)]);
      return blob;
    }
    

    and then call saveAs on the blob, as like:

    var myString = "my string with some stuff";
    saveAs( data2blob(myString), "myString.txt" );
    

    Of course remember to include the above-mentioned javascript library on your webpage using <script src=FileSaver.js>

    How do I remove packages installed with Python's easy_install?

    pip, an alternative to setuptools/easy_install, provides an "uninstall" command.

    Install pip according to the installation instructions:

    $ wget https://bootstrap.pypa.io/get-pip.py
    $ python get-pip.py
    

    Then you can use pip uninstall to remove packages installed with easy_install

    PHP substring extraction. Get the string before the first '/' or the whole string

    $string="kalion/home/public_html";
    
    $newstring=( stristr($string,"/")==FALSE ) ? $string : substr($string,0,stripos($string,"/"));
    

    How to set Sqlite3 to be case insensitive when string comparing?

    This is not specific to sqlite but you can just do

    SELECT * FROM ... WHERE UPPER(name) = UPPER('someone')
    

    How to get data by SqlDataReader.GetValue by column name

    thisReader.GetString(int columnIndex)

    How to reload a page after the OK click on the Alert Page

    Use javascript confirm() method instead of alert. It returns true if the user clicked ok button and returns false when user clicked on cancel button. Sample code will look like this :

    if(confirm('Successful Message')){
        window.location.reload();  
    }
    

    Determine the path of the executing BASH script

    echo Running from `dirname $0`
    

    How to find if a native DLL file is compiled as x64 or x86?

    I rewrote c++ solution in first answer in powershell script. Script can determine this types of .exe and .dll files:

    #Description       C# compiler switch             PE type       machine corflags
    #MSIL              /platform:anycpu (default)     PE32  x86     ILONLY
    #MSIL 32 bit pref  /platform:anycpu32bitpreferred PE32  x86     ILONLY | 32BITREQUIRED | 32BITPREFERRED
    #x86 managed       /platform:x86                  PE32  x86     ILONLY | 32BITREQUIRED
    #x86 mixed         n/a                            PE32  x86     32BITREQUIRED
    #x64 managed       /platform:x64                  PE32+ x64     ILONLY
    #x64 mixed         n/a                            PE32+ x64  
    #ARM managed       /platform:arm                  PE32  ARM     ILONLY
    #ARM mixed         n/a                            PE32  ARM  
    

    this solution has some advantages over corflags.exe and loading assembly via Assembly.Load in C# - you will never get BadImageFormatException or message about invalid header.

    function GetActualAddressFromRVA($st, $sec, $numOfSec, $dwRVA)
    {
        [System.UInt32] $dwRet = 0;
        for($j = 0; $j -lt $numOfSec; $j++)   
        {   
            $nextSectionOffset = $sec + 40*$j;
            $VirtualSizeOffset = 8;
            $VirtualAddressOffset = 12;
            $SizeOfRawDataOffset = 16;
            $PointerToRawDataOffset = 20;
    
        $Null = @(
            $curr_offset = $st.BaseStream.Seek($nextSectionOffset + $VirtualSizeOffset, [System.IO.SeekOrigin]::Begin);        
            [System.UInt32] $VirtualSize = $b.ReadUInt32();
            [System.UInt32] $VirtualAddress = $b.ReadUInt32();
            [System.UInt32] $SizeOfRawData = $b.ReadUInt32();
            [System.UInt32] $PointerToRawData = $b.ReadUInt32();        
    
            if ($dwRVA -ge $VirtualAddress -and $dwRVA -lt ($VirtualAddress + $VirtualSize)) {
                $delta = $VirtualAddress - $PointerToRawData;
                $dwRet = $dwRVA - $delta;
                return $dwRet;
            }
            );
        }
        return $dwRet;
    }
    
    function Get-Bitness2([System.String]$path, $showLog = $false)
    {
        $Obj = @{};
        $Obj.Result = '';
        $Obj.Error = $false;
    
        $Obj.Log = @(Split-Path -Path $path -Leaf -Resolve);
    
        $b = new-object System.IO.BinaryReader([System.IO.File]::Open($path,[System.IO.FileMode]::Open,[System.IO.FileAccess]::Read, [System.IO.FileShare]::Read));
        $curr_offset = $b.BaseStream.Seek(0x3c, [System.IO.SeekOrigin]::Begin)
        [System.Int32] $peOffset = $b.ReadInt32();
        $Obj.Log += 'peOffset ' + "{0:X0}" -f $peOffset;
    
        $curr_offset = $b.BaseStream.Seek($peOffset, [System.IO.SeekOrigin]::Begin);
        [System.UInt32] $peHead = $b.ReadUInt32();
    
        if ($peHead -ne 0x00004550) {
            $Obj.Error = $true;
            $Obj.Result = 'Bad Image Format';
            $Obj.Log += 'cannot determine file type (not x64/x86/ARM) - exit with error';
        };
    
        if ($Obj.Error)
        {
            $b.Close();
            Write-Host ($Obj.Log | Format-List | Out-String);
            return $false;
        };
    
        [System.UInt16] $machineType = $b.ReadUInt16();
        $Obj.Log += 'machineType ' + "{0:X0}" -f $machineType;
    
        [System.UInt16] $numOfSections = $b.ReadUInt16();
        $Obj.Log += 'numOfSections ' + "{0:X0}" -f $numOfSections;
        if (($machineType -eq 0x8664) -or ($machineType -eq 0x200)) { $Obj.Log += 'machineType: x64'; }
        elseif ($machineType -eq 0x14c)                             { $Obj.Log += 'machineType: x86'; }
        elseif ($machineType -eq 0x1c0)                             { $Obj.Log += 'machineType: ARM'; }
        else{
            $Obj.Error = $true;
            $Obj.Log += 'cannot determine file type (not x64/x86/ARM) - exit with error';
        };
    
        if ($Obj.Error) {
            $b.Close();
            Write-Output ($Obj.Log | Format-List | Out-String);
            return $false;
        };
    
        $curr_offset = $b.BaseStream.Seek($peOffset+20, [System.IO.SeekOrigin]::Begin);
        [System.UInt16] $sizeOfPeHeader = $b.ReadUInt16();
    
        $coffOffset = $peOffset + 24;#PE header size is 24 bytes
        $Obj.Log += 'coffOffset ' + "{0:X0}" -f $coffOffset;
    
        $curr_offset = $b.BaseStream.Seek($coffOffset, [System.IO.SeekOrigin]::Begin);#+24 byte magic number
        [System.UInt16] $pe32 = $b.ReadUInt16();         
        $clr20headerOffset = 0;
        $flag32bit = $false;
        $Obj.Log += 'pe32 magic number: ' + "{0:X0}" -f $pe32;
        $Obj.Log += 'size of optional header ' + ("{0:D0}" -f $sizeOfPeHeader) + " bytes";
    
        #COMIMAGE_FLAGS_ILONLY               =0x00000001,
        #COMIMAGE_FLAGS_32BITREQUIRED        =0x00000002,
        #COMIMAGE_FLAGS_IL_LIBRARY           =0x00000004,
        #COMIMAGE_FLAGS_STRONGNAMESIGNED     =0x00000008,
        #COMIMAGE_FLAGS_NATIVE_ENTRYPOINT    =0x00000010,
        #COMIMAGE_FLAGS_TRACKDEBUGDATA       =0x00010000,
        #COMIMAGE_FLAGS_32BITPREFERRED       =0x00020000,
    
        $COMIMAGE_FLAGS_ILONLY        = 0x00000001;
        $COMIMAGE_FLAGS_32BITREQUIRED = 0x00000002;
        $COMIMAGE_FLAGS_32BITPREFERRED = 0x00020000;
    
        $offset = 96;
        if ($pe32 -eq 0x20b) {
            $offset = 112;#size of COFF header is bigger for pe32+
        }     
    
        $clr20dirHeaderOffset = $coffOffset + $offset + 14*8;#clr directory header offset + start of section number 15 (each section is 8 byte long);
        $Obj.Log += 'clr20dirHeaderOffset ' + "{0:X0}" -f $clr20dirHeaderOffset;
        $curr_offset = $b.BaseStream.Seek($clr20dirHeaderOffset, [System.IO.SeekOrigin]::Begin);
        [System.UInt32] $clr20VirtualAddress = $b.ReadUInt32();
        [System.UInt32] $clr20Size = $b.ReadUInt32();
        $Obj.Log += 'clr20VirtualAddress ' + "{0:X0}" -f $clr20VirtualAddress;
        $Obj.Log += 'clr20SectionSize ' + ("{0:D0}" -f $clr20Size) + " bytes";
    
        if ($clr20Size -eq 0) {
            if ($machineType -eq 0x1c0) { $Obj.Result = 'ARM native'; }
            elseif ($pe32 -eq 0x10b)    { $Obj.Result = '32-bit native'; }
            elseif($pe32 -eq 0x20b)     { $Obj.Result = '64-bit native'; }
    
           $b.Close();   
           if ($Obj.Result -eq '') { 
                $Obj.Error = $true;
                $Obj.Log += 'Unknown type of file';
           }
           else { 
                if ($showLog) { Write-Output ($Obj.Log | Format-List | Out-String); };
                return $Obj.Result;
           }
        };
    
        if ($Obj.Error) {
            $b.Close();
            Write-Host ($Obj.Log | Format-List | Out-String);
            return $false;
        };
    
        [System.UInt32]$sectionsOffset = $coffOffset + $sizeOfPeHeader;
        $Obj.Log += 'sectionsOffset ' + "{0:X0}" -f $sectionsOffset;
        $realOffset = GetActualAddressFromRVA $b $sectionsOffset $numOfSections $clr20VirtualAddress;
        $Obj.Log += 'real IMAGE_COR20_HEADER offset ' + "{0:X0}" -f $realOffset;
        if ($realOffset -eq 0) {
            $Obj.Error = $true;
            $Obj.Log += 'cannot find COR20 header - exit with error';
            $b.Close();
            return $false;
        };
    
        if ($Obj.Error) {
            $b.Close();
            Write-Host ($Obj.Log | Format-List | Out-String);
            return $false;
        };
    
        $curr_offset = $b.BaseStream.Seek($realOffset + 4, [System.IO.SeekOrigin]::Begin);
        [System.UInt16] $majorVer = $b.ReadUInt16();
        [System.UInt16] $minorVer = $b.ReadUInt16();
        $Obj.Log += 'IMAGE_COR20_HEADER version ' + ("{0:D0}" -f $majorVer) + "." + ("{0:D0}" -f $minorVer);
    
        $flagsOffset = 16;#+16 bytes - flags field
        $curr_offset = $b.BaseStream.Seek($realOffset + $flagsOffset, [System.IO.SeekOrigin]::Begin);
        [System.UInt32] $flag32bit = $b.ReadUInt32();
        $Obj.Log += 'CorFlags: ' + ("{0:X0}" -f $flag32bit);
    
    #Description       C# compiler switch             PE type       machine corflags
    #MSIL              /platform:anycpu (default)     PE32  x86     ILONLY
    #MSIL 32 bit pref  /platform:anycpu32bitpreferred PE32  x86     ILONLY | 32BITREQUIRED | 32BITPREFERRED
    #x86 managed       /platform:x86                  PE32  x86     ILONLY | 32BITREQUIRED
    #x86 mixed         n/a                            PE32  x86     32BITREQUIRED
    #x64 managed       /platform:x64                  PE32+ x64     ILONLY
    #x64 mixed         n/a                            PE32+ x64  
    #ARM managed       /platform:arm                  PE32  ARM     ILONLY
    #ARM mixed         n/a                            PE32  ARM  
    
        $isILOnly = ($flag32bit -band $COMIMAGE_FLAGS_ILONLY) -eq $COMIMAGE_FLAGS_ILONLY;
        $Obj.Log += 'ILONLY: ' + $isILOnly;
        if ($machineType -eq 0x1c0) {#if ARM
            if ($isILOnly) { $Obj.Result = 'ARM managed'; } 
                      else { $Obj.Result = 'ARM mixed'; }
        }
        elseif ($pe32 -eq 0x10b) {#pe32
            $is32bitRequired = ($flag32bit -band $COMIMAGE_FLAGS_32BITREQUIRED) -eq $COMIMAGE_FLAGS_32BITREQUIRED;
            $is32bitPreffered = ($flag32bit -band $COMIMAGE_FLAGS_32BITPREFERRED) -eq $COMIMAGE_FLAGS_32BITPREFERRED;
            $Obj.Log += '32BIT: ' + $is32bitRequired;    
            $Obj.Log += '32BIT PREFFERED: ' + $is32bitPreffered 
            if     ($is32bitRequired  -and $isILOnly  -and $is32bitPreffered) { $Obj.Result = 'AnyCpu 32bit-preffered'; }
            elseif ($is32bitRequired  -and $isILOnly  -and !$is32bitPreffered){ $Obj.Result = 'x86 managed'; }
            elseif (!$is32bitRequired -and !$isILOnly -and $is32bitPreffered) { $Obj.Result = 'x86 mixed'; }
            elseif ($isILOnly)                                                { $Obj.Result = 'AnyCpu'; }
       }
       elseif ($pe32 -eq 0x20b) {#pe32+
            if ($isILOnly) { $Obj.Result = 'x64 managed'; } 
                      else { $Obj.Result = 'x64 mixed'; }
       }
    
       $b.Close();   
       if ($showLog) { Write-Host ($Obj.Log | Format-List | Out-String); }
       if ($Obj.Result -eq ''){ return 'Unknown type of file';};
       $flags = '';
       if ($isILOnly) {$flags += 'ILONLY';}
       if ($is32bitRequired) {
            if ($flags -ne '') {$flags += ' | ';}
            $flags += '32BITREQUIRED';
       }
       if ($is32bitPreffered) {
            if ($flags -ne '') {$flags += ' | ';}
            $flags += '32BITPREFERRED';
       }
       if ($flags -ne '') {$flags = ' (' + $flags +')';}
       return $Obj.Result + $flags;
    }
    

    usage example:

    #$filePath = "C:\Windows\SysWOW64\regedit.exe";#32 bit native on 64bit windows
    $filePath = "C:\Windows\regedit.exe";#64 bit native on 64bit windows | should be 32 bit native on 32bit windows
    
    Get-Bitness2 $filePath $true;
    

    you can omit second parameter if you don't need to see details

    Getting a slice of keys from a map

    You also can take an array of keys with type []Value by method MapKeys of struct Value from package "reflect":

    package main
    
    import (
        "fmt"
        "reflect"
    )
    
    func main() {
        abc := map[string]int{
            "a": 1,
            "b": 2,
            "c": 3,
        }
    
        keys := reflect.ValueOf(abc).MapKeys()
    
        fmt.Println(keys) // [a b c]
    }