Programs & Examples On #Ext.list

JPA Hibernate Persistence exception [PersistenceUnit: default] Unable to build Hibernate SessionFactory

The issue is that you are not able to get a connection to MYSQL database and hence it is throwing an error saying that cannot build a session factory.

Please see the error below:

 Caused by: java.sql.SQLException: Access denied for user ''@'localhost' (using password: NO) 

which points to username not getting populated.

Please recheck system properties


some packages seems to be missing as well pointing to a dependency issue:

package does not exist

Please run a mvn dependency:tree command to check for dependencies

WARNING: Exception encountered during context initialization - cancelling refresh attempt

The important part is this:

Cannot find class [com.rakuten.points.persistence.manager.MemberPointSummaryDAOImpl] for bean with name 'MemberPointSummaryDAOImpl' defined in ServletContext resource [/WEB-INF/context/PersistenceManagerContext.xml];

due to:

nested exception is java.lang.ClassNotFoundException: com.rakuten.points.persistence.manager.MemberPointSummaryDAOImpl

According to this log, Spring could not find your MemberPointSummaryDAOImpl class.

No found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:

Look at the exception:

No qualifying bean of type [] found for dependency

This means that there's no bean available to fulfill that dependency. Yes, you have an implementation of the interface, but you haven't created a bean for that implementation. You have two options:

  • Annotate UserDaoImpl with @Component or @Repository, and let the component scan do the work for you, exactly as you have done with UserService.
  • Add the bean manually to your xml file, the same you have done with UserBoImpl.

Remember that if you create the bean explicitly you need to put the definition before the component scan. In this case the order is important.

Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener

If you are sure you haven't messed the jar, then please clean the project and perform mvn clean install. This should solve the problem.

Could not resolve placeholder in string value

I got same error in my Micro-service, whenever you declare @Value annotation in program i.e @Value("${project.api.key}")

make sure that your file with same values should not be blank project.api.key= add some values

MostIMP :otherwise it will throw error "Error creating bean with name 'ServiceFTP': Injection of autowired dependencies"

BeanFactory not initialized or already closed - call 'refresh' before

In my case, the error "BeanFactory not initialized or already closed - call 'refresh' before" was a consequence of a previous error that I didn't noticed in the server startup. I think that it is not always the real cause of the problem.

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'customerService' is defined

You will have to annotate your service with @Service since you have said I am using annotations for mapping

org.springframework.beans.factory.BeanCreationException: Error creating bean with name

According to the stack trace, your issue is that your app cannot find org.apache.commons.dbcp.BasicDataSource, as per this line:

java.lang.ClassNotFoundException: org.apache.commons.dbcp.BasicDataSource

I see that you have commons-dbcp in your list of jars, but for whatever reason, your app is not finding the BasicDataSource class in it.

java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

When I look at the solutions, it seems the problem is always something that prevents the spring library to be loaded. It could be a dependency problem or a deployment problem.

In my case, it was the maven repository that somehow got corrupt. What solved the problem was to remove the folder `C:\Users(my name).m2\repository' and rebuild.

Could not resolve Spring property placeholder

It's definitely not a problem with propeties file not being found, since in that case another exception is thrown.

Make sure that you actually have a value with key idm.url in your

Error : java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.<init>(I)V

to resolve this kind of problem you should add two jar in your dependency POM (if use Maven)



org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class

I have faced similar problem


I just do

1.update Maven Project

2.install maven.

MySQL - ERROR 1045 - Access denied

The current root password must be empty. Then under "new root password" enter your password and confirm.

How to filter by object property in angularJS

The documentation has the complete answer. Anyway this is how it is done:

<input type="text" ng-model="filterValue">
<li ng-repeat="i in data | filter:{age:filterValue}:true"> {{i | json }}</li>

will filter only age in data array and true is for exact match.

For deep filtering,

<li ng-repeat="i in data | filter:{$:filterValue}:true"> {{i}}</li>

The $ is a special property for deep filter and the true is for exact match like above.

How to create a dump with Oracle PL/SQL Developer?

There are some easy steps to make Dump file of your Tables,Users and Procedures:

Goto sqlplus or any sql*plus connect by your username or password

  1. Now type host it looks like SQL>host.
  2. Now type "exp" means export.
  3. It ask u for username and password give the username and password of that user of which you want to make a dump file.
  4. Now press Enter.
  5. Now option blinks for Export file: EXPDAT.DMP>_ (Give a path and file name to where you want to make a dump file e.g e:\FILENAME.dmp) and the press enter
  6. Select the option "Entire Database" or "Tables" or "Users" then press Enter
  7. Again press Enter 2 more times table data and compress extent
  8. Enter the name of table like i want to make dmp file of table student existing so type student and press Enter
  9. Enter to quit now your file at your given path is dump file now import that dmp file to get all the table data.

How to find a string inside a entire database?

SQL Locator (free) has worked great for me. It comes with a lot of options and it's fairly easy to use.

RuntimeWarning: invalid value encountered in divide

You are dividing by rr which may be 0.0. Check if rr is zero and do something reasonable other than using it in the denominator.

Convert HTML Character Back to Text Using Java Standard Library

The URL decoder should only be used for decoding strings from the urls generated by html forms which are in the "application/x-www-form-urlencoded" mime type. This does not support html characters.

After a search I found a Translate class within the HTML Parser library.

How do I get time of a Python program's execution?

There is a timeit module which can be used to time the execution times of Python code.

It has detailed documentation and examples in Python documentation, 26.6. timeit — Measure execution time of small code snippets.

PHP: How to remove specific element from an array?

I'm currently using this function:

function array_delete($del_val, $array) {
    if(is_array($del_val)) {
         foreach ($del_val as $del_key => $del_value) {
            foreach ($array as $key => $value){
                if ($value == $del_value) {
    } else {
        foreach ($array as $key => $value){
            if ($value == $del_val) {
    return array_values($array);

You can input an array or only a string with the element(s) which should be removed. Write it like this:

$detils = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');
$detils = array_delete(array('orange', 'apple'), $detils);


$detils = array_delete('orange', $detils);

It'll also reindex it.

Spring transaction REQUIRED vs REQUIRES_NEW : Rollback Transaction

If you really need to do it in separate transaction you need to use REQUIRES_NEW and live with the performance overhead. Watch out for dead locks.

I'd rather do it the other way:

  • Validate data on Java side.
  • Run everyting in one transaction.
  • If anything goes wrong on DB side -> it's a major error of DB or validation design. Rollback everything and throw critical top level error.
  • Write good unit tests.

UITextField text change event

As stated here: UITextField text change event, it seems that as of iOS 6 (iOS 6.0 and 6.1 checked) it is not possible to fully detect changes in UITextField objects just by observing the UITextFieldTextDidChangeNotification.

It seems that only those changes made directly by the built-in iOS keyboard are tracked now. This means that if you change your UITextField object just by invoking something like this: myUITextField.text = @"any_text", you won't be notified about any changes at all.

I don't know if this is a bug or it is intended. Seems like a bug since I haven't found any reasonable explanation in documentation. This is also stated here: UITextField text change event.

My "solution" to this is to actually post a notification by myself for every change I make to my UITextField (if that change is done without using the built-in iOS keyboard). Something like this:

myUITextField.text = @"I'm_updating_my_UITextField_directly_in_code";

NSNotification *myTextFieldUpdateNotification  = 
  [NSNotification notificationWithName:UITextFieldTextDidChangeNotification


This way you are 100% confident that you'll receive the same notification when you change the .text property of your UITextField object, either when you update it "manually" in your code or through the built-in iOS keyboard.

It is important to consider that, since this is not a documented behavior, this approach may lead to 2 notifications received for the same change in your UITextField object. Depending on your needs (what you actually do when your UITextField.text changes) this could be an inconvenience for you.

A slightly different approach would be to post a custom notification (this is, with a custom name other than UITextFieldTextDidChangeNotification) if you actually need to know whether the notification was yours or "iOS-made".


I've just found a different approach which I think could be better:

This involves the Key-Value Observing (KVO) feature of Objective-C (

Basically, you register yourself as an observer of a property and if this property changes you get notified about it. The "principle" is quite similar to how NSNotificationCenter works, being the main advantage that this approach works automatically also as of iOS 6 (without any special tweak like having to manually post notifications).

For our UITextField-scenario this works just fine if you add this code to, for example, your UIViewController that contains the text field:

static void *myContext = &myContext;

- (void)viewDidLoad {
  [super viewDidLoad];

  //Observing changes to myUITextField.text:
  [myUITextField addObserver:self forKeyPath:@"text"


- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object 
change:(NSDictionary *)change context:(void *)context {

  if(context == myContext) {
    //Here you get notified every time myUITextField's "text" property is updated
    NSLog(@"New value: %@ - Old value: %@",
      [change objectForKey:NSKeyValueChangeNewKey],
      [change objectForKey:NSKeyValueChangeOldKey]);
    [super observeValueForKeyPath:keyPath ofObject:object 
      change:change context:context];


Credit to this answer regarding "context" management:

Note: Seems like while you are in the process of editing a UITextField with the built-in iOS keyboard, the "text" property of the text field is not updated with every new letter typed/removed. Instead, the text field object gets updated "as a whole" after you resign the first responder status of the text field.

Prevent users from submitting a form by hitting Enter

I needed to prevent only specific inputs from submitting, so I used a class selector, to let this be a "global" feature wherever I need it.

<input id="txtEmail" name="txtEmail" class="idNoEnter" .... />

And this jQuery code:

$('.idNoEnter').keydown(function (e) {
  if (e.keyCode == 13) {

Alternatively, if keydown is insufficient:

$('.idNoEnter').on('keypress keydown keyup', function (e) {
   if (e.keyCode == 13) {

Some notes:

Modifying various good answers here, the Enter key seems to work for keydown on all the browsers. For the alternative, I updated bind() to the on() method.

I'm a big fan of class selectors, weighing all the pros and cons and performance discussions. My naming convention is 'idSomething' to indicate jQuery is using it as an id, to separate it from CSS styling.

Simple way to compare 2 ArrayLists

This should check if two lists are equal, it does some basic checks first (i.e. nulls and lengths), then sorts and uses the collections.equals method to check if they are equal.

public  boolean equalLists(List<String> a, List<String> b){     
    // Check for sizes and nulls

    if (a == null && b == null) return true;

    if ((a == null && b!= null) || (a != null && b== null) || (a.size() != b.size()))
        return false;

    // Sort and compare the two lists          
    return a.equals(b);

How to make child process die after parent exits?

Does the child process have a pipe to/from the parent process? If so, you'd receive a SIGPIPE if writing, or get EOF when reading - these conditions could be detected.

How to monitor Java memory usage?

JavaMelody might be a solution for your need.

Developed for Java EE applications, this tool measure and build report about the real operation of your applications on any environments. It's free and open-source and easy to integrate into applications with some history, no database nor profiling, really lightweight.

Gradle build without tests


gradle assemble

To list all available tasks for your project, try:

gradle tasks


This may not seem the most correct answer at first, but read carefully gradle tasks output or docs.

Build tasks
assemble - Assembles the outputs of this project.
build - Assembles and tests this project.

Can I add a custom attribute to an HTML tag?

use data-any , I use them a lot

<aside data-area="asidetop" data-type="responsive" class="top">

jQuery UI DatePicker to show year only

Try this piece of code, it worked for me:

    format: "yyyy",
    viewMode: "years",
    minViewMode: "years"

I hope it will do magic also for you.

How to fix Warning Illegal string offset in PHP

Please check that your key exists in the array or not, instead of simply trying to access it.


$myVar = $someArray['someKey']

With something like:

if (isset($someArray['someKey'])) {
    $myVar = $someArray['someKey']

or something like:

if(is_array($someArray['someKey'])) {
    $theme_img = 'recent_works_iso_thumbnail';
}else {
    $theme_img = 'recent_works_iso_thumbnail';

Match everything except for specified strings

You don't need negative lookahead. There is working example:



  • [\s\S] - match any character
  • * - match from 0 to unlimited from previous group
  • ? - match as less as possible
  • (red|green|blue|) - match one of this words or nothing
  • g - repeat pattern



Will be:


Test it:

Datetime in where clause

Assuming we're talking SQL Server DateTime

Note: BETWEEN includes both ends of the range, so technically this pattern will be wrong:

errorDate BETWEEN '12/20/2008' AND '12/21/2008'

My preferred method for a time range like that is:

'20081220' <= errorDate AND errordate < '20081221'

Works with common indexes (range scan, SARGable, functionless) and correctly clips off midnight of the next day, without relying on SQL Server's time granularity (e.g. 23:59:59.997)

How to return a string from a C++ function?

You never give any value to your strings in main so they are empty, and thus obviously the function returns an empty string.


string str1, str2, str3;


string str1 = "the dog jumped over the fence";
string str2 = "the";
string str3 = "that";

Also, you have several problems in your replaceSubstring function:

int index = s1.find(s2, 0);
s1.replace(index, s2.length(), s3);
  • std::string::find returns a std::string::size_type (aka. size_t) not an int. Two differences: size_t is unsigned, and it's not necessarily the same size as an int depending on your platform (eg. on 64 bits Linux or Windows size_t is unsigned 64 bits while int is signed 32 bits).
  • What happens if s2 is not part of s1? I'll leave it up to you to find how to fix that. Hint: std::string::npos ;)

Checking if a key exists in a JavaScript object?

const object1 = {
  a: 'something',
  b: 'something',
  c: 'something'

const key = 's';

// Object.keys(object1) will return array of the object keys ['a', 'b', 'c']

Object.keys(object1).indexOf(key) === -1 ? 'the key is not there' : 'yep the key is exist';

Proper way to concatenate variable strings

As simple as joining lists in python itself.

ansible -m debug -a msg="{{ '-'.join(('list', 'joined', 'together')) }}" localhost

localhost | SUCCESS => {
  "msg": "list-joined-together" }

Works the same way using variables:

ansible -m debug -a msg="{{ '-'.join((var1, var2, var3)) }}" localhost

VBScript: Using WScript.Shell to Execute a Command Line Program That Accesses Active Directory

When you run WScript.Shell it runs under the local system account, this account has full rights on the machine, but no rights in Active Directory.

day of the week to day number (Monday = 1, Tuesday = 2)

$tm = localtime($timestamp, TRUE);
$dow = $tm['tm_wday'];

Where $dow is the day of (the) week. Be aware of the herectic approach of localtime, though (pun): Sunday is not the last day of the week, but the first (0).

The type 'string' must be a non-nullable type in order to use it as parameter T in the generic type or method 'System.Nullable<T>'

System.String (with capital S) is already nullable, you do not need to declare it as such.

(string? myStr) is wrong.

How do I convert number to string and pass it as argument to Execute Process Task?

Expression: "Total Count: " + (DT_WSTR, 5)@[User::Cnt]

Store multiple values in single key in json

  "number" : ["1","2","3"],
  "alphabet" : ["a", "b", "c"]

Drawable-hdpi, Drawable-mdpi, Drawable-ldpi Android

I got one good solution. Here I have attached it as the image below. So try it. It may be helpful to you...!

Enter image description here

How to get an object's methods?

the best way is:

let methods = Object.getOwnPropertyNames(yourobject);

use 'let' only in es6, use 'var' instead

How to access parameters in a RESTful POST method

Your @POST method should be accepting a JSON object instead of a string. Jersey uses JAXB to support marshaling and unmarshaling JSON objects (see the jersey docs for details). Create a class like:

public class MyJaxBean {
    @XmlElement public String param1;
    @XmlElement public String param2;

Then your @POST method would look like the following:

@POST @Consumes("application/json")
public void create(final MyJaxBean input) {
    System.out.println("param1 = " + input.param1);
    System.out.println("param2 = " + input.param2);

This method expects to receive JSON object as the body of the HTTP POST. JAX-RS passes the content body of the HTTP message as an unannotated parameter -- input in this case. The actual message would look something like:

POST /create HTTP/1.1
Content-Type: application/json
Content-Length: 35


Using JSON in this way is quite common for obvious reasons. However, if you are generating or consuming it in something other than JavaScript, then you do have to be careful to properly escape the data. In JAX-RS, you would use a MessageBodyReader and MessageBodyWriter to implement this. I believe that Jersey already has implementations for the required types (e.g., Java primitives and JAXB wrapped classes) as well as for JSON. JAX-RS supports a number of other methods for passing data. These don't require the creation of a new class since the data is passed using simple argument passing.


The parameters would be annotated using @FormParam:

public void create(@FormParam("param1") String param1,
                   @FormParam("param2") String param2) {

The browser will encode the form using "application/x-www-form-urlencoded". The JAX-RS runtime will take care of decoding the body and passing it to the method. Here's what you should see on the wire:

POST /create HTTP/1.1
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 25


The content is URL encoded in this case.

If you do not know the names of the FormParam's you can do the following:

@POST @Consumes("application/x-www-form-urlencoded")
public void create(final MultivaluedMap<String, String> formParams) {

HTTP Headers

You can using the @HeaderParam annotation if you want to pass parameters via HTTP headers:

public void create(@HeaderParam("param1") String param1,
                   @HeaderParam("param2") String param2) {

Here's what the HTTP message would look like. Note that this POST does not have a body.

POST /create HTTP/1.1
Content-Length: 0
param1: hello
param2: world

I wouldn't use this method for generalized parameter passing. It is really handy if you need to access the value of a particular HTTP header though.

HTTP Query Parameters

This method is primarily used with HTTP GETs but it is equally applicable to POSTs. It uses the @QueryParam annotation.

public void create(@QueryParam("param1") String param1,
                   @QueryParam("param2") String param2) {

Like the previous technique, passing parameters via the query string does not require a message body. Here's the HTTP message:

POST /create?param1=hello&param2=world HTTP/1.1
Content-Length: 0

You do have to be particularly careful to properly encode query parameters on the client side. Using query parameters can be problematic due to URL length restrictions enforced by some proxies as well as problems associated with encoding them.

HTTP Path Parameters

Path parameters are similar to query parameters except that they are embedded in the HTTP resource path. This method seems to be in favor today. There are impacts with respect to HTTP caching since the path is what really defines the HTTP resource. The code looks a little different than the others since the @Path annotation is modified and it uses @PathParam:

public void create(@PathParam("param1") String param1,
                   @PathParam("param2") String param2) {

The message is similar to the query parameter version except that the names of the parameters are not included anywhere in the message.

POST /create/hello/world HTTP/1.1
Content-Length: 0

This method shares the same encoding woes that the query parameter version. Path segments are encoded differently so you do have to be careful there as well.

As you can see, there are pros and cons to each method. The choice is usually decided by your clients. If you are serving FORM-based HTML pages, then use @FormParam. If your clients are JavaScript+HTML5-based, then you will probably want to use JAXB-based serialization and JSON objects. The MessageBodyReader/Writer implementations should take care of the necessary escaping for you so that is one fewer thing that can go wrong. If your client is Java based but does not have a good XML processor (e.g., Android), then I would probably use FORM encoding since a content body is easier to generate and encode properly than URLs are. Hopefully this mini-wiki entry sheds some light on the various methods that JAX-RS supports.

Note: in the interest of full disclosure, I haven't actually used this feature of Jersey yet. We were tinkering with it since we have a number of JAXB+JAX-RS applications deployed and are moving into the mobile client space. JSON is a much better fit that XML on HTML5 or jQuery-based solutions.

Bootstrap 4, how to make a col have a height of 100%?

Use bootstrap class vh-100 for exp:

<div class="vh-100">

Fixed footer in Bootstrap

You can do this by wrapping the page contents in a div with the following id styling applied:

#wrap {
   min-height: 100%;
   height: auto !important;
   height: 100%;
   margin: 0 auto -60px;

<div id="wrap">
    <!-- Your page content here... -->

Worked for me.

Remove all special characters with RegExp

The first solution does not work for any UTF-8 alphabet. (It will cut text such as ????). I have managed to create a function which does not use RegExp and use good UTF-8 support in the JavaScript engine. The idea is simple if a symbol is equal in uppercase and lowercase it is a special character. The only exception is made for whitespace.

function removeSpecials(str) {
    var lower = str.toLowerCase();
    var upper = str.toUpperCase();

    var res = "";
    for(var i=0; i<lower.length; ++i) {
        if(lower[i] != upper[i] || lower[i].trim() === '')
            res += str[i];
    return res;

Update: Please note, that this solution works only for languages where there are small and capital letters. In languages like Chinese, this won't work.

Update 2: I came to the original solution when I was working on a fuzzy search. If you also trying to remove special characters to implement search functionality, there is a better approach. Use any transliteration library which will produce you string only from Latin characters and then the simple Regexp will do all magic of removing special characters. (This will work for Chinese also and you also will receive side benefits by making Tromsø == Tromso).

Detecting when the 'back' button is pressed on a navbar

Those who claim that this doesn't work are mistaken:

override func viewWillDisappear(_ animated: Bool) {
    if self.isMovingFromParent {
        print("we are being popped")

That works fine. So what is causing the widespread myth that it doesn’t?

The problem seems to be due to an incorrect implementation of a different method, namely that the implementation of willMove(toParent:) forgot to call super.

If you implement willMove(toParent:) without calling super, then self.isMovingFromParent will be false and the use of viewWillDisappear will appear to fail. It didn't fail; you broke it.

NOTE: The real problem is usually the second view controller detecting that the first view controller was popped. Please see also the more general discussion here: Unified UIViewController "became frontmost" detection?

EDIT A comment suggests that this should be viewDidDisappear rather than viewWillDisappear.

Tensorflow image reading & display

You can use tf.keras API.

import tensorflow as tf
import numpy as np
from tensorflow.keras.preprocessing.image import load_img, array_to_img


img = load_img("example.png")
img = tf.convert_to_tensor(np.asarray(img))
image = tf.image.resize_images(img, (800, 800))
to_img = array_to_img(image)

Get current value selected in dropdown using jQuery

To get the value of a drop-down (select) element, just use val().

$('._someDropDown').live('change', function(e) {

If you want to the text of the selected option, using this:

$('._someDropDown').live('change', function(e) {
  alert($('[value=' + $(this).val() + ']', this).text());

Function to calculate R2 (R-squared) in R

You can also use the summary for linear models:

summary(lm(obs ~ mod, data=df))$r.squared 

What is the PostgreSQL equivalent for ISNULL()


SELECT COALESCE(NULLIF(field, ''), another_field) FROM table_name

how to overcome ERROR 1045 (28000): Access denied for user 'ODBC'@'localhost' (using password: NO) permanently

Why you can't just use mysqlsh?

PS C:\Users\artur\Desktop> mysqlsh --user root
MySQL Shell 8.0.17

Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its affiliates.
Other names may be trademarks of their respective owners.

Type '\help' or '\?' for help; '\quit' to exit.
Creating a session to 'root@localhost'
Fetching schema names for autocompletion... Press ^C to stop.
Your MySQL connection id is 13 (X protocol)
Server version: 8.0.17 MySQL Community Server - GPL
No default schema selected; type \use <schema> to set one.
 MySQL  localhost:33060+ ssl  JS >

mysqlsh on windows terminal (pic)

Firebase cloud messaging notification not received by device

When you copying your device token, it might copying the space, double check you have copied the correct token

Where does one get the "sys/socket.h" header/source file?

Since you've labeled the question C++, you might be interested in using boost::asio, ACE, or some other cross-platform socket library for C++ or for C. Some other cross-platform libraries may be found in the answers to C++ sockets library for cross-platform and Cross platform Networking API.

Assuming that using a third party cross-platform sockets library is not an option for you...

The header <sys/socket.h> is defined in IEEE Std. 1003.1 (POSIX), but sadly Windows is non-compliant with the POSIX standard. The MinGW compiler is a port of GCC for compiling Windows applications, and therefore does not include these POSIX system headers. If you install GCC using Cygwin, then it will include these system headers to emulate a POSIX environment on Windows. Be aware, however, that if you use Cygwin for sockets that a.) you will need to put the cygwin DLL in a place where your application can read it and b.) Cygwin headers and Windows headers don't interact very well (so if you plan on including windows.h, then you probably don't want to be including sys/socket.h).

My personal recommendation would be to download a copy of VirtualBox, download a copy of Ubuntu, install Ubuntu into VirtualBox, and then do your coding and testing on Ubuntu. Alternatively, I am told that Microsoft sells a "UNIX subsystem" and that it is pre-installed on certain higher-end editions of Windows, although I have no idea how compliant this system is (and, if it is compliant, with which edition of the UNIX standard it is compliant). Winsockets are also an option, although they can behave in subtly different ways than their POSIX counterparts, even though the signatures may be similar.

How to pattern match using regular expression in Scala?

As delnan pointed out, the match keyword in Scala has nothing to do with regexes. To find out whether a string matches a regex, you can use the String.matches method. To find out whether a string starts with an a, b or c in lower or upper case, the regex would look like this:


You can read this regex as "one of the characters a, b, c, A, B or C followed by anything" (. means "any character" and * means "zero or more times", so ".*" is any string).

Oracle "(+)" Operator

In practice, the + symbol is placed directly in the conditional statement and on the side of the optional table (the one which is allowed to contain empty or null values within the conditional).

C# Parsing JSON array of objects

Use newtonsoft like so:

using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.Linq;

class Program
    static void Main()
        string json = "{'results':[{'SwiftCode':'','City':'','BankName':'Deutsche    Bank','Bankkey':'10020030','Bankcountry':'DE'},{'SwiftCode':'','City':'10891    Berlin','BankName':'Commerzbank Berlin (West)','Bankkey':'10040000','Bankcountry':'DE'}]}";

        var resultObjects = AllChildren(JObject.Parse(json))
            .First(c => c.Type == JTokenType.Array && c.Path.Contains("results"))

        foreach (JObject result in resultObjects) {
            foreach (JProperty property in result.Properties()) {
                // do something with the property belonging to result

    // recursively yield all children of json
    private static IEnumerable<JToken> AllChildren(JToken json)
        foreach (var c in json.Children()) {
            yield return c;
            foreach (var cc in AllChildren(c)) {
                yield return cc;

Use a LIKE statement on SQL Server XML Datatype

Yet another option is to cast the XML as nvarchar, and then search for the given string as if the XML vas a nvarchar field.

FROM Table
WHERE CAST(Column as nvarchar(max)) LIKE '%TEST%'

I love this solution as it is clean, easy to remember, hard to mess up, and can be used as a part of a where clause.

EDIT: As Cliff mentions it, you could use:

...nvarchar if there's characters that don't convert to varchar

How to update and delete a cookie?

update would just be resetting it using createCookie

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 *1000));
        var expires = "; expires=" + date.toGMTString();
    } else {
        var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') {
            c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) {
            return c.substring(nameEQ.length,c.length);
    return null;

function eraseCookie(name) {

How to check if a column exists in a SQL Server table?

Execute the below query to check if the column exists in the given table:

PRINT 'Column Exists in the given table';

How do I find out if a column exists in a VB.Net DataRow

Another way to find out if a column exists is to check for Nothing the value returned from the Columns collection indexer when passing the column name to it:

If dataRow.Table.Columns("ColumnName") IsNot Nothing Then
End If

This approach might be preferred over the one that uses the Contains("ColumnName") method when the following code will subsequently need to get that DataColumn for further usage. For example, you may want to know which type has a value stored in the column:

Dim column = DataRow.Table.Columns("ColumnName")
If column IsNot Nothing Then
    Dim type = column.DataType
End If

In this case this approach saves you a call to the Contains("ColumnName") at the same time making your code a bit cleaner.

AndroidStudio: Failed to sync Install build tools


Error:failed to find Build Tools revision 23.0.0 rc2


File > Project Structure > click on Modules > Properties
Change Build Tool Version to 23.0.1

its work for me

PyTorch: How to get the shape of a Tensor as a list of int

For PyTorch v1.0 and possibly above:

>>> import torch
>>> var = torch.tensor([[1,0], [0,1]])

# Using .size function, returns a torch.Size object.
>>> var.size()
torch.Size([2, 2])
>>> type(var.size())
<class 'torch.Size'>

# Similarly, using .shape
>>> var.shape
torch.Size([2, 2])
>>> type(var.shape)
<class 'torch.Size'>

You can cast any torch.Size object to a native Python list:

>>> list(var.size())
[2, 2]
>>> type(list(var.size()))
<class 'list'>

In PyTorch v0.3 and 0.4:

Simply list(var.size()), e.g.:

>>> import torch
>>> from torch.autograd import Variable
>>> from torch import IntTensor
>>> var = Variable(IntTensor([[1,0],[0,1]]))

>>> var
Variable containing:
 1  0
 0  1
[torch.IntTensor of size 2x2]

>>> var.size()
torch.Size([2, 2])

>>> list(var.size())
[2, 2]

How to get docker-compose to always re-create containers from fresh images?

By current official documentation there is a short cut that stops and removes containers, networks, volumes, and images created by up, if they are already stopped or partially removed and so on, then it will do the trick too:

docker-compose down

Then if you have new changes on your images or Dockerfiles use:

docker-compose build --no-cache

Finally:docker-compose up

In one command: docker-compose down && docker-compose build --no-cache && docker-compose up

SQL Server: Cannot insert an explicit value into a timestamp column

create table demo ( id int, ts timestamp )

insert into demo(id,ts) values (1, DEFAULT)

calling another method from the main method in java

Check out for the static before the main method, this declares the method as a class method, which means it needs no instance to be called. So as you are going to call a non static method, Java complains because you are trying to call a so called "instance method", which, of course needs an instance first ;)

If you want a better understanding about classes and instances, create a new class with instance and class methods, create a object in your main loop and call the methods!

 class Foo{

    public static void main(String[] args){
       Bar myInstance = new Bar();; // works!; // doesn't work!

       Bar.doSomethingStatic(); // works!

class Bar{

   public do() {
   // do something

   public static doSomethingStatic(){

Also remember, classes in Java should start with an uppercase letter.

Flutter: Run method on Widget build complete

You could use

which executes a function only one time after the layout is completed. Or just look at its implementation and add it to your code :-)

Which is basically

  void initState() {
        .addPostFrameCallback((_) => yourFunction(context));

Store boolean value in SQLite

Further to ericwa's answer. CHECK constraints can enable a pseudo boolean column by enforcing a TEXT datatype and only allowing TRUE or FALSE case specific values e.g.

,   "boolean" TEXT NOT NULL 
        CHECK( typeof("boolean") = "text" AND
               "boolean" IN ("TRUE","FALSE")

INSERT INTO "boolean_test" ("boolean") VALUES ("TRUE");
INSERT INTO "boolean_test" ("boolean") VALUES ("FALSE");
INSERT INTO "boolean_test" ("boolean") VALUES ("TEST");

Error: CHECK constraint failed: boolean_test

INSERT INTO "boolean_test" ("boolean") VALUES ("true");

Error: CHECK constraint failed: boolean_test

INSERT INTO "boolean_test" ("boolean") VALUES ("false");

Error: CHECK constraint failed: boolean_test

INSERT INTO "boolean_test" ("boolean") VALUES (1);

Error: CHECK constraint failed: boolean_test

select * from boolean_test;

id  boolean
1   TRUE

PHP unable to load php_curl.dll extension

Insert to file httpd.conf

LoadFile "D:/DevKit/PHP7.1/libeay32.dll"
LoadFile "D:/DevKit/PHP7.1/libssh2.dll"
LoadFile "D:/DevKit/PHP7.1/ssleay32.dll"

Escaping ampersand character in SQL string

Escape is set to \ by default, so you don't need to set it; but if you do, don't wrap it in quotes.

Ampersand is the SQL*Plus substitution variable marker; but you can change it, or more usefully in your case turn it off completely, with:

set define off

Then you don't need to bother escaping the value at all.

Twitter Bootstrap modal on mobile devices

you can add this property globally in javascript:

if( navigator.userAgent.match(/iPhone|iPad|iPod/i) ) {
    var styleEl = document.createElement('style'), styleSheet;
    styleSheet = styleEl.sheet;
    styleSheet.insertRule(".modal { position:absolute; bottom:auto; }", 0);

How do I create a self-signed certificate for code signing on Windows?

As of PowerShell 4.0 (Windows 8.1/Server 2012 R2) it is possible to make a certificate in Windows without makecert.exe.

The commands you need are New-SelfSignedCertificate and Export-PfxCertificate.

Instructions are in Creating Self Signed Certificates with PowerShell.

How can I serve static html from spring boot?

You can quickly serve static content in JAVA Spring-boot App via thymeleaf (ref: source)

I assume you have already added Spring Boot plugin apply plugin: 'org.springframework.boot' and the necessary buildscript

Then go ahead and ADD thymeleaf to your build.gradle ==>

dependencies {

Lets assume you have added home.html at src/main/resources To serve this file, you will need to create a controller.


  import org.springframework.stereotype.Controller;
  import org.springframework.web.bind.annotation.RequestMapping;

  public class HomePageController {

      public String homePage() {
        return "home";


Thats it ! Now restart your gradle server. ./gradlew bootRun

Are there any standard exit status codes in Linux?

Part 1: Advanced Bash Scripting Guide

As always, the Advanced Bash Scripting Guide has great information: (This was linked in another answer, but to a non-canonical URL.)

1: Catchall for general errors
2: Misuse of shell builtins (according to Bash documentation)
126: Command invoked cannot execute
127: "command not found"
128: Invalid argument to exit
128+n: Fatal error signal "n"
255: Exit status out of range (exit takes only integer args in the range 0 - 255)

Part 2: sysexits.h

The ABSG references sysexits.h.

On Linux:

$ find /usr -name sysexits.h
$ cat /usr/include/sysexits.h

 * Copyright (c) 1987, 1993
 *  The Regents of the University of California.  All rights reserved.

 (A whole bunch of text left out.)

#define EX_OK           0       /* successful termination */
#define EX__BASE        64      /* base value for error messages */
#define EX_USAGE        64      /* command line usage error */
#define EX_DATAERR      65      /* data format error */
#define EX_NOINPUT      66      /* cannot open input */    
#define EX_NOUSER       67      /* addressee unknown */    
#define EX_NOHOST       68      /* host name unknown */
#define EX_UNAVAILABLE  69      /* service unavailable */
#define EX_SOFTWARE     70      /* internal software error */
#define EX_OSERR        71      /* system error (e.g., can't fork) */
#define EX_OSFILE       72      /* critical OS file missing */
#define EX_CANTCREAT    73      /* can't create (user) output file */
#define EX_IOERR        74      /* input/output error */
#define EX_TEMPFAIL     75      /* temp failure; user is invited to retry */
#define EX_PROTOCOL     76      /* remote error in protocol */
#define EX_NOPERM       77      /* permission denied */
#define EX_CONFIG       78      /* configuration error */

#define EX__MAX 78      /* maximum listed value */

C++ delete vector, objects, free memory

Move semantics allows for a straightforward way to release memory, by simply applying the assignment (=) operator from an empty rvalue:

std::vector<uint32_t> vec(100, 0);
std::cout << vec.capacity(); // 100

vec = vector<uint32_t>();    // Same as "vector<uint32_t>().swap(vec)";    
std::cout << vec.capacity(); // 0

It is as much efficient as the "swap()"-based method described in other answers (indeed, both are conceptually doing the same thing). When it comes to readability, however, the assignment version makes a better job at expressing the programmer's intention while being more concise.

Eclipse: Enable autocomplete / content assist

For anyone having this problem with newer versions of Eclipse, head over to Window->Preferences->Java->Editor->Content assist->Advanced and mark Java Proposals and Chain Template Proposals as active.

How to find whether a number belongs to a particular range in Python?

I would use the numpy library, which would allow you to do this for a list of numbers as well:

from numpy import array
a = array([1, 2, 3, 4, 5, 6,])
a[a < 2]

Turn on torch/flash on iPhone

//import fremework in .h file 

#import <AVFoundation/AVFoundation.h>
 AVCaptureSession *torchSession;

@property(nonatomic,retain)AVCaptureSession *torchSession;


//implement in .m file

@synthesize torchSession;

    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if ([device hasTorch] && [device hasFlash])
        if (device.torchMode == AVCaptureTorchModeOff) 
            [button setTitle:@"OFF" forState:UIControlStateNormal];

            AVCaptureDeviceInput *flashInput = [AVCaptureDeviceInput deviceInputWithDevice:device error: nil];

            AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init];
            AVCaptureSession *session = [[AVCaptureSession alloc] init];

            [session beginConfiguration];
            [device lockForConfiguration:nil];
            [device setTorchMode:AVCaptureTorchModeOn];
            [device setFlashMode:AVCaptureFlashModeOn];
            [session addInput:flashInput];
            [session addOutput:output];
            [device unlockForConfiguration];
            [output release];
            [session commitConfiguration];
            [session startRunning];
            [self setTorchSession:session];
            [session release];
            [button setTitle:@"ON" forState:UIControlStateNormal];
            [torchSession stopRunning];

- (void)dealloc
    [torchSession release];
    [super dealloc];

Onclick on bootstrap button

<a class="btn btn-large btn-success" id="fire" href="">Send Email</a>

$('#fire').on('click', function (e) {

     //your awesome code here


querySelector and querySelectorAll vs getElementsByClassName and getElementById in JavaScript

collecting from Mozilla Documentation:

The NodeSelector interface This specification adds two new methods to any objects implementing the Document, DocumentFragment, or Element interfaces:


Returns the first matching Element node within the node's subtree. If no matching node is found, null is returned.


Returns a NodeList containing all matching Element nodes within the node's subtree, or an empty NodeList if no matches are found.


Note: The NodeList returned by querySelectorAll() is not live, which means that changes in the DOM are not reflected in the collection. This is different from other DOM querying methods that return live node lists.

How to create a sticky navigation bar that becomes fixed to the top after scrolling

This worked great for me. Don't forget to put a filler div in there where the navigation bar used to be, or else the content will jump every time it's fixed/unfixed.

function setSkrollr(){
    var objDistance = $navbar.offset().top;
    $(window).scroll(function() {
        var myDistance = $(window).scrollTop();
        if (myDistance > objDistance){
        if (objDistance > myDistance){

Very Simple, Very Smooth, JavaScript Marquee

I made my own version, based in the code presented above by @Tats_innit . The difference is the pause function. Works a little better in that aspect.

(function ($) {
var timeVar, width=0;

$.fn.textWidth = function () {
    var calc = '<span style="display:none">' + $(this).text() + '</span>';
    var width = $('body').find('span:last').width();
    return width;

$.fn.marquee = function (args) {
    var that = $(this);
    if (width == 0) { width = that.width(); };
    var textWidth = that.textWidth(), offset = that.width(), i = 0, stop = textWidth * -1, dfd = $.Deferred(),
        css = {
            'text-indent': that.css('text-indent'),
            'overflow': that.css('overflow'),
            'white-space': that.css('white-space')
        marqueeCss = {
            'text-indent': width,
            'overflow': 'hidden',
            'white-space': 'nowrap'
        args = $.extend(true, { count: -1, speed: 1e1, leftToRight: false, pause: false }, args);

    function go() {
        if (!that.length) return dfd.reject();
        if (width <= stop) {
            if (i <= args.count) {
                return dfd.resolve();
            if (args.leftToRight) {
                width = textWidth * -1;
            } else {
                width = offset;
        that.css('text-indent', width + 'px');
        if (args.leftToRight) {
        } else {
        if (args.pause == false) { timeVar = setTimeout(function () { go() }, args.speed); };
        if (args.pause == true) { clearTimeout(timeVar); };

    if (args.leftToRight) {
        width = textWidth * -1;
        stop = offset;
    } else {

    timeVar = setTimeout(function () { go() }, 100);

    return dfd.promise();


for start: $('#Text1').marquee()

pause: $('#Text1').marquee({ pause: true })

resume: $('#Text1').marquee({ pause: false })

Add unique constraint to combination of two columns

And if you have lot insert queries but not wanna ger a ERROR message everytime , you can do it:

CREATE UNIQUE NONCLUSTERED INDEX SK01 ON dbo.Person(ID,Name,Active,PersonNumber) 

enter image description here

javascript find and remove object in array based on key value

I can grep the array for the id, but how can I delete the entire object where id == 88

Simply filter by the opposite predicate:

var data = $.grep(data, function(e){ 
     return != id; 

How to determine if Javascript array contains an object with an attribute that equals a given value?

Many answers here are good and pretty easy. But if your array of object is having a fixed set of value then you can use below trick:

Map all the name in a object.

vendors = [
      Name: 'Magenic',
      ID: 'ABC'
      Name: 'Microsoft',
      ID: 'DEF'

var dirtyObj = {}
for(var count=0;count<vendors.length;count++){
   dirtyObj[vendors[count].Name] = true //or assign which gives you true.

Now this dirtyObj you can use again and again without any loop.

  console.log("Hey! I am available.");

C#: Waiting for all threads to complete

This may not be an option for you, but if you can use the Parallel Extension for .NET then you could use Tasks instead of raw threads and then use Task.WaitAll() to wait for them to complete.

clearInterval() not working

setInterval returns an ID which you then use to clear the interval.

var intervalId;
on.onclick = function() {
    if (intervalId) {
    intervalId = setInterval(fontChange, 500);

off.onclick = function() {

Java 8 stream's .min() and .max(): why does this compile?

Comparator is a functional interface, and Integer::max complies with that interface (after autoboxing/unboxing is taken into consideration). It takes two int values and returns an int - just as you'd expect a Comparator<Integer> to (again, squinting to ignore the Integer/int difference).

However, I wouldn't expect it to do the right thing, given that Integer.max doesn't comply with the semantics of And indeed it doesn't really work in general. For example, make one small change:

for (int i = 1; i <= 20; i++)

... and now the max value is -20 and the min value is -1.

Instead, both calls should use Integer::compare:


PermissionError: [Errno 13] in python

For me, I was writing to a file that is opened in Excel.

Scale iFrame css width 100% like an image

Big difference between an image and an iframe is the fact that an image keeps its aspect-ratio. You could combine an image and an iframe with will result in a responsive iframe. Hope this answerers your question.

Check this link for example :


<div class="wrapper">
    <div class="h_iframe">
        <!-- a transparent image is preferable -->
        <img class="ratio" src=""/>
        <iframe src="" frameborder="0" allowfullscreen></iframe>
    <p>Please scale the "result" window to notice the effect.</p>


html,body        {height:100%;}
.wrapper         {width:80%;height:100%;margin:0 auto;background:#CCC}
.h_iframe        {position:relative;}
.h_iframe .ratio {display:block;width:100%;height:auto;}
.h_iframe iframe {position:absolute;top:0;left:0;width:100%; height:100%;}

note: This only works with a fixed aspect-ratio.

Angular 2 execute script after template render

I have found that the best place is in NgAfterViewChecked(). I tried to execute code that would scroll to an ng-accordion panel when the page was loaded. I tried putting the code in NgAfterViewInit() but it did not work there (NPE). The problem was that the element had not been rendered yet. There is a problem with putting it in NgAfterViewChecked(). NgAfterViewChecked() is called several times as the page is rendered. Some calls are made before the element is rendered. This means a check for null may be required to guard the code from NPE. I am using Angular 8.

Best practice for storing and protecting private API keys in applications

Keep the secret in firebase database and get from it when app starts , It is far better than calling a web service .

Linq to Entities - SQL "IN" clause

This should suffice your purpose. It compares two collections and checks if one collection has the values matching those in the other collection

fea_Features.Where(s => selectedFeatures.Contains(s.feaId))

fitting data with numpy

Unfortunately, np.polynomial.polynomial.polyfit returns the coefficients in the opposite order of that for np.polyfit and np.polyval (or, as you used np.poly1d). To illustrate:

In [40]: np.polynomial.polynomial.polyfit(x, y, 4)
array([  84.29340848, -100.53595376,   44.83281408,   -8.85931101,

In [41]: np.polyfit(x, y, 4)
array([   0.65459882,   -8.859311  ,   44.83281407, -100.53595375,

In general: np.polynomial.polynomial.polyfit returns coefficients [A, B, C] to A + Bx + Cx^2 + ..., while np.polyfit returns: ... + Ax^2 + Bx + C.

So if you want to use this combination of functions, you must reverse the order of coefficients, as in:

ffit = np.polyval(coefs[::-1], x_new)

However, the documentation states clearly to avoid np.polyfit, np.polyval, and np.poly1d, and instead to use only the new(er) package.

You're safest to use only the polynomial package:

import numpy.polynomial.polynomial as poly

coefs = poly.polyfit(x, y, 4)
ffit = poly.polyval(x_new, coefs)
plt.plot(x_new, ffit)

Or, to create the polynomial function:

ffit = poly.Polynomial(coefs)    # instead of np.poly1d
plt.plot(x_new, ffit(x_new))

fit and data plot

Android fade in and fade out with ImageView

you can do it by two simple point and change in your code

1.In your xml in anim folder of your project, Set the fade in and fade out duration time not equal

2.In you java class before the start of fade out animation, set second imageView visibility Gone then after fade out animation started set second imageView visibility which you want to fade in visible


    android:toAlpha="0.0" />


    android:toAlpha="1.0" />

In you java class

Animation animFadeOut = AnimationUtils.loadAnimation(this, R.anim.fade_out);
    ImageView iv = (ImageView) findViewById(;
    ImageView iv2 = (ImageView) findViewById(;

    Animation animFadeIn = AnimationUtils.loadAnimation(this, R.anim.fade_in);

Qt jpg image display

#include ...

int main(int argc, char *argv[])
    QApplication a(argc, argv);
    QGraphicsScene scene;
    QGraphicsView view(&scene);
    QGraphicsPixmapItem item(QPixmap("c:\\test.png"));
    return a.exec();

This should work. :) List of supported formats can be found here

how to check for datatype in node js- specifically for integer

You can check your numbers by checking their constructor.

var i = "5";

if( i.constructor !== Number )
 console.log('This is not number'));

Subtract days from a DateTime

DateTime dateForButton = DateTime.Now.AddDays(-1);

How to create an instance of System.IO.Stream stream

You have to create an instance of one of the subclasses. Stream is an abstract class that can't be instantiated directly.

There are a bunch of choices if you look at the bottom of the reference here:

Stream Class | Microsoft Developer Network

The most common probably being FileStream or MemoryStream. Basically, you need to decide where you wish the data backing your stream to come from, then create an instance of the appropriate subclass.

How to determine the version of Gradle?

I running the following in my project:

./gradlew --version

Gradle 4.7

Build time:   2018-04-18 09:09:12 UTC
Revision:     b9a962bf70638332300e7f810689cb2febbd4a6c

Groovy:       2.4.12
Ant:          Apache Ant(TM) version 1.9.9 compiled on February 2 2017
JVM:          1.8.0_212 (AdoptOpenJDK 25.212-b03)
OS:           Mac OS X 10.15 x86_64

Javascript call() & apply() vs bind()?

bind: It binds the function with provided value and context but it does not executes the function. To execute function you need to call the function.

call: It executes the function with provided context and parameter.

apply: It executes the function with provided context and parameter as array.

How to load external webpage in WebView

public class WebViewController extends WebViewClient {
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        return true;
webView.setWebViewClient(new WebViewController());

Get an element by index in jQuery

There is another way of getting an element by index in jQuery using CSS :nth-of-type pseudo-class:

    // css selector that describes what you need:
    // ul li:nth-of-type(3)
    var selector = 'ul li:nth-of-type(' + index + ')';

There are other selectors that you may use with jQuery to match any element that you need.

What replaces cellpadding, cellspacing, valign, and align in HTML5 tables?

Alternatively, can use for particular table

 <table style="width:1000px; height:100px;">
        <td align="center" valign="top">Text</td> //Remove it
        <td class="tableFormatter">Text></td>

Add this css in external file


How do I check if a file exists in Java?

I would recommend using isFile() instead of exists(). Most of the time you are looking to check if the path points to a file not only that it exists. Remember that exists() will return true if your path points to a directory.

new File("path/to/file.txt").isFile();

new File("C:/").exists() will return true but will not allow you to open and read from it as a file.

How to match any non white space character except a particular one?

This worked for me using sed [Edit: comment below points out sed doesn't support \s]

[^ ]




# Delete everything except space and 'g'
echo "ghai ghai" | sed "s/[^\sg]//g"

echo "ghai ghai" | sed "s/[^ g]//g"
g g

How to create a scrollable Div Tag Vertically?

Adding overflow:auto before setting overflow-y seems to do the trick in Google Chrome.

    overflow: auto;
    overflow-y: scroll;

Get the time difference between two datetimes

If you want difference of two timestamp into total days,hours and minutes only, not in months and years .

var now  = "01/08/2016 15:00:00";
var then = "04/02/2016 14:20:30";
var diff = moment.duration(moment(then).diff(moment(now)));

diff contains 2 months,23 days,23 hours and 20 minutes. But we need result only in days,hours and minutes so the simple solution is:

var days = parseInt(diff.asDays()); //84

var hours = parseInt(diff.asHours()); //2039 hours, but it gives total hours in given miliseconds which is not expacted.

hours = hours - days*24;  // 23 hours

var minutes = parseInt(diff.asMinutes()); //122360 minutes,but it gives total minutes in given miliseconds which is not expacted.

minutes = minutes - (days*24*60 + hours*60); //20 minutes.

Final result will be : 84 days, 23 hours, 20 minutes.

Android Device not recognized by adb

  1. Download and install Moborobo software on your computer.
  2. Connect your device with USB debugging through USB cable.
  3. Now open moborobo and it will connect to your android.
  4. Stay connected, now your device should recognize as adb devices and get listed.

Rename multiple columns by names

You can use a named vector.

With base R (maybe somewhat clunky):

x = data.frame(q = 1, w = 2, e = 3) 

rename_vec <- c(q = "A", e = "B")

names(x) <- ifelse([names(x)]), names(x), rename_vec[names(x)])

#>   A w B
#> 1 1 2 3

Or a dplyr option with !!!:


rename_vec <- c(A = "q", B = "e") # the names are just the other way round than in the base R way!

x %>% rename(!!!rename_vec)
#>   A w B
#> 1 1 2 3

The latter works because the 'big-bang' operator !!! is forcing evaluation of a list or a vector.


!!! forces-splice a list of objects. The elements of the list are spliced in place, meaning that they each become one single argument.

How to find Max Date in List<Object>?

Just use Kotlin!

val list = listOf(user1, user2, user3)
val maxDate = list.maxBy { }?.date

How to plot two histograms together in R?

Here is an even simpler solution using base graphics and alpha-blending (which does not work on all graphics devices):

p1 <- hist(rnorm(500,4))                     # centered at 4
p2 <- hist(rnorm(500,6))                     # centered at 6
plot( p1, col=rgb(0,0,1,1/4), xlim=c(0,10))  # first histogram
plot( p2, col=rgb(1,0,0,1/4), xlim=c(0,10), add=T)  # second

The key is that the colours are semi-transparent.

Edit, more than two years later: As this just got an upvote, I figure I may as well add a visual of what the code produces as alpha-blending is so darn useful:

enter image description here

How to Deep clone in javascript

var newDate = new Date(this.oldDate); I was passing oldDate to function and generating newDate from this.oldDate, but it was changing this.oldDate also.So i used that solution and it worked.

angularjs to output plain text instead of html

Use ng-bind-html this is only proper and simplest way

How can I align YouTube embedded video in the center in bootstrap

make iframe with align="middle" and put it in paragraph with style="text-aling:center":

<p style="text-align:center;">
<iframe width="420" height="315" align="middle" src="">

How to list records with date from the last 10 days?

I would check datatypes.

current_date has "date" datatype, 10 is a number, and - you need to look at your table.

While loop in batch

It was very useful for me i have used in the following way to add user in active directory:

:: This file is used to automatically add list of user to activedirectory
:: First ask for username,pwd,dc details and run in loop
:: dsadd user cn=jai,cn=users,dc=mandrac,dc=com -pwd `1q`1q`1q`1q

@echo off
setlocal enableextensions enabledelayedexpansion
set /a "x = 1"
set /p lent="Enter how many Users you want to create : "
set /p Uname="Enter the user name which will be rotated with number ex:ram then ram1 ..etc : "
set /p DcName="Enter the DC name ex:mandrac : "
set /p Paswd="Enter the password you want to give to all the users : "



if %x% leq %lent% (

    dsadd user cn=%Uname%%x%,cn=users,dc=%DcName%,dc=com -pwd %Paswd%
    echo User %Uname%%x% with DC %DcName% is created
    set /a "x = x + 1"
    goto :while1


How different is Scrum practice from Agile Practice?

Agile is a platform and scrum is a methodology to follow. Scrum recommends certain practices to be followed. Some of the basic scrum practices are following.

  • Fixed length Scrum/Releases.
  • Suggested meeting Structures (Release planning meeting, Sprint planning meeting, Sprint Review and Sprint Retrospective meetings)
  • Scrum also recommends roles. Following are the roles recommended by Scrum.

     - Scrum Master
     - Developer Team
     - Product Owner

The Scrum, just like other Agile methodologies follow iterative approach.

Following are some other Agile methodologies.

  • Extreme Programming.
  • Agile unified process
  • Dynamic System Development Method (DSDM)
  • Feature Driven Development (FDD)
  • Lean Software Development
  • Kanban
  • Scrum-ban

There are many scrum tool in the market. Yodiz is one of them that we use.

Why do I need to explicitly push a new branch?

The actual reason is that, in a new repo (git init), there is no branch (no master, no branch at all, zero branches)

So when you are pushing for the first time to an empty upstream repo (generally a bare one), that upstream repo has no branch of the same name.


In both cases, since the upstream empty repo has no branch:

  • there is no matching named branch yet
  • there is no upstream branch at all (with or without the same name! Tracking or not)

That means your local first push has no idea:

  • where to push
  • what to push (since it cannot find any upstream branch being either recorded as a remote tracking branch, and/or having the same name)

So you need at least to do a:

git push origin master

But if you do only that, you:

  • will create an upstream master branch on the upstream (now non-empty repo): good.
  • won't record that the local branch 'master' needs to be pushed to upstream (origin) 'master' (upstream branch): bad.

That is why it is recommended, for the first push, to do a:

git push -u origin master

That will record origin/master as a remote tracking branch, and will enable the next push to automatically push master to origin/master.

git checkout master
git push

And that will work too with push policies 'current' or 'upstream'.
In each case, after the initial git push -u origin master, a simple git push will be enough to continue pushing master to the right upstream branch.

SelectedValue vs SelectedItem.Value of DropDownList

SelectedValue returns the same value as SelectedItem.Value.

SelectedItem.Value and SelectedItem.Text might have different values and the performance is not a factor here, only the meanings of these properties matters.

<asp:DropDownList runat="server" ID="ddlUserTypes">
    <asp:ListItem Text="Admins" Value="1" Selected="true" />
    <asp:ListItem Text="Users" Value="2"/>

Here, ddlUserTypes.SelectedItem.Value == ddlUserTypes.SelectedValue and both would return the value "1".

ddlUserTypes.SelectedItem.Text would return "Admins", which is different from ddlUserTypes.SelectedValue


under the hood, SelectedValue looks like this

public virtual string SelectedValue
        int selectedIndex = this.SelectedIndex;
        if (selectedIndex >= 0)
            return this.Items[selectedIndex].Value;
        return string.Empty;

and SelectedItem looks like this:

public virtual ListItem SelectedItem
        int selectedIndex = this.SelectedIndex;
        if (selectedIndex >= 0)
            return this.Items[selectedIndex];
        return null;

One major difference between these two properties is that the SelectedValue has a setter also, since SelectedItem doesn't. The getter of SelectedValue is faster when writing code, and the problem of execution performance has no real reason to be discussed. Also a big advantage of SelectedValue is when using Binding expressions.

edit data binding scenario (you can't use SelectedItem.Value)

<asp:Repeater runat="server">
     <asp:DropDownList ID="ddlCategories" runat="server" 
                       SelectedValue='<%# Eval("CategoryId")%>'>

Read from file in eclipse

Did you try refreshing (right click -> refresh) the project folder after copying the file in there? That will SYNC your file system with Eclipse's internal file system.

When you run Eclipse projects, the CWD (current working directory) is project's root directory. Not bin's directory. Not src's directory, but the root dir.

Also, if you're in Linux, remember that its file systems are usually case sensitive.

How to make the background image to fit into the whole page without repeating using plain css?

background:url(bgimage.jpg) no-repeat; background-size: cover;

This did the trick

Why does "return list.sort()" return None, not the list?

Python habitually returns None from functions and methods that mutate the data, such as list.sort, list.append, and random.shuffle, with the idea being that it hints to the fact that it was mutating.

If you want to take an iterable and return a new, sorted list of its items, use the sorted builtin function.

Executing Javascript from Python

One more solution as PyV8 seems to be unmaintained and dependent on the old version of libv8.

PyMiniRacer It's a wrapper around the v8 engine and it works with the new version and is actively maintained.

pip install py-mini-racer

from py_mini_racer import py_mini_racer
ctx = py_mini_racer.MiniRacer()
function escramble_758(){
    var a,b,c
    a='+1 '
    return a+c+b;

And yes, you have to replace document.write with return as others suggested

get jquery `$(this)` id

Do you mean that for a select element with an id of "next" you need to perform some specific script?

    //enter code here

Text was truncated or one or more characters had no match in the target code page including the primary key in an unpivot

None of the above worked for me. I SOLVED my problem by saving my source data (save as) Excel file as a single xls Worksheet Excel 5.0/95 and imported without column headings. Also, I created the table in advance and mapped manually instead of letting SQL create the table.

Get the current fragment object

This will give you the current fragment class name -->

String fr_name = getSupportFragmentManager().findFragmentById(;

Purpose of "%matplotlib inline"

It just means that any graph which we are creating as a part of our code will appear in the same notebook and not in separate window which would happen if we have not used this magic statement.

gradlew command not found?

Gradle wrapper needs to be built. Try running gradle wrapper --gradle-version 2.13 Remember to change 2.13 to your gradle version number. After running this command, you should see new scripts added to your project folder. You should be able to run the wrapper with ./gradlew build to build your code. Please refer to this guid for more information

Is visible in Python 3? has been renamed to g.__next__(). The reason for this is consistency: special methods like __init__() and __del__() all have double underscores (or "dunder" in the current vernacular), and .next() was one of the few exceptions to that rule. This was fixed in Python 3.0. [*]

But instead of calling g.__next__(), use next(g).

[*] There are other special attributes that have gotten this fix; func_name, is now __name__, etc.

iPhone Safari Web App opens links in new window

I found JavaScript solution in iWebKit framework:

var a=document.getElementsByTagName("a");
for(var i=0;i<a.length;i++)
        return false

What is the difference between "long", "long long", "long int", and "long long int" in C++?

Historically, in early C times, when processors had 8 or 16 bit wordlength,intwas identical to todays short(16 bit). In a certain sense, int is a more abstract data type thanchar,short,longorlong long, as you cannot be sure about the bitwidth.

When definingint n;you could translate this with "give me the best compromise of bitwidth and speed on this machine for n". Maybe in the future you should expect compilers to translateintto be 64 bit. So when you want your variable to have 32 bits and not more, better use an explicitlongas data type.

[Edit: #include <stdint.h> seems to be the proper way to ensure bitwidths using the int##_t types, though it's not yet part of the standard.]

How to save all files from source code of a web site?

In Chrome, go to options (Customize and Control, the 3 dots/bars at top right) ---> More Tools ---> save page as

save page as  
filename     : any_name.html 
save as type : webpage complete.

Then you will get any_name.html and any_name folder.

C# Base64 String to JPEG Image

Front :

  <Image Name="camImage"/>


 public async void Base64ToImage(string base64String)
            // read stream
            var bytes = Convert.FromBase64String(base64String);
            var image = bytes.AsBuffer().AsStream().AsRandomAccessStream();

            // decode image
            var decoder = await BitmapDecoder.CreateAsync(image);

            // create bitmap
            var output = new WriteableBitmap((int)decoder.PixelHeight, (int)decoder.PixelWidth);
            await output.SetSourceAsync(image);

            camImage.Source = output;

Importing project into Netbeans

Follow these steps:

  1. Open Netbeans
  2. Click File > New Project > JavaFX > JavaFX with existing sources
  3. Click Next
  4. Name the project
  5. Click Next
  6. Under Source Package Folders click Add Folder
  7. Select the nbproject folder under the zip file you wish to upload (Note: you need to unzip the folder)
  8. Click Next
  9. All the files will be included but you can exclude some if you wish
  10. Click Finish and the project should be there

If you don't have the source folder added do the following

  1. Under your projects directory tree right click on Source Packages
  2. Click New
  3. Click Java Package and name it with the name of the package the source files have
  4. Go to the directory location (i.e., using Windows Explorer not Netbeans) of those source files, highlight them all, then drag and drop them under that Java Package you just created
  5. Click Run
  6. Click Clean and Build Project

Now you can have fun and run the application.

How do I connect to a SQL Server 2008 database using JDBC?

You can use this :

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class ConnectMSSQLServer
   public void dbConnect(String db_connect_string,
            String db_userid,
            String db_password)
      try {
         Connection conn = DriverManager.getConnection(db_connect_string,
                  db_userid, db_password);
         Statement statement = conn.createStatement();
         String queryString = "select * from sysobjects where type='u'";
         ResultSet rs = statement.executeQuery(queryString);
         while ( {
      } catch (Exception e) {

   public static void main(String[] args)
      ConnectMSSQLServer connServer = new ConnectMSSQLServer();
      connServer.dbConnect("jdbc:sqlserver://<hostname>", "<user>",

Sequence contains no matching element

Maybe using Where() before First() can help you, as my problem has been solved in this case.

var documentRow = _dsACL.Documents.Where(o => o.ID == id).FirstOrDefault();

What's the function like sum() but for multiplication? product()?

There's a prod() in numpy that does what you're asking for.

Weblogic Transaction Timeout : how to set in admin console in WebLogic AS 8.1

The link above is rather outdated. For WebLogic 12c you may define the transaction timout in a transaction-descriptor for each EJB in the WebLogic deployment descriptor weblogic-ejb-jar.xml, see weblogic-ejb-jar.xml Deployment Descriptor Reference.

For a message driven been it looks like this:


How do I use Apache tomcat 7 built in Host Manager gui?

Host Manager is a web application inside of Tomcat that creates/removes Virtual Hosts within Tomcat.

A Virtual Host allows you to define multiple hostnames on a single server, so you can use the same server to handles requests to, for example, and

Unfortunately documentation on the GUI side of the Host Manager doesn't appear to exist, but documentation on configuring the virtual hosts manually in context.xml is here:

The full explanation of the Host parameters you can find here:

Adding a virtual host

Once you have access to the host-manager (see other answers on setting up the permissions, the GUI will let you add a (temporary - see edit at the end of this post) virtual host.

Tomcat Host Manager - Add Virtual Host Panel

At a minimum you need the Name and App Base fields defined. Tomcat will then create the following directories:

  • App Base will be where web applications will be deployed to the virtual host. Can be relative or absolute.
  • Name is usually the fully-qualified domain name (e.g.
  • Alias can be used to extend the Name also where two addresses should resolve to the same host (e.g. Note that this needs to be reflected in DNS records.

The checkboxes are as follows:

  • Auto Deploy: Automatically redeploy applications placed into App Base. Dangerous for Production environments!
  • Deploy On Startup: Automatically boot up applications under App Base when Tomcat starts
  • Deploy XML: Determines whether to parse the application's /META-INF/context.xml
  • Unpack WARs: Unpack WAR files placed or uploaded to the App Base, as opposed to running them directly from the WAR.
  • Tomcat 8 Copy XML: Copy an application's META-INF/context.xml to the App Base/XML Base on deployment, and use that exclusively, regardless of whether the application is updated. Irrelevant if Deploy XML is false.
  • Manager App: Add the manager application to the Virtual Host (Useful for controlling the applications you might have underneath

Update: After playing around with this same process on Tomcat8, the behaviour I'm seeing is that adding a virtual host via the GUI isn't persistent - it doesn't get written to server.xml, even on shutdown. Therefore (unless I'm doing something terribly wrong), you can create it in the GUI, but you'll need to edit server.xml anyway, as per the first link above, to make it stick.

Getting an object array from an Angular service

Take a look at your code :

 getUsers(): Observable<User[]> {
        return Observable.create(observer => {
            this.http.get('').map(response => response.json();

and code from (BTW. really good tutorial, you should check it out)

 getHeroes(): Promise<Hero[]> {
    return this.http.get(this.heroesUrl)
               .then(response => response.json().data as Hero[])

The HttpService inside Angular2 already returns an observable, sou don't need to wrap another Observable around like you did here:

   return Observable.create(observer => {
        this.http.get('').map(response => response.json()

Try to follow the guide in link that I provided. You should be just fine when you study it carefully.


First of all WHERE you log the this.users variable? JavaScript isn't working that way. Your variable is undefined and it's fine, becuase of the code execution order!

Try to do it like this:

  getUsers(): void {
            .then(users => {
               this.users = users
               console.log('this.users=' + this.users);


See where the console.log(...) is!

Try to resign from toPromise() it's seems to be just for ppl with no RxJs background.

Catch another link: Build your service once again with RxJs observables.

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException Error

NullPointerExceptions are among the easier exceptions to diagnose, frequently. Whenever you get an exception in Java and you see the stack trace ( that's what your second quote-block is called, by the way ), you read from top to bottom. Often, you will see exceptions that start in Java library code or in native implementations methods, for diagnosis you can just skip past those until you see a code file that you wrote.

Then you like at the line indicated and look at each of the objects ( instantiated classes ) on that line -- one of them was not created and you tried to use it. You can start by looking up in your code to see if you called the constructor on that object. If you didn't, then that's your problem, you need to instantiate that object by calling new Classname( arguments ). Another frequent cause of NullPointerExceptions is accidentally declaring an object with local scope when there is an instance variable with the same name.

In your case, the exception occurred in your constructor for Workshop on line 75. <init> means the constructor for a class. If you look on that line in your code, you'll see the line


There are fairly clearly two objects on this line: denimjeansButton and this. this is synonymous with the class instance you are currently in and you're in the constructor, so it can't be this. denimjeansButton is your culprit. You never instantiated that object. Either remove the reference to the instance variable denimjeansButton or instantiate it.

Convert a String to a byte array and then back to the original String

import; import;

public class FileHashStream { // write a new method that will provide a new Byte array, and where this generally reads from an input stream

public static byte[] read(InputStream is) throws Exception
    String path = /* type in the absolute path for the '' */;

    // must need a Byte buffer

    byte[] buf = new byte[1024 * 16]

    // we will use 16 kilobytes

    int len = 0;

    // we need a new input stream

    FileInputStream is = new FileInputStream(path);

    // use the buffer to update our "MessageDigest" instance

        len =;
        if(len < 0) break;
        md.update(buf, 0, len);

    // close the input stream


    // call the "digest" method for obtaining the final hash-result

    byte[] ret = md.digest();

    System.out.println("Length of Hash: " + ret.length);

    for(byte b : ret)
        System.out.println(b + ", ");

    String compare = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d";

    String verification = Hex.encodeHexString(ret);




    System.out.println("Equals? " + verification.equals(compare));



How to install "ifconfig" command in my ubuntu docker image?

I came here because I was trying to use ifconfig on the container to find its IPAaddress and there was no ifconfig. If you really need ifconfig on the container go with @vishnu-narayanan answer above, however you may be able to get the information you need by using docker inspect on the host:

docker inspect <containerid>

There is lots of good stuff in the output including IPAddress of container:

"Networks": {
    "bridge": {
        "IPAMConfig": null,
        "Links": null,
        "Aliases": null,
        "NetworkID": "12345FAKEID",
        "EndpointID": "12345FAKEENDPOINTID",
        "Gateway": "",
        "IPAddress": "",
        "IPPrefixLen": 16,
        "IPv6Gateway": "",
        "GlobalIPv6Address": "",
        "GlobalIPv6PrefixLen": 0,
        "MacAddress": "01:02:03:04:05:06",
        "DriverOpts": null

Problem in running .net framework 4.0 website on iis 7.0

If you are running Delphi, or other native compiled CGI, this solution will work:

  1. As other pointed, go to IIS manager and click on the server name. Then click on the "ISAPI and CGI Restrictions" icon under the IIS header.

  2. If you have everything allowed, it will still not work. You need to click on "Edit Feature Settings" in Actions (on the right side), and check "Allow unspecified CGI modules", or "Allow unspecified ISAPI modules" respectively.

  3. Click OK

PHP Pass by reference in foreach

This question has a lot of explanations provided, but no clear examples of how to solve the problem that this behavior causes. In most cases, you'll probably want the following code in your pass by reference foreach.

foreach ($array as &$row) {
    // Do stuff
// Unset to remove the reference

Git diff --name-only and copy that list

# Target directory

for i in $(git diff --name-only)
        # First create the target directory, if it doesn't exist.
        mkdir -p "$TARGET/$(dirname $i)"
        # Then copy over the file.
        cp -rf "$i" "$TARGET/$i"

How do you convert CString and std::string std::wstring to each other?

It is more effecient to convert CString to std::string using the conversion where the length is specified.

CString someStr("Hello how are you");
std::string std(somStr, someStr.GetLength());

In tight loop this makes a significant performance improvement.

Pandas conditional creation of a series/dataframe column

Here's yet another way to skin this cat, using a dictionary to map new values onto the keys in the list:

def map_values(row, values_dict):
    return values_dict[row]

values_dict = {'A': 1, 'B': 2, 'C': 3, 'D': 4}

df = pd.DataFrame({'INDICATOR': ['A', 'B', 'C', 'D'], 'VALUE': [10, 9, 8, 7]})

df['NEW_VALUE'] = df['INDICATOR'].apply(map_values, args = (values_dict,))

What's it look like:

0         A     10          1
1         B      9          2
2         C      8          3
3         D      7          4

This approach can be very powerful when you have many ifelse-type statements to make (i.e. many unique values to replace).

And of course you could always do this:

df['NEW_VALUE'] = df['INDICATOR'].map(values_dict)

But that approach is more than three times as slow as the apply approach from above, on my machine.

And you could also do this, using dict.get:

df['NEW_VALUE'] = [values_dict.get(v, None) for v in df['INDICATOR']]

how to set default method argument values?

You can accomplish this via method overloading.

public int doSomething(int arg1, int arg2)
        return 0;

public int doSomething()
        return doSomething(defaultValue0, defaultValue1);

By creating this parameterless method you are allowing the user to call the parameterfull method with the default arguments you supply within the implementation of the parameterless method. This is known as overloading the method.

Installing PG gem on OS X - failure to build native extension

i got same problem and i solved

gem update --system 3.0.6

What is the iPad user agent?

Mine says:

Mozilla/5.0 (iPad; U; CPU OS 4_3 like Mac OS X; da-dk) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8F190 Safari/6533.18.5

How to change default JRE for all Eclipse workspaces?

when you select run configuration, there is a JRE tap up next the main tap, select "Workspace default JRE(JDK1.7)".

Be sure to use the jdk in Prefs->Java->Installed JREs ->Execution Environment

Difference between "or" and || in Ruby?

Both or and || evaluate to true if either operand is true. They evaluate their second operand only if the first is false.

As with and, the only difference between or and || is their precedence.

Just to make life interesting, and and or have the same precedence, while && has a higher precedence than ||.

Maven plugins can not be found in IntelliJ

For me the Plugins were related to a Profile. I have to enable the relevant profile via Maven (right sidebar menu), Profiles and let the dependencies download.

How can I get a uitableViewCell by indexPath?

[(UITableViewCell *)[(UITableView *)self cellForRowAtIndexPath:nowIndex]

will give you uitableviewcell. But I am not sure what exactly you are asking for! Because you have this code and still you asking how to get uitableviewcell. Some more information will help to answer you :)

ADD: Here is an alternate syntax that achieves the same thing without the cast.

UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:nowIndex];

How to avoid Python/Pandas creating an index in a saved csv?

If you want no index, read file using:

import pandas as pd
df = pd.read_csv('file.csv', index_col=0)

save it using

df.to_csv('file.csv', index=False)

How to loop and render elements in React-native?

If u want a direct/ quick away, without assing to variables:

{, key) => {
     return <Picker.Item label={emp.Name} value={} />;

A non-blocking read on a subprocess.PIPE in Python

EDIT: This implementation still blocks. Use J.F.Sebastian's answer instead.

I tried the top answer, but the additional risk and maintenance of thread code was worrisome.

Looking through the io module (and being limited to 2.6), I found BufferedReader. This is my threadless, non-blocking solution.

import io
from subprocess import PIPE, Popen

p = Popen(['myprogram.exe'], stdout=PIPE)


# Create an io.BufferedReader on the file descriptor for stdout
with, 'rb', closefd=False) as buffer:
  while p.poll() == None:
      while '\n' in bufferedStdout.peek(bufferedStdout.buffer_size):
          line = buffer.readline()
          # do stuff with the line

  # Handle any remaining output after the process has ended
  while buffer.peek():
    line = buffer.readline()
    # do stuff with the line

Difference of keywords 'typename' and 'class' in templates?

While there is no technical difference, I have seen the two used to denote slightly different things.

For a template that should accept any type as T, including built-ins (such as an array )

template<typename T>
class Foo { ... }

For a template that will only work where T is a real class.

template<class T>
class Foo { ... }

But keep in mind that this is purely a style thing some people use. Not mandated by the standard or enforced by compilers

Automating running command on Linux from Windows using PuTTY

Putty usually comes with the "plink" utility.
This is essentially the "ssh" command line command implemented as a windows .exe.
It pretty well documented in the putty manual under "Using the command line tool plink".

You just need to wrap a command like:

plink root@myserver /etc/backups/

in a .bat script.

You can also use common shell constructs, like semicolons to execute multiple commands. e.g:

plink read@myhost ls -lrt /home/read/files;/etc/backups/

Use of PUT vs PATCH methods in REST API real life scenarios

TLDR - Dumbed Down Version

PUT => Set all new attributes for an existing resource.

PATCH => Partially update an existing resource (not all attributes required).

How do I set the request timeout for one controller action in an mvc application

<location path="ControllerName/ActionName">
        <httpRuntime executionTimeout="1000"/>

Probably it is better to set such values in web.config instead of controller. Hardcoding of configurable options is considered harmful.

how to get right offset of an element? - jQuery

There's a native DOM API that achieves this out of the box — getBoundingClientRect:


Virtualbox "port forward" from Guest to Host

That's not possible. localhost always defaults to the loopback device on the local operating system.
As your virtual machine runs its own operating system it has its own loopback device which you cannot access from the outside.

If you want to access it e.g. in a browser, connect to it using the local IP instead:

This is just an example of course, you can find out the actual IP by issuing an ifconfig command on a shell in the guest operating system.

Flutter: Setting the height of the AppBar

Use toolbarHeight:

enter image description here

There's no longer a need to use PreferredSize. Use toolbarHeight with flexibleSpace.

  toolbarHeight: 120, // Set this height
  flexibleSpace: Container(
    child: Column(
      children: [

How to print / echo environment variables?

This works too, with the semi-colon.

NAME=sam; echo $NAME

Which ChromeDriver version is compatible with which Chrome Browser version?

This is a helpful website listing the mapping for the latest releases of Chrome -

TypeError: a bytes-like object is required, not 'str'

This code is probably good for Python 2. But in Python 3, this will cause an issue, something related to bit encoding. I was trying to make a simple TCP server and encountered the same problem. Encoding worked for me. Try this with sendto command.

clientSocket.sendto(message.encode(),(serverName, serverPort))

Similarly you would use .decode() to receive the data on the UDP server side, if you want to print it exactly as it was sent.

Using DISTINCT inner join in SQL

I did a test on MS SQL 2005 using the following tables: A 400K rows, B 26K rows and C 450 rows.

The estimated query plan indicated that the basic inner join would be 3 times slower than the nested sub-queries, however when actually running the query, the basic inner join was twice as fast as the nested queries, The basic inner join took 297ms on very minimal server hardware.

What database are you using, and what times are you seeing? I'm thinking if you are seeing poor performance then it is probably an index problem.

Tomcat: java.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names must be tokens

I was getting the same exception, whenever a page was getting loaded,

NFO: Error parsing HTTP request header
 Note: further occurrences of HTTP header parsing errors will be logged at DEBUG level.
java.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names must be tokens
    at org.apache.coyote.http11.InternalInputBuffer.parseRequestLine(
    at org.apache.coyote.http11.AbstractHttp11Processor.process(
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(
    at java.util.concurrent.ThreadPoolExecutor.runWorker(
    at java.util.concurrent.ThreadPoolExecutor$
    at org.apache.tomcat.util.threads.TaskThread$

I found that one of my page URL was https instead of http, when I changed the same, error was gone.

(Deep) copying an array using jQuery

If you want to use pure JavaScript then try this:

 var arr=["apple","ball","cat","dog"];
 var narr=[];

 for(var i=0;i<arr.length;i++){
 alert(narr); //output: apple,ball,vat,dog
 alert(arr); // output: apple,ball,vat,dog
 alert(narr); // apple,ball,vat,dog,elephant

Countdown timer using Moment js

In the last statement you are converting the duration to time which also considers the timezone. I assume that your timezone is +530, so 5 hours and 30 minutes gets added to 30 minutes. You can do as given below.

var eventTime= 1366549200; // Timestamp - Sun, 21 Apr 2013 13:00:00 GMT
var currentTime = 1366547400; // Timestamp - Sun, 21 Apr 2013 12:30:00 GMT
var diffTime = eventTime - currentTime;
var duration = moment.duration(diffTime*1000, 'milliseconds');
var interval = 1000;

  duration = moment.duration(duration - interval, 'milliseconds');
    $('.countdown').text(duration.hours() + ":" + duration.minutes() + ":" + duration.seconds())
}, interval);

SSH Key - Still asking for password and passphrase

If you used for your GIT the password authentication before, but now are using SSH authentication, you need to switch remote URLs from HTTPS to SSH:

git remote set-url origin [email protected]:USERNAME/REPOSITORY.git

Parser Error Message: Could not load type 'TestMvcApplication.MvcApplication'

I solved my problem by renaming lots of things. If your problem is cause by creating a new project from copying an existing project like me, you may try these steps.

  1. rename solution - in solution explorer
  2. rename project - in solution explorer
  3. rename namespace - in code
  4. rename assembly name and default namespace - in project>property>application
  5. rename AssemblyTitle and update GUID - in project>property>application>aseembly information
  6. rebuild and run

some of these steps may be worthless, but following them all should solve your problem.

Set background color of WPF Textbox in C# code

textBox1.Background = Brushes.Blue;
textBox1.Foreground = Brushes.Yellow;

WPF Foreground and Background is of type System.Windows.Media.Brush. You can set another color like this:

using System.Windows.Media;

textBox1.Background = Brushes.White;
textBox1.Background = new SolidColorBrush(Colors.White);
textBox1.Background = new SolidColorBrush(Color.FromArgb(0xFF, 0xFF, 0, 0));
textBox1.Background = System.Windows.SystemColors.MenuHighlightBrush;

'module' object has no attribute 'DataFrame'

For me he problem was that my script was called in the folder pandas which obviously messed up my imports.

How do I merge a git tag onto a branch

Remember before you merge you need to update the tag, it's quite different from branches (git pull origin tag_name won't update your local tags). Thus, you need the following command:

git fetch --tags origin

Then you can perform git merge tag_name to merge the tag onto a branch.

javac option to compile all java files under a given directory recursively

I'm just using make with a simple makefile that looks like this:

JAVAC = javac -Xlint:unchecked
sources = $(shell find . -type f -name '*.java')
classes = $(

all : $(classes)

clean :
        rm -f $(classes)

%.class :
        $(JAVAC) $<

It compiles the sources one at a time and only recompiles if necessary.

What file uses .md extension and how should I edit them?

The easiest thing to do, if you do not have a reader, is to open the MD file with a text editor and then write the MD file out as an HTML file and then double click to view it with browser.

Get folder name of the file in Python

You are looking to use dirname. If you only want that one directory, you can use os.path.basename,

When put all together it looks like this:


That should get you "other_sub_dir"

The following is not the ideal approach, but I originally proposed,using os.path.split, and simply get the last item. which would look like this:


Invalid URI: The format of the URI could not be determined

Sounds like it might be a realative uri. I ran into this problem when doing cross-browser Silverlight; on my blog I mentioned a workaround: pass a "context" uri as the first parameter.

If the uri is realtive, the context uri is used to create a full uri. If the uri is absolute, then the context uri is ignored.

EDIT: You need a "scheme" in the uri, e.g., "ftp://" or "http://"

What is the significance of 1/1/1753 in SQL Server?

Incidentally, Windows no longer knows how to correctly convert UTC to U.S. local time for certain dates in March/April or October/November of past years. UTC-based timestamps from those dates are now somewhat nonsensical. It would be very icky for the OS to simply refuse to handle any timestamps prior to the U.S. government's latest set of DST rules, so it simply handles some of them wrong. SQL Server refuses to process dates before 1753 because lots of extra special logic would be required to handle them correctly and it doesn't want to handle them wrong.

plotting different colors in matplotlib

@tcaswell already answered, but I was in the middle of typing my answer up, so I'll go ahead and post it...

There are a number of different ways you could do this. To begin with, matplotlib will automatically cycle through colors. By default, it cycles through blue, green, red, cyan, magenta, yellow, black:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 10)
for i in range(1, 6):
    plt.plot(x, i * x + i, label='$y = {i}x + {i}$'.format(i=i))

enter image description here

If you want to control which colors matplotlib cycles through, use ax.set_color_cycle:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 10)
fig, ax = plt.subplots()
ax.set_color_cycle(['red', 'black', 'yellow'])
for i in range(1, 6):
    plt.plot(x, i * x + i, label='$y = {i}x + {i}$'.format(i=i))

enter image description here

If you'd like to explicitly specify the colors that will be used, just pass it to the color kwarg (html colors names are accepted, as are rgb tuples and hex strings):

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 10)
for i, color in enumerate(['red', 'black', 'blue', 'brown', 'green'], start=1):
    plt.plot(x, i * x + i, color=color, label='$y = {i}x + {i}$'.format(i=i))

enter image description here

Finally, if you'd like to automatically select a specified number of colors from an existing colormap:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 10)
number = 5
cmap = plt.get_cmap('gnuplot')
colors = [cmap(i) for i in np.linspace(0, 1, number)]

for i, color in enumerate(colors, start=1):
    plt.plot(x, i * x + i, color=color, label='$y = {i}x + {i}$'.format(i=i))

enter image description here

Setting focus on an HTML input box on page load

This line:

<input type="password" name="PasswordInput"/>

should have an id attribute, like so:

<input type="password" name="PasswordInput" id="PasswordInput"/>

PHP error: Notice: Undefined index:

I did define all the variables that was the first thing I checked. I know it's not required in PHP, but old habits die hard. Then I sanatized the info like this:

  if (empty($_POST["name1"])) {
    $name1Err = " First Name is a required field.";
  } else {
      $name1 = test_input($_POST["name1"]);
    // check if name only contains letters and whitespace
      if (!preg_match("/^[a-zA-Z ]*$/",$name1)) {
      $name1Err = "Only letters and white space allowed";

of course test_input is another function that does a trim, strilashes, and htmlspecialchars. I think the input is pretty well sanitized. Not trying to be rude just showing what I did. When it came to the email I also checked to see if it was the proper format. I think the real answer is in the fact that some variables are local and some are global. I have got it working without errors for now so, while I'm extremely busy right now I'll accept shutting off errors as my answer. Don't worry I'll figure it out it's just not vitally important right now!

Conditional WHERE clause in SQL Server

Try this

    (ActQty-LtrPrinted) AS L,
    (ActQty-QtyInserted) AS M,
    ((ActQty-LtrPrinted)-(ActQty-QtyInserted)) AS N
    DateDropped = 0
    AND (
    (ISNULL(@JobsOnHold, 0) = 1 AND DateAppr >= 0) 
    (ISNULL(@JobsOnHold, 0) != 1 AND DateAppr != 0)

You can read more about conditional WHERE here.

C++: variable 'std::ifstream ifs' has initializer but incomplete type

This seems to be answered - #include <fstream>.

The message means :-

incomplete type - the class has not been defined with a full class. The compiler has seen statements such as class ifstream; which allow it to understand that a class exists, but does not know how much memory the class takes up.

The forward declaration allows the compiler to make more sense of :-

void BindInput( ifstream & inputChannel ); 

It understands the class exists, and can send pointers and references through code without being able to create the class, see any data within the class, or call any methods of the class.

The has initializer seems a bit extraneous, but is saying that the incomplete object is being created.

CardView Corner Radius

You can use this drawable xml and set as background to cardview :

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="">
    <solid android:color="#ffffffff"/>

    <stroke android:width="1dp"

    <padding android:left="1dp"


Passing references to pointers in C++

&s produces temporary pointer to string and you can't make reference to temporary object.

Match exact string

Use the start and end delimiters: ^abc$

Parameter binding on left joins with array in Laravel Query Builder

You don't have to bind parameters if you use query builder or eloquent ORM. However, if you use DB::raw(), ensure that you binding the parameters.

Try the following:

$array = array(1,2,3);       $query = DB::table('offers');             $query->select('id', 'business_id', 'address_id', 'title', 'details', 'value', 'total_available', 'start_date', 'end_date', 'terms', 'type', 'coupon_code', 'is_barcode_available', 'is_exclusive', 'userinformations_id', 'is_used');             $query->leftJoin('user_offer_collection', function ($join) use ($array)             {                 $join->on('user_offer_collection.offers_id', '=', '')                       ->whereIn('user_offer_collection.user_id', $array);             });       $query->get(); 

how to bind img src in angular 2 in ngFor?

Angular 2.x to 8 Compatible!

You can directly give the source property of the current object in the img src attribute. Please see my code below:

<div *ngFor="let brochure of brochureList">
    <img class="brochure-poster" [src]="brochure.imageUrl" />

NOTE: You can as well use string interpolation but that is not a legit way to do it. Property binding was created for this very purpose hence better use this.


<img class="brochure-poster" src="{{brochure.imageUrl}}"/>

Its because that defeats the purpose of property binding. It is more meaningful to use that for setting the properties. {{}} is a normal string interpolation expression, that does not reveal to anyone reading the code that it makes special meaning. Using [] makes it easily to spot the properties that are set dynamically.

Here is my brochureList contains the following json received from service(you can assign it to any variable):

[ {
            "productName":"Beauty Products",
            "productCode": "XXXXXX",            
            "description":  "Skin Care",           
            "productName":"Samsung Galaxy J5",
            "productCode": "MOB-124",      
            "description":  "8GB, Gold",

CSS border less than 1px

try giving border in % for exapmle 0.1% according to your need.

Laravel where on relationship object

The correct syntax to do this on your relations is:

Event::whereHas('participants', function ($query) {
    return $query->where('IDUser', '=', 1);


How can I set the request header for curl?

Just use the -H parameter several times:

curl -H "Accept-Charset: utf-8" -H "Content-Type: application/x-www-form-urlencoded"

How to split a dataframe string column into two columns?

If you don't want to create a new dataframe, or if your dataframe has more columns than just the ones you want to split, you could:

df["flips"], df["row_name"] = zip(*df["row"].str.split().tolist())
del df["row"]  

Detailed 500 error message, ASP + IIS 7.5

One thing nobody's mentioned is as a very quick and temporary fix, you can view the error on the localhost of that web server.

RGB to hex and hex to RGB

My example =)

color: {_x000D_
            toHex: function(num){_x000D_
                var str = num.toString(16);_x000D_
                return (str.length<6?'#00'+str:'#'+str);_x000D_
            toNum: function(hex){_x000D_
                return parseInt(hex.replace('#',''), 16);_x000D_
            rgbToHex: function(color)_x000D_
                color = color.replace(/\s/g,"");_x000D_
                var aRGB = color.match(/^rgb\((\d{1,3}[%]?),(\d{1,3}[%]?),(\d{1,3}[%]?)\)$/i);_x000D_
                    color = '';_x000D_
                    for (var i=1;  i<=3; i++) color += Math.round((aRGB[i][aRGB[i].length-1]=="%"?2.55:1)*parseInt(aRGB[i])).toString(16).replace(/^(.)$/,'0$1');_x000D_
                else color = color.replace(/^#?([\da-f])([\da-f])([\da-f])$/i, '$1$1$2$2$3$3');_x000D_
                return '#'+color;_x000D_

Redirecting unauthorized controller in ASP.NET MVC

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

public override void OnAuthorization(AuthorizationContext filterContext)

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

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

How remove border around image in css?

Also, in your html, remember to delete all blanks / line feeds / tabs between the closing tag and the opening tag.

<img src='a.png' /> <img src='b.png' /> will always display a space between the images even if the border attribute is set to 0, whereas <img src='a.png' /><img src='b.png' /> will not.

Display a decimal in scientific notation

My decimals are too big for %E so I had to improvize:

def format_decimal(x, prec=2):
    tup = x.as_tuple()
    digits = list(tup.digits[:prec + 1])
    sign = '-' if tup.sign else ''
    dec = ''.join(str(i) for i in digits[1:])
    exp = x.adjusted()
    return '{sign}{int}.{dec}e{exp}'.format(sign=sign, int=digits[0], dec=dec, exp=exp)

Here's an example usage:

>>> n = decimal.Decimal(4.3) ** 12314
>>> print format_decimal(n)
>>> print '%e' % n

How to find the Target *.exe file of *.appref-ms

The app is stored in %LocalAppData% in your %UserProfile%. So the full path could be:


Get the current first responder without using a private API

Peter Steinberger just tweeted about the private notification UIWindowFirstResponderDidChangeNotification, which you can observe if you want to watch the firstResponder change.

What is the id( ) function used for?

I am starting out with python and I use id when I use the interactive shell to see whether my variables are assigned to the same thing or if they just look the same.

Every value is an id, which is a unique number related to where it is stored in the memory of the computer.

Xcode iOS 8 Keyboard types not supported

I have fixed this issue by unchecking 'Connect Hardware Keyboard'. Please refer to the image below to fix this issueenter image description here

Rotate label text in seaborn factorplot

This is still a matplotlib object. Try this:

# <your code here>
locs, labels = plt.xticks()
plt.setp(labels, rotation=45)

Why do I get AttributeError: 'NoneType' object has no attribute 'something'?

When building a estimator (sklearn), if you forget to return self in the fit function, you get the same error.

class ImputeLags(BaseEstimator, TransformerMixin):
    def __init__(self, columns):
        self.columns = columns

    def fit(self, x, y=None):
        """ do something """

    def transfrom(self, x):
        return x

AttributeError: 'NoneType' object has no attribute 'transform'?

Adding return self to the fit function fixes the error.