Programs & Examples On #Testcomplete

TestComplete is a functional automated testing platform developed by SmartBear Software. TestComplete gives testers the ability to create automated tests for Microsoft Windows, Web, Android (operating system), and iOS applications.

How to escape a JSON string to have it in a URL?

Using encodeURIComponent():

var url = 'index.php?data='+encodeURIComponent(JSON.stringify({"json":[{"j":"son"}]})),

The simplest possible JavaScript countdown timer?

I have two demos, one with jQuery and one without. Neither use date functions and are about as simple as it gets.

Demo with vanilla JavaScript

function startTimer(duration, display) {_x000D_
    var timer = duration, minutes, seconds;_x000D_
    setInterval(function () {_x000D_
        minutes = parseInt(timer / 60, 10);_x000D_
        seconds = parseInt(timer % 60, 10);_x000D_
        minutes = minutes < 10 ? "0" + minutes : minutes;_x000D_
        seconds = seconds < 10 ? "0" + seconds : seconds;_x000D_
        display.textContent = minutes + ":" + seconds;_x000D_
        if (--timer < 0) {_x000D_
            timer = duration;_x000D_
    }, 1000);_x000D_
window.onload = function () {_x000D_
    var fiveMinutes = 60 * 5,_x000D_
        display = document.querySelector('#time');_x000D_
    startTimer(fiveMinutes, display);_x000D_
    <div>Registration closes in <span id="time">05:00</span> minutes!</div>_x000D_

Demo with jQuery

function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
        minutes = parseInt(timer / 60, 10);
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.text(minutes + ":" + seconds);

        if (--timer < 0) {
            timer = duration;
    }, 1000);

jQuery(function ($) {
    var fiveMinutes = 60 * 5,
        display = $('#time');
    startTimer(fiveMinutes, display);

However if you want a more accurate timer that is only slightly more complicated:

function startTimer(duration, display) {_x000D_
    var start =,_x000D_
    function timer() {_x000D_
        // get the number of seconds that have elapsed since _x000D_
        // startTimer() was called_x000D_
        diff = duration - ((( - start) / 1000) | 0);_x000D_
        // does the same job as parseInt truncates the float_x000D_
        minutes = (diff / 60) | 0;_x000D_
        seconds = (diff % 60) | 0;_x000D_
        minutes = minutes < 10 ? "0" + minutes : minutes;_x000D_
        seconds = seconds < 10 ? "0" + seconds : seconds;_x000D_
        display.textContent = minutes + ":" + seconds; _x000D_
        if (diff <= 0) {_x000D_
            // add one second so that the count down starts at the full duration_x000D_
            // example 05:00 not 04:59_x000D_
            start = + 1000;_x000D_
    // we don't want to wait a full second before the timer starts_x000D_
    setInterval(timer, 1000);_x000D_
window.onload = function () {_x000D_
    var fiveMinutes = 60 * 5,_x000D_
        display = document.querySelector('#time');_x000D_
    startTimer(fiveMinutes, display);_x000D_
    <div>Registration closes in <span id="time"></span> minutes!</div>_x000D_

Now that we have made a few pretty simple timers we can start to think about re-usability and separating concerns. We can do this by asking "what should a count down timer do?"

  • Should a count down timer count down? Yes
  • Should a count down timer know how to display itself on the DOM? No
  • Should a count down timer know to restart itself when it reaches 0? No
  • Should a count down timer provide a way for a client to access how much time is left? Yes

So with these things in mind lets write a better (but still very simple) CountDownTimer

function CountDownTimer(duration, granularity) {
  this.duration = duration;
  this.granularity = granularity || 1000;
  this.tickFtns = [];
  this.running = false;

CountDownTimer.prototype.start = function() {
  if (this.running) {
  this.running = true;
  var start =,
      that = this,
      diff, obj;

  (function timer() {
    diff = that.duration - ((( - start) / 1000) | 0);

    if (diff > 0) {
      setTimeout(timer, that.granularity);
    } else {
      diff = 0;
      that.running = false;

    obj = CountDownTimer.parse(diff);
    that.tickFtns.forEach(function(ftn) {, obj.minutes, obj.seconds);
    }, that);

CountDownTimer.prototype.onTick = function(ftn) {
  if (typeof ftn === 'function') {
  return this;

CountDownTimer.prototype.expired = function() {
  return !this.running;

CountDownTimer.parse = function(seconds) {
  return {
    'minutes': (seconds / 60) | 0,
    'seconds': (seconds % 60) | 0

So why is this implementation better than the others? Here are some examples of what you can do with it. Note that all but the first example can't be achieved by the startTimer functions.

An example that displays the time in XX:XX format and restarts after reaching 00:00

An example that displays the time in two different formats

An example that has two different timers and only one restarts

An example that starts the count down timer when a button is pressed

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

I've had the same issue. Try to:

Right click on the project and select Clean, then right click on it again and select Rebuild and run the project to see if it worked.

Mock functions in Go

If you change your function definition to use a variable instead:

var get_page = func(url string) string {

You can override it in your tests:

func TestDownloader(t *testing.T) {
    get_page = func(url string) string {
        if url != "expected" {
            t.Fatal("good message")
        return "something"

Careful though, your other tests might fail if they test the functionality of the function you override!

The Go authors use this pattern in the Go standard library to insert test hooks into code to make things easier to test:

How to check if pytorch is using the GPU?

If you are here because your pytorch always gives False for torch.cuda.is_available() that's probably because you installed your pytorch version without GPU support. (Eg: you coded up in laptop then testing on server).

The solution is to uninstall and install pytorch again with the right command from pytorch downloads page. Also refer this pytorch issue.

The controller for path was not found or does not implement IController

If appropriate to your design, you can make sure the access modifier on your controller class is 'public', not something that could limit access like 'internal' or 'private'.

How to build a Debian/Ubuntu package from source?

Here is a tutorial for building a Debian package.

Basically, you need to:

  1. Set up your folder structure
  2. Create a control file
  3. Optionally create postinst or prerm scripts
  4. Run dpkg-deb

I usually do all of this in my Makefile so I can just type make to spit out the binary and package it in one go.

Double % formatting question for printf in Java

%d is for integers use %f instead, it works for both float and double types:

double d = 1.2;
float f = 1.2f;
System.out.printf("%f %f",d,f); // prints 1.200000 1.200000

Reverse Contents in Array

my approach is swapping the first and last element of the array

int i,j;
for ( i = 0,j = size - 1 ; i < j ; i++,j--)
    int temp = A[i];
    A[i] = A[j];
    A[j] = temp; 

how to install apk application from my pc to my mobile android

To install an APK on your mobile, you can either:

  1. Use ADB from the Android SDK, and do the following command: adb install filename.apk. Note, you'll need to enable USB debugging for this to work.
  2. Transfer the file to your device, then open it with a file manager, such as Linda File Manager.

Note, that you'll have to enable installing packages from Unknown Sources in your Applications settings.

As for getting USB to work, I suggest consulting the Android StackExchange for advice.

ASP.NET Core Identity - get current user

If you are using Bearing Token Auth, the above samples do not return an Application User.

Instead, use this:

ClaimsPrincipal currentUser = this.User;
var currentUserName = currentUser.FindFirst(ClaimTypes.NameIdentifier).Value;
ApplicationUser user = await _userManager.FindByNameAsync(currentUserName);

This works in apsnetcore 2.0. Have not tried in earlier versions.

How to add/update an attribute to an HTML element using JavaScript?

Obligatory jQuery solution. Finds and sets the title attribute to foo. Note this selects a single element since I'm doing it by id, but you could easily set the same attribute on a collection by changing the selector.

$('#element').attr( 'title', 'foo' );

In practice, what are the main uses for the new "yield from" syntax in Python 3.3?

Let's get one thing out of the way first. The explanation that yield from g is equivalent to for v in g: yield v does not even begin to do justice to what yield from is all about. Because, let's face it, if all yield from does is expand the for loop, then it does not warrant adding yield from to the language and preclude a whole bunch of new features from being implemented in Python 2.x.

What yield from does is it establishes a transparent bidirectional connection between the caller and the sub-generator:

  • The connection is "transparent" in the sense that it will propagate everything correctly too, not just the elements being generated (e.g. exceptions are propagated).

  • The connection is "bidirectional" in the sense that data can be both sent from and to a generator.

(If we were talking about TCP, yield from g might mean "now temporarily disconnect my client's socket and reconnect it to this other server socket".)

BTW, if you are not sure what sending data to a generator even means, you need to drop everything and read about coroutines first—they're very useful (contrast them with subroutines), but unfortunately lesser-known in Python. Dave Beazley's Curious Course on Coroutines is an excellent start. Read slides 24-33 for a quick primer.

Reading data from a generator using yield from

def reader():
    """A generator that fakes a read from a file, socket, etc."""
    for i in range(4):
        yield '<< %s' % i

def reader_wrapper(g):
    # Manually iterate over data produced by reader
    for v in g:
        yield v

wrap = reader_wrapper(reader())
for i in wrap:

# Result
<< 0
<< 1
<< 2
<< 3

Instead of manually iterating over reader(), we can just yield from it.

def reader_wrapper(g):
    yield from g

That works, and we eliminated one line of code. And probably the intent is a little bit clearer (or not). But nothing life changing.

Sending data to a generator (coroutine) using yield from - Part 1

Now let's do something more interesting. Let's create a coroutine called writer that accepts data sent to it and writes to a socket, fd, etc.

def writer():
    """A coroutine that writes data *sent* to it to fd, socket, etc."""
    while True:
        w = (yield)
        print('>> ', w)

Now the question is, how should the wrapper function handle sending data to the writer, so that any data that is sent to the wrapper is transparently sent to the writer()?

def writer_wrapper(coro):
    # TBD

w = writer()
wrap = writer_wrapper(w)
wrap.send(None)  # "prime" the coroutine
for i in range(4):

# Expected result
>>  0
>>  1
>>  2
>>  3

The wrapper needs to accept the data that is sent to it (obviously) and should also handle the StopIteration when the for loop is exhausted. Evidently just doing for x in coro: yield x won't do. Here is a version that works.

def writer_wrapper(coro):
    coro.send(None)  # prime the coro
    while True:
            x = (yield)  # Capture the value that's sent
            coro.send(x)  # and pass it to the writer
        except StopIteration:

Or, we could do this.

def writer_wrapper(coro):
    yield from coro

That saves 6 lines of code, make it much much more readable and it just works. Magic!

Sending data to a generator yield from - Part 2 - Exception handling

Let's make it more complicated. What if our writer needs to handle exceptions? Let's say the writer handles a SpamException and it prints *** if it encounters one.

class SpamException(Exception):

def writer():
    while True:
            w = (yield)
        except SpamException:
            print('>> ', w)

What if we don't change writer_wrapper? Does it work? Let's try

# writer_wrapper same as above

w = writer()
wrap = writer_wrapper(w)
wrap.send(None)  # "prime" the coroutine
for i in [0, 1, 2, 'spam', 4]:
    if i == 'spam':

# Expected Result
>>  0
>>  1
>>  2
>>  4

# Actual Result
>>  0
>>  1
>>  2
Traceback (most recent call last):
  ... redacted ...
  File ... in writer_wrapper
    x = (yield)

Um, it's not working because x = (yield) just raises the exception and everything comes to a crashing halt. Let's make it work, but manually handling exceptions and sending them or throwing them into the sub-generator (writer)

def writer_wrapper(coro):
    """Works. Manually catches exceptions and throws them"""
    coro.send(None)  # prime the coro
    while True:
                x = (yield)
            except Exception as e:   # This catches the SpamException
        except StopIteration:

This works.

# Result
>>  0
>>  1
>>  2
>>  4

But so does this!

def writer_wrapper(coro):
    yield from coro

The yield from transparently handles sending the values or throwing values into the sub-generator.

This still does not cover all the corner cases though. What happens if the outer generator is closed? What about the case when the sub-generator returns a value (yes, in Python 3.3+, generators can return values), how should the return value be propagated? That yield from transparently handles all the corner cases is really impressive. yield from just magically works and handles all those cases.

I personally feel yield from is a poor keyword choice because it does not make the two-way nature apparent. There were other keywords proposed (like delegate but were rejected because adding a new keyword to the language is much more difficult than combining existing ones.

In summary, it's best to think of yield from as a transparent two way channel between the caller and the sub-generator.


  1. PEP 380 - Syntax for delegating to a sub-generator (Ewing) [v3.3, 2009-02-13]
  2. PEP 342 - Coroutines via Enhanced Generators (GvR, Eby) [v2.5, 2005-05-10]

Execution sequence of Group By, Having and Where clause in SQL Server?

in order:

FROM & JOINs determine & filter rows
WHERE more filters on the rows
GROUP BY combines those rows into groups
HAVING filters groups
ORDER BY arranges the remaining rows/groups
LIMIT filters on the remaining rows/groups

Dependency Injection vs Factory Pattern

I know this question is old but i would like to add my five cents,

I think that dependency injection (DI) is in many ways like a configurable Factory Pattern (FP), and in that sense anything that you could do with DI you will be able to do it with such factory.

Actually, if you use spring for example, you have the option of autowiring resources (DI) or doing something like this:

MyBean mb = ctx.getBean("myBean");

And then use that 'mb' instance to do anything. Isn't that a call to a factory that will return you an instance??

The only real difference I notice between most of the FP examples is that you can configure what "myBean" is in an xml or in another class, and a framework will work as the factory, but other than that is the same thing, and you can have a certainly have a Factory that reads a config file or gets the implementation as it needs.

And if you ask me for my opinion (And I know you didn't), I believe that DI does the same thing but just adds more complexity to the development, why?

well, for one thing, for you to know what is the implementation being used for any bean you autowire with DI, you have to go to the configuration itself.

but... what about that promise that you will not have to know the implementation of the object you are using? pfft! seriously? when you use an approach like this... aren't you the same that writes the implementation?? and even if you don't, arent you almost all the time looking at how the implementation does what it is supposed to do??

and for one last thing, it doesn't matter how much a DI framework promises you that you will build things decoupled from it, with no dependencies to their classes, if you are using a framework you build everything aroud it, if you have to change the approach or the framework it will not be an easy task... EVER!... but, since you buil everything around that particular framework instead of worrying of whats the best solution for your business, then you will face a biiig problen when doing that.

In fact, the only real business application for a FP or DI approach that I can see is if you need to change the implementations being used at runtime, but at least the frameworks I know do not allow you to do that, you have to leave everything perfect in the configuration at development time an if you need that use another approach.

So, if I have a class that performs differently in two scopes in the same application (lets say, two companies of a holding) I have to configure the framework to create two different beans, and adapt my code to use each. Isn't that the same as if I would just write something like this:

MyBean mb = MyBeanForEntreprise1(); //In the classes of the first enterprise
MyBean mb = MyBeanForEntreprise2(); //In the classes of the second enterprise

the same as this:

@Autowired MyBean mbForEnterprise1; //In the classes of the first enterprise
@Autowired MyBean mbForEnterprise2; //In the classes of the second enterprise

And this:

MyBean mb = (MyBean)MyFactory.get("myBeanForEntreprise1"); //In the classes of the first enterprise
MyBean mb = (MyBean)MyFactory.get("myBeanForEntreprise2"); //In the classes of the second enterprise

In any case you will have to change something in your application, whether classes or configuration files, but you will have to do it an redeploy it.

Wouldn't it be nice to do just something like this:

MyBean mb = (MyBean)MyFactory.get("mb"); 

And that way, you set the code of the factory to get the right implementation at runtime depending on the logged user enterprise?? Now THAT would be helpful. You could just add a new jar with the new classes and set the rules maybe even also at runtime (or add a new config file if you leave this option open), no changes to existing classes. This would be a Dynamic factory!

wouldn't that be more helpful than having to write two configurations for each enterprise, and maybe even having two different applications for each??

You can tell me, I don't need to do the switch at runtime ever, so I configure the app, and if I inherit the class or use another implementation I just change the config and redeploy. Ok, that can also be done with a factory. And be honest, how many times do you do this? maybe only when you have an app that's going to be used somewhere else in your company, and you are going to pass the code to another team, and they will do things like this. But hey, that can also be done with the factory, and would be even better with a dynamic factory!!

Anyway, the comment section if open for you to kill me.

Read properties file outside JAR file

I have an example of doing both by classpath or from external config with

package org.mmartin.app1;

import java.util.Properties;

import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.LogManager;

public class App1 {
    private static Logger logger=null; 
    private static final String LOG_PROPERTIES_FILE = "config/";
    private static final String  CONFIG_PROPERTIES_FILE = "config/";

    private Properties properties= new Properties();

    public App1() {
        System.out.println("--Logger intialized with classpath properties file--");
        System.out.println("--Logger intialized with external file--");

    public void readProperties()  {
        InputStream input = null;
        try {
            input = new FileInputStream(CONFIG_PROPERTIES_FILE);
        } catch (IOException e) {
            logger.error("Unable to read the file.",e);

    public void printProperties() {;

    public void testLogging() {
        logger.debug("This is a debug message");"This is an info message");
        logger.warn("This is a warn message");
        logger.error("This is an error message");
        logger.fatal("This is a fatal message");"Logger's name: "+logger.getName());

    private void intializeLogger1() {
        logger = LogManager.getLogger(App1.class);
    private void intializeLogger2() {
        LoggerContext context = (org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false);
        File file = new File(LOG_PROPERTIES_FILE);
        // this will force a reconfiguration
        logger = context.getLogger(App1.class.getName());

    public static void main(String[] args) {
        App1 app1 = new App1();

--Logger intialized with classpath properties file--
[DEBUG] 2018-08-27 10:35:14.510 [main] App1 - This is a debug message
[INFO ] 2018-08-27 10:35:14.513 [main] App1 - This is an info message
[WARN ] 2018-08-27 10:35:14.513 [main] App1 - This is a warn message
[ERROR] 2018-08-27 10:35:14.513 [main] App1 - This is an error message
[FATAL] 2018-08-27 10:35:14.513 [main] App1 - This is a fatal message
[INFO ] 2018-08-27 10:35:14.514 [main] App1 - Logger's name: org.mmartin.app1.App1
--Logger intialized with external file--
[DEBUG] 2018-08-27 10:35:14.524 [main] App1 - This is a debug message
[INFO ] 2018-08-27 10:35:14.525 [main] App1 - This is an info message
[WARN ] 2018-08-27 10:35:14.525 [main] App1 - This is a warn message
[ERROR] 2018-08-27 10:35:14.525 [main] App1 - This is an error message
[FATAL] 2018-08-27 10:35:14.525 [main] App1 - This is a fatal message
[INFO ] 2018-08-27 10:35:14.525 [main] App1 - Logger's name: org.mmartin.app1.App1
-- listing properties --

How to export all collections in MongoDB?

If you want to dump all collections in all databases (which is an expansive interpretation of the original questioner's intent) then use


All the databases and collections will be created in a directory called 'dump' in the 'current' location

Android - Spacing between CheckBox and text

You need to get the size of the image that you are using in order to add your padding to this size. On the Android internals, they get the drawable you specify on src and use its size afterwards. Since it's a private variable and there are no getters you cannot access to it. Also you cannot get the and get the drawable from there.

So you need to create your own styleable (i.e. custom_src) or you can add it directly in your implementation of the RadioButton:

public class CustomRadioButton extends RadioButton {

    private Drawable mButtonDrawable = null;

    public CustomRadioButton(Context context) {
        this(context, null);

    public CustomRadioButton(Context context, AttributeSet attrs) {
        this(context, attrs, 0);

    public CustomRadioButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mButtonDrawable = context.getResources().getDrawable(R.drawable.rbtn_green);

    public int getCompoundPaddingLeft() {
        if (Util.getAPILevel() <= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            if (drawable != null) {
                paddingLeft += drawable.getIntrinsicWidth();
        return paddingLeft;


this statement

DBMS_OUTPUT.PUT_LINE('a.firstName' || 'a.lastName');

means to print the string as it is.. remove the quotes to get the values to be printed.So the correct syntax is

DBMS_OUTPUT.PUT_LINE(a.firstName || a.lastName);

What are the rules for casting pointers in C?

When thinking about pointers, it helps to draw diagrams. A pointer is an arrow that points to an address in memory, with a label indicating the type of the value. The address indicates where to look and the type indicates what to take. Casting the pointer changes the label on the arrow but not where the arrow points.

d in main is a pointer to c which is of type char. A char is one byte of memory, so when d is dereferenced, you get the value in that one byte of memory. In the diagram below, each cell represents one byte.

 |    | c  |    |    |    |    | 
       | char

When you cast d to int*, you're saying that d really points to an int value. On most systems today, an int occupies 4 bytes.

 |    | c  | ?1 | ?2 | ?3 |    | 
       | int

When you dereference (int*)d, you get a value that is determined from these four bytes of memory. The value you get depends on what is in these cells marked ?, and on how an int is represented in memory.

A PC is little-endian, which means that the value of an int is calculated this way (assuming that it spans 4 bytes): * ((int*)d) == c + ?1 * 28 + ?2 * 2¹6 + ?3 * 2²4. So you'll see that while the value is garbage, if you print in in hexadecimal (printf("%x\n", *n)), the last two digits will always be 35 (that's the value of the character '5').

Some other systems are big-endian and arrange the bytes in the other direction: * ((int*)d) == c * 2²4 + ?1 * 2¹6 + ?2 * 28 + ?3. On these systems, you'd find that the value always starts with 35 when printed in hexadecimal. Some systems have a size of int that's different from 4 bytes. A rare few systems arrange int in different ways but you're extremely unlikely to encounter them.

Depending on your compiler and operating system, you may find that the value is different every time you run the program, or that it's always the same but changes when you make even minor tweaks to the source code.

On some systems, an int value must be stored in an address that's a multiple of 4 (or 2, or 8). This is called an alignment requirement. Depending on whether the address of c happens to be properly aligned or not, the program may crash.

In contrast with your program, here's what happens when you have an int value and take a pointer to it.

int x = 42;
int *p = &x;
 |    |         x         |    | 
       | int

The pointer p points to an int value. The label on the arrow correctly describes what's in the memory cell, so there are no surprises when dereferencing it.

What is and how to fix System.TypeInitializationException error?

I have the error of system.typeintialzationException, which is due to when I tried to move the file like:

 File.Move(DestinationFilePath, SourceFilePath)

That error was due to I had swapped the path actually, correct one is:

 File.Move(SourceFilePath, DestinationFilePath)

What is the difference between tinyint, smallint, mediumint, bigint and int in MySQL?

When it gets to real world usage of these datatypes, it is very important that you understand that using certain integer types could just be an overkill or under used. For example, using integer datatype for employeeCount in a table say employee could be an overkill since it supports a range of integer values from ~ negative 2 billion to positive 2 billion or zero to approximately 4 billion (unsigned). So, even if you consider one of the US biggest employer such as Walmart with roughly about 2.2 million employees using an integer datatype for the employeeCount column would be unnecessary. In such a case you use mediumint (that supports from 0 to 16 million (unsigned)) for example. Having said that if your range is expected to be unusually large you might consider bigint which as you can see from Daniel's notes supports a range larger than I care to decipher.

How to respond with HTTP 400 error in a Spring MVC @ResponseBody method returning String?

Not necessarily the most compact way of doing this, but quite clean IMO

if(json == null) {
    throw new BadThingException();

@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public @ResponseBody MyError handleException(BadThingException e) {
    return new MyError("That doesnt work");

Edit you can use @ResponseBody in the exception handler method if using Spring 3.1+, otherwise use a ModelAndView or something.

How do I replace part of a string in PHP?

This is probably what you need:

$text = str_replace(' ', '_', substr($text, 0, 10));

How to extract year and month from date in PostgreSQL without using to_char() function?

You Can use EXTRACT function pgSQL

EX- date = 1981-05-31
it will Give 05

For more details PGSQL Date-Time

awk without printing newline

You can simply use ORS dynamically like this:

awk '{ORS="" ; print($1" "$2" "$3" "$4" "$5" "); ORS="\n"; print($6-=2*$6)}' file_in > file_out

Remove first Item of the array (like popping from stack)

Just use arr.slice(startingIndex, endingIndex).

If you do not specify the endingIndex, it returns all the items starting from the index provided.

In your case arr=arr.slice(1).

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

Use [String.getBytes()][1] to convert to bytes and use [String(byte[] data)][2] constructor to convert back to string.

find all unchecked checkbox in jquery

$("input[type='checkbox']:not(:checked):not('\#chkAll\')").map(function () { 
   var a = ""; 
   if ( != "chkAll") { 
      a = + "|off"; 
   return a; 

This will retrieve all unchecked checkboxes and exclude the "chkAll" checkbox that I use to check|uncheck all checkboxes. Since I want to know what value I'm passing to the database I set these to off, since the checkboxes give me a value of on.

//looking for unchecked checkboxes, but don’t include the checkbox all that checks or unchecks all checkboxes
//.map - Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.

//.get - Retrieve the DOM elements matched by the jQuery object.
//.join - (javascript) joins the elements of an array into a string, and returns the string.The elements will be separated by a specified separator. The default separator is comma (,).

Angular2 disable button

Using ngClass to disabled the button for invalid form is not good practice in Angular2 when its providing inbuilt features to enable and disable the button if form is valid and invalid respectively without doing any extra efforts/logic.

[disabled] will do all thing like if form is valid then it will be enabled and if form is invalid then it will be disabled automatically.

See Example:

<form (ngSubmit)="f.form.valid" #f="ngForm" novalidate>
<input type="text" placeholder="Name" [(ngModel)]="txtName" name="txtname" #textname="ngModel" required>
<input type="button" class="mdl-button" [disabled]="!f.form.valid" (click)="onSave()" name="">

How do implement a breadth first traversal?

For implementing the breadth first search, you should use a queue. You should push the children of a node to the queue (left then right) and then visit the node (print data). Then, yo should remove the node from the queue. You should continue this process till the queue becomes empty. You can see my implementation of the BFS here:

R dplyr: Drop multiple columns

Be careful with the select() function, because it's used both in the dplyr and MASS packages, so if MASS is loaded, select() may not work properly. To find out what packages are loaded, type sessionInfo() and look for it in the "other attached packages:" section. If it is loaded, type detach( "package:MASS", unload = TRUE ), and your select() function should work again.

Google Maps v2 - set both my location and zoom in

You also could set both parameters like,

mMap.moveCamera( CameraUpdateFactory.newLatLngZoom(new LatLng(21.000000, -101.400000) ,4) );

This locates your map on a specific position and zoom. I use this on the setting up my map.

copy db file with adb pull results in 'permission denied' error

The pull command is:

adb pull source dest

When you write:

adb pull /data/data/ /sdcard/test

It means that you'll pull from /data/data/ and you'll copy it to /sdcard/test, but the destination MUST be a local directory. You may write C:\Users\YourName\temp instead.

For example:

adb pull /data/data/ c:\Users\YourName\temp

Python conversion between coordinates

Thinking about it in general, I would strongly consider hiding coordinate system behind well-designed abstraction. Quoting Uncle Bob and his book:

class Point(object)
    def setCartesian(self, x, y)
    def setPolar(self, rho, theta)
    def getX(self)
    def getY(self)
    def getRho(self)
    def setTheta(self)

With interface like that any user of Point class may choose convenient representation, no explicit conversions will be performed. All this ugly sines, cosines etc. will be hidden in one place. Point class. Only place where you should care which representation is used in computer memory.

Is it valid to replace http:// with // in a <script src="http://...">?

It is indeed correct, as other answers have stated. You should note though, that some web crawlers will set off 404s for these by requesting them on your server as if a local URL. (They disregard the double slash and treat it as a single slash).

You may want to set up a rule on your webserver to catch these and redirect them.

For example, with Nginx, you'd add something like:

location ~* /(?<redirect_domain>((([a-z]|[0-9]|\-)+)\.)+([a-z])+)/(?<redirect_path>.*) {
  return 301 $scheme:/$redirect_domain/$redirect_path;

Do note though, that if you use periods in your URIs, you'll need to increase the specificity or it will end up redirecting those pages to nonexistent domains.

Also, this is a rather massive regex to be running for each query -- in my opinion, it's worth punishing non-compliant browsers with 404s over a (slight) performance hit on the majority of compliant browsers.

Plugin org.apache.maven.plugins:maven-compiler-plugin or one of its dependencies could not be resolved

You only need to delete one folder it is throwing error for. Just go to your M2 repo and org/apache/maven/plugins/maven-compiler-plugins and delete the folder 2.3.2

Clear variable in python

I used a few options mentioned above :

del self.left

or setting value to None using

self.left = None

It's important to know the differences and put a few exception handlers in place when you use set the value to None. If you're printing the value of the conditional statements using a template, say,

print("The value of the variable is {}".format(self.left))

you might see the value of the variable printing "The value of the variable is None". Thus, you'd have to put a few exception handlers there :

if self.left:
    #Then only print stuff

The above command will only print values if self.left is not None

React Native fetch() Network Request Failed

React Native Docs gives the answer for this.

Apple has blocked implicit cleartext HTTP resource loading. So we need to add the following our project's Info.plist (or equivalent) file.


React Native Docs -> Integration With Existing Apps -> Test your integration -> Add App Transport Security exception

Server Error in '/' Application. ASP.NET

  • right-click virtual directory (e.g. MyVirtualDirectory)

  • click convert to application.

Image Processing: Algorithm Improvement for 'Coca-Cola Can' Recognition

Looking at shape

Take a gander at the shape of the red portion of the can/bottle. Notice how the can tapers off slightly at the very top whereas the bottle label is straight. You can distinguish between these two by comparing the width of the red portion across the length of it.

Looking at highlights

One way to distinguish between bottles and cans is the material. A bottle is made of plastic whereas a can is made of aluminum metal. In sufficiently well-lit situations, looking at the specularity would be one way of telling a bottle label from a can label.

As far as I can tell, that is how a human would tell the difference between the two types of labels. If the lighting conditions are poor, there is bound to be some uncertainty in distinguishing the two anyways. In that case, you would have to be able to detect the presence of the transparent/translucent bottle itself.

How do I import other TypeScript files?

import {className} from 'filePath';

remember also. The class you are importing , that must be exported in the .ts file.

How to view the committed files you have not pushed yet?

The push command has a -n/--dry-run option which will compute what needs to be pushed but not actually do it. Does that work for you?

angular.service vs angular.factory


1) When you’re using a Factory you create an object, add properties to it, then return that same object. When you pass this factory into your controller, those properties on the object will now be available in that controller through your factory.

app.controller('myFactoryCtrl', function($scope, myFactory){
  $scope.artist = myFactory.getArtist();

app.factory('myFactory', function(){
  var _artist = 'Shakira';
  var service = {};

  service.getArtist = function(){
    return _artist;

  return service;

2) When you’re using Service, Angular instantiates it behind the scenes with the ‘new’ keyword. Because of that, you’ll add properties to ‘this’ and the service will return ‘this’. When you pass the service into your controller, those properties on ‘this’ will now be available on that controller through your service.

app.controller('myServiceCtrl', function($scope, myService){
  $scope.artist = myService.getArtist();

app.service('myService', function(){
  var _artist = 'Nelly';
  this.getArtist = function(){
    return _artist;


1) Factory
Factories are the most popular way to create and configure a service. There’s really not much more than what the TL;DR said. You just create an object, add properties to it, then return that same object. Then when you pass the factory into your controller, those properties on the object will now be available in that controller through your factory. A more extensive example is below.

app.factory('myFactory', function(){
  var service = {};
  return service;

Now whatever properties we attach to ‘service’ will be available to us when we pass ‘myFactory’ into our controller.

Now let’s add some ‘private’ variables to our callback function. These won’t be directly accessible from the controller, but we will eventually set up some getter/setter methods on ‘service’ to be able to alter these ‘private’ variables when needed.

app.factory('myFactory', function($http, $q){
  var service = {};
  var baseUrl = '';
  var _artist = '';
  var _finalUrl = '';

  var makeUrl = function(){
   _artist = _artist.split(' ').join('+');
    _finalUrl = baseUrl + _artist + '&callback=JSON_CALLBACK';
    return _finalUrl

  return service;

Here you’ll notice we’re not attaching those variables/function to ‘service’. We’re simply creating them in order to either use or modify them later.

  • baseUrl is the base URL that the iTunes API requires
  • _artist is the artist we wish to lookup
  • _finalUrl is the final and fully built URL to which we’ll make the call to iTunes makeUrl is a function that will create and return our iTunes friendly URL.

Now that our helper/private variables and function are in place, let’s add some properties to the ‘service’ object. Whatever we put on ‘service’ we’ll be able to directly use in whichever controller we pass ‘myFactory’ into.

We are going to create setArtist and getArtist methods that simply return or set the artist. We are also going to create a method that will call the iTunes API with our created URL. This method is going to return a promise that will fulfill once the data has come back from the iTunes API. If you haven’t had much experience using promises in Angular, I highly recommend doing a deep dive on them.

Below setArtist accepts an artist and allows you to set the artist. getArtist returns the artist callItunes first calls makeUrl() in order to build the URL we’ll use with our $http request. Then it sets up a promise object, makes an $http request with our final url, then because $http returns a promise, we are able to call .success or .error after our request. We then resolve our promise with the iTunes data, or we reject it with a message saying ‘There was an error’.

app.factory('myFactory', function($http, $q){
  var service = {};
  var baseUrl = '';
  var _artist = '';
  var _finalUrl = '';

  var makeUrl = function(){
    _artist = _artist.split(' ').join('+');
    _finalUrl = baseUrl + _artist + '&callback=JSON_CALLBACK'
    return _finalUrl;

  service.setArtist = function(artist){
    _artist = artist;

  service.getArtist = function(){
    return _artist;

  service.callItunes = function(){
    var deferred = $q.defer();
      method: 'JSONP',
      url: _finalUrl
      deferred.reject('There was an error')
    return deferred.promise;

  return service;

Now our factory is complete. We are now able to inject ‘myFactory’ into any controller and we’ll then be able to call our methods that we attached to our service object (setArtist, getArtist, and callItunes).

app.controller('myFactoryCtrl', function($scope, myFactory){
  $ = {};
  $scope.updateArtist = function(){

  $scope.submitArtist = function(){
        $ = data;
      }, function(data){

In the controller above we’re injecting in the ‘myFactory’ service. We then set properties on our $scope object that are coming from data from ‘myFactory’. The only tricky code above is if you’ve never dealt with promises before. Because callItunes is returning a promise, we are able to use the .then() method and only set $ once our promise is fulfilled with the iTunes data. You’ll notice our controller is very ‘thin’. All of our logic and persistent data is located in our service, not in our controller.

2) Service
Perhaps the biggest thing to know when dealing with creating a Service is that that it’s instantiated with the ‘new’ keyword. For you JavaScript gurus this should give you a big hint into the nature of the code. For those of you with a limited background in JavaScript or for those who aren’t too familiar with what the ‘new’ keyword actually does, let’s review some JavaScript fundamentals that will eventually help us in understanding the nature of a Service.

To really see the changes that occur when you invoke a function with the ‘new’ keyword, let’s create a function and invoke it with the ‘new’ keyword, then let’s show what the interpreter does when it sees the ‘new’ keyword. The end results will both be the same.

First let’s create our Constructor.

var Person = function(name, age){ = name;
  this.age = age;

This is a typical JavaScript constructor function. Now whenever we invoke the Person function using the ‘new’ keyword, ‘this’ will be bound to the newly created object.

Now let’s add a method onto our Person’s prototype so it will be available on every instance of our Person ‘class’.

Person.prototype.sayName = function(){
  alert('My name is ' +;

Now, because we put the sayName function on the prototype, every instance of Person will be able to call the sayName function in order alert that instance’s name.

Now that we have our Person constructor function and our sayName function on its prototype, let’s actually create an instance of Person then call the sayName function.

var tyler = new Person('Tyler', 23);
tyler.sayName(); //alerts 'My name is Tyler'

So all together the code for creating a Person constructor, adding a function to it’s prototype, creating a Person instance, and then calling the function on its prototype looks like this.

var Person = function(name, age){ = name;
  this.age = age;
Person.prototype.sayName = function(){
  alert('My name is ' +;
var tyler = new Person('Tyler', 23);
tyler.sayName(); //alerts 'My name is Tyler'

Now let’s look at what actually is happening when you use the ‘new’ keyword in JavaScript. First thing you should notice is that after using ‘new’ in our example, we’re able to call a method (sayName) on ‘tyler’ just as if it were an object - that’s because it is. So first, we know that our Person constructor is returning an object, whether we can see that in the code or not. Second, we know that because our sayName function is located on the prototype and not directly on the Person instance, the object that the Person function is returning must be delegating to its prototype on failed lookups. In more simple terms, when we call tyler.sayName() the interpreter says “OK, I’m going to look on the ‘tyler’ object we just created, locate the sayName function, then call it. Wait a minute, I don’t see it here - all I see is name and age, let me check the prototype. Yup, looks like it’s on the prototype, let me call it.”.

Below is code for how you can think about what the ‘new’ keyword is actually doing in JavaScript. It’s basically a code example of the above paragraph. I’ve put the ‘interpreter view’ or the way the interpreter sees the code inside of notes.

var Person = function(name, age){
  //The line below this creates an obj object that will delegate to the person's prototype on failed lookups.
  //var obj = Object.create(Person.prototype);

  //The line directly below this sets 'this' to the newly created object
  //this = obj; = name;
  this.age = age;

  //return this;

Now having this knowledge of what the ‘new’ keyword really does in JavaScript, creating a Service in Angular should be easier to understand.

The biggest thing to understand when creating a Service is knowing that Services are instantiated with the ‘new’ keyword. Combining that knowledge with our examples above, you should now recognize that you’ll be attaching your properties and methods directly to ‘this’ which will then be returned from the Service itself. Let’s take a look at this in action.

Unlike what we originally did with the Factory example, we don’t need to create an object then return that object because, like mentioned many times before, we used the ‘new’ keyword so the interpreter will create that object, have it delegate to it’s prototype, then return it for us without us having to do the work.

First things first, let’s create our ‘private’ and helper function. This should look very familiar since we did the exact same thing with our factory. I won’t explain what each line does here because I did that in the factory example, if you’re confused, re-read the factory example.

app.service('myService', function($http, $q){
  var baseUrl = '';
  var _artist = '';
  var _finalUrl = '';

  var makeUrl = function(){
    _artist = _artist.split(' ').join('+');
    _finalUrl = baseUrl + _artist + '&callback=JSON_CALLBACK'
    return _finalUrl;

Now, we’ll attach all of our methods that will be available in our controller to ‘this’.

app.service('myService', function($http, $q){
  var baseUrl = '';
  var _artist = '';
  var _finalUrl = '';

  var makeUrl = function(){
    _artist = _artist.split(' ').join('+');
    _finalUrl = baseUrl + _artist + '&callback=JSON_CALLBACK'
    return _finalUrl;

  this.setArtist = function(artist){
    _artist = artist;

  this.getArtist = function(){
    return _artist;

  this.callItunes = function(){
    var deferred = $q.defer();
      method: 'JSONP',
      url: _finalUrl
      deferred.reject('There was an error')
    return deferred.promise;


Now just like in our factory, setArtist, getArtist, and callItunes will be available in whichever controller we pass myService into. Here’s the myService controller (which is almost exactly the same as our factory controller).

app.controller('myServiceCtrl', function($scope, myService){
  $ = {};
  $scope.updateArtist = function(){

  $scope.submitArtist = function(){
        $ = data;
      }, function(data){

Like I mentioned before, once you really understand what ‘new’ does, Services are almost identical to factories in Angular.

How to delete row based on cell value

This is the autofilter macro you could base a function off of:

ActiveSheet.Range("$A$1:$A$10").AutoFilter Field:=1, Criteria1:="=*-*", Operator:=xlAnd

I use this autofilter function to delete matching rows:

Public Sub FindDelete(sCol As String, vSearch As Variant)
'Simple find and Delete
Dim lLastRow As Integer
Dim rng As Range
Dim rngDelete As Range
    Range(sCol & 1).Select
    Range(sCol & 2) = "temp"
    With ActiveSheet
            lLastRow = .Cells.SpecialCells(xlCellTypeLastCell).Row
        Set rng = Range(sCol & 2, Cells(lLastRow, sCol))
            rng.AutoFilter Field:=1, Criteria1:=vSearch, Operator:=xlAnd
        Set rngDelete = rng.SpecialCells(xlCellTypeVisible)
    End With
End Sub

call it like:

call FindDelete "A", "=*-*"

It's saved me a lot of work. Good luck!

Graphical HTTP client for windows

Honestly, for simplistic stuff like that I typically whip up a quick HTML form in a local file and load that up in a browser.

Go to next item in ForEach-Object

You may want to use the Continue statement to continue with the innermost loop.

Excerpt from PowerShell help file:

In a script, the continue statement causes program flow to move immediately to the top of the innermost loop controlled by any of these statements:

  • for
  • foreach
  • while

Create a new file in git bash

Yes, it is. Just create files in the windows explorer and git automatically detects these files as currently untracked. Then add it with the command you already mentioned.

git add does not create any files. See also

Github probably creates the file with touch and adds the file for tracking automatically. You can do this on the bash as well.

How to read a file line-by-line into a list?

I like to use the following. Reading the lines immediately.

contents = []
for line in open(filepath, 'r').readlines():

Or using list comprehension:

contents = [line.strip() for line in open(filepath, 'r').readlines()]

How to import cv2 in python3?

well, there was 2 issues: 1.instead of pip, pip3 should be used. 2.its better to use virtual env. because i have had multiple python version installed

HttpClient - A task was cancelled?

in my .net core 3.1 applications I am getting two problem where inner cause was timeout exception. 1, one is i am getting aggregate exception and in it's inner exception was timeout exception 2, other case was Task canceled exception

My solution is

catch (Exception ex)
                if (ex.InnerException is TimeoutException)
                    ex = ex.InnerException;
                else if (ex is TaskCanceledException)
                    if ((ex as TaskCanceledException).CancellationToken == null || (ex as TaskCanceledException).CancellationToken.IsCancellationRequested == false)
                        ex = new TimeoutException("Timeout occurred");
                Logger.Fatal(string.Format("Exception at calling {0} :{1}", url, ex.Message), ex);

how to remove key+value from hash in javascript

Another option may be this John Resig remove method. can better fit what you need. if you know the index in the array.

ProcessBuilder: Forwarding stdout and stderr of started processes without blocking the main thread

Use ProcessBuilder.inheritIO, it sets the source and destination for subprocess standard I/O to be the same as those of the current Java process.

Process p = new ProcessBuilder().inheritIO().command("command1").start();

If Java 7 is not an option

public static void main(String[] args) throws Exception {
    Process p = Runtime.getRuntime().exec("cmd /c dir");
    inheritIO(p.getInputStream(), System.out);
    inheritIO(p.getErrorStream(), System.err);


private static void inheritIO(final InputStream src, final PrintStream dest) {
    new Thread(new Runnable() {
        public void run() {
            Scanner sc = new Scanner(src);
            while (sc.hasNextLine()) {

Threads will die automatically when subprocess finishes, because src will EOF.

Failed to install android-sdk: "java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema"

Just had this error, solved by downloading the Android SDK Command-line Tools (latest) on Android Studio, under settings > Appearance & Behavior > System Settings > Android SDK > SDK Tools and re-running flutter doctor --android-licenses

Android SDK path on Android Studio

Command-line Tools

Java, How to specify absolute value and square roots

Try using Math.abs:

variableAbs = Math.abs(variable);

For square root use:

variableSqRt = Math.sqrt(variable);

Check if string contains \n Java

I'd rather trust JDK over System property. Following is a working snippet.

    private boolean checkIfStringContainsNewLineCharacters(String str){
            Scanner scanner = new Scanner(str);
            boolean hasNextLine =  scanner.hasNextLine();
            return hasNextLine;
        return false;

Dynamically adding properties to an ExpandoObject

dynamic x = new ExpandoObject();
x.NewProp = string.Empty;


var x = new ExpandoObject() as IDictionary<string, Object>;
x.Add("NewProp", string.Empty);

Display/Print one column from a DataFrame of Series in Pandas

Not sure what you are really after but if you want to print exactly what you have you can do:

Option 1



Option 2

for v in df['Item']:


How to close a thread from within?

If you want force stop your thread: thread._Thread_stop() For me works very good.

Currency formatting in Python

I've come to look at the same thing and found python-money not really used it yet but maybe a mix of the two would be good

How to build and use Google TensorFlow C++ api

You can use this ShellScript to install (most) of it's dependencies, clone, build, compile and get all the necessary files into ../src/includes folder:

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint

Smutje is correct and Chad HedgeCock offered a great layman's example. Id like to build on Chad's example by offering a way to find/delete those records. We will use Customer as the Parent and Order as the child. CustomerId is the common field.

select * from Order Child 
left join Customer Parent on Child.CustomerId = Parent.CustomerId
where Parent.CustomerId is null 

if you are reading this thread... you will get results. These are orphaned children. select * from Order Child left join Customer Parent on Child.CustomerId = Parent.CustomerId where Parent.CustomerId is null Note the row count in the bottom right.

Go verify w/ whomever you need to that you are going to delete these rows!

begin tran 
delete Order
from Order Child 
left join Customer Parent on Child.CustomerId = Parent.CustomerId
where Parent.CustomerId is null 

Run the first bit. Check that row count = what you expected

commit the tran

commit tran 

Be careful. Someone's sloppy programming got you into this mess. Make sure you understand the why before you delete the orphans. Maybe the parent needs to be restored.

Twitter Bootstrap Form File Element Upload Button

Solution for multiple upload

I tweaked two previous answers to include multiple uploads. In this way the label shows the file name, if only one is selected, or x files in the opposite case.

<label class="btn btn-primary" for="my-file-selector">
    <input id="my-file-selector" type="file" multiple="multiple" style="display:none"
            (this.files.length > 1) ? this.files.length + ' files' : this.files[0].name)">                     
<span class='label label-info' id="upload-file-info"></span>

enter image description here

It may also apply to change the button text and class.

<label class="btn btn-primary" for="multfile">
    <input id="multfile" type="file" multiple="multiple" style="display:none"
            (this.files.length == 1) ? this.files[0].name : this.files.length + ' files');
    <span id="multfile-label">Files&hellip;</span>

enter image description here

Display string as html in mvc view

I had a similar problem recently, and google landed me here, so I put this answer here in case others land here as well, for completeness.

I noticed that when I had badly formatted html, I was actually having all my html tags stripped out, with just the non-tag content remaining. I particularly had a table with a missing opening table tag, and then all my html tags from the entire string where ripped out completely.

So, if the above doesn't work, and you're still scratching your head, then also check you html for being valid.

I notice even after I got it working, MVC was adding tbody tags where I had none. This tells me there is clean up happening (MVC 5), and that when it can't happen, it strips out all/some tags.

Groovy built-in REST/HTTP client?

You can take advantage of Groovy features like with(), improvements to URLConnection, and simplified getters/setters:


String getResult = new URL('http://mytestsite/bloop').text


String postResult
((HttpURLConnection)new URL('http://mytestsite/bloop').openConnection()).with({
    requestMethod = 'POST'
    doOutput = true
    setRequestProperty('Content-Type', '...') // Set your content type.
    outputStream.withPrintWriter({printWriter ->
        printWriter.write('...') // Your post data. Could also use withWriter() if you don't want to write a String.
    // Can check 'responseCode' here if you like.
    postResult = inputStream.text // Using 'inputStream.text' because 'content' will throw an exception when empty.

Note, the POST will start when you try to read a value from the HttpURLConnection, such as responseCode, inputStream.text, or getHeaderField('...').

Testing if a checkbox is checked with jQuery

// use ternary operators
$("#ans").is(':checked') ? 1 : 0;

Batch / Find And Edit Lines in TXT file

This is the kind of stuff sed was made for (of course, you need sed on your system for that).

sed 's/ex3/ex5/g' input.txt > output.txt

You will either need a Unix system or a Windows Cygwin kind of platform for this.
There is also GnuWin32 for sed. (GnuWin32 installation and usage).

Working with time DURATION, not time of day

I don't know how to make the chart label the axis in the format "X1 min : X2 sec", but here's another way to get durations, in the format of minutes with decimals representing seconds (.5 = 30 sec, .25 = 15 sec, etc.)

Suppose in column A you have your time data, for example in cell A1 you have 12:03:06, which your 3min 6sec data misinterpreted as 3:06 past midnight, and column B is free.

In cell B1 enter this formula: =MINUTE(A1) + SECOND(A1)/60 and hit enter/return. Grab the lower right corner of cell B2 and drag as far down as the A column goes to apply the formula to all data in col A.

Last step, be sure to highlight all of column B and set it to Number format (the application of the formula may have automatically set format to Time).

null terminating a string

From the comp.lang.c FAQ:

In essence: NULL (the preprocessor macro for the null pointer) is not the same as NUL (the null character).

Python Error: unsupported operand type(s) for +: 'int' and 'NoneType'

When none of the if test in number_translator() evaluate to true, the function returns None. The error message is the consequence of that.

Whenever you see an error that include 'NoneType' that means that you have an operand or an object that is None when you were expecting something else.

How to redirect the output of the time command to a file in Linux?

Simple. The GNU time utility has an option for that.

But you have to ensure that you are not using your shell's builtin time command, at least the bash builtin does not provide that option! That's why you need to give the full path of the time utility:

/usr/bin/time -o time.txt sleep 1

Why an inline "background-image" style doesn't work in Chrome 10 and Internet Explorer 8?

As c-smile mentioned: Just need to remove the apostrophes in the url():

<div style="background-image: url("></div>

Demo here

Two decimal places using printf( )

What you want is %.2f, not 2%f.

Also, you might want to replace your %d with a %f ;)

#include <cstdio>
int main()
printf("When this number: %f is assigned to 2 dp, it will be: %.2f ", 94.9456, 94.9456);
return 0;

This will output:

When this number: 94.945600 is assigned to 2 dp, it will be: 94.95

See here for a full description of the printf formatting options: printf

Where can I find error log files?

What OS you are using and which Webserver? On Linux and Apache you can find the apache error_log in /var/log/apache2/

Android: how to draw a border to a LinearLayout

Extend LinearLayout/RelativeLayout and use it straight on the XML

package com.pkg_name ;
public class LinearLayoutOutlined extends LinearLayout {
    Paint paint;    

    public LinearLayoutOutlined(Context context) {
        // TODO Auto-generated constructor stub
        setWillNotDraw(false) ;
        paint = new Paint();
    public LinearLayoutOutlined(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
        setWillNotDraw(false) ;
        paint = new Paint();
    protected void onDraw(Canvas canvas) {
        Paint fillPaint = paint;
        fillPaint.setARGB(255, 0, 255, 0);
        canvas.drawPaint(fillPaint) ;

        Paint strokePaint = paint;
        strokePaint.setARGB(255, 255, 0, 0);
        Rect r = canvas.getClipBounds() ;
        Rect outline = new Rect( 1,1,r.right-1, r.bottom-1) ;
        canvas.drawRect(outline, strokePaint) ;


<?xml version="1.0" encoding="utf-8"?>

   ... your widgets here ...


Python 2.7 getting user input and manipulating as string without quotations

We can use the raw_input() function in Python 2 and the input() function in Python 3. By default the input function takes an input in string format. For other data type you have to cast the user input.

In Python 2 we use the raw_input() function. It waits for the user to type some input and press return and we need to store the value in a variable by casting as our desire data type. Be careful when using type casting

x = raw_input("Enter a number: ") #String input

x = int(raw_input("Enter a number: ")) #integer input

x = float(raw_input("Enter a float number: ")) #float input

x = eval(raw_input("Enter a float number: ")) #eval input

In Python 3 we use the input() function which returns a user input value.

x = input("Enter a number: ") #String input

If you enter a string, int, float, eval it will take as string input

x = int(input("Enter a number: ")) #integer input

If you enter a string for int cast ValueError: invalid literal for int() with base 10:

x = float(input("Enter a float number: ")) #float input

If you enter a string for float cast ValueError: could not convert string to float

x = eval(input("Enter a float number: ")) #eval input

If you enter a string for eval cast NameError: name ' ' is not defined Those error also applicable for Python 2.

There is already an open DataReader associated with this Command which must be closed first

In my case, I had opened a query from data context, like

    Dim stores = DataContext.Stores _
        .Where(Function(d) filter.Contains(d.code)) _

... and then subsequently queried the same...

    Dim stores = DataContext.Stores _
        .Where(Function(d) filter.Contains(d.code)).ToList

Adding the .ToList to the first resolved my issue. I think it makes sense to wrap this in a property like:

Public ReadOnly Property Stores As List(Of Store)
        If _stores Is Nothing Then
            _stores = DataContext.Stores _
                .Where(Function(d) Filters.Contains(d.code)).ToList
        End If
        Return _stores
    End Get
End Property

Where _stores is a private variable, and Filters is also a readonly property that reads from AppSettings.

MVC which submit button has been pressed

// Buttons
<input name="submit" type="submit" id="submit" value="Save" />
<input name="process" type="submit" id="process" value="Process" />

// Controller
public ActionResult index(FormCollection collection)
    string submitType = "unknown";

    if(collection["submit"] != null)
        submitType = "submit";
    else if (collection["process"] != null)
        submitType = "process";

} // End of the index method

What does 'x packages are looking for funding' mean when running `npm install`?

When you run npm update in the command prompt, when it is done it will recommend you type a new command called npm fund.

When you run npm fund it will list all the modules and packages you have installed that were created by companies or organizations that need money for their IT projects. You will see a list of webpages where you can send them money. So "funds" means "Angular packages you installed that could use some money from you as an option to help support their businesses".

It's basically a list of the modules you have that need contributions or donations of money to their projects and which list websites where you can enter a credit card to help pay for them.

Spring configure @ResponseBody JSON format

Take a look at Rick Hightower's approach. His approach avoids configuring ObjectMapper as a singleton and allows you to filter the JSON response for the same object in different ways per each request method.

Pip error: Microsoft Visual C++ 14.0 is required

Pycrypto has vulnerabilities assigned the CVE-2013-7459 number, and the repo hasn't accept PRs since June 23, 2014.

Pycryptodome is a drop-in replacement for the PyCrypto library, which exposes almost the same API as the old PyCrypto, see Compatibility with PyCrypto.

If you haven't install pycrypto yet, you can use pip install pycryptodome to install pycryptodome in which you won't get Microsoft Visual C++ 14.0 issue.

Context.startForegroundService() did not then call Service.startForeground()

Ok, something I noticed on this that might help a few others too. This is strictly from testing to see if I could figure out how to fix the occurrences I am seeing. For simplicity sake, let's say I have a method that calls this from the presenter.

context.startForegroundService(new Intent(context, TaskQueueExecutorService.class));

try {
} catch (InterruptedException e) {

This will crash with the same error. The Service will NOT start until the method is complete, therefore no onCreate() in the service.

So even if you update the UI off the main thread, IF you have anything that might hold up that method after it, it won't start on time and give you the dreaded Foreground Error. In my case we were loading some things onto a queue and each called startForegroundService, but some logic was involved with each in the background. So if the logic took too long to finish that method since they were called back to back, crash time. The old startService just ignored it and went on it's way and since we called it each time, the next round would finish up.

This left me wondering, if I called the service from a thread in the background, could it not be fully bound on the start and run immediately, so I started experimenting. Even though this does NOT start it immediately, it does not crash.

new Handler(Looper.getMainLooper()).post(new Runnable() {
        public void run() {
               context.startForegroundService(new Intent(context, 
               try {
               } catch (InterruptedException e) {

I will not pretend to know why it does not crash although I suspect this forces it to wait until the main thread can handle it in a timely fashion. I know it's not ideal to tie it to the main thread, but since my usage calls it in the background, I'm not real concerned if it waits until it can complete rather than crash.

makefiles - compile all c files at once

LIBS  = -lkernel32 -luser32 -lgdi32 -lopengl32
CFLAGS = -Wall

# Should be equivalent to your list of C files, if you don't build selectively
SRC=$(wildcard *.c)

test: $(SRC)
    gcc -o $@ $^ $(CFLAGS) $(LIBS)

How to modify WooCommerce cart, checkout pages (main theme portion)

Another way to totally override the cart.php is to copy:

woocommerce/templates/cart/cart.php to   

Then do whatever you need at the yourtheme/woocommerce/cart/cart.php

How to convert an int to string in C?

After having looked at various versions of itoa for gcc, the most flexible version I have found that is capable of handling conversions to binary, decimal and hexadecimal, both positive and negative is the fourth version found at While sprintf/snprintf have advantages, they will not handle negative numbers for anything other than decimal conversion. Since the link above is either off-line or no longer active, I've included their 4th version below:

 * C++ version 0.4 char* style "itoa":
 * Written by Lukás Chmela
 * Released under GPLv3.
char* itoa(int value, char* result, int base) {
    // check that the base if valid
    if (base < 2 || base > 36) { *result = '\0'; return result; }

    char* ptr = result, *ptr1 = result, tmp_char;
    int tmp_value;

    do {
        tmp_value = value;
        value /= base;
        *ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)];
    } while ( value );

    // Apply negative sign
    if (tmp_value < 0) *ptr++ = '-';
    *ptr-- = '\0';
    while(ptr1 < ptr) {
        tmp_char = *ptr;
        *ptr--= *ptr1;
        *ptr1++ = tmp_char;
    return result;

How to install python-dateutil on Windows?

Looks like the uses easy_install (i.e. setuptools). Just install the setuptools package and you will be all set.

To install setuptools in Python 2.6, see the answer to this question.

How to check the first character in a string in Bash or UNIX shell?

Consider the case statement as well which is compatible with most sh-based shells:

case $str in
    echo 1
    echo 0

Shortcut to create properties in Visual Studio?

In addition to Amra's answer, you can find other snippets by typing

Ctrl + K, Ctrl + X

Which is mapped to Edit.InsertSnippet in my Visual Studio and shows you the full list of snippets available.

Also remember that you can configure your own snippets by using the Snippets Manager, which is available in the Tools menu, Code Snippets Manager.... Basically you create a file *.snippet and use the Import button in the Code Snippets Manager to add it to Visual Studio. For a full tutorial you can go to the docs; Walkthrough: Create a code snippet.

In Visual Studio Code snippets are handled slightly different than in Visual Studio. You can access all snippets by typing Ctrl + Shift + P and type in snippet. Two options should be available, Insert Snippet and Preferences: Configure User Snippets.

The former inserts a snippet from your list of snippets (using the Language Mode which you can see in the status bar), and with the latter you can create your own snippets for any Language Mode.

If you know the shortname you can just type that and use Tab to expand the snippet. For inserting a C# property you have three snippets available, prop, propfull, and propg, for different purposes.

Git pull - Please move or remove them before you can merge

I just faced the same issue and solved it using the following.First clear tracked files by using :

git clean -d -f

then try git pull origin master

You can view other git clean options by typing git clean -help

Count the number of Occurrences of a Word in a String

public class TestWordCount {

public static void main(String[] args) {

    int count = numberOfOccurences("Alice", "Alice in wonderland. Alice & chinki are classmates. Chinki is better than Alice.occ");
    System.out.println("count : "+count);


public static int numberOfOccurences(String findWord, String sentence) {

    int length = sentence.length();
    int lengthWithoutFindWord = sentence.replace(findWord, "").length();
    return (length - lengthWithoutFindWord)/findWord.length();



Gradient borders

Mozilla currently only supports CSS gradients as values of the background-image property, as well as within the shorthand background.

Example 3 - Gradient Borders

border: 8px solid #000;
-moz-border-bottom-colors: #555 #666 #777 #888 #999 #aaa #bbb #ccc;
-moz-border-top-colors: #555 #666 #777 #888 #999 #aaa #bbb #ccc;
-moz-border-left-colors: #555 #666 #777 #888 #999 #aaa #bbb #ccc;
-moz-border-right-colors: #555 #666 #777 #888 #999 #aaa #bbb #ccc;
padding: 5px 5px 5px 15px;

Javascript wait() function

Javascript isn't threaded, so a "wait" would freeze the entire page (and probably cause the browser to stop running the script entirely).

To specifically address your problem, you should remove the brackets after donothing in your setTimeout call, and make waitsecs a number not a string:

setTimeout(donothing,500); // run donothing after 0.5 seconds

But that won't stop execution; "after" will be logged before your function runs.

To wait properly, you can use anonymous functions:


All your variables will still be there in the "after" section. You shouldn't chain these - if you find yourself needing to, you need to look at how you're structuring the program. Also you may want to use setInterval / clearInterval if it needs to loop.

Do I need to convert .CER to .CRT for Apache SSL certificates? If so, how?

According to documentation mod_ssl:

   Name: SSLCertificateFile
   Description: Server PEM-encoded X.509 certificate file

Certificate file should be PEM-encoded X.509 Certificate file:

openssl x509 -inform DER -in certificate.cer -out certificate.pem

Save range to variable

In your own answer, you effectively do this:

Dim SrcRange As Range ' you should always declare things explicitly
Set SrcRange = Sheets("Src").Range("A2:A9")
SrcRange.Copy Destination:=Sheets("Dest").Range("A2")

You're not really "extracting" the range to a variable, you're setting a reference to the range.

In many situations, this can be more efficient as well as more flexible:

Dim Src As Variant
Src= Sheets("Src").Range("A2:A9").Value 'Read range to array
'Here you can add code to manipulate your Src array
Sheets("Dest").Range("A2:A9").Value = Src 'Write array back to another range

SQL Server reports 'Invalid column name', but the column is present and the query works through management studio

I eventually shut-down and restarted Microsoft SQL Server Management Studio; and that fixed it for me. But at other times, just starting a new query window was enough.

Function or sub to add new row and data to table

Is this what you are looking for?

Option Explicit

Public Sub addDataToTable(ByVal strTableName As String, ByVal strData As String, ByVal col As Integer)
    Dim lLastRow As Long
    Dim iHeader As Integer

    With ActiveSheet.ListObjects(strTableName)
        'find the last row of the list
        lLastRow = ActiveSheet.ListObjects(strTableName).ListRows.Count
        'shift from an extra row if list has header
        If .Sort.Header = xlYes Then
            iHeader = 1
            iHeader = 0
        End If
    End With
    'add the data a row after the end of the list
    ActiveSheet.Cells(lLastRow + 1 + iHeader, col).Value = strData
End Sub

It handles both cases whether you have header or not.

How to find which version of Oracle is installed on a Linux server (In terminal)

As A.B.Cada pointed out, you can query the database itself with sqlplus for the db version. That is the easiest way to findout what is the version of the db that is actively running. If there is more than one you will have to set the oracle_sid appropriately and run the query against each instance.

You can view /etc/oratab file to see what instance and what db home is used per instance. Its possible to have multiple version of oracle installed per server as well as multiple instances. The /etc/oratab file will list all instances and db home. From with the oracle db home you can run "opatch lsinventory" to find out what exaction version of the db is installed as well as any patches applied to that db installation.

Jenkins / Hudson environment variables

On Ubuntu I just edit /etc/default/jenkins and add source /etc/profile at the end and it works to me.

mkdir -p functionality in Python

import os
from os.path import join as join_paths

def mk_dir_recursive(dir_path):

    if os.path.isdir(dir_path):
    h, t = os.path.split(dir_path)  # head/tail
    if not os.path.isdir(h):

    new_path = join_paths(h, t)
    if not os.path.isdir(new_path):

based on @Dave C's answer but with a bug fixed where part of the tree already exists

How to convert column with dtype as object to string in Pandas Dataframe

Not answering the question directly, but it might help someone else.

I have a column called Volume, having both - (invalid/NaN) and numbers formatted with ,

df['Volume'] = df['Volume'].astype('str')
df['Volume'] = df['Volume'].str.replace(',', '')
df['Volume'] = pd.to_numeric(df['Volume'], errors='coerce')

Casting to string is required for it to apply to str.replace


Exit/save edit to sudoers file? Putty SSH

Be careful to type exactly :wq as Wouter Verleur said at step 7. After type enter, you will save the changes and exit the visudo editor to bash.

How do I auto-resize an image to fit a 'div' container?

You have to tell the browser the height of where you are placing it:

.example {
    height: 220px; /* DEFINE HEIGHT */
    background: url('../img/example.png');
    background-size: 100% 100%;
    background-repeat: no-repeat;

Variables within app.config/web.config

I would recommend following Matt Hamsmith's solution. If it's an issue to implement, then why not create an extension method that implements this in the background on the AppSettings class?

Something like:

    public static string GetValue(this NameValueCollection settings, string key)


Inside the method you search through the DictionaryInfoConfigSection using Linq and return the value with the matching key. You'll need to update the config file though, to something along these lines:

    <DirectoryMap key="MyBaseDir" value="C:\MyBase" />
    <DirectoryMap key="Dir1" value="[MyBaseDir]\Dir1"/>
    <DirectoryMap key="Dir2" value="[MyBaseDir]\Dir2"/>

How to bind inverse boolean properties in WPF?

Don't know if this is relevant to XAML, but in my simple Windows app I created the binding manually and added a Format event handler.

public FormMain() {

  Binding argBinding = new Binding("Enabled", uxCheckBoxArgsNull, "Checked", false, DataSourceUpdateMode.OnPropertyChanged);
  argBinding.Format += new ConvertEventHandler(Binding_Format_BooleanInverse);

void Binding_Format_BooleanInverse(object sender, ConvertEventArgs e) {
  bool boolValue = (bool)e.Value;
  e.Value = !boolValue;

How to change legend size with matplotlib.pyplot

using import matplotlib.pyplot as plt

Method 1: specify the fontsize when calling legend (repetitive)

plt.legend(fontsize=20) # using a size in points
plt.legend(fontsize="x-large") # using a named size

With this method you can set the fontsize for each legend at creation (allowing you to have multiple legends with different fontsizes). However, you will have to type everything manually each time you create a legend.

(Note: @Mathias711 listed the available named fontsizes in his answer)

Method 2: specify the fontsize in rcParams (convenient)

plt.rc('legend',fontsize=20) # using a size in points
plt.rc('legend',fontsize='medium') # using a named size

With this method you set the default legend fontsize, and all legends will automatically use that unless you specify otherwise using method 1. This means you can set your legend fontsize at the beginning of your code, and not worry about setting it for each individual legend.

If you use a named size e.g. 'medium', then the legend text will scale with the global font.size in rcParams. To change font.size use plt.rc(font.size='medium')

How can I tell what edition of SQL Server runs on the machine?

You can get just the edition (plus under individual properties) using SERVERPROPERTY



Quote (for "Edition"):

Installed product edition of the instance of SQL Server. Use the value of this property to determine the features and the limits, such as maximum number of CPUs, that are supported by the installed product.
'Desktop Engine' (Not available for SQL Server 2005.)
'Developer Edition'
'Enterprise Edition'
'Enterprise Evaluation Edition'
'Personal Edition'(Not available for SQL Server 2005.)
'Standard Edition'
'Express Edition'
'Express Edition with Advanced Services'
'Workgroup Edition'
'Windows Embedded SQL'
Base data type: nvarchar(128)

How to select option in drop down protractorjs e2e tests

You can try this hope it will work

element.all('locregion')).then(function(selectItem) {
  expect(selectItem[0].getText()).toEqual('Ranjans Mobile Testing')
  selectItem[0].click(); //will click on first item
  selectItem[3].click(); //will click on fourth item

Good examples using java.util.logging

There are many examples and also of different types for logging. Take a look at the java.util.logging package.

Example code:

import java.util.logging.Logger;

public class Main {

  private static Logger LOGGER = Logger.getLogger("InfoLogging");

  public static void main(String[] args) {"Logging an INFO-level message");

Without hard-coding the class name:

import java.util.logging.Logger;

public class Main {
  private static final Logger LOGGER = Logger.getLogger(
    Thread.currentThread().getStackTrace()[0].getClassName() );

  public static void main(String[] args) {"Logging an INFO-level message");

How to randomize (shuffle) a JavaScript array?

a shuffle function that doesn't change the source array

Update: Here I'm suggesting a relatively simple (not from complexity perspective) and short algorithm that will do just fine with small sized arrays, but it's definitely going to cost a lot more than the classic Durstenfeld algorithm when you deal with huge arrays. You can find the Durstenfeld in one of the top replies to this question.

Original answer:

If you don't wish your shuffle function to mutate the source array, you can copy it to a local variable, then do the rest with a simple shuffling logic.

function shuffle(array) {
  var result = [], source = array.concat([]);

  while (source.length) {
    let index = Math.floor(Math.random() * source.length);
    source.splice(index, 1);

  return result;

Shuffling logic: pick up a random index, then add the corresponding element to the result array and delete it from the source array copy. Repeat this action until the source array gets empty.

And if you really want it short, here's how far I could get:

function shuffle(array) {
  var result = [], source = array.concat([]);

  while (source.length) {
    let index = Math.floor(Math.random() * source.length);
    result.push(source.splice(index, 1)[0]);

  return result;

Can't find bundle for base name

When you create an initialization of the ResourceBundle, you can do this way also.

For testing and development I have created a properties file under \src with the name

Use this way:

ResourceBundle rb = ResourceBundle.getBundle("prp");

Naming convention and stuff:

Difference between \w and \b regular expression meta characters

\w matches a word character. \b is a zero-width match that matches a position character that has a word character on one side, and something that's not a word character on the other. (Examples of things that aren't word characters include whitespace, beginning and end of the string, etc.)

\w matches a, b, c, d, e, and f in "abc def"
\b matches the (zero-width) position before a, after c, before d, and after f in "abc def"


`ui-router` $stateParams vs. $state.params

I have a root state which resolves sth. Passing $state as a resolve parameter won't guarantee the availability for $state.params. But using $stateParams will.

var rootState = {
    name: 'root',
    url: '/:stubCompanyId',
    abstract: true,

// case 1:
rootState.resolve = {
    authInit: ['AuthenticationService', '$state', function (AuthenticationService, $state) {
        console.log('rootState.resolve', $state.params);
        return AuthenticationService.init($state.params);
// output:
// rootState.resolve Object {}

// case 2:
rootState.resolve = {
    authInit: ['AuthenticationService', '$stateParams', function (AuthenticationService, $stateParams) {
        console.log('rootState.resolve', $stateParams);
        return AuthenticationService.init($stateParams);
// output:
// rootState.resolve Object {stubCompanyId:...}

Using "angular": "~1.4.0", "angular-ui-router": "~0.2.15"

What does "javascript:void(0)" mean?

The void operator evaluates the given expression and then returns undefined.

The void operator is often used merely to obtain the undefined primitive value, usually using “void(0)” (which is equivalent to “void 0”). In these cases, the global variable undefined can be used instead (assuming it has not been assigned to a non-default value).

An explanation is provided here: void operator.

The reason you’d want to do this with the href of a link is that normally, a javascript: URL will redirect the browser to a plain text version of the result of evaluating that JavaScript. But if the result is undefined, then the browser stays on the same page. void(0) is just a short and simple script that evaluates to undefined.

HTML/CSS font color vs span style

Use style. The font tag is deprecated (W3C Wiki).

Hide strange unwanted Xcode logs

Alright. There seems to be a lot of commotion about this one, so I'll give y'all a way to persist it without using that scheme trick. I'll address the iOS Simulator specifically, but this also might need to be applied for the TV Sim as well which is located in a different dir.

The problem that is causing all of this stuff are plists located within the Xcode directory. There is a process that gets launched called configd_sim when the Sim starts that reads the plists in and prints debugging information if the plists specify they should be logged.

The plists are located here:


If you are playing around with a beta, take note that the dir will be different.

You will see numerous plists in this directory. Now, build and run your application and observe the logs. You are looking for the content immediately followed by the subsystem: part. It is the name immediately following this that represents the corresponding problematic plist.

enter image description here

From there, either modify the plist to knock out the debugging [Level] key/value which is a dictionary containing the "Enable" => "Default" key/value... or just simply delete the plist. Note, that you will need to be root to do either of these since they're located in the Xcode application.

the plutil -p command might be of use to you as well. i.e.

plutil -p /Applications/

This gave me one of the problematic plists which contained:

{ "DEFAULT-OPTIONS" => { "Level" => { "Enable" => "Default" }}}

Good luck :]

Explain ggplot2 warning: "Removed k rows containing missing values"

The behavior you're seeing is due to how ggplot2 deals with data that are outside the axis ranges of the plot. You can change this behavior depending on whether you use scale_y_continuous (or, equivalently, ylim) or coord_cartesian to set axis ranges, as explained below.


# All points are visible in the plot
ggplot(mtcars, aes(mpg, hp)) + 

In the code below, one point with hp = 335 is outside the y-range of the plot. Also, because we used scale_y_continuous to set the y-axis range, this point is not included in any other statistics or summary measures calculated by ggplot, such as the linear regression line.

ggplot(mtcars, aes(mpg, hp)) + 
  geom_point() +
  scale_y_continuous(limits=c(0,300)) +  # Change this to limits=c(0,335) and the warning disappars

Warning messages:
1: Removed 1 rows containing missing values (stat_smooth). 
2: Removed 1 rows containing missing values (geom_point).

In the code below, the point with hp = 335 is still outside the y-range of the plot, but this point is nevertheless included in any statistics or summary measures that ggplot calculates, such as the linear regression line. This is because we used coord_cartesian to set the y-axis range, and this function does not exclude points that are outside the plot ranges when it does other calculations on the data.

If you compare this and the previous plot, you can see that the linear regression line in the second plot has a slightly steeper slope, because the point with hp=335 is included when calculating the regression line, even though it's not visible in the plot.

ggplot(mtcars, aes(mpg, hp)) + 
  geom_point() +
  coord_cartesian(ylim=c(0,300)) +

Python Pandas merge only certain columns

This is to merge selected columns from two tables.

If table_1 contains t1_a,t1_b,t1_c..,id,..t1_z columns, and table_2 contains t2_a, t2_b, t2_c..., id,..t2_z columns, and only t1_a, id, t2_a are required in the final table, then

mergedCSV = table_1[['t1_a','id']].merge(table_2[['t2_a','id']], on = 'id',how = 'left')
# save resulting output file    
mergedCSV.to_csv('output.csv',index = False)

Usages of doThrow() doAnswer() doNothing() and doReturn() in mockito

If you are testing a logic class and it is calling some internal void methods the doNothing is perfect.

How to make a .NET Windows Service start right after the installation?

You can do this all from within your service executable in response to events fired from the InstallUtil process. Override the OnAfterInstall event to use a ServiceController class to start the service.

Why does a base64 encoded string have an = sign at the end

Its defined in RFC 2045 as a special padding character if fewer than 24 bits are available at the end of the encoded data.

How to read a file without newlines?

my_file = open("first_file.txt", "r")
for line in my_file.readlines():
    if line[-1:] == "\n":

permission denied - php unlink

You (as in the process that runs b.php, either you through CLI or a webserver) need write access to the directory in which the files are located. You are updating the directory content, so access to the file is not enough.

Note that if you use the PHP chmod() function to set the mode of a file or folder to 777 you should use 0777 to make sure the number is correctly interpreted as an octal number.

Remove empty strings from array while keeping record Without Loop?

var arr = ["I", "am", "", "still", "here", "", "man"]
// arr = ["I", "am", "", "still", "here", "", "man"]
arr = arr.filter(Boolean)
// arr = ["I", "am", "still", "here", "man"]

filter documentation

// arr = ["I", "am", "", "still", "here", "", "man"]
arr = arr.filter(v=>v!='');
// arr = ["I", "am", "still", "here", "man"]

Arrow functions documentation

How to pass object from one component to another in Angular 2?

From component

import { Component, OnInit, ViewChild} from '@angular/core';_x000D_
    import { HttpClient } from '@angular/common/http';_x000D_
    import { dataService } from "src/app/service/data.service";_x000D_
    @Component( {_x000D_
        selector: 'app-sideWidget',_x000D_
        templateUrl: './sideWidget.html',_x000D_
        styleUrls: ['./linked-widget.component.css']_x000D_
    } )_x000D_
    export class sideWidget{_x000D_
    TableColumnNames: object[];_x000D_
    SelectedtableName: string = "patient";_x000D_
    constructor( private LWTableColumnNames: dataService ) { _x000D_
    ngOnInit() {_x000D_ 'getColumns', this.SelectedtableName )_x000D_
            ( data: object[] ) => {_x000D_
                this.TableColumnNames = data;_x000D_
     this.LWTableColumnNames.refLWTableColumnNames = this.TableColumnNames; //this line of code will pass the value through data service_x000D_
            } );_x000D_
    }    _x000D_


import { Injectable } from '@angular/core';_x000D_
import { BehaviorSubject, Observable } from 'rxjs';_x000D_
export class dataService {_x000D_
    refLWTableColumnNames: object;//creating an object for the data_x000D_

To Component

import { Component, OnInit } from '@angular/core';_x000D_
import { dataService } from "src/app/service/data.service";_x000D_
@Component( {_x000D_
    selector: 'app-linked-widget',_x000D_
    templateUrl: './linked-widget.component.html',_x000D_
    styleUrls: ['./linked-widget.component.css']_x000D_
} )_x000D_
export class LinkedWidgetComponent implements OnInit {_x000D_
    constructor(private LWTableColumnNames: dataService) { }_x000D_
    ngOnInit() {_x000D_
        console.log(this.LWTableColumnNames.refLWTableColumnNames);// calling the object from another component_x000D_

Difference between Statement and PreparedStatement

PreparedStatement is a very good defense (but not foolproof) in preventing SQL injection attacks. Binding parameter values is a good way to guarding against "little Bobby Tables" making an unwanted visit.

How to add checkboxes to JTABLE swing

1) JTable knows JCheckbox with built-in Boolean TableCellRenderers and TableCellEditor by default, then there is contraproductive declare something about that,

2) AbstractTableModel should be useful, where is in the JTable required to reduce/restrict/change nested and inherits methods by default implemented in the DefaultTableModel,

3) consider using DefaultTableModel, (if you are not sure about how to works) instead of AbstractTableModel,


could be generated from simple code:

import javax.swing.*;
import javax.swing.table.*;

public class TableCheckBox extends JFrame {

    private static final long serialVersionUID = 1L;
    private JTable table;

    public TableCheckBox() {
        Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
        Object[][] data = {
            {"Buy", "IBM", new Integer(1000), new Double(80.50), false},
            {"Sell", "MicroSoft", new Integer(2000), new Double(6.25), true},
            {"Sell", "Apple", new Integer(3000), new Double(7.35), true},
            {"Buy", "Nortel", new Integer(4000), new Double(20.00), false}
        DefaultTableModel model = new DefaultTableModel(data, columnNames);
        table = new JTable(model) {

            private static final long serialVersionUID = 1L;

            public Class getColumnClass(int column) {
            return getValueAt(0, column).getClass();
            public Class getColumnClass(int column) {
                switch (column) {
                    case 0:
                        return String.class;
                    case 1:
                        return String.class;
                    case 2:
                        return Integer.class;
                    case 3:
                        return Double.class;
                        return Boolean.class;
        JScrollPane scrollPane = new JScrollPane(table);

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                TableCheckBox frame = new TableCheckBox();
                frame.setLocation(150, 150);

Using Camera in the Android emulator

There is an updated version of Tom Gibara's tutorial. You can change the Webcam Broadcaster to work with JMyron instead of the old JMF.

The new emulator (sdk r15) manage webcams ; but it has some problems with integrated webcams (at least with mine's ^^)

Docker is installed but Docker Compose is not ? why?

The above solutions didn't work for me. But I found this that worked:

sudo apt-get update -y && sudo apt-get install -y python3-pip python3-dev
sudo apt-get remove docker docker-engine
curl -fsSL -o
sudo sh
sudo pip3 install docker-compose
#sudo docker-compose -f docker-compose-profess.yml pull ofw
sudo usermod -a -G docker $USER
sudo reboot

How do I replace whitespaces with underscore?

Using the re module:

import re
re.sub('\s+', '_', "This should be connected") # This_should_be_connected
re.sub('\s+', '_', 'And     so\tshould this')  # And_so_should_this

Unless you have multiple spaces or other whitespace possibilities as above, you may just wish to use string.replace as others have suggested.

Python - Locating the position of a regex match in a string?

re.Match objects have a number of methods to help you with this:

>>> m ="is", String)
>>> m.span()
(2, 4)
>>> m.start()
>>> m.end()

How to respond to clicks on a checkbox in an AngularJS directive?

This is the way I've been doing this sort of stuff. Angular tends to favor declarative manipulation of the dom rather than a imperative one(at least that's the way I've been playing with it).

The markup

<table class="table">
        <input type="checkbox" 
    <tr ng-repeat="e in entities" ng-class="getSelectedClass(e)">
        <input type="checkbox" name="selected"

And in the controller

var updateSelected = function(action, id) {
  if (action === 'add' && $scope.selected.indexOf(id) === -1) {
  if (action === 'remove' && $scope.selected.indexOf(id) !== -1) {
    $scope.selected.splice($scope.selected.indexOf(id), 1);

$scope.updateSelection = function($event, id) {
  var checkbox = $;
  var action = (checkbox.checked ? 'add' : 'remove');
  updateSelected(action, id);

$scope.selectAll = function($event) {
  var checkbox = $;
  var action = (checkbox.checked ? 'add' : 'remove');
  for ( var i = 0; i < $scope.entities.length; i++) {
    var entity = $scope.entities[i];

$scope.getSelectedClass = function(entity) {
  return $scope.isSelected( ? 'selected' : '';

$scope.isSelected = function(id) {
  return $scope.selected.indexOf(id) >= 0;

//something extra I couldn't resist adding :)
$scope.isSelectedAll = function() {
  return $scope.selected.length === $scope.entities.length;

EDIT: getSelectedClass() expects the entire entity but it was being called with the id of the entity only, which is now corrected

Copy Image from Remote Server Over HTTP

PHP has a built-in function file_get_contents(), which reads the content of a file into a string.

//Get the file
$content = file_get_contents("");

//Store in the filesystem. $fp = fopen("/location/to/save/image.jpg", "w"); fwrite($fp, $content); fclose($fp); ?>

If you wish to store the file in a database, simply use the $content variable and don't save the file to disk.

How to check version of python modules?

In Summary:

conda list   

(It will provide all the libraries along with version details).


pip show tensorflow

(It gives complete library details).

Is ini_set('max_execution_time', 0) a bad idea?

Reason is to have some value other than zero. General practice to have it short globally and long for long working scripts like parsers, crawlers, dumpers, exporting & importing scripts etc.

  1. You can halt server, corrupt work of other people by memory consuming script without even knowing it.
  2. You will not be seeing mistakes where something, let's say, infinite loop happened, and it will be harder to diagnose.
  3. Such site may be easily DoSed by single user, when requesting pages with long execution time

How to get textLabel of selected row in swift?

If you want to print the text of a UITableViewCell according to its matching NSIndexPath, you have to use UITableViewDelegate's tableView:didSelectRowAtIndexPath: method and get a reference of the selected UITableViewCell with UITableView's cellForRowAtIndexPath: method.

For example:

import UIKit

class TableViewController: UITableViewController {

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 4

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)

        switch indexPath.row {
        case 0: cell.textLabel?.text = "Bike"
        case 1: cell.textLabel?.text = "Car"
        case 2: cell.textLabel?.text = "Ball"
        default: cell.textLabel?.text = "Boat"

        return cell

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let selectedCell = tableView.cellForRowAtIndexPath(indexPath)
        // this will print Optional("Bike") if indexPath.row == 0


However, for many reasons, I would not encourage you to use the previous code. Your UITableViewCell should only be responsible for displaying some content given by a model. In most cases, what you want is to print the content of your model (could be an Array of String) according to a NSIndexPath. By doing things like this, you will separate each element's responsibilities.

Thereby, this is what I would recommend:

import UIKit

class TableViewController: UITableViewController {

    let toysArray = ["Bike", "Car", "Ball", "Boat"]

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return toysArray.count

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
        cell.textLabel?.text = toysArray[indexPath.row]
        return cell

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let toy = toysArray[indexPath.row]
        // this will print "Bike" if indexPath.row == 0


As you can see, with this code, you don't have to deal with optionals and don't even need to get a reference of the matching UITableViewCell inside tableView:didSelectRowAtIndexPath: in order to print the desired text.

Command for restarting all running docker containers?

For me its now :

docker restart $(docker ps -a -q)

How do I launch the Android emulator from the command line?

Nowadays asuming you have Android Studio installed (2.2) in my case and just 1 emulator you might use this one liner

export ANDROID_SDK_ROOT=~/Library/Android/sdk/ && emulator '@'`emulator -list-avds`

If you do this often, make it easier:

$ echo 'export ANDROID_SDK_ROOT=~/Library/Android/sdk/' >> ~/.profile

Add an alias to ~.aliases

alias androidup="emulator '@'`emulator -list-avds`" 

Recall to source ~/.profile ~/.aliases before testing it

Next time just $ androidup

how to create a logfile in php?

You could use built-in function trigger_error() to trigger user errors/warnings/notices and set_error_handler() to handle them. Inside your error handler you might want to use error_log() or file_put_contents() to store all records on files. To have a single file for every day just use something like sprintf('%s.log', date('Y-m-d')) as filename. And now you should know where to start... :)

Cannot read property length of undefined

perhaps, you can first determine if the DOM does really exists,

function walkmydog() {
    //when the user starts entering
    var dom = document.getElementById('WallSearch');
    if(dom == null){
        alert('sorry, WallSearch DOM cannot be found');
        return false;    

    if(dom.value.length == 0){

if (document.addEventListener){
    document.addEventListener("DOMContentLoaded", walkmydog, false);

How can one see the structure of a table in SQLite?

If you are using PHP you can get it this way:

    $dbname = 'base.db';
    $db = new SQLite3($dbname);
    $sturturequery = $db->query("SELECT sql FROM sqlite_master WHERE name='foo'");

    $table = $sturturequery->fetchArray();
    echo '<pre>' . $table['sql'] . '</pre>';


How do I install and use the ASP.NET AJAX Control Toolkit in my .NET 3.5 web applications?

Install the ASP.NET AJAX Control Toolkit

  1. Download the ZIP file from the ASP.NET AJAX Control Toolkit Releases page of the CodePlex web site.

  2. Copy the contents of this zip file directly into the bin directory of your web site.

Update web.config

  1. Put this in your web.config under the <controls> section:

    <?xml version="1.0"?>
                    <add tagPrefix="ajaxtoolkit"

Setup Visual Studio

  1. Right-click on the Toolbox and select "Add Tab", and add a tab called "AJAX Control Toolkit"

  2. Inside that tab, right-click on the Toolbox and select "Choose Items..."

  3. When the "Choose Toolbox Items" dialog appears, click the "Browse..." button. Navigate to your project's "bin" folder. Inside that folder, select "AjaxControlToolkit.dll" and click OK. Click OK again to close the Choose Items Dialog.

You can now use the controls in your web sites!

Getting the client's time zone (and offset) in JavaScript

you can simply try this. it will return you current machine time

var _d = new Date(), t = 0, d = new Date(t*1000 + _d.getTime())

Shorter syntax for casting from a List<X> to a List<Y>?

dynamic data = List<x> val;  
List<y> val2 = ((IEnumerable)data).Cast<y>().ToList();

jQuery preventDefault() not triggered

If you already test with a submit action, you have noticed that not works too.

The reason is the form is alread posted in a $(document).read(...

So, all you need to do is change that to $(document).load(...

Now, in the moment of you browaser load the page, he will execute.

And will work ;D

Cannot ignore .idea/workspace.xml - keeps popping up

Same problem for me with PHPStorm

Finally I solved doing the following:

  • Remove .idea/ directory
  • Move .gitignore to the same level will be the new generated .idea/
  • Write the files you need to be ignored, and .idea/ too. To be sure it will be ignored I put the following:

    • .idea/
    • .idea
    • .idea/*

I don't know why works this way, maybe .gitignore need to be at the same level of .idea to can be ignored this directory.

Converting binary to decimal integer output

There is actually a much faster alternative to convert binary numbers to decimal, based on artificial intelligence (linear regression) model:

  1. Train an AI algorithm to convert 32-binary number to decimal based.
  2. Predict a decimal representation from 32-binary.

See example and time comparison below:

from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
import numpy as np

y = np.random.randint(0, 2**32, size=10_000)

def gen_x(y):
    _x = bin(y)[2:]
    n = 32 - len(_x)
    return [int(sym) for sym in '0'*n + _x]

X = np.array([gen_x(x) for x in y])

model = LinearRegression(), y)

def convert_bin_to_dec_ai(array):
    return model.predict(array)

y_pred = convert_bin_to_dec_ai(X)

Time comparison:

enter image description here

This AI solution converts numbers almost x10 times faster than conventional way!

Call Python script from bash with argument

use in the script:

echo $(python arg1 arg2) > /dev/null


python "string arg"  > /dev/null

The script will be executed without output.

DateTime's representation in milliseconds?

You're probably trying to convert to a UNIX-like timestamp, which are in UTC:

    new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)

This also avoids summertime issues, since UTC doesn't have those.

What is a semaphore?

So imagine everyone is trying to go to the bathroom and there's only a certain number of keys to the bathroom. Now if there's not enough keys left, that person needs to wait. So think of semaphore as representing those set of keys available for bathrooms (the system resources) that different processes (bathroom goers) can request access to.

Now imagine two processes trying to go to the bathroom at the same time. That's not a good situation and semaphores are used to prevent this. Unfortunately, the semaphore is a voluntary mechanism and processes (our bathroom goers) can ignore it (i.e. even if there are keys, someone can still just kick the door open).

There are also differences between binary/mutex & counting semaphores.

Check out the lecture notes at

Add to Array jQuery

push is a native javascript method. You could use it like this:

var array = [1, 2, 3];
array.push(4); // array now is [1, 2, 3, 4]
array.push(5, 6, 7); // array now is [1, 2, 3, 4, 5, 6, 7]

Executing a command stored in a variable from PowerShell

Here is yet another way without Invoke-Expression but with two variables (command:string and parameters:array). It works fine for me. Assume 7z.exe is in the system path.

$cmd = '7z.exe'
$prm = 'a', '-tzip', 'c:\temp\with space\', 'C:\TEMP\with space\changelog'

& $cmd $prm

If the command is known (7z.exe) and only parameters are variable then this will do

$prm = 'a', '-tzip', 'c:\temp\with space\', 'C:\TEMP\with space\changelog'

& 7z.exe $prm

BTW, Invoke-Expression with one parameter works for me, too, e.g. this works

$cmd = '& 7z.exe a -tzip "c:\temp\with space\" "C:\TEMP\with space\changelog"'

Invoke-Expression $cmd

P.S. I usually prefer the way with a parameter array because it is easier to compose programmatically than to build an expression for Invoke-Expression.

Return date as ddmmyyyy in SQL Server

select replace(convert(VARCHAR,getdate(),103),'/','')

select right(convert(VARCHAR,getdate(),112),2) + 
       substring(convert(VARCHAR,getdate(),112),5,2) + 

jQuery AJAX form using mail() PHP script sends email, but POST data from HTML form is undefined

There is no need to make a query string. Just put your values in an object and jQuery will take care of the rest for you.

var data = {
    name: $("#form_name").val(),
    email: $("#form_email").val(),
    message: $("#msg_text").val()
    type: "POST",
    url: "email.php",
    data: data,
    success: function(){

ASP.NET Core - Swashbuckle not creating swagger.json file

I was able to fix and understand my issue when I tried to go to the swagger.json URL location:


The page will show the error and reason why it is not found.

In my case, I saw that there was a misconfigured XML definition of one of my methods based on the error it returned:

NotSupportedException: HTTP method "GET" & path "api/Values/{id}" overloaded by actions - ...

vi/vim editor, copy a block (not usual action)

I found the below command much more convenient. If you want to copy lines from 6 to 12 and paste from the current cursor position.

:6,12 co .

If you want to copy lines from 6 to 12 and paste from 100th line.



Why doesn't java.util.Set have get(int index)?

I'm not sure if anybody has spelled it out exactly this way, but you need to understand the following:

There is no "first" element in a set.

Because, as others have said, sets have no ordering. A set is a mathematical concept that specifically does not include ordering.

Of course, your computer can't really keep a list of stuff that's not ordered in memory. It has to have some ordering. Internally it's an array or a linked list or something. But you don't really know what it is, and it doesn't really have a first element; the element that comes out "first" comes out that way by chance, and might not be first next time. Even if you took steps to "guarantee" a particular first element, it's still coming out by chance, because you just happened to get it right for one particular implementation of a Set; a different implementation might not work that way with what you did. And, in fact, you may not know the implementation you're using as well as you think you do.

People run into this ALL. THE. TIME. with RDBMS systems and don't understand. An RDBMS query returns a set of records. This is the same type of set from mathematics: an unordered collection of items, only in this case the items are records. An RDBMS query result has no guaranteed order at all unless you use the ORDER BY clause, but all the time people assume it does and then trip themselves up some day when the shape of their data or code changes slightly and triggers the query optimizer to work a different way and suddenly the results don't come out in the order they expect. These are typically the people who didn't pay attention in database class (or when reading the documentation or tutorials) when it was explained to them, up front, that query results do not have a guaranteed ordering.

Fastest way to get the first n elements of a List into an Array

Option 1 Faster Than Option 2

Because Option 2 creates a new List reference, and then creates an n element array from the List (option 1 perfectly sizes the output array). However, first you need to fix the off by one bug. Use < (not <=). Like,

String[] out = new String[n];
for(int i = 0; i < n; i++) {
    out[i] = in.get(i);

Does calling clone() on an array also clone its contents?

1D array of primitives does copy elements when it is cloned. This tempts us to clone 2D array(Array of Arrays).

Remember that 2D array clone doesn't work due to shallow copy implementation of clone().

public static void main(String[] args) {
    int row1[] = {0,1,2,3};
    int row2[] =  row1.clone();
    row2[0] = 10;
    System.out.println(row1[0] == row2[0]); // prints false

    int table1[][]={{0,1,2,3},{11,12,13,14}};
    int table2[][] = table1.clone();
    table2[0][0] = 100;
    System.out.println(table1[0][0] == table2[0][0]); //prints true

How to get a user's time zone?

You can use below code for getting current time zone

 func getCurrentTimeZone() -> String{

         return TimeZone.current.identifier


  let currentTimeZone = getCurrentTimeZone()

Merge a Branch into Trunk

If your working directory points to the trunk, then you should be able to merge your branch with:

svn merge https://HOST/repository/branches/branch_1

be sure to be to issue this command in the root directory of your trunk

How can I make a menubar fixed on the top while scrolling

This should get you started

 <div class="menuBar">
        <img class="logo" src="logo.jpg"/>
        <div class="nav"> 
                <li>Menu 2</li>
                <li>Menu 3</li>

.nav ul li{

How to retrieve a recursive directory and file list from PowerShell excluding some files and folders?

Commenting here as this seems to be the most popular answer on the subject for searching for files whilst excluding certain directories in powershell.

To avoid issues with post filtering of results (i.e. avoiding permission issues etc), I only needed to filter out top level directories and that is all this example is based on, so whilst this example doesn't filter child directory names, it could very easily be made recursive to support this, if you were so inclined.

Quick breakdown of how the snippet works

$folders << Uses Get-Childitem to query the file system and perform folder exclusion

$file << The pattern of the file I am looking for

foreach << Iterates the $folders variable performing a recursive search using the Get-Childitem command

$folders = Get-ChildItem -Path C:\ -Directory -Name -Exclude Folder1,"Folder 2"
$file = "*filenametosearchfor*.extension"

foreach ($folder in $folders) {
   Get-Childitem -Path "C:/$folder" -Recurse -Filter $file | ForEach-Object { Write-Output $_.FullName }

Spring Data: "delete by" is supported?

Yes , deleteBy method is supported To use it you need to annotate method with @Transactional

How to picture "for" loop in block representation of algorithm

The Algorithm for given flow chart :

enter image description here


Step :01

  • Start

Step :02 [Variable initialization]

  • Set counter: i<----K [Where K:Positive Number]

Step :03[Condition Check]

  • If condition True then Do your task, set i=i+N and go to Step :03 [Where N:Positive Number]
  • If condition False then go to Step :04


  • Stop

Spring Data and Native Query with pagination

Using "ORDER BY id DESC \n-- #pageable\n " instead of "ORDER BY id \n#pageable\n" worked for me with MS SQL SERVER

jQuery - hashchange event

try Mozilla official site:

cite as follow:

if ("onhashchange" in window) {
    alert("The browser supports the hashchange event!");

function locationHashChanged() {
    if (location.hash === "#somecoolfeature") {

window.onhashchange = locationHashChanged;

How to use source: function()... and AJAX in JQuery UI autocomplete

  source: function(request, response) {
      url: "api/listBasicsubject",
      dataType: "json",
      type: "post",
      data: {
        search: request.term
      success: function(data) {

        if (!data.length) {
          var result = [{
            label: 'Subject not found',
            value: response.term
        } else {
          response($.map(, function(item) {
            return {
              label: item.subject_name,
              value: item.subject_id
  change: function(event, ui) {
    if (ui.item == null) {

  minLength: 0,
  classes: {
    "ui-autocomplete": "auto_compl-cat"

  focus: function(event, ui) {
    // $("#subject_name").val(ui.item.label);



  select: function(event, ui) {
    if (ui.item.label == "Subject not found") {

      return false;
    //console.log( "Selected: " + ui.item.label + " aka " + ui.item.value);
    return false;

Even though JRE 8 is installed on my MAC -" No Java Runtime present,requesting to install " gets displayed in terminal

I have Mojave 10.14.6 and the only thing that did work for me was:

  • setting JAVA_HOME to the following:
export JAVA_HOME=/Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin/Contents/Home
  • source .bash_profile (or wherever you keep your vars, in my case .zshrc)

Hope it helps! You can now type java --version and it should work

keycloak Invalid parameter: redirect_uri

It seems that this problem can occur if you put whitespace in your Realm name. I had name set to Debugging Realm and I got this error. When I changed to DebuggingRealm it worked.

You can still have whitespace in the display name. Odd that keycloak doesn't check for this on admin input.

How to check if variable's type matches Type stored in a variable

You need to see if the Type of your instance is equal to the Type of the class. To get the type of the instance you use the GetType() method:




should do it. Obviously you could use '==' to do your comparison if you prefer.

Objective-C: Calling selectors with multiple arguments

Your method signature is:

- (void) myTest:(NSString *)

withAString happens to be the parameter (the name is misleading, it looks like it is part of the selector's signature).

If you call the function in this manner:

[self performSelector:@selector(myTest:) withObject:myString];

It will work.

But, as the other posters have suggested, you may want to rename the method:

- (void)myTestWithAString:(NSString*)aString;

And call:

[self performSelector:@selector(myTestWithAString:) withObject:myString];

Using Pandas to pd.read_excel() for multiple worksheets of the same workbook

You can also use the index for the sheet:

xls = pd.ExcelFile('path_to_file.xls')
sheet1 = xls.parse(0)

will give the first worksheet. for the second worksheet:

sheet2 = xls.parse(1)

How to reload .bash_profile from the command line?

Simply type source ~/.bash_profile

Alternatively, if you like saving keystrokes you can type . ~/.bash_profile

T-SQL: Opposite to string concatenation - how to split string into multiple records

I use this function (SQL Server 2005 and above).

create function [dbo].[Split]
    @string nvarchar(4000),
    @delimiter nvarchar(10)
returns @table table
    [Value] nvarchar(4000)
    declare @nextString nvarchar(4000)
    declare @pos int, @nextPos int

    set @nextString = ''
    set @string = @string + @delimiter

    set @pos = charindex(@delimiter, @string)
    set @nextPos = 1
    while (@pos <> 0)
        set @nextString = substring(@string, 1, @pos - 1)

        insert into @table

        set @string = substring(@string, @pos + len(@delimiter), len(@string))
        set @nextPos = @pos
        set @pos = charindex(@delimiter, @string)

How to open an existing project in Eclipse?

In case you closed multiple projects and trying to re-open all of them then in Project Explorer, select all projects. Go to Project -> Open Project.

Class extending more than one class Java?

Most of the answers given seem to assume that all the classes we are looking to inherit from are defined by us.

But what if one of the classes is not defined by us, i.e. we cannot change what one of those classes inherits from and therefore cannot make use of the accepted answer, what happens then?

Well the answer depends on if we have at least one of the classes having been defined by us. i.e. there exists a class A among the list of classes we would like to inherit from, where A is created by us.

In addition to the already accepted answer, I propose 3 more instances of this multiple inheritance problem and possible solutions to each.

Inheritance type 1

Ok say you want a class C to extend classes, A and B, where B is a class defined somewhere else, but A is defined by us. What we can do with this is to turn A into an interface then, class C can implement A while extending B.

class A {}
class B {} // Some external class
class C {}

Turns into

interface A {}
class AImpl implements A {}
class B {} // Some external class
class C extends B implements A

Inheritance type 2

Now say you have more than two classes to inherit from, well the same idea still holds - all but one of the classes has to be defined by us. So say we want class A to inherit from the following classes, B, C, ... X where X is a class which is external to us, i.e. defined somewhere else. We apply the same idea of turning all the other classes but the last into an interface then we can have:

interface B {}
class BImpl implements B {}
interface C {}
class CImpl implements C {}
class X {}
class A extends X implements B, C, ...

Inheritance type 3

Finally, there is also the case where you have just a bunch of classes to inherit from, but none of them are defined by you. This is a bit trickier, but it is doable by making use of delegation. Delegation allows a class A to pretend to be some other class B but any calls on A to some public method defined in B, actually delegates that call to an object of type B and the result is returned. This makes class A what I would call a Fat class

How does this help?

Well it's simple. You create an interface which specifies the public methods within the external classes which you would like to make use of, as well as methods within the new class you are creating, then you have your new class implement that interface. That may have sounded confusing, so let me explain better.

Initially we have the following external classes B, C, D, ..., X, and we want our new class A to inherit from all those classes.

class B {
    public void foo() {}

class C {
    public void bar() {}

class D {
    public void fooFoo() {}


class X {
    public String fooBar() {}

Next we create an interface A which exposes the public methods that were previously in class A as well as the public methods from the above classes

interface A {
    void doSomething(); // previously defined in A
    String fooBar(); // from class X
    void fooFoo(); // from class D
    void bar(); // from class C
    void foo(); // from class B

Finally, we create a class AImpl which implements the interface A.

class AImpl implements A {
    // It needs instances of the other classes, so those should be
    // part of the constructor
    public AImpl(B b, C c, D d, X x) {}
    ... // define the methods within the interface

And there you have it! This is sort of pseudo-inheritance because an object of type A is not a strict descendant of any of the external classes we started with but rather exposes an interface which defines the same methods as in those classes.

You might ask, why we didn't just create a class that defines the methods we would like to make use of, rather than defining an interface. i.e. why didn't we just have a class A which contains the public methods from the classes we would like to inherit from? This is done in order to reduce coupling. We don't want to have classes that use A to have to depend too much on class A (because classes tend to change a lot), but rather to rely on the promise given within the interface A.

Java Spring - How to use classpath to specify a file location?

looks like you have maven project and so resources are in classpath by

go for


How to exclude property from Json Serialization

If you are not so keen on having to decorate code with Attributes as I am, esp when you cant tell at compile time what will happen here is my solution.

Using the Javascript Serializer

    public static class JsonSerializerExtensions
        public static string ToJsonString(this object target,bool ignoreNulls = true)
            var javaScriptSerializer = new JavaScriptSerializer();
                javaScriptSerializer.RegisterConverters(new[] { new PropertyExclusionConverter(target.GetType(), true) });
            return javaScriptSerializer.Serialize(target);

        public static string ToJsonString(this object target, Dictionary<Type, List<string>> ignore, bool ignoreNulls = true)
            var javaScriptSerializer = new JavaScriptSerializer();
            foreach (var key in ignore.Keys)
                javaScriptSerializer.RegisterConverters(new[] { new PropertyExclusionConverter(key, ignore[key], ignoreNulls) });
            return javaScriptSerializer.Serialize(target);

public class PropertyExclusionConverter : JavaScriptConverter
        private readonly List<string> propertiesToIgnore;
        private readonly Type type;
        private readonly bool ignoreNulls;

        public PropertyExclusionConverter(Type type, List<string> propertiesToIgnore, bool ignoreNulls)
            this.ignoreNulls = ignoreNulls;
            this.type = type;
            this.propertiesToIgnore = propertiesToIgnore ?? new List<string>();

        public PropertyExclusionConverter(Type type, bool ignoreNulls)
            : this(type, null, ignoreNulls){}

        public override IEnumerable<Type> SupportedTypes
            get { return new ReadOnlyCollection<Type>(new List<Type>(new[] { this.type })); }

        public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
            var result = new Dictionary<string, object>();
            if (obj == null)
                return result;
            var properties = obj.GetType().GetProperties();
            foreach (var propertyInfo in properties)
                if (!this.propertiesToIgnore.Contains(propertyInfo.Name))
                    if(this.ignoreNulls && propertyInfo.GetValue(obj, null) == null)
                    result.Add(propertyInfo.Name, propertyInfo.GetValue(obj, null));
            return result;

        public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
            throw new NotImplementedException(); //Converter is currently only used for ignoring properties on serialization

Generate a random letter in Python

import string
import random

KEY_LEN = 20

def base_str():
    return (string.letters+string.digits)   
def key_gen():
    keylist = [random.choice(base_str()) for i in range(KEY_LEN)]
    return ("".join(keylist))

You can get random strings like this:


What does 'IISReset' do?

IISReset stops and restarts the entire web server (including non-ASP.NET apps)
Recycling an app pool will only affect applications running in that app pool.
Editing the web.config in a web application only affects that web application (recycles just that app).
Editing the machine.config on the machine will recycle all app pools running.

IIS will monitor the /bin directory of your application. Whenever a change is detected in those dlls, it will recycle the app and re-load those new dlls. It also monitors the web.config & machine.config in the same way and performs the same action for the applicable apps.

Can the Android drawable directory contain subdirectories?

Actually, on Android Studio it is possible. You can have nested resources as shown here :

enter image description here

There is also a plugin to group resources here.

I recommend to avoid this though.

How to indent/format a selection of code in Visual Studio Code with Ctrl + Shift + F

(This works at least up to version 1.52.0, 10 Dec 2020)

On macOS Visual Studio Code version 1.36.1 (2019)

Visual Studio Code version 1.36.1 (2019)

To auto-format the selection, use ?K ?F (the trick is that this is to be done in sequence, ?K first, followed by ?F).

Auto-format selection or document

To just indent (shift right) without auto-formatting, use ?]

Indent options

As in Keyboard Shortcuts (?K ?S, or from the menu as shown below)

Keyboard shortcuts

How to check if a socket is connected/disconnected in C#?

I made an extension method based on this MSDN article. This is how you can determine whether a socket is still connected.

public static bool IsConnected(this Socket client)
    bool blockingState = client.Blocking;

        byte[] tmp = new byte[1];

        client.Blocking = false;
        client.Send(tmp, 0, 0);
        return true;
    catch (SocketException e)
        // 10035 == WSAEWOULDBLOCK
        if (e.NativeErrorCode.Equals(10035))
            return true;
            return false;
        client.Blocking = blockingState;

Bad File Descriptor with Linux Socket write() Bad File Descriptor C

In general, when "Bad File Descriptor" is encountered, it means that the socket file descriptor you passed into the API is not valid, which has multiple possible reasons:

  1. The fd is already closed somewhere.
  2. The fd has a wrong value, which is inconsistent with the value obtained from socket() api

error CS0234: The type or namespace name 'Script' does not exist in the namespace 'System.Web'

Since JsonSerializer is deprecated in .Net 4.0+ I used to solve this issue.

NuGet- > Install-Package Newtonsoft.Json

How to resize images proportionally / keeping the aspect ratio?

Have a look at this piece of code from

$(document).ready(function() {
    $('.story-small img').each(function() {
        var maxWidth = 100; // Max width for the image
        var maxHeight = 100;    // Max height for the image
        var ratio = 0;  // Used for aspect ratio
        var width = $(this).width();    // Current image width
        var height = $(this).height();  // Current image height

        // Check if the current width is larger than the max
        if(width > maxWidth){
            ratio = maxWidth / width;   // get ratio for scaling image
            $(this).css("width", maxWidth); // Set new width
            $(this).css("height", height * ratio);  // Scale height based on ratio
            height = height * ratio;    // Reset height to match scaled image
            width = width * ratio;    // Reset width to match scaled image

        // Check if current height is larger than max
        if(height > maxHeight){
            ratio = maxHeight / height; // get ratio for scaling image
            $(this).css("height", maxHeight);   // Set new height
            $(this).css("width", width * ratio);    // Scale width based on ratio
            width = width * ratio;    // Reset width to match scaled image
            height = height * ratio;    // Reset height to match scaled image

How do I delete an item or object from an array using ng-click?

if you have ID or any specific field in your item, you can use filter(). its act like Where().

<a class="btn" ng-click="remove(item)">Delete</a>

in controller:

$scope.remove = function(item) { 
  $scope.bdays = $scope.bdays.filter(function (element) {
                    return element.ID!=item.ID

using wildcards in LDAP search filters/queries

Your best bet would be to anticipate prefixes, so:

"(|(displayName=SEARCHKEY*)(displayName=ITSM - SEARCHKEY*)(displayName=alt prefix - SEARCHKEY*))"

Clunky, but I'm doing a similar thing within my organization.

Reporting Services Remove Time from DateTime in Expression

Just use DateValue(Now) if you want the result to be of DateTime data type.

How to label each equation in align environment?

like this


x_{\rm L} & = L \int{\cos\theta\left(\xi\right) d\xi}, \label{eq_1} \\\\

y_{\rm L} & = L \int{\sin\theta\left(\xi\right) d\xi}, \nonumber


How to Navigate from one View Controller to another using Swift

If you don't want the back button to appear (which was my case, because I wanted to present after a user logged in) here is how to set the root of the nav controller:

let vc = self.storyboard?.instantiateViewControllerWithIdentifier("YourViewController") as! YourViewController
        let navigationController = UINavigationController(rootViewController: vc)
        self.presentViewController(navigationController, animated: true, completion: nil)

How do I display Ruby on Rails form validation error messages one at a time?

I resolved it like this:

<% @user.errors.each do |attr, msg| %>
    <%= @user.errors.full_messages_for(attr).first if @user.errors[attr].first == msg %>
<% end %>

This way you are using the locales for the error messages.

When should I use a List vs a LinkedList

When you need built-in indexed access, sorting (and after this binary searching), and "ToArray()" method, you should use List.

How to make HTML open a hyperlink in another window or tab?

The target attribute is your best way of doing this.

<a href="" target="_blank">

will open it in a new tab or window. As for which, it depends on the users settings.

<a href="" target="_self">

is default. It makes the page open in the same tab (or iframe, if that's what you're dealing with).
The next two are only good if you're dealing with an iframe.

<a href="" target="_parent">

will open the link in the iframe that the iframe that had the link was in.

<a href="" target="_top">

will open the link in the tab, no matter how many iframes it has to go through.

True and False for && logic and || Logic table

I think You ask for Boolean algebra which describes the output of various operations performed on boolean variables. Just look at the article on Wikipedia.