Programs & Examples On #Database theory

Default value for field in Django model

Set editable to False and default to your default value.

http://docs.djangoproject.com/en/stable/ref/models/fields/#editable

b = models.CharField(max_length=7, default='0000000', editable=False)

Also, your id field is unnecessary. Django will add it automatically.

How can I have two fixed width columns with one flexible column in the center?

Compatibility with older browsers can be a drag, so be adviced.

If that is not a problem then go ahead. Run the snippet. Go to full page view and resize. Center will resize itself with no changes to the left or right divs.

Change left and right values to meet your requirement.

Thank you.

Hope this helps.

_x000D_
_x000D_
#container {_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
.column.left {_x000D_
  width: 100px;_x000D_
  flex: 0 0 100px;_x000D_
}_x000D_
_x000D_
.column.right {_x000D_
  width: 100px;_x000D_
  flex: 0 0 100px;_x000D_
}_x000D_
_x000D_
.column.center {_x000D_
  flex: 1;_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
.column.left,_x000D_
.column.right {_x000D_
  background: orange;_x000D_
  text-align: center;_x000D_
}
_x000D_
<div id="container">_x000D_
  <div class="column left">this is left</div>_x000D_
  <div class="column center">this is center</div>_x000D_
  <div class="column right">this is right</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

npm ERR cb() never called

Updating the NodeJS https://nodejs.org/en/ Fixed My Issue.

Run npm install -g npm & npm cache clean

jQuery not working with IE 11

Thanks @Arnaud & @Conny for highlighting this answer. This really helped me. I would like to add one more thing here is, adding this line <meta http-equiv="x-ua-compatible" content="IE=edge"> just after the title in tag prior to all meta tags is must for to work as it overrides the compatibility mode of IE.

Embed HTML5 YouTube video without iframe?

Here is a example of embedding without an iFrame:

_x000D_
_x000D_
<div style="width: 560px; height: 315px; float: none; clear: both; margin: 2px auto;">
  <embed
    src="https://www.youtube.com/embed/J---aiyznGQ?autohide=1&autoplay=1"
    wmode="transparent"
    type="video/mp4"
    width="100%" height="100%"
    allow="autoplay; encrypted-media; picture-in-picture"
    allowfullscreen
    title="Keyboard Cat"
  >
</div>
_x000D_
_x000D_
_x000D_

compare to regular iframe "embed" code from YouTube:

_x000D_
_x000D_
<iframe
  width="560"
  height="315"
  src="https://www.youtube.com/embed/J---aiyznGQ?autoplay=1"
  frameborder="0"
  allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
  allowfullscreen>
</iframe>
_x000D_
_x000D_
_x000D_

and as far as HTML5 goes, use <object> tag like so (corrected):

_x000D_
_x000D_
<object
  style="width: 820px; height: 461.25px; float: none; clear: both; margin: 2px auto;"
  data="http://www.youtube.com/embed/J---aiyznGQ?autoplay=1">
</object>
_x000D_
_x000D_
_x000D_

Calling a stored procedure in Oracle with IN and OUT parameters

I had the same problem. I used a trigger and in that trigger I called a procedure which computed some values into 2 OUT variables. When I tried to print the result in the trigger body, nothing showed on screen. But then I solved this problem by making 2 local variables in a function, computed what I need with them and finally, copied those variables in your OUT procedure variables. I hope it'll be useful and successful!

Store images in a MongoDB database

You can try this one:

String newFileName = "my-image";
File imageFile = new File("/users/victor/images/image.png");
GridFS gfsPhoto = new GridFS(db, "photo");
GridFSInputFile gfsFile = gfsPhoto.createFile(imageFile);
gfsFile.setFilename(newFileName);
gfsFile.save();

How to edit nginx.conf to increase file size upload

You can increase client_max_body_size and upload_max_filesize + post_max_size all day long. Without adjusting HTTP timeout it will never work.

//You need to adjust this, and probably on PHP side also. client_body_timeout 2min // 1GB fileupload

How to lazy load images in ListView in Android

Novoda also has a great lazy image loading library and many apps like Songkick, Podio, SecretDJ and ImageSearch use their library.

Their library is hosted here on Github and they have a pretty active issues tracker as well. Their project seems to be pretty active too, with over 300+ commits at the time of writing this reply.

Pointer to incomplete class type is not allowed

One thing to check for...

If your class is defined as a typedef:

typedef struct myclass { };

Then you try to refer to it as struct myclass anywhere else, you'll get Incomplete Type errors left and right. It's sometimes a mistake to forget the class/struct was typedef'ed. If that's the case, remove "struct" from:

typedef struct mystruct {}...

struct mystruct *myvar = value;

Instead use...

mystruct *myvar = value;

Common mistake.

How to get last 7 days data from current datetime to last 7 days in sql server

Try something like:

 SELECT id, NewsHeadline as news_headline, NewsText as news_text, state CreatedDate as created_on
 FROM News 
 WHERE CreatedDate >= DATEADD(day,-7, GETDATE())

How to simulate a click by using x,y coordinates in JavaScript?

For security reasons, you can't move the mouse pointer with javascript, nor simulate a click with it.

What is it that you are trying to accomplish?

Print the data in ResultSet along with column names

1) Instead of PreparedStatement use Statement

2) After executing query in ResultSet, extract values with the help of rs.getString() as :

Statement st=cn.createStatement();
ResultSet rs=st.executeQuery(sql);
while(rs.next())
{
    rs.getString(1); //or rs.getString("column name");
}

Ruby: kind_of? vs. instance_of? vs. is_a?

What is the difference?

From the documentation:

- (Boolean) instance_of?(class)
Returns true if obj is an instance of the given class.

and:

- (Boolean) is_a?(class)
- (Boolean) kind_of?(class)
Returns true if class is the class of obj, or if class is one of the superclasses of obj or modules included in obj.

If that is unclear, it would be nice to know what exactly is unclear, so that the documentation can be improved.

When should I use which?

Never. Use polymorphism instead.

Why are there so many of them?

I wouldn't call two "many". There are two of them, because they do two different things.

FTP/SFTP access to an Amazon S3 Bucket

As other posters have pointed out, there are some limitations with the AWS Transfer for SFTP service. You need to closely align requirements. For example, there are no quotas, whitelists/blacklists, file type limits, and non key based access requires external services. There is also a certain overhead relating to user management and IAM, which can get to be a pain at scale.

We have been running an SFTP S3 Proxy Gateway for about 5 years now for our customers. The core solution is wrapped in a collection of Docker services and deployed in whatever context is needed, even on-premise or local development servers. The use case for us is a little different as our solution is focused data processing and pipelines vs a file share. In a Salesforce example, a customer will use SFTP as the transport method sending email, purchase...data to an SFTP/S3 enpoint. This is mapped an object key on S3. Upon arrival, the data is picked up, processed, routed and loaded to a warehouse. We also have fairly significant auditing requirements for each transfer, something the Cloudwatch logs for AWS do not directly provide.

As other have mentioned, rolling your own is an option too. Using AWS Lightsail you can setup a cluster, say 4, of $10 2GB instances using either Route 53 or an ELB.

In general, it is great to see AWS offer this service and I expect it to mature over time. However, depending on your use case, alternative solutions may be a better fit.

Change drawable color programmatically

I have wrote a generic function in which you can pass context, icon is id drawable/mipmap image icon and new color which you need for that icon.

This function returns a drawable.

public static Drawable changeDrawableColor(Context context,int icon, int newColor) {
    Drawable mDrawable = ContextCompat.getDrawable(context, icon).mutate(); 
    mDrawable.setColorFilter(new PorterDuffColorFilter(newColor, PorterDuff.Mode.SRC_IN)); 
    return mDrawable;
} 

changeDrawableColor(getContext(),R.mipmap.ic_action_tune, Color.WHITE);

Variable used in lambda expression should be final or effectively final

A final variable means that it can be instantiated only one time. in Java you can't use non-final variables in lambda as well as in anonymous inner classes.

You can refactor your code with the old for-each loop:

private TimeZone extractCalendarTimeZoneComponent(Calendar cal,TimeZone calTz) {
    try {
        for(Component component : cal.getComponents().getComponents("VTIMEZONE")) {
        VTimeZone v = (VTimeZone) component;
           v.getTimeZoneId();
           if(calTz==null) {
               calTz = TimeZone.getTimeZone(v.getTimeZoneId().getValue());
           }
        }
    } catch (Exception e) {
        log.warn("Unable to determine ical timezone", e);
    }
    return null;
}

Even if I don't get the sense of some pieces of this code:

  • you call a v.getTimeZoneId(); without using its return value
  • with the assignment calTz = TimeZone.getTimeZone(v.getTimeZoneId().getValue()); you don't modify the originally passed calTz and you don't use it in this method
  • You always return null, why don't you set void as return type?

Hope also these tips helps you to improve.

How to switch to other branch in Source Tree to commit the code?

  1. Go to the log view (to be able to go here go to View -> log view).
  2. Double click on the line with the branch label stating that branch. Automatically, it will switch branch. (A prompt will dropdown and say switching branch.)
  3. If you have two or more branches on the same line, it will ask you via prompt which branch you want to switch. Choose the specific branch from the dropdown and click ok.

To determine which branch you are now on, look at the side bar, under BRANCHES, you are in the branch that is in BOLD LETTERS.

How to list files in a directory in a C program?

Below code will only print files within directory and exclude directories within given directory while traversing.

#include <dirent.h>
#include <stdio.h>
#include <errno.h>
#include <sys/stat.h>
#include<string.h>
int main(void)
{
    DIR *d;
    struct dirent *dir;
    char path[1000]="/home/joy/Downloads";
    d = opendir(path);
    char full_path[1000];
    if (d)
    {
        while ((dir = readdir(d)) != NULL)
        {
            //Condition to check regular file.
            if(dir->d_type==DT_REG){
                full_path[0]='\0';
                strcat(full_path,path);
                strcat(full_path,"/");
                strcat(full_path,dir->d_name);
                printf("%s\n",full_path);
            }
        }
        closedir(d);
    }
    return(0);     
}

Android - How to decode and decompile any APK file?

To decompile APK Use APKTool.
You can learn how APKTool works on http://www.decompileandroid.com/ or by reading the documentation.

Given an RGB value, how do I create a tint (or shade)?

Some definitions

  • A shade is produced by "darkening" a hue or "adding black"
  • A tint is produced by "ligthening" a hue or "adding white"

Creating a tint or a shade

Depending on your Color Model, there are different methods to create a darker (shaded) or lighter (tinted) color:

  • RGB:

    • To shade:

      newR = currentR * (1 - shade_factor)
      newG = currentG * (1 - shade_factor)
      newB = currentB * (1 - shade_factor)
      
    • To tint:

      newR = currentR + (255 - currentR) * tint_factor
      newG = currentG + (255 - currentG) * tint_factor
      newB = currentB + (255 - currentB) * tint_factor
      
    • More generally, the color resulting in layering a color RGB(currentR,currentG,currentB) with a color RGBA(aR,aG,aB,alpha) is:

      newR = currentR + (aR - currentR) * alpha
      newG = currentG + (aG - currentG) * alpha
      newB = currentB + (aB - currentB) * alpha
      

    where (aR,aG,aB) = black = (0,0,0) for shading, and (aR,aG,aB) = white = (255,255,255) for tinting

  • HSV or HSB:

    • To shade: lower the Value / Brightness or increase the Saturation
    • To tint: lower the Saturation or increase the Value / Brightness
  • HSL:
    • To shade: lower the Lightness
    • To tint: increase the Lightness

There exists formulas to convert from one color model to another. As per your initial question, if you are in RGB and want to use the HSV model to shade for example, you can just convert to HSV, do the shading and convert back to RGB. Formula to convert are not trivial but can be found on the internet. Depending on your language, it might also be available as a core function :

Comparing the models

  • RGB has the advantage of being really simple to implement, but:
    • you can only shade or tint your color relatively
    • you have no idea if your color is already tinted or shaded
  • HSV or HSB is kind of complex because you need to play with two parameters to get what you want (Saturation & Value / Brightness)
  • HSL is the best from my point of view:
    • supported by CSS3 (for webapp)
    • simple and accurate:
      • 50% means an unaltered Hue
      • >50% means the Hue is lighter (tint)
      • <50% means the Hue is darker (shade)
    • given a color you can determine if it is already tinted or shaded
    • you can tint or shade a color relatively or absolutely (by just replacing the Lightness part)

How to create a unique index on a NULL column?

The calculated column trick is widely known as a "nullbuster"; my notes credit Steve Kass:

CREATE TABLE dupNulls (
pk int identity(1,1) primary key,
X  int NULL,
nullbuster as (case when X is null then pk else 0 end),
CONSTRAINT dupNulls_uqX UNIQUE (X,nullbuster)
)

How to create a .gitignore file

If you're using Windows it will not let you create a file without a filename in Windows Explorer. It will give you the error "You must type a file name" if you try to rename a text file as .gitignore

enter image description here

To get around this I used the following steps

  1. Create the text file gitignore.txt
  2. Open it in a text editor and add your rules, then save and close
  3. Hold SHIFT, right click the folder you're in, then select Open command window here
  4. Then rename the file in the command line, with ren gitignore.txt .gitignore

Alternatively @HenningCash suggests in the comments

You can get around this Windows Explorer error by appending a dot to the filename without extension: .gitignore. will be automatically changed to .gitignore

Declare and assign multiple string variables at the same time

You can to do it this way:

string Camnr = "", Klantnr = "", ... // or String.Empty

Or you could declare them all first and then in the next line use your way.

How to find the foreach index?

These two loops are equivalent (bar the safety railings of course):

for ($i=0; $i<count($things); $i++) { ... }

foreach ($things as $i=>$thing) { ... }

eg

for ($i=0; $i<count($things); $i++) {
    echo "Thing ".$i." is ".$things[$i];
}

foreach ($things as $i=>$thing) {
    echo "Thing ".$i." is ".$thing;
}

Python Pandas : group by in group by and average?

I would simply do this, which literally follows what your desired logic was:

df.groupby(['org']).mean().groupby(['cluster']).mean()

css width: calc(100% -100px); alternative using jquery

Its not that hard to replicate in javascript :-) , though it will only work for width and height the best but you can expand it as per your expectations :-)

function calcShim(element,property,expression){
    var calculated = 0;
    var freed_expression = expression.replace(/ /gi,'').replace("(","").replace(")","");
    // Remove all the ( ) and spaces 
    // Now find the parts 
    var parts = freed_expression.split(/[\*+-\/]/gi);

    var units = {
        'px':function(quantity){
            var part = 0;
            part = parseFloat(quantity,10);
            return part;
        },
        '%':function(quantity){
            var part = 0,
            parentQuantity = parseFloat(element.parent().css(property));
            part = parentQuantity * ((parseFloat(quantity,10))/100);
            return part;
        } // you can always add more units here.
    }

    for( var i = 0; i < parts.length; i++ ){
        for( var unit in units ){
            if( parts[i].indexOf(unit) != -1 ){
               // replace the expression by calculated part.
               expression = expression.replace(parts[i],units[unit](parts[i]));
               break;
            }
        }
    }
    // And now compute it. though eval is evil but in some cases its a good friend.
    // Though i wish there was math. calc
    element.css(property,eval(expression));
}

How do I use su to execute the rest of the bash script as that user?

Here is yet another approach, which was more convenient in my case (I just wanted to drop root privileges and do the rest of my script from restricted user): you can make the script restart itself from correct user. Let's suppose it is run as root initially. Then it will look like this:

#!/bin/bash
if [ $UID -eq 0 ]; then
  user=$1
  dir=$2
  shift 2     # if you need some other parameters
  cd "$dir"
  exec su "$user" "$0" -- "$@"
  # nothing will be executed beyond that line,
  # because exec replaces running process with the new one
fi

echo "This will be run from user $UID"
...

How do I redirect output to a variable in shell?

TL;DR

To store "abc" into $foo:

echo "abc" | read foo

But, because pipes create forks, you have to use $foo before the pipe ends, so...

echo "abc" | ( read foo; date +"I received $foo on %D"; )

Sure, all these other answers show ways to not do what the OP asked, but that really screws up the rest of us who searched for the OP's question.

The answer to the question is to use the read command.

Here's how you do it

# I would usually do this on one line, but for readability...
series | of | commands \
| \
(
  read string;
  mystic_command --opt "$string" /path/to/file
) \
| \
handle_mystified_file

Here is what it is doing and why it is important:

  1. Let's pretend that the series | of | commands is a very complicated series of piped commands.

  2. mystic_command can accept the content of a file as stdin in lieu of a file path, but not the --opt arg therefore it must come in as a variable. The command outputs the modified content and would commonly be redirected into a file or piped to another command. (E.g. sed, awk, perl, etc.)

  3. read takes stdin and places it into the variable $string

  4. Putting the read and the mystic_command into a "sub shell" via parenthesis is not necessary but makes it flow like a continuous pipe as if the 2 commands where in a separate script file.

There is always an alternative, and in this case the alternative is ugly and unreadable compared to my example above.

# my example above as a oneliner
series | of | commands | (read string; mystic_command --opt "$string" /path/to/file) | handle_mystified_file

# ugly and unreadable alternative
mystic_command --opt "$(series | of | commands)" /path/to/file | handle_mystified_file

My way is entirely chronological and logical. The alternative starts with the 4th command and shoves commands 1, 2, and 3 into command substitution.

I have a real world example of this in this script but I didn't use it as the example above because it has some other crazy/confusing/distracting bash magic going on also.

How can I capture the right-click event in JavaScript?

Use the oncontextmenu event.

Here's an example:

<div oncontextmenu="javascript:alert('success!');return false;">
    Lorem Ipsum
</div>

And using event listeners (credit to rampion from a comment in 2011):

el.addEventListener('contextmenu', function(ev) {
    ev.preventDefault();
    alert('success!');
    return false;
}, false);

Don't forget to return false, otherwise the standard context menu will still pop up.

If you are going to use a function you've written rather than javascript:alert("Success!"), remember to return false in BOTH the function AND the oncontextmenu attribute.

Difference between HashMap and Map in Java..?

Map is an interface; HashMap is a particular implementation of that interface.

HashMap uses a collection of hashed key values to do its lookup. TreeMap will use a red-black tree as its underlying data store.

Close/kill the session when the browser or tab is closed

As said, the browser doesn't let the server know when it closes.

Still, there are some ways to achieve close to this behavior. You can put a small AJAX script in place that updates the server regularly that the browser is open. You should pair this with something that fires on actions made by the user, so you can time out an idle session as well as one that has closed out.

Append data to a POST NSURLRequest

 NSURL *url= [NSURL URLWithString:@"https://www.paypal.com/cgi-bin/webscr"];
 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
                                                        cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                    timeoutInterval:10.0];
[request setHTTPMethod:@"POST"];
 NSString *postString = @"userId=2323";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];

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

The XML declaration in the document map consists of the following:

The version number, ?xml version="1.0"?. 

This is mandatory. Although the number might change for future versions of XML, 1.0 is the current version.

The encoding declaration,

encoding="UTF-8"?

This is optional. If used, the encoding declaration must appear immediately after the version information in the XML declaration, and must contain a value representing an existing character encoding.

C error: undefined reference to function, but it IS defined

How are you doing the compiling and linking? You'll need to specify both files, something like:

gcc testpoint.c point.c

...so that it knows to link the functions from both together. With the code as it's written right now, however, you'll then run into the opposite problem: multiple definitions of main. You'll need/want to eliminate one (undoubtedly the one in point.c).

In a larger program, you typically compile and link separately to avoid re-compiling anything that hasn't changed. You normally specify what needs to be done via a makefile, and use make to do the work. In this case you'd have something like this:

OBJS=testpoint.o point.o

testpoint.exe: $(OBJS)
    gcc $(OJBS)

The first is just a macro for the names of the object files. You get it expanded with $(OBJS). The second is a rule to tell make 1) that the executable depends on the object files, and 2) telling it how to create the executable when/if it's out of date compared to an object file.

Most versions of make (including the one in MinGW I'm pretty sure) have a built-in "implicit rule" to tell them how to create an object file from a C source file. It normally looks roughly like this:

.c.o:
    $(CC) -c $(CFLAGS) $<

This assumes the name of the C compiler is in a macro named CC (implicitly defined like CC=gcc) and allows you to specify any flags you care about in a macro named CFLAGS (e.g., CFLAGS=-O3 to turn on optimization) and $< is a special macro that expands to the name of the source file.

You typically store this in a file named Makefile, and to build your program, you just type make at the command line. It implicitly looks for a file named Makefile, and runs whatever rules it contains.

The good point of this is that make automatically looks at the timestamps on the files, so it will only re-compile the files that have changed since the last time you compiled them (i.e., files where the ".c" file has a more recent time-stamp than the matching ".o" file).

Also note that 1) there are lots of variations in how to use make when it comes to large projects, and 2) there are also lots of alternatives to make. I've only hit on the bare minimum of high points here.

Node / Express: EADDRINUSE, Address already in use - Kill server

server.close() takes a while to close the connection, thus we should make this an asynchronous call as such:

await server.close();

IMPORTANT: when using await, we must use the async keyword in our encapsulating function as such:

async () => {
  await server.close();
}

How can I escape white space in a bash loop list?

First, don't do it that way. The best approach is to use find -exec properly:

# this is safe
find test -type d -exec echo '{}' +

The other safe approach is to use NUL-terminated list, though this requires that your find support -print0:

# this is safe
while IFS= read -r -d '' n; do
  printf '%q\n' "$n"
done < <(find test -mindepth 1 -type d -print0)

You can also populate an array from find, and pass that array later:

# this is safe
declare -a myarray
while IFS= read -r -d '' n; do
  myarray+=( "$n" )
done < <(find test -mindepth 1 -type d -print0)
printf '%q\n' "${myarray[@]}" # printf is an example; use it however you want

If your find doesn't support -print0, your result is then unsafe -- the below will not behave as desired if files exist containing newlines in their names (which, yes, is legal):

# this is unsafe
while IFS= read -r n; do
  printf '%q\n' "$n"
done < <(find test -mindepth 1 -type d)

If one isn't going to use one of the above, a third approach (less efficient in terms of both time and memory usage, as it reads the entire output of the subprocess before doing word-splitting) is to use an IFS variable which doesn't contain the space character. Turn off globbing (set -f) to prevent strings containing glob characters such as [], * or ? from being expanded:

# this is unsafe (but less unsafe than it would be without the following precautions)
(
 IFS=$'\n' # split only on newlines
 set -f    # disable globbing
 for n in $(find test -mindepth 1 -type d); do
   printf '%q\n' "$n"
 done
)

Finally, for the command-line parameter case, you should be using arrays if your shell supports them (i.e. it's ksh, bash or zsh):

# this is safe
for d in "$@"; do
  printf '%s\n' "$d"
done

will maintain separation. Note that the quoting (and the use of $@ rather than $*) is important. Arrays can be populated in other ways as well, such as glob expressions:

# this is safe
entries=( test/* )
for d in "${entries[@]}"; do
  printf '%s\n' "$d"
done

Is it not possible to stringify an Error using JSON.stringify?

I was working on a JSON format for log appenders and ended up here trying to solve a similar problem. After a while, I realized I could just make Node do the work:

const util = require("util");
...
return JSON.stringify(obj, (name, value) => {
    if (value instanceof Error) {
        return util.format(value);
    } else {
        return value;
    }
}

MySQL Foreign Key Error 1005 errno 150 primary key as foreign key

When a there are 2 columns for primary keys they make up a composite primary key therefore you have to make sure that in the table that is being referenced there are also 2 columns of the same data type.

How to fix/convert space indentation in Sublime Text?

While many of the suggestions work when converting 2 -> 4 space. I ran into some issues when converting 4 -> 2.

Here's what I ended up using:

Sublime Text 3/Packages/User/to-2.sublime-macro

[
  { "args": null, "command": "select_all" },
  { "args": { "set_translate_tabs": true }, "command": "unexpand_tabs" },
  { "args": { "setting": "tab_size", "value": 1 }, "command": "set_setting" },
  { "args": { "set_translate_tabs": true }, "command": "expand_tabs" },
  { "args": { "setting": "tab_size", "value": 2 }, "command": "set_setting" }
]

Display QImage with QtGui

Drawing an image using a QLabel seems like a bit of a kludge to me. With newer versions of Qt you can use a QGraphicsView widget. In Qt Creator, drag a Graphics View widget onto your UI and name it something (it is named mainImage in the code below). In mainwindow.h, add something like the following as private variables to your MainWindow class:

QGraphicsScene *scene;
QPixmap image;

Then just edit mainwindow.cpp and make the constructor something like this:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    image.load("myimage.png");
    scene = new QGraphicsScene(this);
    scene->addPixmap(image);
    scene->setSceneRect(image.rect());

    ui->mainImage->setScene(scene);
}

iPad WebApp Full Screen in Safari

  1. First, launch your Safari browser from the Home screen and go to the webpage that you want to view full screen.

  2. After locating the webpage, tap on the arrow icon at the top of your screen.

  3. In the drop-down menu, tap on the Add to Home Screen option.

  4. The Add to Home window should be displayed. You can customize the description that will appear as a title on the home screen of your iPad. When you are done, tap on the Add button.

  5. A new icon should now appear on your home screen. Tapping on the icon will open the webpage in the fullscreen mode.

Note: The icon on your iPad home screen only opens the bookmarked page in the fullscreen mode. The next page you visit will be contain the Safari address and title bars. This way of playing your webpage or HTML5 presentation in the fullscreen mode works if the source code of the webpage contains the following tag:

<meta name="apple-mobile-web-app-capable" content="yes">

You can add this tag to your webpage using a third-party tool, for example iWeb SEO Tool or any other you like. Please note that you need to add the tag first, refresh the page and then add a bookmark to your home screen.

How to specify the JDK version in android studio?

In Android Studio 4.0.1, Help -> About shows the details of the Java version used by the studio, in my case:

Android Studio 4.0.1
Build #AI-193.6911.18.40.6626763, built on June 25, 2020
Runtime version: 1.8.0_242-release-1644-b01 amd64
VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Windows 10 10.0
GC: ParNew, ConcurrentMarkSweep
Memory: 1237M
Cores: 8
Registry: ide.new.welcome.screen.force=true
Non-Bundled Plugins: com.google.services.firebase

Decimal values in SQL for dividing results

Just another approach:

SELECT col1 * 1.0 / col2 FROM tbl1

Multiplying by 1.0 turns an integer into a float numeric(13,1) and so works like a typecast, but most probably it is slower than that.

A slightly shorter variation suggested by Aleksandr Fedorenko in a comment:

SELECT col1 * 1. / col2 FROM tbl1

The effect would be basically the same. The only difference is that the multiplication result in this case would be numeric(12,0).

Principal advantage: less wordy than other approaches.

Can Google Chrome open local links?

From what I've seen of this the following is true for Firefox and Chrome;

1) If you have a HTML page open from a remote host then file:// links will not work i.e. Your address bar reads http://someserver.domain and the page contains a link such as <a href="file:///S:/sharedfile.txt">

2) If you have a HTML page open from your local host then file:// links will work i.e. your address bar reads file:///C:/mydir/index.html and the page contains a link such as <a href="file:///S:/sharedfile.txt">

For Internet Explorer point 1) does not hold true. A file on your local host can be accessed using the file:// link syntax from a webpage on a remote host. This is considered a security flaw in IE(By who? References?) (and it's there in IE8 too) because a remote host can access files on your local computer without your knowledge .... admittedly they have to get lucky with the filename but there are plenty of commonly named files there with the potential to contain personal/private information.

Saving and Reading Bitmaps/Images from Internal memory in Android

For Kotlin users, I created a ImageStorageManager class which will handle save, get and delete actions for images easily:

class ImageStorageManager {
    companion object {
        fun saveToInternalStorage(context: Context, bitmapImage: Bitmap, imageFileName: String): String {
            context.openFileOutput(imageFileName, Context.MODE_PRIVATE).use { fos ->
                bitmapImage.compress(Bitmap.CompressFormat.PNG, 25, fos)
            }
            return context.filesDir.absolutePath
        }

        fun getImageFromInternalStorage(context: Context, imageFileName: String): Bitmap? {
            val directory = context.filesDir
            val file = File(directory, imageFileName)
            return BitmapFactory.decodeStream(FileInputStream(file))
        }

        fun deleteImageFromInternalStorage(context: Context, imageFileName: String): Boolean {
            val dir = context.filesDir
            val file = File(dir, imageFileName)
            return file.delete()
        }
    }
}

Read more here

When to use the !important property in CSS

Strictly speaking you shouldn't need to use !important if you've structured your CSS well and don't have too many degrees of specificity.

The most appropriate time to use !important is when you have one exceptional style that you want to style outside of your site's normal cascade.

Inserting data into a temporary table

The right query:

drop table #tmp_table

select new_acc_no, count(new_acc_no) as count1
into #tmp_table
from table
where unit_id = '0007' 
group by unit_id, new_acc_no
having count(new_acc_no) > 1

What does += mean in Python?

a += b

is in this case the same as

a = a + b

In this case cnt += 1 means that cnt is increased by one.

Note that the code you pasted will loop indefinitely if cnt > 0 and len(aStr) > 1.

Edit: quote Carl Meyer: ``[..] the answer is misleadingly mostly correct. There is a subtle but very significant difference between + and +=, see Bastien's answer.''.

What is the Windows equivalent of the diff command?

The windows equivalent to the diff command is the fc (File Comapre) command.

Here are the basic steps to do so:
1. Keep the two files in a folder (Example file1.html and file2.html)
2. Launch command prompt
3. Type fc file1Location file2Location

Have found a detailed tutorial on the same:

http://www.howtogeek.com/206123/how-to-use-fc-file-compare-from-the-windows-command-prompt/

How to check if matching text is found in a string in Lua?

There are 2 options to find matching text; string.match or string.find.

Both of these perform a regex search on the string to find matches.


string.find()

string.find(subject string, pattern string, optional start position, optional plain flag)

Returns the startIndex & endIndex of the substring found.

The plain flag allows for the pattern to be ignored and intead be interpreted as a literal. Rather than (tiger) being interpreted as a regex capture group matching for tiger, it instead looks for (tiger) within a string.

Going the other way, if you want to regex match but still want literal special characters (such as .()[]+- etc.), you can escape them with a percentage; %(tiger%).

You will likely use this in combination with string.sub

Example

str = "This is some text containing the word tiger."
if string.find(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

string.match()

string.match(s, pattern, optional index)

Returns the capture groups found.

Example

str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

How to import Maven dependency in Android Studio/IntelliJ?

  1. Uncheck "Offline work" in File>Settings>Gradle>Global Gradle Settings
  2. Resync the project, for example by restarting the Android Studio
  3. Once synced, you can check the option again to work offline.

What are queues in jQuery?

The uses of jQuery .queue() and .dequeue()

Queues in jQuery are used for animations. You can use them for any purpose you like. They are an array of functions stored on a per element basis, using jQuery.data(). They are First-In-First-Out (FIFO). You can add a function to the queue by calling .queue(), and you remove (by calling) the functions using .dequeue().

To understand the internal jQuery queue functions, reading the source and looking at examples helps me out tremendously. One of the best examples of a queue function I've seen is .delay():

$.fn.delay = function( time, type ) {
  time = jQuery.fx ? jQuery.fx.speeds[time] || time : time;
  type = type || "fx";

  return this.queue( type, function() {
    var elem = this;
    setTimeout(function() {
      jQuery.dequeue( elem, type );
    }, time );
  });
};

The default queue - fx

The default queue in jQuery is fx. The default queue has some special properties that are not shared with other queues.

  1. Auto Start: When calling $(elem).queue(function(){}); the fx queue will automatically dequeue the next function and run it if the queue hasn't started.
  2. 'inprogress' sentinel: Whenever you dequeue() a function from the fx queue, it will unshift() (push into the first location of the array) the string "inprogress" - which flags that the queue is currently being run.
  3. It's the default! The fx queue is used by .animate() and all functions that call it by default.

NOTE: If you are using a custom queue, you must manually .dequeue() the functions, they will not auto start!

Retrieving/Setting the queue

You can retrieve a reference to a jQuery queue by calling .queue() without a function argument. You can use the method if you want to see how many items are in the queue. You can use push, pop, unshift, shift to manipulate the queue in place. You can replace the entire queue by passing an array to the .queue() function.

Quick Examples:

// lets assume $elem is a jQuery object that points to some element we are animating.
var queue = $elem.queue();
// remove the last function from the animation queue.
var lastFunc = queue.pop(); 
// insert it at the beginning:    
queue.unshift(lastFunc);
// replace queue with the first three items in the queue
$elem.queue(queue.slice(0,3)); 

An animation (fx) queue example:

Run example on jsFiddle

$(function() {
    // lets do something with google maps:
    var $map = $("#map_canvas");
    var myLatlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {zoom: 8, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP};
    var geocoder = new google.maps.Geocoder();
    var map = new google.maps.Map($map[0], myOptions);
    var resized = function() {
        // simple animation callback - let maps know we resized
        google.maps.event.trigger(map, 'resize');
    };

    // wait 2 seconds
    $map.delay(2000);
    // resize the div:
    $map.animate({
        width: 250,
        height: 250,
        marginLeft: 250,
        marginTop:250
    }, resized);
    // geocode something
    $map.queue(function(next) {
        // find stackoverflow's whois address:
      geocoder.geocode({'address': '55 Broadway New York NY 10006'},handleResponse);

      function handleResponse(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
              var location = results[0].geometry.location;
              map.setZoom(13);
              map.setCenter(location);
              new google.maps.Marker({ map: map, position: location });
          }
          // geocoder result returned, continue with animations:
          next();
      }
    });
    // after we find stack overflow, wait 3 more seconds
    $map.delay(3000);
    // and resize the map again
    $map.animate({
        width: 500,
        height: 500,
        marginLeft:0,
        marginTop: 0
    }, resized);
});

Another custom queue example

Run example on jsFiddle

var theQueue = $({}); // jQuery on an empty object - a perfect queue holder

$.each([1,2,3],function(i, num) {
  // lets add some really simple functions to a queue:
  theQueue.queue('alerts', function(next) { 
    // show something, and if they hit "yes", run the next function.
    if (confirm('index:'+i+' = '+num+'\nRun the next function?')) {
      next();
    }
  }); 
});

// create a button to run the queue:
$("<button>", {
  text: 'Run Queue', 
  click: function() { 
    theQueue.dequeue('alerts'); 
  }
}).appendTo('body');

// create a button to show the length:
$("<button>", {
  text: 'Show Length', 
  click: function() { 
    alert(theQueue.queue('alerts').length); 
  }
}).appendTo('body');

Queueing Ajax Calls:

I developed an $.ajaxQueue() plugin that uses the $.Deferred, .queue(), and $.ajax() to also pass back a promise that is resolved when the request completes. Another version of $.ajaxQueue that still works in 1.4 is posted on my answer to Sequencing Ajax Requests

/*
* jQuery.ajaxQueue - A queue for ajax requests
* 
* (c) 2011 Corey Frang
* Dual licensed under the MIT and GPL licenses.
*
* Requires jQuery 1.5+
*/ 
(function($) {

// jQuery on an empty object, we are going to use this as our Queue
var ajaxQueue = $({});

$.ajaxQueue = function( ajaxOpts ) {
    var jqXHR,
        dfd = $.Deferred(),
        promise = dfd.promise();

    // queue our ajax request
    ajaxQueue.queue( doRequest );

    // add the abort method
    promise.abort = function( statusText ) {

        // proxy abort to the jqXHR if it is active
        if ( jqXHR ) {
            return jqXHR.abort( statusText );
        }

        // if there wasn't already a jqXHR we need to remove from queue
        var queue = ajaxQueue.queue(),
            index = $.inArray( doRequest, queue );

        if ( index > -1 ) {
            queue.splice( index, 1 );
        }

        // and then reject the deferred
        dfd.rejectWith( ajaxOpts.context || ajaxOpts,
            [ promise, statusText, "" ] );

        return promise;
    };

    // run the actual query
    function doRequest( next ) {
        jqXHR = $.ajax( ajaxOpts )
            .done( dfd.resolve )
            .fail( dfd.reject )
            .then( next, next );
    }

    return promise;
};

})(jQuery);

I have now added this as an article on learn.jquery.com, there are other great articles on that site about queues, go look.

Regular expression which matches a pattern, or is an empty string

To match pattern or an empty string, use

^$|pattern

Explanation

  • ^ and $ are the beginning and end of the string anchors respectively.
  • | is used to denote alternates, e.g. this|that.

References


On \b

\b in most flavor is a "word boundary" anchor. It is a zero-width match, i.e. an empty string, but it only matches those strings at very specific places, namely at the boundaries of a word.

That is, \b is located:

  • Between consecutive \w and \W (either order):
    • i.e. between a word character and a non-word character
  • Between ^ and \w
    • i.e. at the beginning of the string if it starts with \w
  • Between \w and $
    • i.e. at the end of the string if it ends with \w

References


On using regex to match e-mail addresses

This is not trivial depending on specification.

Related questions

Usage of the backtick character (`) in JavaScript

It's a pretty useful functionality, for example here is a Node.js code snippet to test the set up of a 3 second timing function.

const waitTime = 3000;
console.log(`setting a ${waitTime/1000} second delay`);

Explanation

  1. Declare wait time as 3000
  2. Using the backtick you can embed the result of the calculation of 'wait time' divided by 1000 in the same line with your chosen text.
  3. Further calling a timer function using the 'waitTime' constant will result in a 3 second delay, as calculated in the console.log argument.

How do I get a file's last modified time in Perl?

This is very old thread, but I tried using the solution and could not get the information out of File::stat. (Perl 5.10.1)

I had to do the following:

my $f_stats = stat($fh);
my $timestamp_mod = localtime($f_stats->mtime);
print "MOD_TIME = $timestamp_mod \n";

Just thought I share in case anyone else had the same trouble.

How to show and update echo on same line

I use printf, is shorter as it doesn't need flags to do the work:

printf "\rMy static $myvars composed text"

How do I push to GitHub under a different username?

I have been using one machine to push code to two different GitHub accounts with different username. Assuming you already set up one account and want to add a new one:

  1. Generate new SSH key ssh-keygen -t rsa -C "[email protected]"
  2. Save it, but remember not to override the existent one id_rsa. Give it a different name, e.g. id_rsa_another
  3. Copy the contents of the key to your GitHub account:

Settings -> SSH and GPG keys -> New SSH key -> Give a label and paste the key -> Add SSH key

  1. Add the key to the ssh agent: ssh-add ~/.ssh/id_rsa_another
  2. Setup a GitHub host: Create a config file with touch ~/.ssh/config and edit the file by providing configurations to your accounts:
#first account
Host github.com-first
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_rsa

#another account
Host github.com-another
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_rsa_another

Now you should be able to push from different accounts depending on what key you add to the ssh agent, i.e. to use your first account, do ssh-add ~/.ssh/id_rsa.

You might also want to change your user email:

git config --global user.email "[email protected]"

or clean out ssh keys in case of permission error when pusing code to one of the accounts:

ssh-add -D

Deleting an object in C++

Your code is indeed using the normal way to create and delete a dynamic object. Yes, it's perfectly normal (and indeed guaranteed by the language standard!) that delete will call the object's destructor, just like new has to invoke the constructor.

If you weren't instantiating Object1 directly but some subclass thereof, I'd remind you that any class intended to be inherited from must have a virtual destructor (so that the correct subclass's destructor can be invoked in cases analogous to this one) -- but if your sample code is indeed representative of your actual code, this cannot be your current problem -- must be something else, maybe in the destructor code you're not showing us, or some heap-corruption in the code you're not showing within that function or the ones it calls...?

BTW, if you're always going to delete the object just before you exit the function which instantiates it, there's no point in making that object dynamic -- just declare it as a local (storage class auto, as is the default) variable of said function!

How to select the comparison of two columns as one column in Oracle

If you want to consider null values equality too, try the following

select column1, column2, 
   case
      when column1 is NULL and column2 is NULL then 'true'  
      when column1=column2 then 'true' 
      else 'false' 
   end 
from table;

NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equalsIgnoreCase(java.lang.String)' on a null object reference

This is the error line:

if (called_from.equalsIgnoreCase("add")) {  --->38th error line

This means that called_from is null. Simple check if it is null above:

String called_from = getIntent().getStringExtra("called");

if(called_from == null) {
    called_from = "empty string";
}
if (called_from.equalsIgnoreCase("add")) {
    // do whatever
} else {
    // do whatever
}

That way, if called_from is null, it'll execute the else part of your if statement.

Clear text input on click with AngularJS

Easiest way to clear/reset the text field on click is to clear/reset the scope

<input type="text" class="form-control" ng-model="searchAll" ng-click="clearfunction(this)"/>

In Controller

$scope.clearfunction=function(event){
   event.searchAll=null;
}

Get top n records for each group of grouped results

SELECT
p1.Person,
p1.`GROUP`,
p1.Age  
   FROM
person AS p1 
 WHERE
(
SELECT
    COUNT( DISTINCT ( p2.age ) ) 
FROM
    person AS p2 
WHERE
    p2.`GROUP` = p1.`GROUP` 
    AND p2.Age >= p1.Age 
) < 2 
ORDER BY
p1.`GROUP` ASC,
p1.age DESC

reference leetcode

Get PostGIS version

Since some of the functions depend on other libraries like GEOS and proj4 you might want to get their versions too. Then use:

SELECT PostGIS_full_version();

Chrome - ERR_CACHE_MISS

Yes, this is a current issue in Chrome. There is an issue report here.

The fix will appear in 40.x.y.z versions.

Until then? I don't think you can resolve the issue yourself. But you can ignore it. The shown error is only related to the dev tools and does not influence the behavior of your website. If you have any other problems they are not related to this error.

How to save username and password with Mercurial?

If you are using TortoiseHg you have to perform these three steps shown in the attached screen shot, this would add your credentials for the specific repository you are working with.

enter image description here

To add global settings you can access the file C:\users\user.name\mercurial.ini and add the section

[auth]
bb.prefix=https://bitbucket.org/zambezia/packagemanager
bb.username = $username
bb.password = $password

Hope this helps.

How to lowercase a pandas dataframe string column if it has missing values?

Use apply function,

Xlower = df['x'].apply(lambda x: x.upper()).head(10) 

creating triggers for After Insert, After Update and After Delete in SQL

(Update: overlooked a fault in the matter, I have corrected)

(Update2: I wrote from memory the code screwed up, repaired it)

(Update3: check on SQLFiddle)

create table Derived_Values
  (
    BusinessUnit nvarchar(100) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

create table Derived_Values_Test
  (
    BusinessUnit nvarchar(150)
    ,Questions nvarchar(100)
    ,Answer nvarchar(100)
    )

go

CREATE TRIGGER trgAfterUpdate ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Updated Record -- After Update Trigger.'

    insert into 
        [Derived_Values_Test]
        --(BusinessUnit,Questions, Answer) 
    SELECT 
        @BusinessUnit + i.BusinessUnit, i.Questions, i.Answer
    FROM 
        inserted i
        inner join deleted d on i.BusinessUnit = d.BusinessUnit
end

go

CREATE TRIGGER trgAfterDelete ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Deleted Record -- After Delete Trigger.'

    insert into 
        [Derived_Values_Test]
        --(BusinessUnit,Questions, Answer) 
    SELECT 
        @BusinessUnit + d.BusinessUnit, d.Questions, d.Answer
    FROM 
        deleted d
end

go

insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')

UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');

delete Derived_Values;

and then:

SELECT * FROM Derived_Values;
go

select * from Derived_Values_Test;


Record Count: 0;

BUSINESSUNIT    QUESTIONS   ANSWER
Updated Record -- After Update Trigger.BU1  Q11 Updated Answers A11
Deleted Record -- After Delete Trigger.BU1  Q11 A11
Updated Record -- After Update Trigger.BU1  Q12 Updated Answers A12
Deleted Record -- After Delete Trigger.BU1  Q12 A12
Updated Record -- After Update Trigger.BU2  Q21 Updated Answers A21
Deleted Record -- After Delete Trigger.BU2  Q21 A21
Updated Record -- After Update Trigger.BU2  Q22 Updated Answers A22
Deleted Record -- After Delete Trigger.BU2  Q22 A22

(Update4: If you want to sync: SQLFiddle)

create table Derived_Values
  (
    BusinessUnit nvarchar(100) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

create table Derived_Values_Test
  (
    BusinessUnit nvarchar(150) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values_Test ADD CONSTRAINT PK_Derived_Values_Test
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

CREATE TRIGGER trgAfterInsert ON  [Derived_Values]
FOR INSERT
AS  
begin
    insert
        [Derived_Values_Test]
        (BusinessUnit,Questions,Answer)
    SELECT 
        i.BusinessUnit, i.Questions, i.Answer
    FROM 
        inserted i
end

go


CREATE TRIGGER trgAfterUpdate ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Updated Record -- After Update Trigger.'

    update
        [Derived_Values_Test]
    set
        --BusinessUnit = i.BusinessUnit
        --,Questions = i.Questions
        Answer = i.Answer
    from
        [Derived_Values]
        inner join inserted i 
    on
        [Derived_Values].BusinessUnit = i.BusinessUnit
        and
        [Derived_Values].Questions = i.Questions
end

go

CREATE TRIGGER trgAfterDelete ON  [Derived_Values]
FOR DELETE
AS  
begin
    delete 
        [Derived_Values_Test]
    from
        [Derived_Values_Test]
        inner join deleted d 
    on
        [Derived_Values_Test].BusinessUnit = d.BusinessUnit
        and
        [Derived_Values_Test].Questions = d.Questions
end

go

insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')

UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');

--delete Derived_Values;

And then:

SELECT * FROM Derived_Values;
go

select * from Derived_Values_Test;


BUSINESSUNIT    QUESTIONS   ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22

BUSINESSUNIT    QUESTIONS   ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22

Rotate image with javascript

CSS can be applied and you will have to set transform-origin correctly to get the applied transformation in the way you want

See the fiddle:

http://jsfiddle.net/OMS_/gkrsz/

Main code:

/* assuming that the image's height is 70px */

img.rotated {
    transform: rotate(90deg);
    -webkit-transform: rotate(90deg);
    -moz-transform: rotate(90deg);
    -ms-transform: rotate(90deg);

    transform-origin: 35px 35px;
    -webkit-transform-origin: 35px 35px;
    -moz-transform-origin: 35px 35px;
    -ms-transform-origin: 35px 35px;
}

jQuery and JS:

$(img)
    .css('transform-origin-x', imgWidth / 2)
    .css('transform-origin-y', imgHeight / 2);

// By calculating the height and width of the image in the load function

// $(img).css('transform-origin', (imgWidth / 2) + ' ' + (imgHeight / 2) );

Logic:

Divide the image's height by 2. The transform-x and transform-y values should be this value

Link:

transform-origin at CSS | MDN

Appending a list to a list of lists in R

The purrr package has a lot of handy functions for working on lists. The flatten command can clean up unwanted nesting.

resultsa <- list(1,2,3,4,5)
resultsb <- list(6,7,8,9,10)
resultsc <- list(11,12,13,14,15)

nested_outlist <- list(resultsa, resultsb, resultsc)
outlist <- purrr::flatten(nested_outlist)

See last changes in svn

You could use CommitMonitor. This little tool uses very little RAM and notifies you of all the commits you've missed.

Android 8.0: java.lang.IllegalStateException: Not allowed to start service Intent

In Oreo Android defined limits to background services.

To improve the user experience, Android 8.0 (API level 26) imposes limitations on what apps can do while running in the background.

Still if you need always running service, then you can use foreground service.

Background Service Limitations: While an app is idle, there are limits to its use of background services. This does not apply to foreground services, which are more noticeable to the user.

So you can make a foreground service. You will need to show a notification to user when your service is running. See this answer (There are many others)

A solution if -

you don't want a notification for your service?

You can make periodic task, 1. it starts your service, 2. service will do its work and 3. stops itself. By this your app will not be considered battery draining.

You can use periodic task with Alarm Manager, Job Scheduler, Evernote-Jobs or Work Manager.

I have tested forever running service with Work-Manager.

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

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

How can I rollback a git repository to a specific commit?

In github, the easy way is to delete the remote branch in the github UI, under branches tab. You have to make sure remove following settings to make the branch deletable:

  1. Not a default branch
  2. No opening poll requests.
  3. The branch is not protected.

Now recreate it in your local repository to point to the previous commit point. and add it back to remote repo.

git checkout -b master 734c2b9b   # replace with your commit point

Then push the local branch to remote

git push -u origin master

Add back the default branch and branch protection, etc.

RegEx for validating an integer with a maximum length of 10 characters

0123456789 is not a valid integer (usually zeros will be stripped)

I think something like this regexp would be better to use:

^[1-9]([0-9]*)$

(does not support signed numbers)

How to repair COMException error 80040154?

Move excel variables which are global declare in your form to local like in my form I have:

Dim xls As New MyExcel.Interop.Application  
Dim xlb As MyExcel.Interop.Workbook

above two lines were declare global in my form so i moved these two lines to local function and now tool is working fine.

Find difference between timestamps in seconds in PostgreSQL

select age(timestamp_A, timestamp_B)

Answering to Igor's comment:

select age('2013-02-28 11:01:28'::timestamp, '2011-12-31 11:00'::timestamp);
              age              
-------------------------------
 1 year 1 mon 28 days 00:01:28

Detecting TCP Client Disconnect

If you're using overlapped (i.e. asynchronous) I/O with completion routines or completion ports, you will be notified immediately (assuming you have an outstanding read) when the client side closes the connection.

Switch firefox to use a different DNS than what is in the windows.host file

It appears from your question that you already have a second set of DNS servers available that reference the development site instead of the live site.

I would suggest that you simply run a standard SOCKS proxy either on that DNS server system or on a low-end spare system and have that system configured to use the development DNS server. You can then tell Firefox to use that proxy instead of downloading pages directly.

Doing it this way, the actual DNS lookups will be done on the proxy machine and not on the machine that's running the web browser.

Have a variable in images path in Sass?

No need for a function:

$assetPath : "/assets/images";

...

body {
  margin: 0 auto;
  background: url(#{$assetPath}/site/background.jpg) repeat-x fixed 0 0;
  width: 100%; }

See the interpolation docs for details.

Tomcat 8 Maven Plugin for Java 8

Plugin run Tomcat 7.0.47:

mvn org.apache.tomcat.maven:tomcat7-maven-plugin:2.2:run

 ...
 INFO: Starting Servlet Engine: Apache Tomcat/7.0.47

This is sample to run plugin with Tomcat 8 and Java 8: Cargo embedded tomcat: custom context.xml

RelativeLayout center vertical

If View's height/width = wrap_content

use:

android:layout_centerHorizontal="true"
android:layout_centerVertical="true"

If View's height/width = match_parent

use:

android:gravity="center_vertical|center_horizontal"

how to determine size of tablespace oracle 11g

The following query can be used to detemine tablespace and other params:

select df.tablespace_name "Tablespace",
       totalusedspace "Used MB",
       (df.totalspace - tu.totalusedspace) "Free MB",
       df.totalspace "Total MB",
       round(100 * ( (df.totalspace - tu.totalusedspace)/ df.totalspace)) "Pct. Free"
  from (select tablespace_name,
               round(sum(bytes) / 1048576) TotalSpace
          from dba_data_files 
         group by tablespace_name) df,
       (select round(sum(bytes)/(1024*1024)) totalusedspace,
               tablespace_name
          from dba_segments 
         group by tablespace_name) tu
 where df.tablespace_name = tu.tablespace_name 
   and df.totalspace <> 0;

Source: https://community.oracle.com/message/1832920

For your case if you want to know the partition name and it's size just run this query:

select owner,
       segment_name,
       partition_name,
       segment_type,
       bytes / 1024/1024 "MB" 
  from dba_segments 
 where owner = <owner_name>;

Package signatures do not match the previously installed version

This occurs due to the availability of the previous version of the Application, that is not installed on the device but its data is present in the device memory. So it fails to upgrade this uninstalled application data on the device

Try this :

Go to Device Settings ==> Apps(All Apps) ==> search your App OR search for 'client' ==> In App info screen , press the triple dots option on top right corner ==> select 'Uninstall for All Users' ==> a promt appears select 'OK'

It works for me every time this error occurs

Android getText from EditText field

Try out this will solve ur problem ....

EditText etxt = (EditText)findviewbyid(R.id.etxt);
String str_value = etxt.getText().toString();

Can't bind to 'ngForOf' since it isn't a known property of 'tr' (final release)

Future Readers

Check each of the following:

  1. The component is declared in a SINGLE angular module
  2. Make sure you have import { CommonModule } from '@angular/common';
  3. Restart the IDE/editor
  4. Restart the dev server (ng serve)

Exponentiation in Python - should I prefer ** operator instead of math.pow and math.sqrt?

math.sqrt is the C implementation of square root and is therefore different from using the ** operator which implements Python's built-in pow function. Thus, using math.sqrt actually gives a different answer than using the ** operator and there is indeed a computational reason to prefer numpy or math module implementation over the built-in. Specifically the sqrt functions are probably implemented in the most efficient way possible whereas ** operates over a large number of bases and exponents and is probably unoptimized for the specific case of square root. On the other hand, the built-in pow function handles a few extra cases like "complex numbers, unbounded integer powers, and modular exponentiation".

See this Stack Overflow question for more information on the difference between ** and math.sqrt.

In terms of which is more "Pythonic", I think we need to discuss the very definition of that word. From the official Python glossary, it states that a piece of code or idea is Pythonic if it "closely follows the most common idioms of the Python language, rather than implementing code using concepts common to other languages." In every single other language I can think of, there is some math module with basic square root functions. However there are languages that lack a power operator like ** e.g. C++. So ** is probably more Pythonic, but whether or not it's objectively better depends on the use case.

How do I test which class an object is in Objective-C?

You can also check run time. Put one breakpoint in code and inside (lldb) console write

(lldb) po [yourObject class]

Like this..

enter image description here

How to concatenate string and int in C?

Use sprintf (or snprintf if like me you can't count) with format string "pre_%d_suff".

For what it's worth, with itoa/strcat you could do:

char dst[12] = "pre_";
itoa(i, dst+4, 10);
strcat(dst, "_suff");

Load resources from relative path using local html in uiwebview

This is how to load/use a local html with relative references.

  1. Drag the resource into your xcode project (I dragged a folder named www from my finder window), you will get two options "create groups for any added folders" and "create folders references for any added folders".
  2. Select the "create folder references.." option.
  3. Use the below given code. It should work like a charm.

    NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:@"www"]];
    [webview loadRequest:[NSURLRequest requestWithURL:url]];

Now all your relative links(like img/.gif, js/.js) in the html should get resolved.

Swift 3

    if let path = Bundle.main.path(forResource: "dados", ofType: "html", inDirectory: "root") {
        webView.load( URLRequest(url: URL(fileURLWithPath: path)) )
    }

call javascript function onchange event of dropdown list

I don't know why do you need this onmousedown event here, but what you have to do is put your function above actual usage. Look at the snipplet below:

_x000D_
_x000D_
<script type="text/javascript">_x000D_
function jsFunction(value)_x000D_
{_x000D_
    alert(value);_x000D_
}_x000D_
</script>_x000D_
_x000D_
<select id ="ddl" name="ddl" onmousedown="this.value='';" onchange="jsFunction(this.value);">_x000D_
  <option value='1'>One</option>_x000D_
  <option value='2'>Two</option>_x000D_
  <option value='3'>Three</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

HTML-5 date field shows as "mm/dd/yyyy" in Chrome, even when valid date is set

I was having the same problem, with a value like 2016-08-8, then I solved adding a zero to have two digits days, and it works. Tested in chrome, firefox, and Edge

today:function(){
   var today = new Date();
   var d = (today.getDate() < 10 ? '0' : '' )+ today.getDate();
   var m = ((today.getMonth() + 1) < 10 ? '0' :'') + (today.getMonth() + 1);
   var y = today.getFullYear();
   var x = String(y+"-"+m+"-"+d); 
   return x;
}

How to calculate a logistic sigmoid function in Python?

Below is the python function to do the same.

def sigmoid(x) :
    return 1.0/(1+np.exp(-x))

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

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

The message means :-

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

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

void BindInput( ifstream & inputChannel ); 

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

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

Handling file renames in git

you have to git add css/mobile.css the new file and git rm css/iphone.css, so git knows about it. then it will show the same output in git status

you can see it clearly in the status output (the new name of the file):

# Untracked files:
#   (use "git add <file>..." to include in what will be committed)

and (the old name):

# Changed but not updated:
#   (use "git add/rm <file>..." to update what will be committed)

i think behind the scenes git mv is nothing more than a wrapper script which does exactly that: delete the file from the index and add it under a different name

Count the Number of Tables in a SQL Server Database

Try this:

SELECT Count(*)
FROM <DATABASE_NAME>.INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'

Center button under form in bootstrap

Try adding this class

class="pager"

<p class="pager" style="line-height: 70px;">
    <button type="submit" class="btn">Confirm</button>
</p>

I tried mine within a <div class=pager><button etc etc></div> which worked well

See http://getbootstrap.com/components/ look under Pagination -> Pager

This looks like the correct bootstrap class to center this, text-align: center; is meant for text not images and blocks etc.

ignoring any 'bin' directory on a git project

[Bb]in/

matches both upper and lower case

xsl: how to split strings?

If your XSLT processor supports EXSLT, you can use str:tokenize, otherwise, the link contains an implementation using functions like substring-before.

Unsupported major.minor version 52.0

Just go to http://java.com/en/download/ and update your version of JRE

How to use "/" (directory separator) in both Linux and Windows in Python?

Use:

import os
print os.sep

to see how separator looks on a current OS.
In your code you can use:

import os
path = os.path.join('folder_name', 'file_name')

Byte Array and Int conversion in Java

I like owlstead's original answer, and if you don't like the idea of creating a ByteBuffer on every method call then you can reuse the ByteBuffer by calling it's .clear() and .flip() methods:

ByteBuffer _intShifter = ByteBuffer.allocate(Integer.SIZE / Byte.SIZE)
                                   .order(ByteOrder.LITTLE_ENDIAN);

public byte[] intToByte(int value) {
    _intShifter.clear();
    _intShifter.putInt(value);      
    return _intShifter.array();
}

public int byteToInt(byte[] data)
{
    _intShifter.clear();
    _intShifter.put(data, 0, Integer.SIZE / Byte.SIZE);
    _intShifter.flip();
    return _intShifter.getInt();
}

How can I implement a tree in Python?

I've implemented trees using nested dicts. It is quite easy to do, and it has worked for me with pretty large data sets. I've posted a sample below, and you can see more at Google code

  def addBallotToTree(self, tree, ballotIndex, ballot=""):
    """Add one ballot to the tree.

    The root of the tree is a dictionary that has as keys the indicies of all 
    continuing and winning candidates.  For each candidate, the value is also
    a dictionary, and the keys of that dictionary include "n" and "bi".
    tree[c]["n"] is the number of ballots that rank candidate c first.
    tree[c]["bi"] is a list of ballot indices where the ballots rank c first.

    If candidate c is a winning candidate, then that portion of the tree is
    expanded to indicate the breakdown of the subsequently ranked candidates.
    In this situation, additional keys are added to the tree[c] dictionary
    corresponding to subsequently ranked candidates.
    tree[c]["n"] is the number of ballots that rank candidate c first.
    tree[c]["bi"] is a list of ballot indices where the ballots rank c first.
    tree[c][d]["n"] is the number of ballots that rank c first and d second.
    tree[c][d]["bi"] is a list of the corresponding ballot indices.

    Where the second ranked candidates is also a winner, then the tree is 
    expanded to the next level.  

    Losing candidates are ignored and treated as if they do not appear on the 
    ballots.  For example, tree[c][d]["n"] is the total number of ballots
    where candidate c is the first non-losing candidate, c is a winner, and
    d is the next non-losing candidate.  This will include the following
    ballots, where x represents a losing candidate:
    [c d]
    [x c d]
    [c x d]
    [x c x x d]

    During the count, the tree is dynamically updated as candidates change
    their status.  The parameter "tree" to this method may be the root of the
    tree or may be a sub-tree.
    """

    if ballot == "":
      # Add the complete ballot to the tree
      weight, ballot = self.b.getWeightedBallot(ballotIndex)
    else:
      # When ballot is not "", we are adding a truncated ballot to the tree,
      # because a higher-ranked candidate is a winner.
      weight = self.b.getWeight(ballotIndex)

    # Get the top choice among candidates still in the running
    # Note that we can't use Ballots.getTopChoiceFromWeightedBallot since
    # we are looking for the top choice over a truncated ballot.
    for c in ballot:
      if c in self.continuing | self.winners:
        break # c is the top choice so stop
    else:
      c = None # no candidates left on this ballot

    if c is None:
      # This will happen if the ballot contains only winning and losing
      # candidates.  The ballot index will not need to be transferred
      # again so it can be thrown away.
      return

    # Create space if necessary.
    if not tree.has_key(c):
      tree[c] = {}
      tree[c]["n"] = 0
      tree[c]["bi"] = []

    tree[c]["n"] += weight

    if c in self.winners:
      # Because candidate is a winner, a portion of the ballot goes to
      # the next candidate.  Pass on a truncated ballot so that the same
      # candidate doesn't get counted twice.
      i = ballot.index(c)
      ballot2 = ballot[i+1:]
      self.addBallotToTree(tree[c], ballotIndex, ballot2)
    else:
      # Candidate is in continuing so we stop here.
      tree[c]["bi"].append(ballotIndex)

Using for loop inside of a JSP

You concrete problem is caused because you're mixing discouraged and old school scriptlets <% %> with its successor EL ${}. They do not share the same variable scope. The allFestivals is not available in scriptlet scope and the i is not available in EL scope.

You should install JSTL (<-- click the link for instructions) and declare it in top of JSP as follows:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

and then iterate over the list as follows:

<c:forEach items="${allFestivals}" var="festival">
    <tr>      
        <td>${festival.festivalName}</td>
        <td>${festival.location}</td>
        <td>${festival.startDate}</td>
        <td>${festival.endDate}</td>
        <td>${festival.URL}</td>  
    </tr>
</c:forEach>

(beware of possible XSS attack holes, use <c:out> accordingly)

Don't forget to remove the <jsp:useBean> as it has no utter value here when you're using a servlet as model-and-view controller. It would only lead to confusion. See also our servlets wiki page. Further you would do yourself a favour to disable scriptlets by the following entry in web.xml so that you won't accidently use them:

<jsp-config>
    <jsp-property-group>
        <url-pattern>*.jsp</url-pattern>
        <scripting-invalid>true</scripting-invalid>
    </jsp-property-group>
</jsp-config>

Default values and initialization in Java

In the first case you are declaring "int a" as a local variable(as declared inside a method) and local varible do not get default value.

But instance variable are given default value both for static and non-static.

Default value for instance variable:

int = 0

float,double = 0.0

reference variable = null

char = 0 (space character)

boolean = false

How to format strings in Java

The org.apache.commons.text.StringSubstitutor helper class from Apache Commons Text provides named variable substitution

Map<String, String> valuesMap = new HashMap<>();
valuesMap.put("animal", "quick brown fox");
valuesMap.put("target", "lazy dog");
String resolved = new StringSubstitutor(valuesMap).replace("The ${animal} jumped over the ${target}.");
System.out.println(resolved); // The quick brown fox jumped over the lazy dog.

How to use conditional statement within child attribute of a Flutter Widget (Center Widget)

I personally use if/else statement in children with this kind of block statement. It only supports on Dart version 2.3.0 above.

if / else

Column(
    children: [
        if (_selectedIndex == 0) ...[
          DayScreen(),
        ] else ...[
          StatsScreen(),
        ],
    ],
 ),

if / else if

Column(
    children: [
        if (_selectedIndex == 0) ...[
          DayScreen(),
        ] else if(_selectedIndex == 1)...[
          StatsScreen(),
        ],
    ],
 ),

Format a datetime into a string with milliseconds

I assume you mean you're looking for something that is faster than datetime.datetime.strftime(), and are essentially stripping the non-alpha characters from a utc timestamp.

You're approach is marginally faster, and I think you can speed things up even more by slicing the string:

>>> import timeit
>>> t=timeit.Timer('datetime.utcnow().strftime("%Y%m%d%H%M%S%f")','''
... from datetime import datetime''')
>>> t.timeit(number=10000000)
116.15451288223267

>>> def replaceutc(s):
...     return s\
...         .replace('-','') \
...         .replace(':','') \
...         .replace('.','') \
...         .replace(' ','') \
...         .strip()
... 
>>> t=timeit.Timer('replaceutc(str(datetime.datetime.utcnow()))','''
... from __main__ import replaceutc
... import datetime''')
>>> t.timeit(number=10000000)
77.96774983406067

>>> def sliceutc(s):
...     return s[:4] + s[5:7] + s[8:10] + s[11:13] + s[14:16] + s[17:19] + s[20:]
... 
>>> t=timeit.Timer('sliceutc(str(datetime.utcnow()))','''
... from __main__ import sliceutc
... from datetime import datetime''')
>>> t.timeit(number=10000000)
62.378515005111694

How to close current tab in a browser window?

It is possible. I searched the whole net for this, but once when i took one of microsoft's survey, I finally got the answer.

try this:

window.top.close();

this will close the current tab for you.

How do I extract data from a DataTable?

Please consider using some code like this:

SqlDataReader reader = command.ExecuteReader();
int numRows = 0;
DataTable dt = new DataTable();

dt.Load(reader);
numRows = dt.Rows.Count;

string attended_type = "";

for (int index = 0; index < numRows; index++)
{
    attended_type = dt.Rows[indice2]["columnname"].ToString();
}

reader.Close();

HTTP authentication logout via PHP

Trac - by default - uses HTTP Authentication as well. Logout does not work and can not be fixed:

  • This is an issue with the HTTP authentication scheme itself, and there's nothing we can do in Trac to fix it properly.
  • There is currently no workaround (JavaScript or other) that works with all major browsers.

From: http://trac.edgewall.org/ticket/791#comment:103

Looks like that there is no working answer to the question, that issue has been reported seven years ago and it makes perfect sense: HTTP is stateless. Either a request is done with authentication credentials or not. But that's a matter of the client sending the request, not the server receiving it. The server can only say if a request URI needs authorization or not.

How do I see all foreign keys to a table or column?

This solution will not only display all relations but also the constraint name, which is required in some cases (e.g. drop contraint):

select
    concat(table_name, '.', column_name) as 'foreign key',
    concat(referenced_table_name, '.', referenced_column_name) as 'references',
    constraint_name as 'constraint name'
from
    information_schema.key_column_usage
where
    referenced_table_name is not null;

If you want to check tables in a specific database, at the end of the query add the schema name:

select
    concat(table_name, '.', column_name) as 'foreign key',
    concat(referenced_table_name, '.', referenced_column_name) as 'references',
    constraint_name as 'constraint name'
from
    information_schema.key_column_usage
where
    referenced_table_name is not null
    and table_schema = 'database_name';

Likewise, for a specific column name, add

and table_name = 'table_name

at the end of the query.

Inspired by this post here

npm command to uninstall or prune unused packages in Node.js

If you're not worried about a couple minutes time to do so, a solution would be to rm -rf node_modules and npm install again to rebuild the local modules.

Missing MVC template in Visual Studio 2015

Visual Studio 2015 (Community update 3, in my scenario) uses a default template for the MVC project. You don't have to select it.

I found this tutorial and I think it answers the question: https://docs.asp.net/en/latest/tutorials/first-mvc-app/start-mvc.html

check out the old versions of this: http://www.asp.net/mvc/overview/older-versions-1/getting-started-with-mvc/getting-started-with-mvc-part1

http://www.asp.net/mvc/overview/getting-started/introduction/getting-started

Times have changed. Including .NET

Run a JAR file from the command line and specify classpath

Alternatively, use the manifest to specify the class-path and main-class if you like, so then you don't need to use -cp or specify the main class. In your case it would contain lines like this:

Main-Class: com.test.App
Class-Path: lib/one.jar lib/two.jar

Unfortunately you need to spell out each jar in the manifest (not a biggie as you only do once, and you can use a script to build the file or use a build tool like ANT or Maven or Gradle). And the reference has to be a relative or absolute directory to where you run the java -jar MyJar.jar.

Then execute it with

java -jar MyJar.jar

Subset a dataframe by multiple factor levels

You can use %in%

  data[data$Code %in% selected,]
  Code Value
1    A     1
2    B     2
7    A     3
8    A     4

How to display a list of images in a ListView in Android?

Here is the simple ListView with different images. First of all you have to copy the different kinds of images and paste it to the res/drawable-hdpi in your project. Images should be (.png)file format. then copy this code.

In main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical" >

  <TextView
      android:id="@+id/textview"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content" />

 <ListView
     android:id="@+id/listview"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content" />

create listview_layout.xml and paste this code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

   <ImageView
      android:id="@+id/flag"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:contentDescription="@string/hello"
      android:paddingTop="10dp"
      android:paddingRight="10dp"
      android:paddingBottom="10dp" />

   <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:orientation="vertical" >

     <TextView
        android:id="@+id/txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="15dp"
        android:text="TextView1" />

    <TextView
        android:id="@+id/cur"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="10dp"
        android:text="TextView2" />
   </LinearLayout>

In your Activity

package com.test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class SimpleListImageActivity extends Activity {

    // Array of strings storing country names
    String[] countries = new String[] {
        "India",
        "Pakistan",
        "Sri Lanka",
        "China",
        "Bangladesh",
        "Nepal",
        "Afghanistan",
        "North Korea",
        "South Korea",
        "Japan"
    };

    // Array of integers points to images stored in /res/drawable-hdpi/

   //here you have to give image name which you already pasted it in /res/drawable-hdpi/

     int[] flags = new int[]{
        R.drawable.image1,
        R.drawable.image2,   
        R.drawable.image3,
        R.drawable.image4,
        R.drawable.image5,
        R.drawable.image6,
        R.drawable.image7,
        R.drawable.image8,
        R.drawable.image9,
        R.drawable.image10,
    };

    // Array of strings to store currencies
    String[] currency = new String[]{
        "Indian Rupee",
        "Pakistani Rupee",
        "Sri Lankan Rupee",
        "Renminbi",
        "Bangladeshi Taka",
        "Nepalese Rupee",
        "Afghani",
        "North Korean Won",
        "South Korean Won",
        "Japanese Yen"
    };

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Each row in the list stores country name, currency and flag
        List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();

        for(int i=0;i<10;i++){
            HashMap<String, String> hm = new HashMap<String,String>();
            hm.put("txt", "Country : " + countries[i]);
            hm.put("cur","Currency : " + currency[i]);
            hm.put("flag", Integer.toString(flags[i]) );
            aList.add(hm);
        }

        // Keys used in Hashmap
        String[] from = { "flag","txt","cur" };

        // Ids of views in listview_layout
        int[] to = { R.id.flag,R.id.txt,R.id.cur};

        // Instantiating an adapter to store each items
        // R.layout.listview_layout defines the layout of each item
        SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.listview_layout, from, to);

        // Getting a reference to listview of main.xml layout file
        ListView listView = ( ListView ) findViewById(R.id.listview);

        // Setting the adapter to the listView
        listView.setAdapter(adapter);
    }
}

This is the full code.you can make changes to your need... Comments are welcome

psql - save results of command to a file

Use o parameter of pgsql command.

-o, --output=FILENAME send query results to file (or |pipe)

psql -d DatabaseName -U UserName -c "SELECT * FROM TABLE" -o /root/Desktop/file.txt

How to add calendar events in Android?

you have to add flag:

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

or you will cause error with:

startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK

Angular 2 optional route parameter

rerezz's answer is pretty nice but it has one serious flaw. It causes User component to re-run the ngOnInit method.

It might be problematic when you do some heavy stuff there and don't want it to be re-run when you switch from the non-parametric route to the parametric one. Though those two routes are meant to imitate an optional url parameter, not become 2 separate routes.

Here's what I suggest to solve the problem:

const routes = [
  {
    path: '/user',
    component: User,
    children: [
      { path: ':id', component: UserWithParam, name: 'Usernew' }
    ]
  }
];

Then you can move the logic responsible for handling the param to the UserWithParam component and leave the base logic in the User component. Whatever you do in User::ngOnInit won't be run again when you navigate from /user to /user/123.

Don't forget to put the <router-outlet></router-outlet> in the User's template.

Coarse-grained vs fine-grained

In simple terms

  • Coarse-grained - larger components than fine-grained, large subcomponents. Simply wraps one or more fine-grained services together into a more coarse­-grained operation.
  • Fine-grained - smaller components of which the larger ones are composed, lower­level service

It is better to have more coarse-grained service operations, which are composed by fine-grained operations

enter image description here

How to set a background image in Xcode using swift?

override func viewDidLoad() {
    super.viewDidLoad()
    self.view.backgroundColor = UIColor(patternImage: UIImage(named: "background.png"))
}

Getting unique items from a list

In .Net 2.0 I`m pretty sure about this solution:

public IEnumerable<T> Distinct<T>(IEnumerable<T> source)
{
     List<T> uniques = new List<T>();
     foreach (T item in source)
     {
         if (!uniques.Contains(item)) uniques.Add(item);
     }
     return uniques;
}

Why should I use an IDE?

There might be different reasons for different people. For me these are the advantages.

  1. Provides an integrated feel to the project. For instance i will have all the related projects files in single view.
  2. Provides increased code productivity like
    1. Syntax Highlighting
    2. Referring of assemblies
    3. Intellisense
    4. Centralized view of database and related UI files.
    5. Debugging features

End of the day, it helps me to code faster than i can do in a notepad or wordpad. That is a pretty good reason for me to prefer an IDE.

Giving UIView rounded corners

Swift 4 - Using IBDesignable

   @IBDesignable
    class DesignableView: UIView {
    }

    extension UIView
    {

        @IBInspectable
        var cornerRadius: CGFloat {
            get {
                return layer.cornerRadius
            }
            set {
            layer.cornerRadius = newValue
        }
    }
}

Request format is unrecognized for URL unexpectedly ending in

I did not have the issue when developing in localhost. However, once I published to a web server, the webservice was returning an empty (blank) result and I was seeing the error in my logs.

I fixed it by setting my ajax contentType to :

"application/json; charset=utf-8"

and using :

JSON.stringify()

on the object I was posting.

var postData = {data: myData};
$.ajax({
                type: "POST",
                url: "../MyService.asmx/MyMethod",
                data: JSON.stringify(postData), 
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    console.log(data);
                },
                dataType: "json"
            });

Eclipse won't compile/run java file

  • Make a project to put the files in.
    • File -> New -> Java Project
    • Make note of where that project was created (where your "workspace" is)
  • Move your java files into the src folder which is immediately inside the project's folder.
    • Find the project INSIDE Eclipse's Package Explorer (Window -> Show View -> Package Explorer)
    • Double-click on the project, then double-click on the 'src' folder, and finally double-click on one of the java files inside the 'src' folder (they should look familiar!)
  • Now you can run the files as expected.

Note the hollow 'J' in the image. That indicates that the file is not part of a project.

Hollow J means it is not part of a project

How to convert JSON data into a Python object

This is not code golf, but here is my shortest trick, using types.SimpleNamespace as the container for JSON objects.

Compared to the leading namedtuple solution, it is:

  • probably faster/smaller as it does not create a class for each object
  • shorter
  • no rename option, and probably the same limitation on keys that are not valid identifiers (uses setattr under the covers)

Example:

from __future__ import print_function
import json

try:
    from types import SimpleNamespace as Namespace
except ImportError:
    # Python 2.x fallback
    from argparse import Namespace

data = '{"name": "John Smith", "hometown": {"name": "New York", "id": 123}}'

x = json.loads(data, object_hook=lambda d: Namespace(**d))

print (x.name, x.hometown.name, x.hometown.id)

Jquery find nearest matching element

Get the .column parent of the this element, get its previous sibling, then find any input there:

$(this).closest(".column").prev().find("input:first").val();

Demo: http://jsfiddle.net/aWhtP/

OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection

What you need is a quadrangle instead of a rotated rectangle. RotatedRect will give you incorrect results. Also you will need a perspective projection.

Basicly what must been done is:

  • Loop through all polygon segments and connect those which are almost equel.
  • Sort them so you have the 4 most largest line segments.
  • Intersect those lines and you have the 4 most likely corner points.
  • Transform the matrix over the perspective gathered from the corner points and the aspect ratio of the known object.

I implemented a class Quadrangle which takes care of contour to quadrangle conversion and will also transform it over the right perspective.

See a working implementation here: Java OpenCV deskewing a contour

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

Assign something to your strings. This will definitely help.

Easy way to prevent Heroku idling?

This is my solution.

Use Google Apps Script, and set time trigger.

// main.js
function ping() {
  UrlFetchApp.fetch("https://<Your app>.herokuapp.com/ping_from_GAS");
}

It is very easy!

How to label each equation in align environment?

Within the environment align from the package amsmath it is possible to combine the use of \label and \tag for each equation or line. For example, the code:

\documentclass{article}
\usepackage{amsmath}

\begin{document}
Write
\begin{align}
x+y\label{eq:eq1}\tag{Aa}\\
x+z\label{eq:eq2}\tag{Bb}\\
y-z\label{eq:eq3}\tag{Cc}\\
y-2z\nonumber
\end{align}
then cite \eqref{eq:eq1} and \eqref{eq:eq2} or \eqref{eq:eq3} separately.
\end{document}

produces:

screenshot of output

Uninstall / remove a Homebrew package including all its dependencies

Other answers didn't work for me, but this did (in fish shell):

brew remove <package>
for p in (brew deps <package>)
    brew remove $p
end

Because brew remove $p fails when some other package depends on p.

Tensorflow image reading & display

After speaking with you in the comments, I believe that you can just do this using numpy/scipy. The ideas is to read the image in the numpy 3d-array and feed it into the variable.

from scipy import misc
import tensorflow as tf

img = misc.imread('01.png')
print img.shape    # (32, 32, 3)

img_tf = tf.Variable(img)
print img_tf.get_shape().as_list()  # [32, 32, 3]

Then you can run your graph:

init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
im = sess.run(img_tf)

and verify that it is the same:

import matplotlib.pyplot as plt
fig = plt.figure()
fig.add_subplot(1,2,1)
plt.imshow(im)
fig.add_subplot(1,2,2)
plt.imshow(img)
plt.show()

enter image description here

P.S. you mentioned: Since it's supposed to parallelize reading, it seems useful to know.. To which I can say that rarely in data-analysis reading of the data is the bottleneck. Most of your time you will spend training your model.

What's "this" in JavaScript onclick?

The value of event handler attributes such as onclick should just be JavaScript, without any "javascript:" prefix. The javascript: pseudo-protocol is used in a URL, for example:

<a href="javascript:func(this)">here</a>

You should use the onclick="func(this)" form in preference to this though. Also note that in my example above using the javascript: pseudo-protocol "this" will refer to the window object rather than the <a> element.

How to delete projects in Intellij IDEA 14?

In my strange case, Intellij remembers forever about my project even if I delete .iml... Thus I did the following:

  1. Close project. Delete the .iml file.
  2. Rename my project directory (say my_proj) to my_proj_backup.
  3. (Possibly not needed) Open my_proj_backup in Intellij and close.
  4. Create an empty directory called my_proj, and open it in Intellij. Then close it.
  5. Remove the my_proj and move my_proj_backup back to my_proj. Then open my_proj in Intellij.

Then it happily forgot the old my_proj :)

Deactivate or remove the scrollbar on HTML

If you really need it...

html { overflow-y: hidden; }

How do you rotate a two dimensional array?

C code for matrix transpose & rotate (+/-90, +/-180)

  • Supports square and non-square matrices, has in-place and copy features
  • Supports both 2D arrays and 1D pointers with logical rows/cols
  • Unit tests; see tests for examples of usage
  • tested gcc -std=c90 -Wall -pedantic, MSVC17

`

#include <stdlib.h>
#include <memory.h>
#include <assert.h>

/* 
    Matrix transpose & rotate (+/-90, +/-180)
        Supports both 2D arrays and 1D pointers with logical rows/cols
        Supports square and non-square matrices, has in-place and copy features
        See tests for examples of usage
    tested gcc -std=c90 -Wall -pedantic, MSVC17
*/

typedef int matrix_data_t;  /* matrix data type */

void transpose(const matrix_data_t* src, matrix_data_t* dst, int rows, int cols);
void transpose_inplace(matrix_data_t* data, int n );
void rotate(int direction, const matrix_data_t* src, matrix_data_t* dst, int rows, int cols);
void rotate_inplace(int direction, matrix_data_t* data, int n);
void reverse_rows(matrix_data_t* data, int rows, int cols);
void reverse_cols(matrix_data_t* data, int rows, int cols);

/* test/compare fn */
int test_cmp(const matrix_data_t* lhs, const matrix_data_t* rhs, int rows, int cols );

/* TESTS/USAGE */
void transpose_test() {

    matrix_data_t sq3x3[9] = { 0,1,2,3,4,5,6,7,8 };/* 3x3 square, odd length side */
    matrix_data_t sq3x3_cpy[9];
    matrix_data_t sq3x3_2D[3][3] = { { 0,1,2 },{ 3,4,5 },{ 6,7,8 } };/* 2D 3x3 square */
    matrix_data_t sq3x3_2D_copy[3][3];

    /* expected test values */
    const matrix_data_t sq3x3_orig[9] = { 0,1,2,3,4,5,6,7,8 };
    const matrix_data_t sq3x3_transposed[9] = { 0,3,6,1,4,7,2,5,8};

    matrix_data_t sq4x4[16]= { 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 };/* 4x4 square, even length*/
    const matrix_data_t sq4x4_orig[16] = { 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 };
    const matrix_data_t sq4x4_transposed[16] = { 0,4,8,12,1,5,9,13,2,6,10,14,3,7,11,15 };

    /* 2x3 rectangle */
    const matrix_data_t r2x3_orig[6] = { 0,1,2,3,4,5 };
    const matrix_data_t r2x3_transposed[6] = { 0,3,1,4,2,5 };
    matrix_data_t r2x3_copy[6];

    matrix_data_t r2x3_2D[2][3] = { {0,1,2},{3,4,5} };  /* 2x3 2D rectangle */
    matrix_data_t r2x3_2D_t[3][2];

    /* matrix_data_t r3x2[6] = { 0,1,2,3,4,5 }; */
    matrix_data_t r3x2_copy[6];
    /* 3x2 rectangle */
    const matrix_data_t r3x2_orig[6] = { 0,1,2,3,4,5 };
    const matrix_data_t r3x2_transposed[6] = { 0,2,4,1,3,5 };

    matrix_data_t r6x1[6] = { 0,1,2,3,4,5 };    /* 6x1 */
    matrix_data_t r6x1_copy[6];

    matrix_data_t r1x1[1] = { 0 };  /*1x1*/
    matrix_data_t r1x1_copy[1];

    /* 3x3 tests, 2D array tests */
    transpose_inplace(sq3x3, 3);    /* transpose in place */
    assert(!test_cmp(sq3x3, sq3x3_transposed, 3, 3));
    transpose_inplace(sq3x3, 3);    /* transpose again */
    assert(!test_cmp(sq3x3, sq3x3_orig, 3, 3));

    transpose(sq3x3, sq3x3_cpy, 3, 3);  /* transpose copy 3x3*/
    assert(!test_cmp(sq3x3_cpy, sq3x3_transposed, 3, 3));

    transpose((matrix_data_t*)sq3x3_2D, (matrix_data_t*)sq3x3_2D_copy, 3, 3);   /* 2D array transpose/copy */
    assert(!test_cmp((matrix_data_t*)sq3x3_2D_copy, sq3x3_transposed, 3, 3));
    transpose_inplace((matrix_data_t*)sq3x3_2D_copy, 3);    /* 2D array transpose in place */
    assert(!test_cmp((matrix_data_t*)sq3x3_2D_copy, sq3x3_orig, 3, 3));

    /* 4x4 tests */
    transpose_inplace(sq4x4, 4);    /* transpose in place */
    assert(!test_cmp(sq4x4, sq4x4_transposed, 4,4));
    transpose_inplace(sq4x4, 4);    /* transpose again */
    assert(!test_cmp(sq4x4, sq4x4_orig, 3, 3));

    /* 2x3,3x2 tests */
    transpose(r2x3_orig, r2x3_copy, 2, 3);
    assert(!test_cmp(r2x3_copy, r2x3_transposed, 3, 2));

    transpose(r3x2_orig, r3x2_copy, 3, 2);
    assert(!test_cmp(r3x2_copy, r3x2_transposed, 2,3));

    /* 2D array */
    transpose((matrix_data_t*)r2x3_2D, (matrix_data_t*)r2x3_2D_t, 2, 3);
    assert(!test_cmp((matrix_data_t*)r2x3_2D_t, r2x3_transposed, 3,2));

    /* Nx1 test, 1x1 test */
    transpose(r6x1, r6x1_copy, 6, 1);
    assert(!test_cmp(r6x1_copy, r6x1, 1, 6));

    transpose(r1x1, r1x1_copy, 1, 1);
    assert(!test_cmp(r1x1_copy, r1x1, 1, 1));

}

void rotate_test() {

    /* 3x3 square */
    const matrix_data_t sq3x3[9] = { 0,1,2,3,4,5,6,7,8 };
    const matrix_data_t sq3x3_r90[9] = { 6,3,0,7,4,1,8,5,2 };
    const matrix_data_t sq3x3_180[9] = { 8,7,6,5,4,3,2,1,0 };
    const matrix_data_t sq3x3_l90[9] = { 2,5,8,1,4,7,0,3,6 };
    matrix_data_t sq3x3_copy[9];

    /* 3x3 square, 2D */
    matrix_data_t sq3x3_2D[3][3] = { { 0,1,2 },{ 3,4,5 },{ 6,7,8 } };

    /* 4x4, 2D */
    matrix_data_t sq4x4[4][4] = { { 0,1,2,3 },{ 4,5,6,7 },{ 8,9,10,11 },{ 12,13,14,15 } };
    matrix_data_t sq4x4_copy[4][4];
    const matrix_data_t sq4x4_r90[16] = { 12,8,4,0,13,9,5,1,14,10,6,2,15,11,7,3 };
    const matrix_data_t sq4x4_l90[16] = { 3,7,11,15,2,6,10,14,1,5,9,13,0,4,8,12 };
    const matrix_data_t sq4x4_180[16] = { 15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0 };

    matrix_data_t r6[6] = { 0,1,2,3,4,5 };  /* rectangle with area of 6 (1x6,2x3,3x2, or 6x1) */
    matrix_data_t r6_copy[6];
    const matrix_data_t r1x6_r90[6] = { 0,1,2,3,4,5 };
    const matrix_data_t r1x6_l90[6] = { 5,4,3,2,1,0 };
    const matrix_data_t r1x6_180[6] = { 5,4,3,2,1,0 };

    const matrix_data_t r2x3_r90[6] = { 3,0,4,1,5,2 };
    const matrix_data_t r2x3_l90[6] = { 2,5,1,4,0,3 };
    const matrix_data_t r2x3_180[6] = { 5,4,3,2,1,0 };

    const matrix_data_t r3x2_r90[6] = { 4,2,0,5,3,1 };
    const matrix_data_t r3x2_l90[6] = { 1,3,5,0,2,4 };
    const matrix_data_t r3x2_180[6] = { 5,4,3,2,1,0 };

    const matrix_data_t r6x1_r90[6] = { 5,4,3,2,1,0 };
    const matrix_data_t r6x1_l90[6] = { 0,1,2,3,4,5 };
    const matrix_data_t r6x1_180[6] = { 5,4,3,2,1,0 };

    /* sq3x3 tests */
    rotate(90, sq3x3, sq3x3_copy, 3, 3);    /* +90 */
    assert(!test_cmp(sq3x3_copy, sq3x3_r90, 3, 3));
    rotate(-90, sq3x3, sq3x3_copy, 3, 3);   /* -90 */
    assert(!test_cmp(sq3x3_copy, sq3x3_l90, 3, 3));
    rotate(180, sq3x3, sq3x3_copy, 3, 3);   /* 180 */
    assert(!test_cmp(sq3x3_copy, sq3x3_180, 3, 3));
    /* sq3x3 in-place rotations */
    memcpy( sq3x3_copy, sq3x3, 3 * 3 * sizeof(matrix_data_t));
    rotate_inplace(90, sq3x3_copy, 3);
    assert(!test_cmp(sq3x3_copy, sq3x3_r90, 3, 3));
    rotate_inplace(-90, sq3x3_copy, 3);
    assert(!test_cmp(sq3x3_copy, sq3x3, 3, 3)); /* back to 0 orientation */
    rotate_inplace(180, sq3x3_copy, 3);
    assert(!test_cmp(sq3x3_copy, sq3x3_180, 3, 3));
    rotate_inplace(-180, sq3x3_copy, 3);
    assert(!test_cmp(sq3x3_copy, sq3x3, 3, 3));
    rotate_inplace(180, (matrix_data_t*)sq3x3_2D, 3);/* 2D test */
    assert(!test_cmp((matrix_data_t*)sq3x3_2D, sq3x3_180, 3, 3));

    /* sq4x4 */
    rotate(90, (matrix_data_t*)sq4x4, (matrix_data_t*)sq4x4_copy, 4, 4);
    assert(!test_cmp((matrix_data_t*)sq4x4_copy, sq4x4_r90, 4, 4));
    rotate(-90, (matrix_data_t*)sq4x4, (matrix_data_t*)sq4x4_copy, 4, 4);
    assert(!test_cmp((matrix_data_t*)sq4x4_copy, sq4x4_l90, 4, 4));
    rotate(180, (matrix_data_t*)sq4x4, (matrix_data_t*)sq4x4_copy, 4, 4);
    assert(!test_cmp((matrix_data_t*)sq4x4_copy, sq4x4_180, 4, 4));

    /* r6 as 1x6 */
    rotate(90, r6, r6_copy, 1, 6);
    assert(!test_cmp(r6_copy, r1x6_r90, 1, 6));
    rotate(-90, r6, r6_copy, 1, 6);
    assert(!test_cmp(r6_copy, r1x6_l90, 1, 6));
    rotate(180, r6, r6_copy, 1, 6);
    assert(!test_cmp(r6_copy, r1x6_180, 1, 6));

    /* r6 as 2x3 */
    rotate(90, r6, r6_copy, 2, 3);
    assert(!test_cmp(r6_copy, r2x3_r90, 2, 3));
    rotate(-90, r6, r6_copy, 2, 3);
    assert(!test_cmp(r6_copy, r2x3_l90, 2, 3));
    rotate(180, r6, r6_copy, 2, 3);
    assert(!test_cmp(r6_copy, r2x3_180, 2, 3));

    /* r6 as 3x2 */
    rotate(90, r6, r6_copy, 3, 2);
    assert(!test_cmp(r6_copy, r3x2_r90, 3, 2));
    rotate(-90, r6, r6_copy, 3, 2);
    assert(!test_cmp(r6_copy, r3x2_l90, 3, 2));
    rotate(180, r6, r6_copy, 3, 2);
    assert(!test_cmp(r6_copy, r3x2_180, 3, 2));

    /* r6 as 6x1 */
    rotate(90, r6, r6_copy, 6, 1);
    assert(!test_cmp(r6_copy, r6x1_r90, 6, 1));
    rotate(-90, r6, r6_copy, 6, 1);
    assert(!test_cmp(r6_copy, r6x1_l90, 6, 1));
    rotate(180, r6, r6_copy, 6, 1);
    assert(!test_cmp(r6_copy, r6x1_180, 6, 1));
}

/* test comparison fn, return 0 on match else non zero */
int test_cmp(const matrix_data_t* lhs, const matrix_data_t* rhs, int rows, int cols) {

    int r, c;

    for (r = 0; r < rows; ++r) {
        for (c = 0; c < cols; ++c) {
            if ((lhs + r * cols)[c] != (rhs + r * cols)[c])
                return -1;
        }
    }
    return 0;
}

/*
Reverse values in place of each row in 2D matrix data[rows][cols] or in 1D pointer with logical rows/cols
[A B C] ->  [C B A]
[D E F]     [F E D]
*/
void reverse_rows(matrix_data_t* data, int rows, int cols) {

    int r, c;
    matrix_data_t temp;
    matrix_data_t* pRow = NULL;

    for (r = 0; r < rows; ++r) {
        pRow = (data + r * cols);
        for (c = 0; c < (int)(cols / 2); ++c) { /* explicit truncate */
            temp = pRow[c];
            pRow[c] = pRow[cols - 1 - c];
            pRow[cols - 1 - c] = temp;
        }
    }
}

/*
Reverse values in place of each column in 2D matrix data[rows][cols] or in 1D pointer with logical rows/cols
[A B C] ->  [D E F]
[D E F]     [A B C]
*/
void reverse_cols(matrix_data_t* data, int rows, int cols) {

    int r, c;
    matrix_data_t temp;
    matrix_data_t* pRowA = NULL;
    matrix_data_t* pRowB = NULL;

    for (c = 0; c < cols; ++c) {
        for (r = 0; r < (int)(rows / 2); ++r) { /* explicit truncate */
            pRowA = data + r * cols;
            pRowB = data + cols * (rows - 1 - r);
            temp = pRowA[c];
            pRowA[c] = pRowB[c];
            pRowB[c] = temp;
        }
    }
}

/* Transpose NxM matrix to MxN matrix in O(n) time */
void transpose(const matrix_data_t* src, matrix_data_t* dst, int N, int M) {

    int i;
    for (i = 0; i<N*M; ++i) dst[(i%M)*N + (i / M)] = src[i];    /* one-liner version */

    /*
    expanded version of one-liner:  calculate XY based on array index, then convert that to YX array index
    int i,j,x,y;
    for (i = 0; i < N*M; ++i) {
    x = i % M;
    y = (int)(i / M);
    j = x * N + y;
    dst[j] = src[i];
    }
    */

    /*
    nested for loop version
    using ptr arithmetic to get proper row/column
    this is really just dst[col][row]=src[row][col]

    int r, c;

    for (r = 0; r < rows; ++r) {
        for (c = 0; c < cols; ++c) {
            (dst + c * rows)[r] = (src + r * cols)[c];
        }
    }
    */
}

/*
Transpose NxN matrix in place
*/
void transpose_inplace(matrix_data_t* data, int N ) {

    int r, c;
    matrix_data_t temp;

    for (r = 0; r < N; ++r) {
        for (c = r; c < N; ++c) { /*start at column=row*/
                                    /* using ptr arithmetic to get proper row/column */
                                    /* this is really just
                                    temp=dst[col][row];
                                    dst[col][row]=src[row][col];
                                    src[row][col]=temp;
                                    */
            temp = (data + c * N)[r];
            (data + c * N)[r] = (data + r * N)[c];
            (data + r * N)[c] = temp;
        }
    }
}

/*
Rotate 1D or 2D src matrix to dst matrix in a direction (90,180,-90)
Precondition:  src and dst are 2d matrices with dimensions src[rows][cols] and dst[cols][rows] or 1D pointers with logical rows/cols
*/
void rotate(int direction, const matrix_data_t* src, matrix_data_t* dst, int rows, int cols) {

    switch (direction) {
    case -90:
        transpose(src, dst, rows, cols);
        reverse_cols(dst, cols, rows);
        break;
    case 90:
        transpose(src, dst, rows, cols);
        reverse_rows(dst, cols, rows);
        break;
    case 180:
    case -180:
        /* bit copy to dst, use in-place reversals */
        memcpy(dst, src, rows*cols*sizeof(matrix_data_t));
        reverse_cols(dst, cols, rows);
        reverse_rows(dst, cols, rows);
        break;
    }
}

/*
Rotate array in a direction.
Array must be NxN 2D or 1D array with logical rows/cols
Direction can be (90,180,-90,-180)
*/
void rotate_inplace( int direction, matrix_data_t* data, int n) {

    switch (direction) {
    case -90:
        transpose_inplace(data, n);
        reverse_cols(data, n, n);
        break;
    case 90:
        transpose_inplace(data, n);
        reverse_rows(data, n, n);
        break;
    case 180:
    case -180:
        reverse_cols(data, n, n);
        reverse_rows(data, n, n);
        break;
    }
}

`

maven command line how to point to a specific settings.xml for a single command?

You can simply use:

mvn --settings YourOwnSettings.xml clean install

or

mvn -s YourOwnSettings.xml clean install

Removing double quotes from a string in Java

String withoutQuotes_line1 = line1.replace("\"", "");

have a look here

Increase distance between text and title on the y-axis

From ggplot2 2.0.0 you can use the margin = argument of element_text() to change the distance between the axis title and the numbers. Set the values of the margin on top, right, bottom, and left side of the element.

ggplot(mpg, aes(cty, hwy)) + geom_point()+
  theme(axis.title.y = element_text(margin = margin(t = 0, r = 20, b = 0, l = 0)))

margin can also be used for other element_text elements (see ?theme), such as axis.text.x, axis.text.y and title.

addition

in order to set the margin for axis titles when the axis has a different position (e.g., with scale_x_...(position = "top"), you'll need a different theme setting - e.g. axis.title.x.top. See https://github.com/tidyverse/ggplot2/issues/4343.

Finding which process was killed by Linux OOM killer

Try this out:

grep -i 'killed process' /var/log/messages

How do I convert a float number to a whole number in JavaScript?

To truncate:

_x000D_
_x000D_
// Math.trunc() is part of the ES6 spec
console.log(Math.trunc( 1.5 ));  // returns 1
console.log(Math.trunc( -1.5 )); // returns -1
// Math.floor( -1.5 ) would return -2, which is probably not what you wanted
_x000D_
_x000D_
_x000D_

To round:

_x000D_
_x000D_
console.log(Math.round( 1.5 ));  // 2
console.log(Math.round( 1.49 )); // 1
console.log(Math.round( -1.6 )); // -2
console.log(Math.round( -1.3 )); // -1
_x000D_
_x000D_
_x000D_

Default username password for Tomcat Application Manager

To reset your keyring.

  1. Go into your home folder.

  2. Press ctrl & h to show your hidden folders.

  3. Now look in your .gnome2/keyrings directory.

  4. Find the default.keyring file.

  5. Move that file to a different folder.

  6. Once done, reboot your computer.

How to get file creation date/time in Bash/Debian?

Creation date/time is normally not stored. So no, you can't.

Get the row(s) which have the max value in groups using groupby

df = pd.DataFrame({
'sp' : ['MM1', 'MM1', 'MM1', 'MM2', 'MM2', 'MM2', 'MM4', 'MM4','MM4'],
'mt' : ['S1', 'S1', 'S3', 'S3', 'S4', 'S4', 'S2', 'S2', 'S2'],
'val' : ['a', 'n', 'cb', 'mk', 'bg', 'dgb', 'rd', 'cb', 'uyi'],
'count' : [3,2,5,8,10,1,2,2,7]
})

df.groupby(['sp', 'mt']).apply(lambda grp: grp.nlargest(1, 'count'))

Finding what branch a Git commit came from

khichar.anil covered most of this in his answer.

I am just adding the flag that will remove the tags from the revision names list. This gives us:

git name-rev --name-only --exclude=tags/* $SHA

MVC : The parameters dictionary contains a null entry for parameter 'k' of non-nullable type 'System.Int32'

Also make sure the value is not too large or too small for int like in my case.

How to import set of icons into Android Studio project

Actually if you downloaded the icons pack from the android web site, you will see that you have one folder per resolution named drawable-mdpi etc. Copy all folders into the res (not the drawable) folder in Android Studio. This will automatically make all the different resolution of the icon available.

ImageMagick security policy 'PDF' blocking conversion

On Ubuntu 19.10, I have done this in /etc/ImageMagick-6/policy.xml

uncomment this

<policy domain="module" rights="read | write" pattern="{PS,PDF,XPS}" />

and comment this

<!-- <policy domain="coder" rights="none" pattern="PDF" /> -->

After that, this command work without error

convert -thumbnail x300 -background white -alpha remove sample.pdf sample.png 

How to hide command output in Bash

>/dev/null 2>&1 will mute both stdout and stderr

yum install nano >/dev/null 2>&1

How to set border's thickness in percentages?

Percentage values are not applicable to border-width in CSS. This is listed in the spec.

You will need to use JavaScript to calculate the percentage of the element's width or whatever length quantity you need, and apply the result in px or similar to the element's borders.

How do I format my oracle queries so the columns don't wrap?

Never mind, figured it out:

set wrap off
set linesize 3000 -- (or to a sufficiently large value to hold your results page)

Which I found by:

show all

And looking for some option that seemed relevant.

Youtube - downloading a playlist - youtube-dl

I have tried everything above, but none could solve my problem. I fixed it by updating the old version of youtube-dl to download playlist. To update it

sudo youtube-dl -U

or

youtube-dl -U

after you have successfully updated using the above command

youtube-dl -cit https://www.youtube.com/playlist?list=PLttJ4RON7sleuL8wDpxbKHbSJ7BH4vvCk

Why does Date.parse give incorrect results?

The accepted answer from CMS is correct, I have just added some features :

  • trim and clean input spaces
  • parse slashes, dashes, colons and spaces
  • has default day and time

// parse a date time that can contains spaces, dashes, slashes, colons
function parseDate(input) {
    // trimes and remove multiple spaces and split by expected characters
    var parts = input.trim().replace(/ +(?= )/g,'').split(/[\s-\/:]/)
    // new Date(year, month [, day [, hours[, minutes[, seconds[, ms]]]]])
    return new Date(parts[0], parts[1]-1, parts[2] || 1, parts[3] || 0, parts[4] || 0, parts[5] || 0); // Note: months are 0-based
}

jQuery SVG, why can't I addClass?

After loading jquery.svg.js you must load this file: http://keith-wood.name/js/jquery.svgdom.js.

Source: http://keith-wood.name/svg.html#dom

Working example: http://jsfiddle.net/74RbC/99/

How can I trigger a JavaScript event click

Performing a single click on an HTML element: Simply do element.click(). Most major browsers support this.


To repeat the click more than once: Add an ID to the element to uniquely select it:

<a href="#" target="_blank" id="my-link" onclick="javascript:Test('Test');">Google Chrome</a>

and call the .click() method in your JavaScript code via a for loop:

var link = document.getElementById('my-link');
for(var i = 0; i < 50; i++)
   link.click();

Best way to create a simple python web service

web.py is probably the simplest web framework out there. "Bare" CGI is simpler, but you're completely on your own when it comes to making a service that actually does something.

"Hello, World!" according to web.py isn't much longer than an bare CGI version, but it adds URL mapping, HTTP command distinction, and query parameter parsing for free:

import web

urls = (
    '/(.*)', 'hello'
)
app = web.application(urls, globals())

class hello:        
    def GET(self, name):
        if not name: 
            name = 'world'
        return 'Hello, ' + name + '!'

if __name__ == "__main__":
    app.run()

Clearing NSUserDefaults

Try This, It's working for me .

Single line of code

[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:[[NSBundle mainBundle] bundleIdentifier]];

Print commit message of a given commit in git

I use shortlog for this:

$ git shortlog master..
Username (3):
      Write something
      Add something
      Bump to 1.3.8 

Is there a way to make HTML5 video fullscreen?

Firefox 3.6 has a full screen option for HTML5 video's, right-click on the video and select 'full screen'.

The latest Webkit nightlies also support full screen HTML5 video, try the Sublime player with the latest nightly and hold Cmd / Ctrl while selecting the full screen option.

I guess Chrome / Opera will also support something like this. Hopefully IE9 will also support full screen HTML5 video.

How do I use Assert.Throws to assert the type of the exception?

Assert.That(myTestDelegate, Throws.ArgumentException
    .With.Property("Message").EqualTo("your argument is invalid."));

Google Maps V3 marker with label

The way to do this without use of plugins is to make a subclass of google's OverlayView() method.

https://developers.google.com/maps/documentation/javascript/reference?hl=en#OverlayView

You make a custom function and apply it to the map.

function Label() { 
    this.setMap(g.map);
};

Now you prototype your subclass and add HTML nodes:

Label.prototype = new google.maps.OverlayView; //subclassing google's overlayView
Label.prototype.onAdd = function() {
        this.MySpecialDiv               = document.createElement('div');
        this.MySpecialDiv.className     = 'MyLabel';
        this.getPanes().overlayImage.appendChild(this.MySpecialDiv); //attach it to overlay panes so it behaves like markers

}

you also have to implement remove and draw functions as stated in the API docs, or this won't work.

Label.prototype.onRemove = function() {
... // remove your stuff and its events if any
}
Label.prototype.draw = function() {
      var position = this.getProjection().fromLatLngToDivPixel(this.get('position')); // translate map latLng coords into DOM px coords for css positioning
var pos = this.get('position');
            $('.myLabel')
            .css({
                'top'   : position.y + 'px',
                'left'  : position.x + 'px'
            })
        ;
}

That's the gist of it, you'll have to do some more work in your specific implementation.

How to remove item from list in C#?

{
    class Program
    {
        public static List<Product> list;
        static void Main(string[] args)
        {

            list = new List<Product>() { new Product() { ProductId=1, Name="Nike 12N0",Brand="Nike",Price=12000,Quantity=50},
                 new Product() { ProductId =2, Name = "Puma 560K", Brand = "Puma", Price = 120000, Quantity = 55 },
                 new Product() { ProductId=3, Name="WoodLand V2",Brand="WoodLand",Price=21020,Quantity=25},
                 new Product() { ProductId=4, Name="Adidas S52",Brand="Adidas",Price=20000,Quantity=35},
                 new Product() { ProductId=5, Name="Rebook SPEED2O",Brand="Rebook",Price=1200,Quantity=15}};


            Console.WriteLine("Enter ProductID to remove");
            int uno = Convert.ToInt32(Console.ReadLine());
            var itemToRemove = list.Find(r => r.ProductId == uno);
            if (itemToRemove != null)
                list.Remove(itemToRemove);
            Console.WriteLine($"{itemToRemove.ProductId}{itemToRemove.Name}{itemToRemove.Brand}{itemToRemove.Price}{ itemToRemove.Quantity}");
            Console.WriteLine("------------sucessfully Removed---------------");

            var query2 = from x in list select x;
            foreach (var item in query2)
            {
                /*Console.WriteLine(item.ProductId+" "+item.Name+" "+item.Brand+" "+item.Price+" "+item.Quantity );*/
                Console.WriteLine($"{item.ProductId}{item.Name}{item.Brand}{item.Price}{ item.Quantity}");
            }

        }

    }
}

What is the !! (not not) operator in JavaScript?

!! it's using NOT operation twice together, ! convert the value to a boolean and reverse it, here is a simple example to see how !! works:

At first, the place you have:

var zero = 0;

Then you do !0, it will be converted to boolean and be evaluated to true, because 0 is falsy, so you get the reversed value and converted to boolean, so it gets evaluated to true.

!zero; //true

but we don't want the reversed boolean version of the value, so we can reverse it again to get our result! That's why we use another !.

Basically, !! make us sure, the value we get is boolean, not falsy, truthy or string etc...

So it's like using Boolean function in javascript, but easy and shorter way to convert a value to boolean:

var zero = 0;
!!zero; //false

How do I sleep for a millisecond in Perl?

From the Perldoc page on sleep:

For delays of finer granularity than one second, the Time::HiRes module (from CPAN, and starting from Perl 5.8 part of the standard distribution) provides usleep().

Actually, it provides usleep() (which sleeps in microseconds) and nanosleep() (which sleeps in nanoseconds). You may want usleep(), which should let you deal with easier numbers. 1 millisecond sleep (using each):

use strict;
use warnings;

use Time::HiRes qw(usleep nanosleep);

# 1 millisecond == 1000 microseconds
usleep(1000);
# 1 microsecond == 1000 nanoseconds
nanosleep(1000000);

If you don't want to (or can't) load a module to do this, you may also be able to use the built-in select() function:

# Sleep for 250 milliseconds
select(undef, undef, undef, 0.25);

Getting data-* attribute for onclick event for an html element

Check if the data attribute is present, then do the stuff...

$('body').on('click', '.CLICK_BUTTON_CLASS', function (e) {
                        if(e.target.getAttribute('data-title')) {
                            var careerTitle = $(this).attr('data-title');
                            if (careerTitle.length > 0) $('.careerFormTitle').text(careerTitle);
                        }
                });

Apply CSS style attribute dynamically in Angular JS

ngStyle directive allows you to set CSS style on an HTML element dynamically.

Expression which evals to an object whose keys are CSS style names and values are corresponding values for those CSS keys. Since some CSS style names are not valid keys for an object, they must be quoted.

ng-style="{color: myColor}"

Your code will be:

<div ng-style="{'width':'20px', 'height':'20px', 'margin-top':'10px', 'border':'solid 1px black', 'background-color':'#ff0000'}"></div>

If you want to use scope variables:

<div ng-style="{'background-color': data.backgroundCol}"></div>

Here an example on fiddle that use ngStyle, and below the code with the running snippet:

_x000D_
_x000D_
angular.module('myApp', [])_x000D_
.controller('MyCtrl', function($scope) {_x000D_
  $scope.items = [{_x000D_
      name: 'Misko',_x000D_
      title: 'Angular creator'_x000D_
    }, {_x000D_
      name: 'Igor',_x000D_
      title: 'Meetup master'_x000D_
    }, {_x000D_
      name: 'Vojta',_x000D_
      title: 'All-around superhero'_x000D_
    }_x000D_
_x000D_
  ];_x000D_
});
_x000D_
.pending-delete {_x000D_
  background-color: pink_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<div ng-app="myApp" ng-controller='MyCtrl' ng-style="{color: myColor}">_x000D_
_x000D_
  <input type="text" ng-model="myColor" placeholder="enter a color name">_x000D_
_x000D_
  <div ng-repeat="item in items" ng-class="{'pending-delete': item.checked}">_x000D_
    name: {{item.name}}, {{item.title}}_x000D_
    <input type="checkbox" ng-model="item.checked" />_x000D_
    <span ng-show="item.checked"/><span>(will be deleted)</span>_x000D_
  </div>_x000D_
  <p>_x000D_
    <div ng-hide="myColor== 'red'">I will hide if the color is set to 'red'.</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

<SELECT multiple> - how to allow only one item selected?

I had some dealings with the select \ multi-select this is what did the trick for me

<select name="mySelect" multiple="multiple">
    <option>Foo</option>
    <option>Bar</option>
    <option>Foo Bar</option>
    <option>Bar Foo</option>
</select>

ALTER TABLE, set null in not null column, PostgreSQL 9.1

First, Set :
ALTER TABLE person ALTER COLUMN phone DROP NOT NULL;

How to delete row based on cell value

The screenshot was very helpful - the following code will do the job (assuming data is located in column A starting A1):

Sub RemoveRows()

Dim i As Long

i = 1

Do While i <= ThisWorkbook.ActiveSheet.Range("A1").CurrentRegion.Rows.Count

    If InStr(1, ThisWorkbook.ActiveSheet.Cells(i, 1).Text, "-", vbTextCompare) > 0 Then
        ThisWorkbook.ActiveSheet.Cells(i, 1).EntireRow.Delete
    Else
        i = i + 1
    End If

Loop

End Sub

Sample file is shared: https://www.dropbox.com/s/2vhq6vw7ov7ssya/RemoweDashRows.xlsm

CSS class for pointer cursor

I don't have enough reputation to comment on the relevant answers, but to people reading this; adding .btn does not just add the pointer cursor but adds a lot of other styling as well. Which is great if it's a button and you want the bootstap button styling, but in other cases it would mess a lot up for other elements.

The best thing you can do, like Hari Das suggested, and which I also always do, is to add the following css:

.cursor-pointer {
  cursor: pointer;
}

After which you can add it to any element

<div class="cursor-pointer"> .. </div>

Can you display HTML5 <video> as a full screen background?

Just a comment on this - I've used HTML5 video for a full-screen background and it works a treat - but make sure to use either Height:100% and width:auto or the other way around - to ensure you keep aspect ratio.

As for Ipads -you can (apparently) do this, by having a hidden and then forcing the click event to fire, and having the function of the click event kick off the Load/Play().

P.s - this shouldn't require any plugins and can be done with minimal JS - If you're targeting any mobile device (I would assume you might be..) staying away from any such framework is the way forward.

How to repeat last command in python interpreter shell?

I find information that I copied below answer the question

Adapt yourself to IDLE: Instead of hitting the up arrow to bring back a previous command, if you just put your cursor on the previous command you want to repeat and then press "enter", that command will be repeated at the current command prompt. Press enter again, and the command gets executed.

Force IDLE to adapt itself to you: If you insist on making the arrow keys in the IDLE command prompt window work like those in every other command prompt, you can do this. Go to the "Options" menu, select "Configure IDLE", and then "Keys". Changing the key that is associated with the "previous command" and "next command" actions to be the up arrow, and down arrow, respectively.

source

Merge PDF files with PHP

This worked for me on Windows

  1. download PDFtk free from https://www.pdflabs.com/tools/pdftk-the-pdf-toolkit/
  2. drop folder (PDFtk) into the root of c:
  3. add the following to your php code where $file1 is the location and name of the first PDF file, $file2 is the location and name of the second and $newfile is the location and name of the destination file

    $file1 = ' c:\\\www\\\folder1\\\folder2\\\file1.pdf';  
    $file2 = ' c:\\\www\\\folder1\\\folder2\\\file2.pdf';  
    $file3 = ' c:\\\www\\\folder1\\\folder2\\\file3.pdf';   
    
    $command =  'cmd /c C:\\\pdftk\\\bin\\\pdftk.exe '.$file1.$file2.$newfile;
    $result = exec($command);
    

List<T> OrderBy Alphabetical Order

people.OrderBy(person => person.lastname).ToList();

first-child and last-child with IE8

If your table is only 2 columns across, you can easily reach the second td with the adjacent sibling selector, which IE8 does support along with :first-child:

.editor td:first-child
{
    width: 150px; 
}

.editor td:first-child + td input,
.editor td:first-child + td textarea
{
    width: 500px;
    padding: 3px 5px 5px 5px;
    border: 1px solid #CCC; 
}

Otherwise, you'll have to use a JS selector library like jQuery, or manually add a class to the last td, as suggested by James Allardice.

How to do a Postgresql subquery in select clause with join in from clause like SQL Server?

I am just answering here with the formatted version of the final sql I needed based on Bob Jarvis answer as posted in my comment above:

select n1.name, n1.author_id, cast(count_1 as numeric)/total_count
  from (select id, name, author_id, count(1) as count_1
          from names
          group by id, name, author_id) n1
inner join (select author_id, count(1) as total_count
              from names
              group by author_id) n2
  on (n2.author_id = n1.author_id)

How to check if a process id (PID) exists

You have two ways:

Lets start by looking for a specific application in my laptop:

[root@pinky:~]# ps fax | grep mozilla
 3358 ?        S      0:00  \_ /bin/sh /usr/lib/firefox-3.5/run-mozilla.sh /usr/lib/firefox-3.5/firefox
16198 pts/2    S+     0:00              \_ grep mozilla

All examples now will look for PID 3358.

First way: Run "ps aux" and grep for the PID in the second column. In this example I look for firefox, and then for it's PID:

[root@pinky:~]# ps aux | awk '{print $2 }' | grep 3358
3358

So your code will be:

if [ ps aux | awk '{print $2 }' | grep -q $PID 2> /dev/null ]; then
    kill $PID 
fi

Second way: Just look for something in the /proc/$PID directory. I am using "exe" in this example, but you can use anything else.

[root@pinky:~]# ls -l /proc/3358/exe 
lrwxrwxrwx. 1 elcuco elcuco 0 2010-06-15 12:33 /proc/3358/exe -> /bin/bash

So your code will be:

if [ -f /proc/$PID/exe ]; then
    kill $PID 
fi

BTW: whats wrong with kill -9 $PID || true ?


EDIT:

After thinking about it for a few months.. (about 24...) the original idea I gave here is a nice hack, but highly unportable. While it teaches a few implementation details of Linux, it will fail to work on Mac, Solaris or *BSD. It may even fail on future Linux kernels. Please - use "ps" as described in other responses.

Node Version Manager install - nvm command not found

First add following lines in ~/.bashrc file

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion

then open terminal and source the nvm.sh script

source ~/.nvm/nvm.sh

jQuery creating objects

You can always make it a function

function writeObject(color){
    $('body').append('<div style="color:'+color+';">Hello!</div>')
}

writeObject('blue') ? enter image description here

How to make JQuery-AJAX request synchronous

From jQuery.ajax()

async Boolean
Default: true
By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false.

So in your request, you must do async: false instead of async: "false".

Update:

The return value of ajaxSubmit is not the return value of the success: function(){...}. ajaxSubmit returns no value at all, which is equivalent to undefined, which in turn evaluates to true.

And that is the reason, why the form is always submitted and is independent of sending the request synchronous or not.

If you want to submit the form only, when the response is "Successful", you must return false from ajaxSubmit and then submit the form in the success function, as @halilb already suggested.

Something along these lines should work

function ajaxSubmit() {
    var password = $.trim($('#employee_password').val());
    $.ajax({
        type: "POST",
        url: "checkpass.php",
        data: "password="+password,
        success: function(response) {
            if(response == "Successful")
            {
                $('form').removeAttr('onsubmit'); // prevent endless loop
                $('form').submit();
            }
        }
    });

    return false;
}

How to set an environment variable from a Gradle build?

If you are using an IDE, go to run, edit configurations, gradle, select gradle task and update the environment variables. See the picture below.

enter image description here

Alternatively, if you are executing gradle commands using terminal, just type 'export KEY=VALUE', and your job is done.

Java maximum memory on Windows XP

The Java heap size limits for Windows are:

  • maximum possible heap size on 32-bit Java: 1.8 GB
  • recommended heap size limit on 32-bit Java: 1.5 GB (or 1.8 GB with /3GB option)

This doesn't help you getting a bigger Java heap, but now you know you can't go beyond these values.

How to make System.out.println() shorter

My solution for BlueJ is to edit the New Class template "stdclass.tmpl" in Program Files (x86)\BlueJ\lib\english\templates\newclass and add this method:

public static <T> void p(T s)
{
    System.out.println(s);
}

Or this other version:

public static void p(Object s)
{
    System.out.println(s);
}

As for Eclipse I'm using the suggested shortcut syso + <Ctrl> + <Space> :)

How to access the first property of a Javascript object?

we can also do with this approch.

var example = {
  foo1: { /* stuff1 */},
  foo2: { /* stuff2 */},
  foo3: { /* stuff3 */}
}; 
Object.entries(example)[0][1];

Calling pylab.savefig without display in ipython

This is a matplotlib question, and you can get around this by using a backend that doesn't display to the user, e.g. 'Agg':

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

plt.plot([1,2,3])
plt.savefig('/tmp/test.png')

EDIT: If you don't want to lose the ability to display plots, turn off Interactive Mode, and only call plt.show() when you are ready to display the plots:

import matplotlib.pyplot as plt

# Turn interactive plotting off
plt.ioff()

# Create a new figure, plot into it, then close it so it never gets displayed
fig = plt.figure()
plt.plot([1,2,3])
plt.savefig('/tmp/test0.png')
plt.close(fig)

# Create a new figure, plot into it, then don't close it so it does get displayed
plt.figure()
plt.plot([1,3,2])
plt.savefig('/tmp/test1.png')

# Display all "open" (non-closed) figures
plt.show()

Django: OperationalError No Such Table

For django 1.10 you may have to do python manage.py makemigrations appname.

'LIKE ('%this%' OR '%that%') and something=else' not working

It would be nice if you could, but you can't use that syntax in SQL.

Try this:

(column1 LIKE '%this%' OR column1 LIKE '%that%') AND something = else

Note the use of brackets! You need them around the OR expression.
Without brackets, it will be parsed as A OR (B AND C),which won't give you the results you expect.

Photoshop text tool adds punctuation to the beginning of text

This is a paragraph option. Go to Window>Paragraph then a small window will pop up. You will have two buttons on the bottom. One with a arrow on the left of P and one on the right. Select the right one.

C# Help reading foreign characters using StreamReader

For swedish Å Ä Ö the only solution form the ones above working was:

Encoding.GetEncoding("iso-8859-1")

Hopefully this will save someone time.

Android Studio - Failed to apply plugin [id 'com.android.application']

Whenever you update your Gradle files do not forget to check the compatible Gradle wrapper distibutionUrl, in your case it happened because of the same.

distributionUrl=https://services.gradle.org/distributions/gradle-5.6.4-all.zip

How to use default Android drawables

Better to use android.R.drawable because it is public and documented.

Using jQuery, Restricting File Size Before Uploading

Try below code:

var sizeInKB = input.files[0].size/1024; //Normally files are in bytes but for KB divide by 1024 and so on
var sizeLimit= 30;

if (sizeInKB >= sizeLimit) {
    alert("Max file size 30KB");
    return false;
}

Parsing a YAML file in Python, and accessing the data?

Since PyYAML's yaml.load() function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:

import yaml
with open('tree.yaml', 'r') as f:
    doc = yaml.load(f)

To access branch1 text you would use:

txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"

because, in your YAML document, the value of the branch1 key is under the treeroot key.