Programs & Examples On #Class method

Methods that are called on a class instead of on an object.

Meaning of @classmethod and @staticmethod for beginner?

Though classmethod and staticmethod are quite similar, there's a slight difference in usage for both entities: classmethod must have a reference to a class object as the first parameter, whereas staticmethod can have no parameters at all.

Example

class Date(object):

    def __init__(self, day=0, month=0, year=0):
        self.day = day
        self.month = month
        self.year = year

    @classmethod
    def from_string(cls, date_as_string):
        day, month, year = map(int, date_as_string.split('-'))
        date1 = cls(day, month, year)
        return date1

    @staticmethod
    def is_date_valid(date_as_string):
        day, month, year = map(int, date_as_string.split('-'))
        return day <= 31 and month <= 12 and year <= 3999

date2 = Date.from_string('11-09-2012')
is_date = Date.is_date_valid('11-09-2012')

Explanation

Let's assume an example of a class, dealing with date information (this will be our boilerplate):

class Date(object):

    def __init__(self, day=0, month=0, year=0):
        self.day = day
        self.month = month
        self.year = year

This class obviously could be used to store information about certain dates (without timezone information; let's assume all dates are presented in UTC).

Here we have __init__, a typical initializer of Python class instances, which receives arguments as a typical instancemethod, having the first non-optional argument (self) that holds a reference to a newly created instance.

Class Method

We have some tasks that can be nicely done using classmethods.

Let's assume that we want to create a lot of Date class instances having date information coming from an outer source encoded as a string with format 'dd-mm-yyyy'. Suppose we have to do this in different places in the source code of our project.

So what we must do here is:

  1. Parse a string to receive day, month and year as three integer variables or a 3-item tuple consisting of that variable.
  2. Instantiate Date by passing those values to the initialization call.

This will look like:

day, month, year = map(int, string_date.split('-'))
date1 = Date(day, month, year)

For this purpose, C++ can implement such a feature with overloading, but Python lacks this overloading. Instead, we can use classmethod. Let's create another "constructor".

    @classmethod
    def from_string(cls, date_as_string):
        day, month, year = map(int, date_as_string.split('-'))
        date1 = cls(day, month, year)
        return date1

date2 = Date.from_string('11-09-2012')

Let's look more carefully at the above implementation, and review what advantages we have here:

  1. We've implemented date string parsing in one place and it's reusable now.
  2. Encapsulation works fine here (if you think that you could implement string parsing as a single function elsewhere, this solution fits the OOP paradigm far better).
  3. cls is an object that holds the class itself, not an instance of the class. It's pretty cool because if we inherit our Date class, all children will have from_string defined also.

Static method

What about staticmethod? It's pretty similar to classmethod but doesn't take any obligatory parameters (like a class method or instance method does).

Let's look at the next use case.

We have a date string that we want to validate somehow. This task is also logically bound to the Date class we've used so far, but doesn't require instantiation of it.

Here is where staticmethod can be useful. Let's look at the next piece of code:

    @staticmethod
    def is_date_valid(date_as_string):
        day, month, year = map(int, date_as_string.split('-'))
        return day <= 31 and month <= 12 and year <= 3999

    # usage:
    is_date = Date.is_date_valid('11-09-2012')

So, as we can see from usage of staticmethod, we don't have any access to what the class is---it's basically just a function, called syntactically like a method, but without access to the object and its internals (fields and another methods), while classmethod does.

What is the purpose of class methods?

It allows you to write generic class methods that you can use with any compatible class.

For example:

@classmethod
def get_name(cls):
    print cls.name

class C:
    name = "tester"

C.get_name = get_name

#call it:
C.get_name()

If you don't use @classmethod you can do it with self keyword but it needs an instance of Class:

def get_name(self):
    print self.name

class C:
    name = "tester"

C.get_name = get_name

#call it:
C().get_name() #<-note the its an instance of class C

Ruby: Calling class method from instance

You're doing it the right way. Class methods (similar to 'static' methods in C++ or Java) aren't part of the instance, so they have to be referenced directly.

On that note, in your example you'd be better served making 'default_make' a regular method:

#!/usr/bin/ruby

class Truck
    def default_make
        # Class method.
        "mac"
    end

    def initialize
        # Instance method.
        puts default_make  # gets the default via the class's method.
    end
end

myTruck = Truck.new()

Class methods are more useful for utility-type functions that use the class. For example:

#!/usr/bin/ruby

class Truck
    attr_accessor :make

    def default_make
        # Class method.
        "mac"
    end

    def self.buildTrucks(make, count)
        truckArray = []

        (1..count).each do
            truckArray << Truck.new(make)
        end

        return truckArray
    end

    def initialize(make = nil)
        if( make == nil )
            @make = default_make()
        else
            @make = make
        end
    end
end

myTrucks = Truck.buildTrucks("Yotota", 4)

myTrucks.each do |truck|
    puts truck.make
end

What is the difference between class and instance methods?

In Objective-C all methods start with either a "-" or "+" character. Example:

@interface MyClass : NSObject
// instance method
- (void) instanceMethod;

+ (void) classMethod;
@end

The "+" and "-" characters specify whether a method is a class method or an instance method respectively.

The difference would be clear if we call these methods. Here the methods are declared in MyClass.

instance method require an instance of the class:

MyClass* myClass = [[MyClass alloc] init];
[myClass instanceMethod];

Inside MyClass other methods can call instance methods of MyClass using self:

-(void) someMethod
{
    [self instanceMethod];
}

But, class methods must be called on the class itself:

[MyClass classMethod];

Or:

MyClass* myClass = [[MyClass alloc] init];
[myClass class] classMethod];

This won't work:

// Error
[myClass classMethod];
// Error
[self classMethod];

How to make a class property?

As far as I can tell, there is no way to write a setter for a class property without creating a new metaclass.

I have found that the following method works. Define a metaclass with all of the class properties and setters you want. IE, I wanted a class with a title property with a setter. Here's what I wrote:

class TitleMeta(type):
    @property
    def title(self):
        return getattr(self, '_title', 'Default Title')

    @title.setter
    def title(self, title):
        self._title = title
        # Do whatever else you want when the title is set...

Now make the actual class you want as normal, except have it use the metaclass you created above.

# Python 2 style:
class ClassWithTitle(object):
    __metaclass__ = TitleMeta
    # The rest of your class definition...

# Python 3 style:
class ClassWithTitle(object, metaclass = TitleMeta):
    # Your class definition...

It's a bit weird to define this metaclass as we did above if we'll only ever use it on the single class. In that case, if you're using the Python 2 style, you can actually define the metaclass inside the class body. That way it's not defined in the module scope.

Calling C++ class methods via a function pointer

Minimal runnable example

main.cpp

#include <cassert>

class C {
    public:
        int i;
        C(int i) : i(i) {}
        int m(int j) { return this->i + j; }
};

int main() {
    // Get a method pointer.
    int (C::*p)(int) = &C::m;

    // Create a test object.
    C c(1);
    C *cp = &c;

    // Operator .*
    assert((c.*p)(2) == 3);

    // Operator ->*
    assert((cp->*p)(2) == 3);
}

Compile and run:

g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp
./main.out

Tested in Ubuntu 18.04.

You cannot change the order of the parenthesis or omit them. The following do not work:

c.*p(2)
c.*(p)(2)

GCC 9.2 would fail with:

main.cpp: In function ‘int main()’:
main.cpp:19:18: error: must use ‘.*’ or ‘->*’ to call pointer-to-member function in ‘p (...)’, e.g. ‘(... ->* p) (...)’
   19 |     assert(c.*p(2) == 3);
      |

C++11 standard

.* and ->* are a single operators introduced in C++ for this purpose, and not present in C.

C++11 N3337 standard draft:

  • 2.13 "Operators and punctuators" has a list of all operators, which contains .* and ->*.
  • 5.5 "Pointer-to-member operators" explains what they do

Enable IIS7 gzip

If you use YSlow with Firebug and analyse your page performance, YSlow will certainly tell you what artifacts on your page are not gzip'd!

Exception in thread "main" java.lang.Error: Unresolved compilation problems

For this error:

Exception in thread "main" java.lang.Error: Unresolved compilation problems:

There are problems with your import or package name.
You can delete the package name or fix import errors

Expected response code 250 but got code "535", with message "535-5.7.8 Username and Password not accepted

I had everything fine. Less secure app option was also enabled. Still, I was getting the error. What I have done is:

  • Google will send you Critical security alert
  • Then you have to authorize that activity. ( Clicking on 'YES, THAT WAS ME' type thing )
  • Then you can try sending email again.

Changing the URL in react-router v4 without using Redirect or Link

I'm using this to redirect with React Router v4:

this.props.history.push('/foo');

Hope it work for you ;)

Git keeps asking me for my ssh key passphrase

What worked for me on Windows was (I had cloned code from a repo 1st):

eval $(ssh-agent)
ssh-add 
git pull 

at which time it asked me one last time for my passphrase

Credits: the solution was taken from https://unix.stackexchange.com/questions/12195/how-to-avoid-being-asked-passphrase-each-time-i-push-to-bitbucket

No route matches "/users/sign_out" devise rails 3

I changed this line in devise.rb:

config.sign_out_via = :delete

to

config.sign_out_via = :get

and it started working for me.

input[type='text'] CSS selector does not apply to default-type text inputs?

By CSS specifications, browsers may or may not use information about default attributes; mostly the don’t. The relevant clause in the CSS 2.1 spec is 5.8.2 Default attribute values in DTDs. In CSS 3 Selectors, it’s clause 6.3.4, with the same name. It recommends: “Selectors should be designed so that they work whether or not the default values are included in the document tree.”

It is generally best to explicitly specify essential attributes such as type=text instead of defaulting them. The reason is that there is no simple reliable way to refer to the input elements with defaulted type attribute.

How to stop the task scheduled in java.util.Timer class

Either call cancel() on the Timer if that's all it's doing, or cancel() on the TimerTask if the timer itself has other tasks which you wish to continue.

PivotTable to show values, not sum of values

I fear this might turn out to BE the long way round but could depend on how big your data set is – presumably more than four months for example.

Assuming your data is in ColumnA:C and has column labels in Row 1, also that Month is formatted mmm(this last for ease of sorting):

  1. Sort the data by Name then Month
  2. Enter in D2 =IF(AND(A2=A1,C2=C1),D1+1,1) (One way to deal with what is the tricky issue of multiple entries for the same person for the same month).
  3. Create a pivot table from A1:D(last occupied row no.)
  4. Say insert in F1.
  5. Layout as in screenshot.

SO12803305 example

I’m hoping this would be adequate for your needs because pivot table should automatically update (provided range is appropriate) in response to additional data with refresh. If not (you hard taskmaster), continue but beware that the following steps would need to be repeated each time the source data changes.

  1. Copy pivot table and Paste Special/Values to, say, L1.
  2. Delete top row of copied range with shift cells up.
  3. Insert new cell at L1 and shift down.
  4. Key 'Name' into L1.
  5. Filter copied range and for ColumnL, select Row Labels and numeric values.
  6. Delete contents of L2:L(last selected cell)
  7. Delete blank rows in copied range with shift cells up (may best via adding a column that counts all 12 months). Hopefully result should be as highlighted in yellow.

Happy to explain further/try again (I've not really tested this) if does not suit.

EDIT (To avoid second block of steps above and facilitate updating for source data changes)

.0. Before first step 2. add a blank row at the very top and move A2:D2 up.
.2. Adjust cell references accordingly (in D3 =IF(AND(A3=A2,C3=C2),D2+1,1).
.3. Create pivot table from A:D

.6. Overwrite Row Labels with Name.
.7. PivotTable Tools, Design, Report Layout, Show in Tabular Form and sort rows and columns A>Z.
.8. Hide Row1, ColumnG and rows and columns that show (blank).

additional example

Steps .0. and .2. in the edit are not required if the pivot table is in a different sheet from the source data (recommended).

Step .3. in the edit is a change to simplify the consequences of expanding the source data set. However introduces (blank) into pivot table that if to be hidden may need adjustment on refresh. So may be better to adjust source data range each time that changes instead: PivotTable Tools, Options, Change Data Source, Change Data Source, Select a table or range). In which case copy rather than move in .0.

How to fix/convert space indentation in Sublime Text?

If you find search and replace faster to use, you could use a regex replace like this:

Find (regex): (^|\G) {2} (Instead of " {2}" <space>{2} you can just write two spaces. Used it here for clarity.)

Replace with 4 spaces, or whatever you want, like \t.

No module named 'pymysql'

I ran into the same problem earlier, but solved it in a way slightly different from what we have here. So, I thought I'd add my way as well. Hopefully, it will help someone!

sudo apt-get install mysql-client didn't work for me. However, I have Homebrew already installed. So, instead, I tried:

brew install mysql-client

Now, I don't get the error any more.

Good luck!

What does it mean by select 1 from table?

SELECT 1 FROM TABLE_NAME means, "Return 1 from the table". It is pretty unremarkable on its own, so normally it will be used with WHERE and often EXISTS (as @gbn notes, this is not necessarily best practice, it is, however, common enough to be noted, even if it isn't really meaningful (that said, I will use it because others use it and it is "more obvious" immediately. Of course, that might be a viscous chicken vs. egg issue, but I don't generally dwell)).

 SELECT * FROM TABLE1 T1 WHERE EXISTS (
     SELECT 1 FROM TABLE2 T2 WHERE T1.ID= T2.ID
 );

Basically, the above will return everything from table 1 which has a corresponding ID from table 2. (This is a contrived example, obviously, but I believe it conveys the idea. Personally, I would probably do the above as SELECT * FROM TABLE1 T1 WHERE ID IN (SELECT ID FROM TABLE2); as I view that as FAR more explicit to the reader unless there were a circumstantially compelling reason not to).

EDIT

There actually is one case which I forgot about until just now. In the case where you are trying to determine existence of a value in the database from an outside language, sometimes SELECT 1 FROM TABLE_NAME will be used. This does not offer significant benefit over selecting an individual column, but, depending on implementation, it may offer substantial gains over doing a SELECT *, simply because it is often the case that the more columns that the DB returns to a language, the larger the data structure, which in turn mean that more time will be taken.

python: creating list from string

input = ['word1, 23, 12','word2, 10, 19','word3, 11, 15']
output = []
for item in input:
    items = item.split(',')
    output.append([items[0], int(items[1]), int(items[2])])

What is the difference between '@' and '=' in directive scope in AngularJS?

@ and = see other answers.

One gotcha about &
TL;DR;
& gets expression (not only function like in examples in other answers) from a parent, and sets it as a function in the directive, that calls the expression. And this function has the ability to replace any variable (even function name) of expression, by passing an object with the variables.

explained
& is an expression reference, that means if you pass something like <myDirective expr="x==y"></myDirective>
in the directive this expr will be a function, that calls the expression, like:
function expr(){return x == y}.
so in directive's html <button ng-click="expr()"></button> will call the expression. In js of the directive just $scope.expr() will call the expression too.
The expression will be called with $scope.x and $scope.y of the parent.
You have the ability to override the parameters!
If you set them by call, e.g. <button ng-click="expr({x:5})"></button>
then the expression will be called with your parameter x and parent's parameter y.
You can override both.
Now you know, why <button ng-click="functionFromParent({x:5})"></button> works.
Because it just calls the expression of parent (e.g. <myDirective functionFromParent="function1(x)"></myDirective>) and replaces possible values with your specified parameters, in this case x.
it could be:
<myDirective functionFromParent="function1(x) + 5"></myDirective>
or
<myDirective functionFromParent="function1(x) + z"></myDirective>
with child call:
<button ng-click="functionFromParent({x:5, z: 4})"></button>.
or even with function replacement:
<button ng-click="functionFromParent({function1: myfn, x:5, z: 4})"></button>.

it just an expression, does not matter if it is a function, or many functions, or just comparison. And you can replace any variable of this expression.

Examples:
directive template vs called code:
parent has defined $scope.x, $scope.y:
parent template: <myDirective expr="x==y"></myDirective>
<button ng-click="expr()"></button> calls $scope.x==$scope.y
<button ng-click="expr({x: 5})"></button> calls 5 == $scope.y
<button ng-click="expr({x:5, y:6})"></button> calls 5 == 6

parent has defined $scope.function1, $scope.x, $scope.y:
parent template: <myDirective expr="function1(x) + y"></myDirective>

<button ng-click="expr()"></button> calls $scope.function1($scope.x) + $scope.y
<button ng-click="expr({x: 5})"></button> calls $scope.function1(5) + $scope.y
<button ng-click="expr({x:5, y:6})"></button> calls $scope.function1(5) + 6
directive has $scope.myFn as function:
<button ng-click="expr({function1: myFn, x:5, y:6})"></button> calls $scope.myFn(5) + 6

Disable beep of Linux Bash on Windows 10

@Andrea Tulimiero 's answer works for local, but when you ssh to a remote server, the beep turns on again. My suggestion is to disable from the Windows 10 taskbar. There is volume mixer in the right bottom corner, which works for me.

ActionBarActivity is deprecated

Since the version 22.1.0, the class ActionBarActivity is deprecated. You should use AppCompatActivity.

Read here and here for more information.

Access denied; you need (at least one of) the SUPER privilege(s) for this operation

When you restore backup, Make sure to try with the same username for the old one and the new one.

how to specify local modules as npm package dependencies

I couldn't find a neat way in the end so I went for create a directory called local_modules and then added this bashscript to the package.json in scripts->preinstall

#!/bin/sh
for i in $(find ./local_modules -type d -maxdepth 1) ; do
    packageJson="${i}/package.json"
    if [ -f "${packageJson}" ]; then
        echo "installing ${i}..."
        npm install "${i}"
    fi
done

Is there a way to specify a max height or width for an image?

If you only specify either the height or the width, but not both, most browsers will honor the aspect ratio.

Because you are working with an ASP.NET server control, you may consider executing logic on the server side prior to rendering to decide which (height or width) attribute you want to specify; that is, if you want a fixed height under one condition or a fixed width under another.

Remove Backslashes from Json Data in JavaScript

Your string is invalid, but assuming it was valid, you'd have to do:

var finalData = str.replace(/\\/g, "");

When you want to replace all the occurences with .replace, the first parameter must be a regex, if you supply a string, only the first occurrence will be replaced, that's why your replace wouldn't work.

Cheers

How do I get an empty array of any size in python?

You can use numpy:

import numpy as np

Example from Empty Array:

np.empty([2, 2])
array([[ -9.74499359e+001,   6.69583040e-309],
       [  2.13182611e-314,   3.06959433e-309]])  

How to make an autocomplete TextBox in ASP.NET?

aspx Page Coding

<form id="form1" runat="server">
       <input type="search" name="Search" placeholder="Search for a Product..." list="datalist1"
                    required="">
       <datalist id="datalist1" runat="server">

       </datalist>
 </form>

.cs Page Coding

protected void Page_Load(object sender, EventArgs e)
{
     autocomplete();
}
protected void autocomplete()
{
    Database p = new Database();
    DataSet ds = new DataSet();
    ds = p.sqlcall("select [name] from [stu_reg]");
    int row = ds.Tables[0].Rows.Count;
    string abc="";
    for (int i = 0; i < row;i++ )
        abc = abc + "<option>"+ds.Tables[0].Rows[i][0].ToString()+"</option>";
    datalist1.InnerHtml = abc;
}

Here Database is a File (Database.cs) In Which i have created on method named sqlcall for retriving data from database.

How to run Node.js as a background process and never die?

Try this for a simple solution

cmd & exit

How to set selectedIndex of select element using display text?

You can set the index by this code :

sel.selectedIndex = 0;

but remember a caution in this practice, You would not be able to call the server side onclick method if you select the previous value selected in the drop down..

Meaning of *& and **& in C++

That's passing a pointer by reference rather than by value. This for example allows altering the pointer (not the pointed-to object) in the function is such way that the calling code sees the change.

Compare:

void nochange( int* pointer ) //passed by value
{
   pointer++; // change will be discarded once function returns
}

void change( int*& pointer ) //passed by reference
{
   pointer++; // change will persist when function returns
}

Caching a jquery ajax response in javascript/browser

If I understood your question, here is the solution :

    $.ajaxSetup({ cache: true});

and for specific calls

 $.ajax({
        url: ...,
        type: "GET",
        cache: false,           
        ...
    });

If you want opposite (cache for specific calls) you can set false at the beginning and true for specific calls.

When to use Comparable and Comparator

Use Comparable if you want to define a default (natural) ordering behaviour of the object in question, a common practice is to use a technical or natural (database?) identifier of the object for this.

Use Comparator if you want to define an external controllable ordering behaviour, this can override the default ordering behaviour.

How to open generated pdf using jspdf in new window

Generally you can download it, show, or get a blob string:

const pdfActions = {
    save: () => doc.save(filename),
    getBlob: () => {
      const blob = doc.output('datauristring');
      console.log(blob)
      return blob
    },
    show: () => doc.output('dataurlnewwindow')
  }

Read/write files within a Linux kernel module

You should be aware that you should avoid file I/O from within Linux kernel when possible. The main idea is to go "one level deeper" and call VFS level functions instead of the syscall handler directly:

Includes:

#include <linux/fs.h>
#include <asm/segment.h>
#include <asm/uaccess.h>
#include <linux/buffer_head.h>

Opening a file (similar to open):

struct file *file_open(const char *path, int flags, int rights) 
{
    struct file *filp = NULL;
    mm_segment_t oldfs;
    int err = 0;

    oldfs = get_fs();
    set_fs(get_ds());
    filp = filp_open(path, flags, rights);
    set_fs(oldfs);
    if (IS_ERR(filp)) {
        err = PTR_ERR(filp);
        return NULL;
    }
    return filp;
}

Close a file (similar to close):

void file_close(struct file *file) 
{
    filp_close(file, NULL);
}

Reading data from a file (similar to pread):

int file_read(struct file *file, unsigned long long offset, unsigned char *data, unsigned int size) 
{
    mm_segment_t oldfs;
    int ret;

    oldfs = get_fs();
    set_fs(get_ds());

    ret = vfs_read(file, data, size, &offset);

    set_fs(oldfs);
    return ret;
}   

Writing data to a file (similar to pwrite):

int file_write(struct file *file, unsigned long long offset, unsigned char *data, unsigned int size) 
{
    mm_segment_t oldfs;
    int ret;

    oldfs = get_fs();
    set_fs(get_ds());

    ret = vfs_write(file, data, size, &offset);

    set_fs(oldfs);
    return ret;
}

Syncing changes a file (similar to fsync):

int file_sync(struct file *file) 
{
    vfs_fsync(file, 0);
    return 0;
}

[Edit] Originally, I proposed using file_fsync, which is gone in newer kernel versions. Thanks to the poor guy suggesting the change, but whose change was rejected. The edit was rejected before I could review it.

How to split data into 3 sets (train, validation and test)?

However, one approach to dividing the dataset into train, test, cv with 0.6, 0.2, 0.2 would be to use the train_test_split method twice.

from sklearn.model_selection import train_test_split

x, x_test, y, y_test = train_test_split(xtrain,labels,test_size=0.2,train_size=0.8)
x_train, x_cv, y_train, y_cv = train_test_split(x,y,test_size = 0.25,train_size =0.75)

REST API - why use PUT DELETE POST GET?

Bill Venners: In your blog post entitled "Why REST Failed," you said that we need all four HTTP verbs—GET, POST, PUT, and DELETE— and lamented that browser vendors only GET and POST." Why do we need all four verbs? Why aren't GET and POST enough?

Elliotte Rusty Harold: There are four basic methods in HTTP: GET, POST, PUT, and DELETE. GET is used most of the time. It is used for anything that's safe, that doesn't cause any side effects. GET is able to be bookmarked, cached, linked to, passed through a proxy server. It is a very powerful operation, a very useful operation.

POST by contrast is perhaps the most powerful operation. It can do anything. There are no limits as to what can happen, and as a result, you have to be very careful with it. You don't bookmark it. You don't cache it. You don't pre-fetch it. You don't do anything with a POST without asking the user. Do you want to do this? If the user presses the button, you can POST some content. But you're not going to look at all the buttons on a page, and start randomly pressing them. By contrast browsers might look at all the links on the page and pre-fetch them, or pre-fetch the ones they think are most likely to be followed next. And in fact some browsers and Firefox extensions and various other tools have tried to do that at one point or another.

PUT and DELETE are in the middle between GET and POST. The difference between PUT or DELETE and POST is that PUT and DELETE are *idempotent, whereas POST is not. PUT and DELETE can be repeated if necessary. Let's say you're trying to upload a new page to a site. Say you want to create a new page at http://www.example.com/foo.html, so you type your content and you PUT it at that URL. The server creates that page at that URL that you supply. Now, let's suppose for some reason your network connection goes down. You aren't sure, did the request get through or not? Maybe the network is slow. Maybe there was a proxy server problem. So it's perfectly OK to try it again, or again—as many times as you like. Because PUTTING the same document to the same URL ten times won't be any different than putting it once. The same is true for DELETE. You can DELETE something ten times, and that's the same as deleting it once.

By contrast, POST, may cause something different to happen each time. Imagine you are checking out of an online store by pressing the buy button. If you send that POST request again, you could end up buying everything in your cart a second time. If you send it again, you've bought it a third time. That's why browsers have to be very careful about repeating POST operations without explicit user consent, because POST may cause two things to happen if you do it twice, three things if you do it three times. With PUT and DELETE, there's a big difference between zero requests and one, but there's no difference between one request and ten.

Please visit the url for more details. http://www.artima.com/lejava/articles/why_put_and_delete.html

Update:

Idempotent methods An idempotent HTTP method is a HTTP method that can be called many times without different outcomes. It would not matter if the method is called only once, or ten times over. The result should be the same. Again, this only applies to the result, not the resource itself. This still can be manipulated (like an update-timestamp, provided this information is not shared in the (current) resource representation.

Consider the following examples:

a = 4;

a++;

The first example is idempotent: no matter how many times we execute this statement, a will always be 4. The second example is not idempotent. Executing this 10 times will result in a different outcome as when running 5 times. Since both examples are changing the value of a, both are non-safe methods.

VBA Subscript out of range - error 9

Subscript out of Range error occurs when you try to reference an Index for a collection that is invalid.

Most likely, the index in Windows does not actually include .xls. The index for the window should be the same as the name of the workbook displayed in the title bar of Excel.

As a guess, I would try using this:

Windows("Data Sheet - " & ComboBox_Month.Value & " " & TextBox_Year.Value).Activate

Import existing Gradle Git project into Eclipse

Usually it is a simple as adding apply plugin: "eclipse" in your build.gradle and running

cd myProject/
gradle eclipse

and then refreshing your Eclipse project.

Occasionally you'll need to adjust build.gradle to generate Eclipse settings in some very specific way.

There is gradle support for Eclipse if you are using STS, but I'm not sure how good it is.

The only IDE I know that has decent native support for gradle is IntelliJ IDEA. It can do full import of gradle projects from GUI. There is a free Community Edition that you can try.

Javascript : calling function from another file

Why don't you take a look to this answer

Including javascript files inside javascript files

In short you can load the script file with AJAX or put a script tag on the HTML to include it( before the script that uses the functions of the other script). The link I posted is a great answer and has multiple examples and explanations of both methods.

Python's time.clock() vs. time.time() accuracy?

Right answer : They're both the same length of a fraction.

But which faster if subject is time ?

A little test case :

import timeit
import time

clock_list = []
time_list = []

test1 = """
def test(v=time.clock()):
    s = time.clock() - v
"""

test2 = """
def test(v=time.time()):
    s = time.time() - v
"""
def test_it(Range) :
    for i in range(Range) :
        clk = timeit.timeit(test1, number=10000)
        clock_list.append(clk)
        tml = timeit.timeit(test2, number=10000)
        time_list.append(tml)

test_it(100)

print "Clock Min: %f Max: %f Average: %f" %(min(clock_list), max(clock_list), sum(clock_list)/float(len(clock_list)))
print "Time  Min: %f Max: %f Average: %f" %(min(time_list), max(time_list), sum(time_list)/float(len(time_list)))

I am not work an Swiss labs but I've tested..

Based of this question : time.clock() is better than time.time()

Edit : time.clock() is internal counter so can't use outside, got limitations max 32BIT FLOAT, can't continued counting if not store first/last values. Can't merge another one counter...

passing form data to another HTML page

You need the get the values from the query string (since you dont have a method set, your using GET by default)

use the following tutorial.

http://papermashup.com/read-url-get-variables-withjavascript/

function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
        vars[key] = value;
    });
    return vars;
}

change pgsql port

You can also change the port when starting up:

$ pg_ctl -o "-F -p 5433" start

Or

$ postgres -p 5433

More about this in the manual.

Is there a list of Pytz Timezones?

EDIT: I would appreciate it if you do not downvote this answer further. This answer is wrong, but I would rather retain it as a historical note. While it is arguable whether the pytz interface is error-prone, it can do things that dateutil.tz cannot do, especially regarding daylight-saving in the past or in the future. I have honestly recorded my experience in an article "Time zones in Python".


If you are on a Unix-like platform, I would suggest you avoid pytz and look just at /usr/share/zoneinfo. dateutil.tz can utilize the information there.

The following piece of code shows the problem pytz can give. I was shocked when I first found it out. (Interestingly enough, the pytz installed by yum on CentOS 7 does not exhibit this problem.)

import pytz
import dateutil.tz
from datetime import datetime
print((datetime(2017,2,13,14,29,29, tzinfo=pytz.timezone('Asia/Shanghai'))
     - datetime(2017,2,13,14,29,29, tzinfo=pytz.timezone('UTC')))
     .total_seconds())
print((datetime(2017,2,13,14,29,29, tzinfo=dateutil.tz.gettz('Asia/Shanghai'))
     - datetime(2017,2,13,14,29,29, tzinfo=dateutil.tz.tzutc()))
     .total_seconds())

-29160.0
-28800.0

I.e. the timezone created by pytz is for the true local time, instead of the standard local time people observe. Shanghai conforms to +0800, not +0806 as suggested by pytz:

pytz.timezone('Asia/Shanghai')
<DstTzInfo 'Asia/Shanghai' LMT+8:06:00 STD>

EDIT: Thanks to Mark Ransom's comment and downvote, now I know I am using pytz the wrong way. In summary, you are not supposed to pass the result of pytz.timezone(…) to datetime, but should pass the datetime to its localize method.

Despite his argument (and my bad for not reading the pytz documentation more carefully), I am going to keep this answer. I was answering the question in one way (how to enumerate the supported timezones, though not with pytz), because I believed pytz did not provide a correct solution. Though my belief was wrong, this answer is still providing some information, IMHO, which is potentially useful to people interested in this question. Pytz's correct way of doing things is counter-intuitive. Heck, if the tzinfo created by pytz should not be directly used by datetime, it should be a different type. The pytz interface is simply badly designed. The link provided by Mark shows that many people, not just me, have been misled by the pytz interface.

MySQL - Cannot add or update a child row: a foreign key constraint fails

I've faced this issue and the solution was making sure that all the data from the child field are matching the parent field

for example, you want to add foreign key inside (attendance) table to the column (employeeName)

where the parent is (employees) table, (employeeName) column

all the data in attendance.employeeName must be matching employee.employeeName

Get pandas.read_csv to read empty values as empty string instead of nan

We have a simple argument in Pandas read_csv for this:

Use:

df = pd.read_csv('test.csv', na_filter= False)

Pandas documentation clearly explains how the above argument works.

Link

c# replace \" characters

Were you trying it like this:

string text = GetTextFromSomewhere();
text.Replace("\\", "");
text.Replace("\"", "");

? If so, that's the problem - Replace doesn't change the original string, it returns a new string with the replacement performed... so you'd want:

string text = GetTextFromSomewhere();
text = text.Replace("\\", "").Replace("\"", "");

Note that this will replace each backslash and each double-quote character; if you only wanted to replace the pair "backslash followed by double-quote" you'd just use:

string text = GetTextFromSomewhere();
text = text.Replace("\\\"", "");

(As mentioned in the comments, this is because strings are immutable in .NET - once you've got a string object somehow, that string will always have the same contents. You can assign a reference to a different string to a variable of course, but that's not actually changing the contents of the existing string.)

How do I clear my local working directory in Git?

All the answers so far retain local commits. If you're really serious, you can discard all local commits and all local edits by doing:

git reset --hard origin/branchname

For example:

git reset --hard origin/master

This makes your local repository exactly match the state of the origin (other than untracked files).

If you accidentally did this after just reading the command, and not what it does :), use git reflog to find your old commits.

How to split data into training/testing sets using sample function

We can divide data into a particular ratio here it is 80% train and 20% in a test dataset.

ind <- sample(2, nrow(dataName), replace = T, prob = c(0.8,0.2))
train <- dataName[ind==1, ]
test <- dataName[ind==2, ]

Assembly Language - How to do Modulo?

An easy way to see what a modulus operator looks like on various architectures is to use the Godbolt Compiler Explorer.

https://godbolt.org/z/64zKGr

How can you detect the version of a browser?

I want to share this code I wrote for the issue I had to resolve. It was tested in most of the major browsers and works like a charm, for me!

It may seems that this code is very similar to the other answers but it modifyed so that I can use it insted of the browser object in jquery which missed for me recently, of course it is a combination from the above codes, with little improvements from my part I made:

(function($, ua){

var M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [],
    tem, 
    res;

if(/trident/i.test(M[1])){
    tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
    res = 'IE ' + (tem[1] || '');
}
else if(M[1] === 'Chrome'){
    tem = ua.match(/\b(OPR|Edge)\/(\d+)/);
    if(tem != null) 
        res = tem.slice(1).join(' ').replace('OPR', 'Opera');
    else
        res = [M[1], M[2]];
}
else {
    M = M[2]? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
    if((tem = ua.match(/version\/(\d+)/i)) != null) M = M.splice(1, 1, tem[1]);
    res = M;
}

res = typeof res === 'string'? res.split(' ') : res;

$.browser = {
    name: res[0],
    version: res[1],
    msie: /msie|ie/i.test(res[0]),
    firefox: /firefox/i.test(res[0]),
    opera: /opera/i.test(res[0]),
    chrome: /chrome/i.test(res[0]),
    edge: /edge/i.test(res[0])
}

})(typeof jQuery != 'undefined'? jQuery : window.$, navigator.userAgent);

 console.log($.browser.name, $.browser.version, $.browser.msie); 
// if IE 11 output is: IE 11 true

Java: Detect duplicates in ArrayList?

Simplest: dump the whole collection into a Set (using the Set(Collection) constructor or Set.addAll), then see if the Set has the same size as the ArrayList.

List<Integer> list = ...;
Set<Integer> set = new HashSet<Integer>(list);

if(set.size() < list.size()){
    /* There are duplicates */
}

Update: If I'm understanding your question correctly, you have a 2d array of Block, as in

Block table[][];

and you want to detect if any row of them has duplicates?

In that case, I could do the following, assuming that Block implements "equals" and "hashCode" correctly:

for (Block[] row : table) {
   Set set = new HashSet<Block>(); 
   for (Block cell : row) {
      set.add(cell);
   }
   if (set.size() < 6) { //has duplicate
   }
}

I'm not 100% sure of that for syntax, so it might be safer to write it as

for (int i = 0; i < 6; i++) {
   Set set = new HashSet<Block>(); 
   for (int j = 0; j < 6; j++)
    set.add(table[i][j]);
 ...

Set.add returns a boolean false if the item being added is already in the set, so you could even short circuit and bale out on any add that returns false if all you want to know is whether there are any duplicates.

How do you change the formatting options in Visual Studio Code?

I just found this extension called beautify in the Market Place and yes, it's another config\settings file. :)

Beautify javascript, JSON, CSS, Sass, and HTML in Visual Studio Code.

VS Code uses js-beautify internally, but it lacks the ability to modify the style you wish to use. This extension enables running js-beautify in VS Code, AND honouring any .jsbeautifyrc file in the open file's path tree to load your code styling. Run with F1 Beautify (to beautify a selection) or F1 Beautify file.

For help on the settings in the .jsbeautifyrc see Settings.md

Here is the GitHub repository: https://github.com/HookyQR/VSCodeBeautify

How to change proxy settings in Android (especially in Chrome)

Found one solution for WIFI (works for Android 4.3, 4.4):

  1. Connect to WIFI network (e.g. 'Alex')
  2. Settings->WIFI
  3. Long tap on connected network's name (e.g. on 'Alex')
  4. Modify network config-> Show advanced options
  5. Set proxy settings

JS search in object values

As a Javascripter Lv. 1 I just learned to search for strings in objects with this:

function isThere( a_string, in_this_object )
{
    if( typeof a_string != 'string' )
    {
        return false;
    }

    for( var key in in_this_object )
    {
        if( typeof in_this_object[key] == 'object' || typeof in_this_object[key] == 'array' )
        {
            if ( isThere( a_string, in_this_object[key] ) )
            {
                return true;
            }
        }
        else if( typeof in_this_object[key] == 'string' )
        {
            if( a_string == in_this_object[key] )
            {
                return true;
            }
        }
    }

    return false;
}

I know is far from perfect but it is useful.

Feel free to comment in order to improve this.

Best way to access a control on another form in Windows Forms?

This looks like a prime candidate for separating the presentation from the data model. In this case, your preferences should be stored in a separate class that fires event updates whenever a particular property changes (look into INotifyPropertyChanged if your properties are a discrete set, or into a single event if they are more free-form text-based keys).

In your tree view, you'll make the changes to your preferences model, it will then fire an event. In your other forms, you'll subscribe to the changes that you're interested in. In the event handler you use to subscribe to the property changes, you use this.InvokeRequired to see if you are on the right thread to make the UI call, if not, then use this.BeginInvoke to call the desired method to update the form.

Steps to upload an iPhone application to the AppStore

This arstechnica article describes the basic steps:

Start by visiting the program portal and make sure that your developer certificate is up to date. It expires every six months and, if you haven't requested that a new one be issued, you cannot submit software to App Store. For most people experiencing the "pink upload of doom," though, their certificates are already valid. What next?

Open your Xcode project and check that you've set the active SDK to one of the device choices, like Device - 2.2. Accidentally leaving the build settings to Simulator can be a big reason for the pink rejection. And that happens more often than many developers would care to admit.

Next, make sure that you've chosen a build configuration that uses your distribution (not your developer) certificate. Check this by double-clicking on your target in the Groups & Files column on the left of the project window. The Target Info window will open. Click the Build tab and review your Code Signing Identity. It should be iPhone Distribution: followed by your name or company name.

You may also want to confirm your application identifier in the Properties tab. Most likely, you'll have set the identifier properly when debugging with your developer certificate, but it never hurts to check.

The top-left of your project window also confirms your settings and configuration. It should read something like "Device - 2.2 | Distribution". This shows you the active SDK and configuration.

If your settings are correct but you still aren't getting that upload finished properly, clean your builds. Choose Build > Clean (Command-Shift-K) and click Clean. Alternatively, you can manually trash the build folder in your Project from Finder. Once you've cleaned, build again fresh.

If this does not produce an app that when zipped properly loads to iTunes Connect, quit and relaunch Xcode. I'm not kidding. This one simple trick solves more signing problems and "pink rejections of doom" than any other solution already mentioned.

XML Error: Extra content at the end of the document

You need a root node

<?xml version="1.0" encoding="ISO-8859-1"?>    
<documents>
    <document>
        <name>Sample Document</name>
        <type>document</type>
        <url>http://nsc-component.webs.com/Office/Editor/new-doc.html?docname=New+Document&amp;titletype=Title&amp;fontsize=9&amp;fontface=Arial&amp;spacing=1.0&amp;text=&amp;wordcount3=0</url>
    </document>

    <document>
        <name>Sample</name>
        <type>document</type>
        <url>http://nsc-component.webs.com/Office/Editor/new-doc.html?docname=New+Document&amp;titletype=Title&amp;fontsize=9&amp;fontface=Arial&amp;spacing=1.0&amp;text=&amp;</url>
    </document>
</documents>

Android button with different background colors

in Mono Android you can use filter like this:

your_button.Background.SetColorFilter(new Android.Graphics.PorterDuffColorFilter(Android.Graphics.Color.Red, Android.Graphics.PorterDuff.Mode.Multiply));

Check if all checkboxes are selected

This is how I achieved it in my code:

if($('.citiescheckbox:checked').length == $('.citiescheckbox').length){
    $('.citycontainer').hide();
}else{
    $('.citycontainer').show();
}

Change :hover CSS properties with JavaScript

If you use lightweight html ux lang, check here an example, write:

div root
 .onmouseover = ev => {root.style.backgroundColor='red'}
 .onmouseleave = ev => {root.style.backgroundColor='initial'}

The code above performes the css :hover metatag.

jQuery checkbox onChange

$('input[type=checkbox]').change(function () {
    alert('changed');
});

Call Javascript function from URL/address bar

you can execute javascript from url via events Ex: www.something.com/home/save?id=12<body onload="alert(1)"></body>

does work if params in url are there.

long long int vs. long int vs. int64_t in C++

You don't need to go to 64-bit to see something like this. Consider int32_t on common 32-bit platforms. It might be typedef'ed as int or as a long, but obviously only one of the two at a time. int and long are of course distinct types.

It's not hard to see that there is no workaround which makes int == int32_t == long on 32-bit systems. For the same reason, there's no way to make long == int64_t == long long on 64-bit systems.

If you could, the possible consequences would be rather painful for code that overloaded foo(int), foo(long) and foo(long long) - suddenly they'd have two definitions for the same overload?!

The correct solution is that your template code usually should not be relying on a precise type, but on the properties of that type. The whole same_type logic could still be OK for specific cases:

long foo(long x);
std::tr1::disable_if(same_type(int64_t, long), int64_t)::type foo(int64_t);

I.e., the overload foo(int64_t) is not defined when it's exactly the same as foo(long).

[edit] With C++11, we now have a standard way to write this:

long foo(long x);
std::enable_if<!std::is_same<int64_t, long>::value, int64_t>::type foo(int64_t);

[edit] Or C++20

long foo(long x);
int64_t foo(int64_t) requires (!std::is_same_v<int64_t, long>);

How to set up file permissions for Laravel?

Change the permissions for your project folder to enable read/write/exec for any user within the group owning the directory (which in your case is _www):

chmod -R 775 /path/to/your/project

Then add your OS X username to the _www group to allow it access to the directory:

sudo dseditgroup -o edit -a yourusername -t user _www

Maven home (M2_HOME) not being picked up by IntelliJ IDEA

If you are having this problem with a homebrew installation of maven 3 on the OSX 10.9.4 then check out this blog post.

Detect whether a Python string is a number or a letter

For a string of length 1 you can simply perform isdigit() or isalpha()

If your string length is greater than 1, you can make a function something like..

def isinteger(a):
    try:
        int(a)
        return True
    except ValueError:
        return False

Spring MVC 4: "application/json" Content Type is not being set correctly

When I upgraded to Spring 4 I needed to update the jackson dependencies as follows:

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.5.1</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.5.1</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.5.1</version>
    </dependency>        

How do you connect to a MySQL database using Oracle SQL Developer?

Under Tools > Preferences > Databases there is a third party JDBC driver path that must be setup. Once the driver path is setup a separate 'MySQL' tab should appear on the New Connections dialog.

Note: This is the same jdbc connector that is available as a JAR download from the MySQL website.

Execute the setInterval function without delay the first time

There's a convenient npm package called firstInterval (full disclosure, it's mine).

Many of the examples here don't include parameter handling, and changing default behaviors of setInterval in any large project is evil. From the docs:

This pattern

setInterval(callback, 1000, p1, p2);
callback(p1, p2);

is identical to

firstInterval(callback, 1000, p1, p2);

If you're old school in the browser and don't want the dependency, it's an easy cut-and-paste from the code.

Objective-C - Remove last character from string

The solutions given here actually do not take into account multi-byte Unicode characters ("composed characters"), and could result in invalid Unicode strings.

In fact, the iOS header file which contains the declaration of substringToIndex contains the following comment:

Hint: Use with rangeOfComposedCharacterSequencesForRange: to avoid breaking up composed characters

See how to use rangeOfComposedCharacterSequenceAtIndex: to delete the last character correctly.

How can I convert bigint (UNIX timestamp) to datetime in SQL Server?

I had to face this problem, too. Unfortunately, none of the answers (here and in dozens of other pages) has been satisfactory to me, as I still cannot reach dates beyond the year 2038 due to 32 bit integer casts somewhere.

A solution that did work for me in the end was to use float variables, so I could have at least a max date of 2262-04-11T23:47:16.854775849. Still, this doesn't cover the entire datetime domain, but it is sufficient for my needs and may help others encountering the same problem.

-- date variables
declare @ts bigint; -- 64 bit time stamp, 100ns precision
declare @d datetime2(7) = GETUTCDATE(); -- 'now'
-- select @d = '2262-04-11T23:47:16.854775849'; -- this would be the max date

-- constants:
declare @epoch datetime2(7) = cast('1970-01-01T00:00:00' as datetime2(7));
declare @epochdiff int = 25567; -- = days between 1900-01-01 and 1970-01-01
declare @ticksofday bigint = 864000000000; -- = (24*60*60*1000*1000*10)

-- helper variables:
declare @datepart float;
declare @timepart float;
declare @restored datetime2(7);

-- algorithm:
select @ts = DATEDIFF_BIG(NANOSECOND, @epoch, @d) / 100; -- 'now' in ticks according to unix epoch
select @timepart = (@ts % @ticksofday) / @ticksofday; -- extract time part and scale it to fractional part (i. e. 1 hour is 1/24th of a day)
select @datepart = (@ts - @timepart) / @ticksofday; -- extract date part and scale it to fractional part
select @restored = cast(@epochdiff + @datepart + @timepart as datetime); -- rebuild parts to a datetime value

-- query original datetime, intermediate timestamp and restored datetime for comparison
select
  @d original,
  @ts unix64,
  @restored restored
;

-- example result for max date:
-- +-----------------------------+-------------------+-----------------------------+
-- | original                    | unix64            | restored                    |
-- +-----------------------------+-------------------+-----------------------------+
-- | 2262-04-11 23:47:16.8547758 | 92233720368547758 | 2262-04-11 23:47:16.8533333 |
-- +-----------------------------+-------------------+-----------------------------+

There are some points to consider:

  • 100ns precision is the requirement in my case, however this seems to be the standard resolution for 64 bit unix timestamps. If you use any other resolution, you have to adjust @ticksofday and the first line of the algorithm accordingly.
  • I'm using other systems that have their problems with time zones etc. and I found the best solution for me would be always using UTC. For your needs, this may differ.
  • 1900-01-01 is the origin date for datetime2, just as is the epoch 1970-01-01 for unix timestamps.
  • floats helped me to solve the year-2038-problem and integer overflows and such, but keep in mind that floating point numbers are not very performant and may slow down processing of a big amount of timestamps. Also, floats may lead to loss of precision due to roundoff errors, as you can see in the comparison of the example results for the max date above (here, the error is about 1.4425ms).
  • In the last line of the algorithm there is a cast to datetime. Unfortunately, there is no explicit cast from numeric values to datetime2 allowed, but it is allowed to cast numerics to datetime explicitly and this, in turn, is cast implicitly to datetime2. This may be correct, for now, but may change in future versions of SQL Server: Either there will be a dateadd_big() function or the explicit cast to datetime2 will be allowed or the explicit cast to datetime will be disallowed, so this may either break or there may come an easier way some day.

Android emulator-5554 offline

In my case the cause was that I had resumed a VM with android-x86 inside. Rebooting the VM with Android-x86 and restarting the adb server fixed the problem.

Removing single-quote from a string in php

Using your current str_replace method:

$FileName = str_replace("'", "", $UserInput);

While it's hard to see, the first argument is a double quote followed by a single quote followed by a double quote. The second argument is two double quotes with nothing in between.

With str_replace, you could even have an array of strings you want to remove entirely:

$remove[] = "'";
$remove[] = '"';
$remove[] = "-"; // just as another example

$FileName = str_replace( $remove, "", $UserInput );

How to generate classes from wsdl using Maven and wsimport?

The key here is keep option of wsimport. And it is configured using element in About keep from the wsimport documentation :

-keep                     keep generated files

Printing Lists as Tabular Data

Some ad-hoc code:

row_format ="{:>15}" * (len(teams_list) + 1)
print(row_format.format("", *teams_list))
for team, row in zip(teams_list, data):
    print(row_format.format(team, *row))

This relies on str.format() and the Format Specification Mini-Language.

add id to dynamically created <div>

Not sure if this is the best way, but it works.

if (cartDiv == null) {
    cartDiv = "<div id='unique_id'></div>"; // document.createElement('div');
    document.body.appendChild(cartDiv);
}

How do I change data-type of pandas data frame to string with a defined format?

If you could reload this, you might be able to use dtypes argument.

pd.read_csv(..., dtype={'COL_NAME':'str'})

What are the most widely used C++ vector/matrix math/linear algebra libraries, and their cost and benefit tradeoffs?

What about GLM?

It's based on the OpenGL Shading Language (GLSL) specification and released under the MIT license. Clearly aimed at graphics programmers

Namenode not getting started

If you kept default configurations when running hadoop the port for the namenode would be 50070. You will need to find any processes running on this port and kill them first.

  • Stop all running hadoop with : bin/stop-all.sh

    check all processes running in port 50070

  • sudo netstat -tulpn | grep :50070 #check any processes running in port 50070, if there are any the / will appear at the RHS of the output.

  • sudo kill -9 <process_id> #kill_the_process.

  • sudo rm -r /app/hadoop/tmp #delete the temp folder

  • sudo mkdir /app/hadoop/tmp #recreate it

  • sudo chmod 777 –R /app/hadoop/tmp (777 is given for this example purpose only)

  • bin/hadoop namenode –format #format hadoop namenode

  • bin/start-all.sh #start-all hadoop services

Refer this blog

How to plot a 2D FFT in Matlab?

Here is an example from my HOW TO Matlab page:

close all; clear all;

img   = imread('lena.tif','tif');
imagesc(img)
img   = fftshift(img(:,:,2));
F     = fft2(img);

figure;

imagesc(100*log(1+abs(fftshift(F)))); colormap(gray); 
title('magnitude spectrum');

figure;
imagesc(angle(F));  colormap(gray);
title('phase spectrum');

This gives the magnitude spectrum and phase spectrum of the image. I used a color image, but you can easily adjust it to use gray image as well.

ps. I just noticed that on Matlab 2012a the above image is no longer included. So, just replace the first line above with say

img = imread('ngc6543a.jpg');

and it will work. I used an older version of Matlab to make the above example and just copied it here.

On the scaling factor

When we plot the 2D Fourier transform magnitude, we need to scale the pixel values using log transform to expand the range of the dark pixels into the bright region so we can better see the transform. We use a c value in the equation

s = c log(1+r) 

There is no known way to pre detrmine this scale that I know. Just need to try different values to get on you like. I used 100 in the above example.

enter image description here

How to add new line in Markdown presentation?

If none of the solutions mentions here work for you, which is what happened with me, then you can do the following: Add an empty header (A hack that ruins semantics)

text
####
text

Just make sure that when the header is added it has no border in bottom of it in the markdown css, so you can try different variations of the headers.

Assigning the output of a command to a variable

You can use a $ sign like:

OUTPUT=$(expression)

Increase days to php current Date()

<?php
$dt = new DateTime;
if(isset($_GET['year']) && isset($_GET['week'])) {
    $dt->setISODate($_GET['year'], $_GET['week']);
} else {
    $dt->setISODate($dt->format('o'), $dt->format('W'));
}
$year = $dt->format('o');
$week = $dt->format('W');
?>

<a href="<?php echo $_SERVER['PHP_SELF'].'?week='.($week-1).'&year='.$year; ?>">Pre Week</a> 
<a href="<?php echo $_SERVER['PHP_SELF'].'?week='.($week+1).'&year='.$year; ?>">Next Week</a>
<table width="100%" style="height: 75px; border: 1px solid #00A2FF;">
<tr>
<td style="display: table-cell;
    vertical-align: middle;
    cursor: pointer;
    width: 75px;
    height: 75px;
    border: 4px solid #00A2FF;
    border-radius: 50%;">Employee</td>
<?php
do {
    echo "<td>" . $dt->format('M') . "<br>" . $dt->format('d M Y') . "</td>\n";
    $dt->modify('+1 day');
} while ($week == $dt->format('W'));
?>
</tr>
</table>

Pass accepts header parameter to jquery ajax

I use jQuery.getJSON( url [, data ] [, success( data, textStatus, jqXHR ) ] ) for example:

var url="my.php";
$.getJSON( url, myObj )
.done(function( json ) { ... }) /* got JSON from server */
.fail(function( jqxhr, textStatus, error ) {
    var err = textStatus + ", " + error;
    console.log( "Failed to obtain JSON data from server: " + err );
  }); /* failed to get JSON */

getJSON is shorthand for:

$.ajax({
  dataType: "json",
  url: url,
  data: data,
  success: success
});

What is LDAP used for?

To take the definitions the other mentioned earlier a bit further, how about this perspective...

LDAP is Lightweight Directory Access Protocol. DAP, is an X.500 notion, and in X.500 is VERY heavy weight! (It sort of requires a full 7 layer ISO network stack, which basically only IBM's SNA protocol ever realistically implemented).

There are many other approaches to DAP. Novell has one called NDAP (NCP Novell Core Protocols are the transport, and NDAP is how it reads the directory).

LDAP is just a very lightweight DAP, as the name suggests.

Extract regression coefficient values

The package broom comes in handy here (it uses the "tidy" format).

tidy(mg) will give a nicely formated data.frame with coefficients, t statistics etc. Works also for other models (e.g. plm, ...).

Example from broom's github repo:

lmfit <- lm(mpg ~ wt, mtcars)
require(broom)    
tidy(lmfit)

      term estimate std.error statistic   p.value
1 (Intercept)   37.285   1.8776    19.858 8.242e-19
2          wt   -5.344   0.5591    -9.559 1.294e-10

is.data.frame(tidy(lmfit))
[1] TRUE

Scheduled run of stored procedure on SQL server

I'll add one thing: where I'm at we used to have a bunch of batch jobs that ran every night. However, we're moving away from that to using a client application scheduled in windows scheduled tasks that kicks off each job. There are (at least) three reasons for this:

  1. We have some console programs that need to run every night as well. This way all scheduled tasks can be in one place. Of course, this creates a single point of failure, but if the console jobs don't run we're gonna lose a day's work the next day anyway.
  2. The program that kicks off the jobs captures print messages and errors from the server and writes them to a common application log for all our batch processes. It makes logging from withing the sql jobs much simpler.
  3. If we ever need to upgrade the server (and we are hoping to do this soon) we don't need to worry about moving the jobs over. Just re-point the application once.

It's a real short VB.Net app: I can post code if any one is interested.

Jasmine JavaScript Testing - toBe vs toEqual

To quote the jasmine github project,

expect(x).toEqual(y); compares objects or primitives x and y and passes if they are equivalent

expect(x).toBe(y); compares objects or primitives x and y and passes if they are the same object

A method to count occurrences in a list

How about something like this ...

var l1 = new List<int>() { 1,2,3,4,5,2,2,2,4,4,4,1 };

var g = l1.GroupBy( i => i );

foreach( var grp in g )
{
  Console.WriteLine( "{0} {1}", grp.Key, grp.Count() );
}

Edit per comment: I will try and do this justice. :)

In my example, it's a Func<int, TKey> because my list is ints. So, I'm telling GroupBy how to group my items. The Func takes a int and returns the the key for my grouping. In this case, I will get an IGrouping<int,int> (a grouping of ints keyed by an int). If I changed it to (i => i.ToString() ) for example, I would be keying my grouping by a string. You can imagine a less trivial example than keying by "1", "2", "3" ... maybe I make a function that returns "one", "two", "three" to be my keys ...

private string SampleMethod( int i )
{
  // magically return "One" if i == 1, "Two" if i == 2, etc.
}

So, that's a Func that would take an int and return a string, just like ...

i =>  // magically return "One" if i == 1, "Two" if i == 2, etc. 

But, since the original question called for knowing the original list value and it's count, I just used an integer to key my integer grouping to make my example simpler.

What is the purpose of "&&" in a shell command?

####################### && or (Logical AND) ######################
first_command="1"
two_command="2"

if [[ ($first_command == 1) && ($two_command == 2)]];then
 echo "Equal"
fi

When program checks if command, then the program creates a number called exit code, if both conditions are true, exit code is zero (0), otherwise, exit code is positive number. only when displaying Equal if exit code is produced zero (0) that means both conditions are true.

How to get unique device hardware id in Android?

I use following code to get Android id.

String android_id = Secure.getString(this.getContentResolver(),
            Secure.ANDROID_ID);

Log.d("Android","Android ID : "+android_id);

enter image description here

How to filter specific apps for ACTION_SEND intent (and set a different text for each app)

If you want a customized option then you should not rely on the default dialog provided by android for this action.

What you need to do instead is roll out your own. You will need to query the PackageManager on which packages handle the action you require and then based on the reply, you apply filtering and customized text.

Specifically, take a look at the method queryIntentActivities of the PackageManager class. You build the intent that would launch the default dialog (the ACTION_SEND intent), pass that to this method and you will receive a list of objects that contain info on the activities that can handle that intent. Using that, you can choose the ones you want.

Once you build your list of packages you want to present, you need to build your own list dialog (preferably an activity with the dialog theme) which will display that list.

One thing to note though is that it's very hard to make that custom dialog look like the default one. The problem is that the theme used in that dialog is an internal theme and cannot be used by your application. You can either try to make it as similar to the native one as you want or go for a completely custom look (many apps do that like the gallery app etc)

CSS last-child(-1)

You can use :nth-last-child(); in fact, besides :nth-last-of-type() I don't know what else you could use. I'm not sure what you mean by "dynamic", but if you mean whether the style applies to the new second last child when more children are added to the list, yes it will. Interactive fiddle.

ul li:nth-last-child(2)

Installing PIL with pip

I take it you're on Mac. See How can I install PIL on mac os x 10.7.2 Lion

If you use [homebrew][], you can install the PIL with just brew install pil. You may then need to add the install directory ($(brew --prefix)/lib/python2.7/site-packages) to your PYTHONPATH, or add the location of PIL directory itself in a file called PIL.pth file in any of your site-packages directories, with the contents:

/usr/local/lib/python2.7/site-packages/PIL

(assuming brew --prefix is /usr/local).

Alternatively, you can just download/build/install it from source:

# download
curl -O -L http://effbot.org/media/downloads/Imaging-1.1.7.tar.gz
# extract
tar -xzf Imaging-1.1.7.tar.gz
cd Imaging-1.1.7
# build and install
python setup.py build
sudo python setup.py install
# or install it for just you without requiring admin permissions:
# python setup.py install --user

I ran the above just now (on OSX 10.7.2, with XCode 4.2.1 and System Python 2.7.1) and it built just fine, though there is a possibility that something in my environment is non-default.

[homebrew]: http://mxcl.github.com/homebrew/ "Homebrew"

using facebook sdk in Android studio

People using Android Studio 0.8.6 could do these:

  1. Download Facebook-android-sdk-xxx.zip & Unzip it
  2. Copy ONLY facebook dir under the Facebook-android-sdk-xxx dir into your project along with app/

    • ImAnApp/
      • |-- app/
      • |-- build/
      • |-- facebook/
  3. Now you should see Android Studio showing facebook as module

  4. Modify the build.gradle of facebook into this.
    • provided files('../libs/bolts.jar') to provided files('./libs/bolts.jar')
    • compileSdkVersion Integer.parseInt(project.ANDROID_BUILD_SDK_VERSION) to compileSdkVersion 20 or other version you defined in the app
    • buildToolsVersion project.ANDROID_BUILD_TOOLS_VERSION to buildToolsVersion '20.0.0'
    • minSdkVersion Integer.parseInt(project.ANDROID_BUILD_MIN_SDK_VERSION) to minSdkVersion 14
    • targetSdkVersion Integer.parseInt(project.ANDROID_BUILD_TARGET_SDK_VERSION) to targetSdkVersion 20

    apply plugin: 'android-library'

    dependencies {
        compile 'com.android.support:support-v4:19.1.+'
        provided files('./libs/bolts.jar')
    }

    android {
        compileSdkVersion 20
        buildToolsVersion '20.0.0'

        defaultConfig {
            minSdkVersion 14
            targetSdkVersion 20
        }

        lintOptions {
            abortOnError false
        }

        sourceSets {
            main {
                manifest.srcFile 'AndroidManifest.xml'
                java.srcDirs = ['src']
                res.srcDirs = ['res']
            }
        }
    }

Resync your gradle file & it should just work fine!

Create new user in MySQL and give it full access to one database

To create a user and grant all privileges on a database.

Log in to MySQL:

mysql -u root

Now create and grant

GRANT ALL PRIVILEGES ON dbTest.* To 'user'@'hostname' IDENTIFIED BY 'password';

Anonymous user (for local testing only)

Alternately, if you just want to grant full unrestricted access to a database (e.g. on your local machine for a test instance, you can grant access to the anonymous user, like so:

GRANT ALL PRIVILEGES ON dbTest.* To ''@'hostname'

Be aware

This is fine for junk data in development. Don't do this with anything you care about.

Best practice for using assert?

In addition to the other answers, asserts themselves throw exceptions, but only AssertionErrors. From a utilitarian standpoint, assertions aren't suitable for when you need fine grain control over which exceptions you catch.

How can I convert a VBScript to an executable (EXE) file?

Here are a couple possible solutions...

I have not tried all of these myself yet, but I will be trying them all soon.

Note: I do not have any personal or financial connection to any of these tools.

1) VB Script to EXE Converter (NOT Compiler): (Free)
vbs2exe.com.

The exe produced appears to be a true EXE.

From their website:

VBS to EXE is a free online converter that doesn't only convert your vbs files into exe but it also:

1- Encrypt your vbs file source code using 128 bit key.
2- Allows you to call win32 API
3- If you have troubles with windows vista especially when UAC is enabled then you may give VBS to EXE a try.
4- No need for wscript.exe to run your vbs anymore.
5- Your script is never saved to the hard disk like some others converters. it is a TRUE exe not an extractor.

This solution should work even if wscript/cscript is not installed on the computer.

Basically, this creates a true .EXE file. Inside the created .EXE is an "engine" that replaces wscript/cscript, and an encrypted copy of your VB Script code. This replacement engine executes your code IN MEMORY without calling wscript/cscript to do it.


2) Compile and Convert VBS to EXE...:
ExeScript

The current version is 3.5.

This is NOT a Free solution. They have a 15 day trial. After that, you need to buy a license for a hefty $44.96 (Home License/noncommercial), or $89.95 (Business License/commercial usage).

It seems to work in a similar way to the previous solution.

According to a forum post there:
Post: "A Exe file still need Windows Scripting Host (WSH) ??"

WSH is not required if "Compile" option was used, since ExeScript
implements it's own scripting host. ...


3) Encrypt the script with Microsoft's ".vbs to .vbe" encryption tool.

Apparently, this does not work for Windows 7/8, and it is possible there are ways to "decrypt" the .vbe file. At the time of writing this, I could not find a working link to download this. If I find one, I will add it to this answer.

c# - How to get sum of the values from List?

You can use the Sum function, but you'll have to convert the strings to integers, like so:

int total = monValues.Sum(x => Convert.ToInt32(x));

Paste multiple columns together

I'd construct a new data.frame:

d <- data.frame('a' = 1:3, 'b' = c('a','b','c'), 'c' = c('d', 'e', 'f'), 'd' = c('g', 'h', 'i')) 

cols <- c( 'b' , 'c' , 'd' )

data.frame(a = d[, 'a'], x = do.call(paste, c(d[ , cols], list(sep = '-'))))

SELECT CASE WHEN THEN (SELECT)

For a start the first select has 6 columns and the second has 4 columns. Perhaps make both have the same number of columns (adding nulls?).

Can Windows' built-in ZIP compression be scripted?

to create a compressed archive you can use the utility MAKECAB.EXE

node.js + mysql connection pooling

You will find this wrapper usefull :)

var pool = mysql.createPool(config.db);

exports.connection = {
    query: function () {
        var queryArgs = Array.prototype.slice.call(arguments),
            events = [],
            eventNameIndex = {};

        pool.getConnection(function (err, conn) {
            if (err) {
                if (eventNameIndex.error) {
                    eventNameIndex.error();
                }
            }
            if (conn) { 
                var q = conn.query.apply(conn, queryArgs);
                q.on('end', function () {
                    conn.release();
                });

                events.forEach(function (args) {
                    q.on.apply(q, args);
                });
            }
        });

        return {
            on: function (eventName, callback) {
                events.push(Array.prototype.slice.call(arguments));
                eventNameIndex[eventName] = callback;
                return this;
            }
        };
    }
};

Require it, use it like this:

db.connection.query("SELECT * FROM `table` WHERE `id` = ? ", row_id)
          .on('result', function (row) {
            setData(row);
          })
          .on('error', function (err) {
            callback({error: true, err: err});
          });

How to check if an element is off-screen

There's a jQuery plugin here which allows users to test whether an element falls within the visible viewport of the browser, taking the browsers scroll position into account.

$('#element').visible();

You can also check for partial visibility:

$('#element').visible( true);

One drawback is that it only works with vertical positioning / scrolling, although it should be easy enough to add horizontal positioning into the mix.

_DEBUG vs NDEBUG

Visual Studio defines _DEBUG when you specify the /MTd or /MDd option, NDEBUG disables standard-C assertions. Use them when appropriate, ie _DEBUG if you want your debugging code to be consistent with the MS CRT debugging techniques and NDEBUG if you want to be consistent with assert().

If you define your own debugging macros (and you don't hack the compiler or C runtime), avoid starting names with an underscore, as these are reserved.

Can't use SURF, SIFT in OpenCV

Change this:

sift = cv2.xfeatures2d.SIFT_create()

By this:

cv2.ORB_create()

Is there any difference between DECIMAL and NUMERIC in SQL Server?

They are exactly the same. When you use it be consistent. Use one of them in your database

Double free or corruption after queue::push

Let's talk about copying objects in C++.

Test t;, calls the default constructor, which allocates a new array of integers. This is fine, and your expected behavior.

Trouble comes when you push t into your queue using q.push(t). If you're familiar with Java, C#, or almost any other object-oriented language, you might expect the object you created earler to be added to the queue, but C++ doesn't work that way.

When we take a look at std::queue::push method, we see that the element that gets added to the queue is "initialized to a copy of x." It's actually a brand new object that uses the copy constructor to duplicate every member of your original Test object to make a new Test.

Your C++ compiler generates a copy constructor for you by default! That's pretty handy, but causes problems with pointer members. In your example, remember that int *myArray is just a memory address; when the value of myArray is copied from the old object to the new one, you'll now have two objects pointing to the same array in memory. This isn't intrinsically bad, but the destructor will then try to delete the same array twice, hence the "double free or corruption" runtime error.

How do I fix it?

The first step is to implement a copy constructor, which can safely copy the data from one object to another. For simplicity, it could look something like this:

Test(const Test& other){
    myArray = new int[10];
    memcpy( myArray, other.myArray, 10 );
}

Now when you're copying Test objects, a new array will be allocated for the new object, and the values of the array will be copied as well.

We're not completely out trouble yet, though. There's another method that the compiler generates for you that could lead to similar problems - assignment. The difference is that with assignment, we already have an existing object whose memory needs to be managed appropriately. Here's a basic assignment operator implementation:

Test& operator= (const Test& other){
    if (this != &other) {
        memcpy( myArray, other.myArray, 10 );
    }
    return *this;
}

The important part here is that we're copying the data from the other array into this object's array, keeping each object's memory separate. We also have a check for self-assignment; otherwise, we'd be copying from ourselves to ourselves, which may throw an error (not sure what it's supposed to do). If we were deleting and allocating more memory, the self-assignment check prevents us from deleting memory from which we need to copy.

Where can I find the Java SDK in Linux after installing it?

Simple, try it:

It's /usr/local/java/jdk[version]

pandas: to_numeric for multiple columns

If you are looking for a range of columns, you can try this:

df.iloc[7:] = df.iloc[7:].astype(float)

The examples above will convert type to be float, for all the columns begin with the 7th to the end. You of course can use different type or different range.

I think this is useful when you have a big range of columns to convert and a lot of rows. It doesn't make you go over each row by yourself - I believe numpy do it more efficiently.

This is useful only if you know that all the required columns contain numbers only - it will not change "bad values" (like string) to be NaN for you.

Connecting to SQL Server using windows authentication

A connection string for SQL Server should look more like: "Server= localhost; Database= employeedetails; Integrated Security=True;"

If you have a named instance of SQL Server, you'll need to add that as well, e.g., "Server=localhost\sqlexpress"

The type or namespace name 'Entity' does not exist in the namespace 'System.Data'

I had entity framework 6.1.3, upgraded (well, more downgraded in NuGet) to 6.1.2. Worked.

C++ vector's insert & push_back difference

The biggest difference is their functionality. push_back always puts a new element at the end of the vector and insert allows you to select new element's position. This impacts the performance. vector elements are moved in the memory only when it's necessary to increase it's length because too little memory was allocated for it. On the other hand insert forces to move all elements after the selected position of a new element. You simply have to make a place for it. This is why insert might often be less efficient than push_back.

Error while trying to run project: Unable to start program. Cannot find the file specified

I had the same problem.
The cause for me was that the Command option in Configuration Properties | Debugging had been reset to its default value.

JPA entity without id

See the Java Persistence book: Identity and Sequencing

The relevant part for your question is the No Primary Key section:

Sometimes your object or table has no primary key. The best solution in this case is normally to add a generated id to the object and table. If you do not have this option, sometimes there is a column or set of columns in the table that make up a unique value. You can use this unique set of columns as your id in JPA. The JPA Id does not always have to match the database table primary key constraint, nor is a primary key or a unique constraint required.

If your table truly has no unique columns, then use all of the columns as the id. Typically when this occurs the data is read-only, so even if the table allows duplicate rows with the same values, the objects will be the same anyway, so it does not matter that JPA thinks they are the same object. The issue with allowing updates and deletes is that there is no way to uniquely identify the object's row, so all of the matching rows will be updated or deleted.

If your object does not have an id, but its' table does, this is fine. Make the object an Embeddable object, embeddable objects do not have ids. You will need a Entity that contains this Embeddable to persist and query it.

Running JAR file on Windows

If you use eclipse for making your java files, you can choose to export it as a runnable jar file. I did this with my programs and I can just click on the jar and it will run just like that. This will work on both windows, as well as os x.

Hadoop/Hive : Loading data from .csv on a local machine

if you have a hive setup you can put the local dataset directly using Hive load command in hdfs/s3.

You will need to use "Local" keyword when writing your load command.

Syntax for hiveload command

LOAD DATA [LOCAL] INPATH 'filepath' [OVERWRITE] INTO TABLE tablename [PARTITION (partcol1=val1, partcol2=val2 ...)]

Refer below link for more detailed information. https://cwiki.apache.org/confluence/display/Hive/LanguageManual%20DML#LanguageManualDML-Loadingfilesintotables

Getting a Request.Headers value

Header exists:

if (Request.Headers["XYZComponent"] != null)

or even better:

string xyzHeader = Request.Headers["XYZComponent"];
bool isXYZ;

if (bool.TryParse(xyzHeader, out isXYZ) && isXYZ)

which will check whether it is set to true. This should be fool-proof because it does not care on leading/trailing whitespace and is case-insensitive (bool.TryParse does work on null)

Addon: You could make this more simple with this extension method which returns a nullable boolean. It should work on both invalid input and null.

public static bool? ToBoolean(this string s)
{
    bool result;

    if (bool.TryParse(s, out result))
        return result;
    else
        return null;
}

Usage (because this is an extension method and not instance method this will not throw an exception on null - it may be confusing, though):

if (Request.Headers["XYZComponent"].ToBoolean() == true)

How do I get the path of the current executed file in Python?

You can't directly determine the location of the main script being executed. After all, sometimes the script didn't come from a file at all. For example, it could come from the interactive interpreter or dynamically generated code stored only in memory.

However, you can reliably determine the location of a module, since modules are always loaded from a file. If you create a module with the following code and put it in the same directory as your main script, then the main script can import the module and use that to locate itself.

some_path/module_locator.py:

def we_are_frozen():
    # All of the modules are built-in to the interpreter, e.g., by py2exe
    return hasattr(sys, "frozen")

def module_path():
    encoding = sys.getfilesystemencoding()
    if we_are_frozen():
        return os.path.dirname(unicode(sys.executable, encoding))
    return os.path.dirname(unicode(__file__, encoding))

some_path/main.py:

import module_locator
my_path = module_locator.module_path()

If you have several main scripts in different directories, you may need more than one copy of module_locator.

Of course, if your main script is loaded by some other tool that doesn't let you import modules that are co-located with your script, then you're out of luck. In cases like that, the information you're after simply doesn't exist anywhere in your program. Your best bet would be to file a bug with the authors of the tool.

How to pad a string to a fixed length with spaces in Python?

I know this is a bit of an old question, but I've ended up making my own little class for it.

Might be useful to someone so I'll stick it up. I used a class variable, which is inherently persistent, to ensure sufficient whitespace was added to clear any old lines. See below:

class consolePrinter():
'''
Class to write to the console

Objective is to make it easy to write to console, with user able to 
overwrite previous line (or not)
'''
# -------------------------------------------------------------------------    
#Class variables
stringLen = 0    
# -------------------------------------------------------------------------    
    
# -------------------------------------------------------------------------
def writeline(stringIn, overwriteFlag=False):
    import sys
    #Get length of stringIn and update stringLen if needed
    if len(stringIn) > consolePrinter.stringLen:
        consolePrinter.stringLen = len(stringIn)+1
    
    ctrlString = "{:<"+str(consolePrinter.stringLen)+"}"
    if overwriteFlag:
        sys.stdout.write("\r" + ctrlString.format(stringIn))
    else:
        sys.stdout.write("\n" + stringIn)
    sys.stdout.flush()
    
    return

Which then is called via:

consolePrinter.writeline("text here", True) 

If you want to overwrite the previous line, or

consolePrinter.writeline("text here",False)

if you don't.

Note, for it to work right, all messages pushed to the console would need to be through consolePrinter.writeline.

How to remove a virtualenv created by "pipenv run"

You can run the pipenv command with the --rm option as in:

pipenv --rm

This will remove the virtualenv created for you under ~/.virtualenvs

See https://pipenv.kennethreitz.org/en/latest/cli/#cmdoption-pipenv-rm

Creating SVG graphics using Javascript?

Currently all major browsers support svg. Create svg in JS is very simple (currently innerHTML=... is quite fast)

element.innerHTML = `
    <svg viewBox="0 0 400 100" >
      <circle id="circ" cx="50" cy="50" r="50" fill="red" />
    </svg>
`;

_x000D_
_x000D_
function createSVG() {
  box.innerHTML = `
    <svg viewBox="0 0 400 100" >
      <circle id="circ" cx="50" cy="50" r="50" fill="red" />
    </svg>
  `;
}

function decRadius() {
  r=circ.getAttribute('r');
  circ.setAttribute('r',r*0.5);
}
_x000D_
<button onclick="createSVG()">Create SVG</button>
<button onclick="decRadius()">Decrease radius</button>
<div id="box"></div>
_x000D_
_x000D_
_x000D_

Error: class X is public should be declared in a file named X.java

I my case, I was using syncthing. It created a duplicate that I was not aware of and my compilation was failing.

Difference between Static methods and Instance methods

Static methods, variables belongs to the whole class, not just an object instance. A static method, variable is associated with the class as a whole rather than with specific instances of a class. Each object will share a common copy of the static methods, variables. There is only one copy per class, no matter how many objects are created from it.

Extracting Nupkg files using command line

You can also use the NuGet command line, by specifying a local host as part of an install. For example if your package is stored in the current directory

nuget install MyPackage -Source %cd% -OutputDirectory packages

will unpack it into the target directory.

Choose folders to be ignored during search in VS Code

Hi you need to find settings and add a new exclude pattern for history files

VSC Screenshot

Split string into strings by length?

Here are two generic approaches. Probably worth adding to your own lib of reusables. First one requires the item to be sliceable and second one works with any iterables (but requires their constructor to accept iterable).

def split_bylen(item, maxlen):
    '''
    Requires item to be sliceable (with __getitem__ defined)
    '''
    return [item[ind:ind+maxlen] for ind in range(0, len(item), maxlen)]
    #You could also replace outer [ ] brackets with ( ) to use as generator.

def split_bylen_any(item, maxlen, constructor=None):
    '''
    Works with any iterables.
    Requires item's constructor to accept iterable or alternatively 
    constructor argument could be provided (otherwise use item's class)
    '''
    if constructor is None: constructor = item.__class__
    return [constructor(part) for part in zip(* ([iter(item)] * maxlen))]
    #OR: return map(constructor, zip(* ([iter(item)] * maxlen)))
    #    which would be faster if you need an iterable, not list

So, in topicstarter's case, the usage is:

string = 'Baboons love bananas'
parts = 5
splitlen = -(-len(string) // parts) # is alternative to math.ceil(len/parts)

first_method = split_bylen(string, splitlen)
#Result :['Babo', 'ons ', 'love', ' ban', 'anas']

second_method = split_bylen_any(string, splitlen, constructor=''.join)
#Result :['Babo', 'ons ', 'love', ' ban', 'anas']

Convert array to JSON

Wow, seems it got a lot easier nowadays... 3 ways you can do it:

json = { ...array };

json = Object.assign({}, array);

json = array.reduce((json, value, key) => { json[key] = value; return json; }, {});

javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25

Try to set the property when starting JVM, for example, add -Djava.net.preferIPv4Stack=true.

You can't set it when code running, as the java.net just read it when jvm starting.

And about the root cause, this article give some hint: Why do I need java.net.preferIPv4Stack=true only on some windows 7 systems?.

How to unapply a migration in ASP.NET Core with EF Core

Note: It might be troublesome later on, I used it as a last resort since non of the solutions provided above and others did not work in my case:

  1. Copy the code from the body of previous successful migration's down() method.
  2. Add a new migration using Add-Migration "migration-name"
  3. Paste the copied code from the down() method of previous migration to the new migration's Up() method:
    Up(){ //paste here }
  4. Run Update-Database
  5. Done, your changes from the previous migration should now have been reverted!

Skip Git commit hooks

For those very beginners who has spend few hours for this commit (with comment and no verify) with no further issue

git commit -m "Some comments" --no-verify

How to split a string and assign it to variables

There's are multiple ways to split a string :

  1. If you want to make it temporary then split like this:

_

import net package

host, port, err := net.SplitHostPort("0.0.0.1:8080")
if err != nil {
fmt.Println("Error is splitting : "+err.error());
//do you code here
}
fmt.Println(host, port)
  1. Split based on struct :

    • Create a struct and split like this

_

type ServerDetail struct {
    Host       string
    Port       string
    err        error
}

ServerDetail = net.SplitHostPort("0.0.0.1:8080") //Specific for Host and Port

Now use in you code like ServerDetail.Host and ServerDetail.Port

If you don't want to split specific string do it like this:

type ServerDetail struct {
    Host       string
    Port       string
}

ServerDetail = strings.Split([Your_String], ":") // Common split method

and use like ServerDetail.Host and ServerDetail.Port.

That's All.

Convert IQueryable<> type object to List<T> type?

System.Linq has ToList() on IQueryable<> and IEnumerable<>. It will cause a full pass through the data to put it into a list, though. You loose your deferred invoke when you do this. Not a big deal if it is the consumer of the data.

How do I prevent Eclipse from hanging on startup?

What worked for me was this-- On Ubuntu

  1. Ctrl+F1
  2. ps -e
  3. kill -9 for process ids of eclipse, java and adb

How can I reduce the waiting (ttfb) time

TTFB is something that happens behind the scenes. Your browser knows nothing about what happens behind the scenes.

You need to look into what queries are being run and how the website connects to the server.

This article might help understand TTFB, but otherwise you need to dig deeper into your application.

Preserve Line Breaks From TextArea When Writing To MySQL

This works:

function getBreakText($t) {
    return strtr($t, array('\\r\\n' => '<br>', '\\r' => '<br>', '\\n' => '<br>'));
}

What is Parse/parsing?

Parsing can be considered as a synonym of "Breaking down into small pieces" and then analysing what is there or using it in a modified way. In Java, Strings are parsed into Decimal, Octal, Binary, Hexadecimal, etc. It is done if your application is taking input from the user in the form of string but somewhere in your application you want to use that input in the form of an integer or of double type. It is not same as type casting. For type casting the types used should be compatible in order to caste but nothing such in parsing.

Resize UIImage by keeping Aspect ratio and width

To improve on Ryan's answer:

   + (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)size {
CGFloat oldWidth = image.size.width;
        CGFloat oldHeight = image.size.height;

//You may need to take some retina adjustments into consideration here
        CGFloat scaleFactor = (oldWidth > oldHeight) ? width / oldWidth : height / oldHeight;

return [UIImage imageWithCGImage:image.CGImage scale:scaleFactor orientation:UIImageOrientationUp];
    }

Set Text property of asp:label in Javascript PROPER way

Place HiddenField Control in your Form.

<asp:HiddenField ID="hidden" runat="server" />

Create a Property in the Form

protected String LabelProperty
{
    get
    {
        return hidden.Value;
    }
    set
    {
        hidden.Value = value;
    }
}

Update the Hidden Field value from JavaScript

<script>
   function UpdateControl() {
            document.getElementById('<%=hidden.ClientID %>').value = '12';
   }
</script>

Now you can access the Property directly across the Postback. The Label Control updated value will be Lost across PostBack in case it is being used directly in code behind .

Duplicate Entire MySQL Database

This worked for me with command prompt, from OUTSIDE mysql shell:

# mysqldump -u root -p password db1 > dump.sql
# mysqladmin -u root -p password create db2
# mysql -u root -p password db2 < dump.sql

This looks for me the best way. If zipping "dump.sql" you can symply store it as a compressed backup. Cool! For a 1GB database with Innodb tables, about a minute to create "dump.sql", and about three minutes to dump data into the new DB db2.

Straight copying the hole db directory (mysql/data/db1) didn't work for me, I guess because of the InnoDB tables.

How to use MapView in android using google map V2?

yes you can use MapView in v2... for further details you can get help from this

https://gist.github.com/joshdholtz/4522551


SomeFragment.java

public class SomeFragment extends Fragment implements OnMapReadyCallback{
 
    MapView mapView;
    GoogleMap map;
 
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.some_layout, container, false);
 
        // Gets the MapView from the XML layout and creates it
        mapView = (MapView) v.findViewById(R.id.mapview);
        mapView.onCreate(savedInstanceState);
 
    
        mapView.getMapAsync(this);
        
 
        return v;
    }
 
   @Override
   public void onMapReady(GoogleMap googleMap) {
       map = googleMap;
       map.getUiSettings().setMyLocationButtonEnabled(false);
       map.setMyLocationEnabled(true);
       /*
       //in old Api Needs to call MapsInitializer before doing any CameraUpdateFactory call
        try {
            MapsInitializer.initialize(this.getActivity());
        } catch (GooglePlayServicesNotAvailableException e) {
            e.printStackTrace();
        } 
       */
        
        // Updates the location and zoom of the MapView
        /*CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(43.1, -87.9), 10);
        map.animateCamera(cameraUpdate);*/
        map.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(43.1, -87.9)));

    }

    @Override
    public void onResume() {
        mapView.onResume();
        super.onResume();
    }


    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }
 
    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }
 
    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mapView.onLowMemory();
    }
 
}

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example"
    android:versionCode="1"
    android:versionName="1.0" >
    
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />
    
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    
    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/>
    
    <permission
        android:name="com.example.permission.MAPS_RECEIVE"
        android:protectionLevel="signature"/>
    <uses-permission android:name="com.example.permission.MAPS_RECEIVE"/>
    
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="your_key"/>
        
        <activity
            android:name=".HomeActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    
    </application>
 
</manifest>

some_layout.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    
    <com.google.android.gms.maps.MapView android:id="@+id/mapview"
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent" />
 
</LinearLayout>

FIX CSS <!--[if lt IE 8]> in IE

<!--[if lt IE 8]><![endif]-->

The lt in the above statement means less than, so 'if less than IE 8'.

For all versions of IE you can just use

<!--[if IE]><![endif]-->

or for all versions above ie 6 for example.

<!--[if gt IE 6]><![endif]-->

Where gt is 'greater than'

If you would like to write specific styles for versions below and including IE8 you can write

<!--[if lte IE 8]><![endif]-->

where lte is 'less than and equal' to

Rename computer and join to domain in one step with PowerShell

This will prompt for computer name and join to domain then restart.

$computerName = Get-WmiObject Win32_ComputerSystem 
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null 
$name = [Microsoft.VisualBasic.Interaction]::InputBox("Enter Desired Computer Name ")
$computername.rename("$name")
Add-Computer -DomainName [domainname] -Credential [user\domain]  -Verbose
Restart-Computer

How to find if directory exists in Python

os provides you with a lot of these capabilities:

import os
os.path.isdir(dir_in) #True/False: check if this is a directory
os.listdir(dir_in)    #gets you a list of all files and directories under dir_in

the listdir will throw an exception if the input path is invalid.

Is `shouldOverrideUrlLoading` really deprecated? What can I use instead?

The version I'm using I think is the good one, since is the exact same as the Android Developer Docs, except for the name of the string, they used "view" and I used "webview", for the rest is the same

No, it is not.

The one that is new to the N Developer Preview has this method signature:

public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request)

The one that is supported by all Android versions, including N, has this method signature:

public boolean shouldOverrideUrlLoading(WebView view, String url)

So why should I do to make it work on all versions?

Override the deprecated one, the one that takes a String as the second parameter.

Merging multiple PDFs using iTextSharp in c#.net

Using iTextSharp.dll

protected void Page_Load(object sender, EventArgs e)
{
    String[] files = @"C:\ENROLLDOCS\A1.pdf,C:\ENROLLDOCS\A2.pdf".Split(',');
    MergeFiles(@"C:\ENROLLDOCS\New1.pdf", files);
}
public void MergeFiles(string destinationFile, string[] sourceFiles)
{
    if (System.IO.File.Exists(destinationFile))
        System.IO.File.Delete(destinationFile);

    string[] sSrcFile;
    sSrcFile = new string[2];

    string[] arr = new string[2];
    for (int i = 0; i <= sourceFiles.Length - 1; i++)
    {
        if (sourceFiles[i] != null)
        {
            if (sourceFiles[i].Trim() != "")
                arr[i] = sourceFiles[i].ToString();
        }
    }

    if (arr != null)
    {
        sSrcFile = new string[2];

        for (int ic = 0; ic <= arr.Length - 1; ic++)
        {
            sSrcFile[ic] = arr[ic].ToString();
        }
    }
    try
    {
        int f = 0;

        PdfReader reader = new PdfReader(sSrcFile[f]);
        int n = reader.NumberOfPages;
        Response.Write("There are " + n + " pages in the original file.");
        Document document = new Document(PageSize.A4);

        PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationFile, FileMode.Create));

        document.Open();
        PdfContentByte cb = writer.DirectContent;
        PdfImportedPage page;

        int rotation;
        while (f < sSrcFile.Length)
        {
            int i = 0;
            while (i < n)
            {
                i++;

                document.SetPageSize(PageSize.A4);
                document.NewPage();
                page = writer.GetImportedPage(reader, i);

                rotation = reader.GetPageRotation(i);
                if (rotation == 90 || rotation == 270)
                {
                    cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
                }
                else
                {
                    cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                }
                Response.Write("\n Processed page " + i);
            }

            f++;
            if (f < sSrcFile.Length)
            {
                reader = new PdfReader(sSrcFile[f]);
                n = reader.NumberOfPages;
                Response.Write("There are " + n + " pages in the original file.");
            }
        }
        Response.Write("Success");
        document.Close();
    }
    catch (Exception e)
    {
        Response.Write(e.Message);
    }


}

sorting dictionary python 3

I'm not sure whether this could help, but I had a similar problem and I managed to solve it, by defining an apposite function:

def sor_dic_key(diction):
    lista = []
    diction2 = {}
    for x in diction:
        lista.append([x, diction[x]])
    lista.sort(key=lambda x: x[0])
    for l in lista:
        diction2[l[0]] = l[1]
    return diction2

This function returns another dictionary with the same keys and relative values, but sorted by its keys. Similarly, I defined a function that could sort a dictionary by its values. I just needed to use x[1] instead of x[0] in the lambda function. I find this second function mostly useless, but one never can tell!

Git asks for username every time I push

ssh + key authentication is more reliable way than https + credential.helper

You can configure to use SSH instead of HTTPS for all the repositories as follows:

git config --global url.ssh://[email protected]/.insteadOf https://github.com/

url.<base>.insteadOf is documented here.

Indexing vectors and arrays with +:

This is another way to specify the range of the bit-vector.

x +: N, The start position of the vector is given by x and you count up from x by N.

There is also

x -: N, in this case the start position is x and you count down from x by N.

N is a constant and x is an expression that can contain iterators.

It has a couple of benefits -

  1. It makes the code more readable.

  2. You can specify an iterator when referencing bit-slices without getting a "cannot have a non-constant value" error.

Table-level backup

If you're looking for something like MySQL's DUMP, then good news: SQL Server 2008 Management Studio added that ability.

In SSMS, just right-click on the DB in question and select Tasks > Generate Scripts. Then in the 2nd page of the options wizard, make sure to select that you'd like the data scripted as well, and it will generate what amounts to a DUMP file for you.

How to Fill an array from user input C#?

string []answer = new string[10];
for(int i = 0;i<answer.length;i++)
{
    answer[i]= Console.ReadLine();
}

Change form size at runtime in C#

Something like this works fine for me:

public partial class Form1 : Form
{
    Form mainFormHandler;
...
}

private void Form1_Load(object sender, EventArgs e){
    mainFormHandler = Application.OpenForms[0];
   //or instead use this one:
   //mainFormHandler = Application.OpenForms["Form1"];
}

Then you can change the size as below:

mainFormHandler.Width = 600;
mainFormHandler.Height= 400;

or

mainFormHandler.Size = new Size(600, 400);

Another useful point is that if you want to change the size of mainForm from another Form, you can simply use Property to set the size.

How to configure nginx to enable kinda 'file browser' mode?

All answers contain part of the answer. Let me try to combine all in one.

Quick setup "file browser" mode on freshly installed nginx server:

  1. Edit default config for nginx:

    sudo vim /etc/nginx/sites-available/default
    
  2. Add following to config section:

    location /myfolder {  # new url path
       alias /home/username/myfolder/; # directory to list
       autoindex on;
    }
    
  3. Create folder and sample file there:

    mkdir -p /home/username/myfolder/
    ls -la >/home/username/myfolder/mytestfile.txt
    
  4. Restart nginx

    sudo systemctl restart nginx
    
  5. Check result: http://<your-server-ip>/myfolder for example http://192.168.0.10/myfolder/

enter image description here

React Router Pass Param to Component

Since react-router v5.1 with hooks:

import { useParams } from 'react-router';

export default function DetailsPage() {
  const { id } = useParams();
}

See https://reacttraining.com/blog/react-router-v5-1/

Is it possible to change the radio button icon in an android radio button group

You can put custom image in radiobutton like normal button. for that create one XML file in drawable folder e.g

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/sub_screens_aus_hl" 
    android:state_pressed="true"/>  
<item android:drawable="@drawable/sub_screens_aus" 
    android:state_checked="true"/>  
<item android:drawable="@drawable/sub_screens_aus" 
    android:state_focused="true" />
<item android:drawable="@drawable/sub_screens_aus_dis" />  
</selector> 

Here you can use 3 different images for radiobutton

and use this file to RadioButton like:

android:button="@drawable/aus"
android:layout_height="120dp"
android:layout_width="wrap_content" 

Pandas group-by and sum

Both the other answers accomplish what you want.

You can use the pivot functionality to arrange the data in a nice table

df.groupby(['Fruit','Name'],as_index = False).sum().pivot('Fruit','Name').fillna(0)



Name    Bob     Mike    Steve   Tom    Tony
Fruit                   
Apples  16.0    9.0     10.0    0.0     0.0
Grapes  35.0    0.0     0.0     87.0    15.0
Oranges 67.0    57.0    0.0     15.0    1.0

How to check if a file exists from a url

    $headers = get_headers((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://" . $_SERVER[HTTP_HOST] . '/uploads/' . $MAIN['id'] . '.pdf');
    $fileExist = (stripos($headers[0], "200 OK") ? true : false);
    if ($fileExist) {
    ?>
    <a class="button" href="/uploads/<?= $MAIN['id'] ?>.pdf" download>???????</a> 
    <? }
    ?>

Should I use scipy.pi, numpy.pi, or math.pi?

>>> import math
>>> import numpy as np
>>> import scipy
>>> math.pi == np.pi == scipy.pi
True

So it doesn't matter, they are all the same value.

The only reason all three modules provide a pi value is so if you are using just one of the three modules, you can conveniently have access to pi without having to import another module. They're not providing different values for pi.

Enum Naming Convention - Plural

Best Practice - use singular. You have a list of items that make up an Enum. Using an item in the list sounds strange when you say Versions.1_0. It makes more sense to say Version.1_0 since there is only one 1_0 Version.

Split large string in n-size chunks in JavaScript

I would use a regex...

var chunkStr = function(str, chunkLength) {
    return str.match(new RegExp('[\\s\\S]{1,' + +chunkLength + '}', 'g'));
}

Sum all the elements java arraylist

Two ways:

Use indexes:

double sum = 0;
for(int i = 0; i < m.size(); i++)
    sum += m.get(i);
return sum;

Use the "for each" style:

double sum = 0;
for(Double d : m)
    sum += d;
return sum;

How to get a value from a Pandas DataFrame and not the index and object type

Nobody mentioned it, but you can also simply use loc with the index and column labels.

df.loc[2, 'Letters']
# 'C'

Or, if you prefer to use "Numbers" column as reference, you can also set is as an index.

df.set_index('Numbers').loc[3, 'Letters']

Track a new remote branch created on GitHub

When the branch is no remote branch you can push your local branch direct to the remote.

git checkout master
git push origin master

or when you have a dev branch

git checkout dev
git push origin dev

or when the remote branch exists

git branch dev -t origin/dev

There are some other posibilites to push a remote branch.

How to filter input type="file" dialog by specific file type?

You can use the accept attribute along with the . It doesn't work in IE and Safari.

Depending on your project scale and extensibility, you could use Struts. Struts offers two ways to limit the uploaded file type, declaratively and programmatically.

For more information: http://struts.apache.org/2.0.14/docs/file-upload.html#FileUpload-FileTypes

Add Text on Image using PIL

To add text on an image file, just copy/paste the code below

<?php
$source = "images/cer.jpg";
$image = imagecreatefromjpeg($source);
$output = "images/certificate".rand(1,200).".jpg";
$white = imagecolorallocate($image,255,255,255);
$black = imagecolorallocate($image,7,94,94);
$font_size = 30;
$rotation = 0;
$origin_x = 250;
$origin_y = 450;
$font = __DIR__ ."/font/Roboto-Italic.ttf";
$text = "Dummy";
$text1 = imagettftext($image,$font_size,$rotation,$origin_x,$origin_y,$black,$font,$text);
     imagejpeg($image,$output,99);
?> <img src="<?php echo $output; ?>"> <a href="<?php echo $output;    ?>" download="<?php echo $output; ?>">Download Certificate</a>

One or more types required to compile a dynamic expression cannot be found. Are you missing references to Microsoft.CSharp.dll and System.Core.dll?

Red lines under the ViewBag was my headache for 3 month ). Just remove the Microsoft.CSharp reference from project and then add it again.

How to get the Mongo database specified in connection string in C#

With version 1.7 of the official 10gen driver, this is the current (non-obsolete) API:

const string uri = "mongodb://localhost/mydb";
var client = new MongoClient(uri);
var db = client.GetServer().GetDatabase(new MongoUrl(uri).DatabaseName);
var collection = db.GetCollection("mycollection");

You don't have write permissions for the /Library/Ruby/Gems/2.3.0 directory. (mac user)

I have faced same issue after install macOS Catalina. I had try below command and its working.

sudo gem update

Get PHP class property by string

What this function does is it checks if the property exist on this class of any of his child's, and if so it gets the value otherwise it returns null. So now the properties are optional and dynamic.

/**
 * check if property is defined on this class or any of it's childes and return it
 *
 * @param $property
 *
 * @return bool
 */
private function getIfExist($property)
{
    $value = null;
    $propertiesArray = get_object_vars($this);

    if(array_has($propertiesArray, $property)){
        $value = $propertiesArray[$property];
    }

    return $value;
}

Usage:

const CONFIG_FILE_PATH_PROPERTY = 'configFilePath';

$configFilePath = $this->getIfExist(self::CONFIG_FILE_PATH_PROPERTY);

104, 'Connection reset by peer' socket error, or When does closing a socket result in a RST rather than FIN?

I've had this problem. See The Python "Connection Reset By Peer" Problem.

You have (most likely) run afoul of small timing issues based on the Python Global Interpreter Lock.

You can (sometimes) correct this with a time.sleep(0.01) placed strategically.

"Where?" you ask. Beats me. The idea is to provide some better thread concurrency in and around the client requests. Try putting it just before you make the request so that the GIL is reset and the Python interpreter can clear out any pending threads.

Force page scroll position to top at page refresh in HTML

This is one of the best way to do so:

_x000D_
_x000D_
<script>
$(window).on('beforeunload', function() {
  $('body').hide();
  $(window).scrollTop(0);
});
</script>
_x000D_
_x000D_
_x000D_

jQuery vs document.querySelectorAll

I think the true answer is that jQuery was developed long before querySelector/querySelectorAll became available in all major browsers.

Initial release of jQuery was in 2006. In fact, even jQuery was not the first which implemented CSS selectors.

IE was the last browser to implement querySelector/querySelectorAll. Its 8th version was released in 2009.

So now, DOM elements selectors is not the strongest point of jQuery anymore. However, it still has a lot of goodies up its sleeve, like shortcuts to change element's css and html content, animations, events binding, ajax.

When to choose mouseover() and hover() function?

You can try it out http://api.jquery.com/mouseover/ on the jQuery doc page. It's a nice little, interactive demo that makes it very clear and you can actually see for yourself.

In short, you'll notice that a mouse over event occurs on an element when you are over it - coming from either its child OR parent element, but a mouse enter event only occurs when the mouse moves from the parent element to the element.

Get current time in milliseconds using C++ and Boost

If you mean milliseconds since epoch you could do

ptime time_t_epoch(date(1970,1,1)); 
ptime now = microsec_clock::local_time();
time_duration diff = now - time_t_epoch;
x = diff.total_milliseconds();

However, it's not particularly clear what you're after.

Have a look at the example in the documentation for DateTime at Boost Date Time

Plotting a python dict in order of key values

Simply pass the sorted items from the dictionary to the plot() function. concentration.items() returns a list of tuples where each tuple contains a key from the dictionary and its corresponding value.

You can take advantage of list unpacking (with *) to pass the sorted data directly to zip, and then again to pass it into plot():

import matplotlib.pyplot as plt

concentration = {
    0: 0.19849878712984576,
    5000: 0.093917341754771386,
    10000: 0.075060643507712022,
    20000: 0.06673074282575861,
    30000: 0.057119318961966224,
    50000: 0.046134834546203485,
    100000: 0.032495766396631424,
    200000: 0.018536317451599615,
    500000: 0.0059499290585381479}

plt.plot(*zip(*sorted(concentration.items())))
plt.show()

sorted() sorts tuples in the order of the tuple's items so you don't need to specify a key function because the tuples returned by dict.item() already begin with the key value.

How to get access to raw resources that I put in res folder?

getClass().getResourcesAsStream() works fine on Android. Just make sure the file you are trying to open is correctly embedded in your APK (open the APK as ZIP).

Normally on Android you put such files in the assets directory. So if you put the raw_resources.dat in the assets subdirectory of your project, it will end up in the assets directory in the APK and you can use:

getClass().getResourcesAsStream("/assets/raw_resources.dat");

It is also possible to customize the build process so that the file doesn't land in the assets directory in the APK.

Where can I find MySQL logs in phpMyAdmin?

If you are using XAMPP as your server, you'll find a logs directory as a child of the XAMPP directory. If you have not tried XAMPP, which runs on any system (Windows, Mac OS & Linux) find more here: http://www.apachefriends.org/en/xampp.html

PHP - how to create a newline character?

Use the PHP nl2br to get the newlines in a text string..

$text = "Manu is a good boy.(Enter)He can code well.

echo nl2br($text);

Result.

Manu is a good boy.

He can code well.

Convert a Pandas DataFrame to a dictionary

For my use (node names with xy positions) I found @user4179775's answer to the most helpful / intuitive:

import pandas as pd

df = pd.read_csv('glycolysis_nodes_xy.tsv', sep='\t')

df.head()
    nodes    x    y
0  c00033  146  958
1  c00031  601  195
...

xy_dict_list=dict([(i,[a,b]) for i, a,b in zip(df.nodes, df.x,df.y)])

xy_dict_list
{'c00022': [483, 868],
 'c00024': [146, 868],
 ... }

xy_dict_tuples=dict([(i,(a,b)) for i, a,b in zip(df.nodes, df.x,df.y)])

xy_dict_tuples
{'c00022': (483, 868),
 'c00024': (146, 868),
 ... }

Addendum

I later returned to this issue, for other, but related, work. Here is an approach that more closely mirrors the [excellent] accepted answer.

node_df = pd.read_csv('node_prop-glycolysis_tca-from_pg.tsv', sep='\t')

node_df.head()
   node  kegg_id kegg_cid            name  wt  vis
0  22    22       c00022   pyruvate        1   1
1  24    24       c00024   acetyl-CoA      1   1
...

Convert Pandas dataframe to a [list], {dict}, {dict of {dict}}, ...

Per accepted answer:

node_df.set_index('kegg_cid').T.to_dict('list')

{'c00022': [22, 22, 'pyruvate', 1, 1],
 'c00024': [24, 24, 'acetyl-CoA', 1, 1],
 ... }

node_df.set_index('kegg_cid').T.to_dict('dict')

{'c00022': {'kegg_id': 22, 'name': 'pyruvate', 'node': 22, 'vis': 1, 'wt': 1},
 'c00024': {'kegg_id': 24, 'name': 'acetyl-CoA', 'node': 24, 'vis': 1, 'wt': 1},
 ... }

In my case, I wanted to do the same thing but with selected columns from the Pandas dataframe, so I needed to slice the columns. There are two approaches.

  1. Directly:

(see: Convert pandas to dictionary defining the columns used fo the key values)

node_df.set_index('kegg_cid')[['name', 'wt', 'vis']].T.to_dict('dict')

{'c00022': {'name': 'pyruvate', 'vis': 1, 'wt': 1},
 'c00024': {'name': 'acetyl-CoA', 'vis': 1, 'wt': 1},
 ... }
  1. "Indirectly:" first, slice the desired columns/data from the Pandas dataframe (again, two approaches),
node_df_sliced = node_df[['kegg_cid', 'name', 'wt', 'vis']]

or

node_df_sliced2 = node_df.loc[:, ['kegg_cid', 'name', 'wt', 'vis']]

that can then can be used to create a dictionary of dictionaries

node_df_sliced.set_index('kegg_cid').T.to_dict('dict')

{'c00022': {'name': 'pyruvate', 'vis': 1, 'wt': 1},
 'c00024': {'name': 'acetyl-CoA', 'vis': 1, 'wt': 1},
 ... }

Styling twitter bootstrap buttons

In order to completely override the bootstrap button styles, you need to override a list of properties. See the below example.

    .btn-primary, .btn-primary:hover, .btn-primary:focus, .btn-primary.focus, 
    .btn-primary:active, .btn-primary.active, .btn-primary:visited,
    .btn-primary:active:hover, .btn-primary.active:hover{
        background-color: #F19425;
        color:#fff;
        border: none;
        outline: none;
    }

If you don't use all the listed styles then you will see the default styles at performing actions on button. For example once you click the button and remove mouse pointer from button, you will see the default color visible. Or keep the button pressed you will see default colors. So, I have listed all the pseudo-styles that are to be overridden.

How do I convert an object to an array?

You can quickly convert deeply nested objects to associative arrays by relying on the behavior of the JSON encode/decode functions:

$array = json_decode(json_encode($response->response->docs), true);

How to get a list of properties with a given attribute?

If you deal regularly with Attributes in Reflection, it is very, very practical to define some extension methods. You will see that in many projects out there. This one here is one I often have:

public static bool HasAttribute<T>(this ICustomAttributeProvider provider) where T : Attribute
{
  var atts = provider.GetCustomAttributes(typeof(T), true);
  return atts.Length > 0;
}

which you can use like typeof(Foo).HasAttribute<BarAttribute>();

Other projects (e.g. StructureMap) have full-fledged ReflectionHelper classes that use Expression trees to have a fine syntax to identity e.g. PropertyInfos. Usage then looks like that:

ReflectionHelper.GetProperty<Foo>(x => x.MyProperty).HasAttribute<BarAttribute>()

Javascript window.open pass values using POST

The code helped me to fulfill my requirement.

I have made some modifications and using a form I completed this. Here is my code-

Need a 'target' attribute for 'form' -- that's it!

Form

<form id="view_form" name="view_form" method="post" action="view_report.php"  target="Map" >
  <input type="text" value="<?php echo $sale->myvalue1; ?>" name="my_value1"/>
  <input type="text" value="<?php echo $sale->myvalue2; ?>" name="my_value2"/>
  <input type="button" id="download" name="download" value="View report" onclick="view_my_report();"   /> 
</form>

JavaScript

function view_my_report() {     
   var mapForm = document.getElementById("view_form");
   map=window.open("","Map","status=0,title=0,height=600,width=800,scrollbars=1");

   if (map) {
      mapForm.submit();
   } else {
      alert('You must allow popups for this map to work.');
   }
}

Full code is explained showing normal form and form elements.

How do I print out the contents of an object in Rails for easy debugging?

define the to_s method in your model. For example

class Person < ActiveRecord::Base
  def to_s
    "Name:#{self.name} Age:#{self.age} Weight: #{self.weight}"
  end
end

Then when you go to print it with #puts it will display that string with those variables.

Reading file contents on the client-side in javascript in various browsers

There's a modern native alternative: File implements Blob, so we can call Blob.text().

_x000D_
_x000D_
async function readText(event) {
  const file = event.target.files.item(0)
  const text = await file.text();
  
  document.getElementById("output").innerText = text
}
_x000D_
<input type="file" onchange="readText(event)" />
<pre id="output"></pre>
_x000D_
_x000D_
_x000D_

Currently (September 2020) this is supported in Chrome and Firefox, for other Browser you need to load a polyfill, e.g. blob-polyfill.

Error:Cannot fit requested classes in a single dex file.Try supplying a main-dex list. # methods: 72477 > 65536

If you are using minifyEnabled with Proguard, you likely won't need to enable multi-dex. I agree with MG Developer that you should try to avoid multi-dex if possible. My solution was to enable multi-dex only for debug builds. minifyEnabled solves the problem for release builds

buildTypes {
    release {
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
    debug {
        // getting error: Cannot fit requested classes in a single dex file.  # methods: 65537 > 65536
        // https://developer.android.com/studio/build/multidex
        // minifyEnabled true (used with release) will fix this by getting rid of unused method calls, but this will hide debugging info on crash
        multiDexEnabled true
    }
}

MySQL: Can't create table (errno: 150)

Try:

CREATE TABLE `data` (
  `id` int(10) unsigned NOT NULL,
  `name` varchar(100) NOT NULL,
  `value` varchar(15) NOT NULL,
UNIQUE KEY `id` (`id`,`name`),
CONSTRAINT `data_ibfk_1`,
FOREIGN KEY (`id`) REFERENCES `keywords` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;  

You need to put a "," between CONSTRAINT and FOREIGN.

How to filter rows in pandas by regex

It may be a bit late, but this is now easier to do in Pandas by calling Series.str.match. The docs explain the difference between match, fullmatch and contains.

Note that in order to use the results for indexing, set the na=False argument (or True if you want to include NANs in the results).

Angular 2 change event - model changes

If this helps you,

<input type="checkbox"  (ngModelChange)="mychange($event)" [ngModel]="mymodel">

mychange(val)
{
   console.log(val); // updated value
}

Run R script from command line

This does not answer the question directly. But someone may end up here because they want to run a oneliner of R from the terminal. For example, if you just want to install some missing packages and quit, this oneliner can be very convenient. I use it a lot when I suddenly find out that I miss some packages, and I want to install them to where I want.

  • To install to the default location:

    R -e 'install.packages(c("package1", "package2"))'
    
  • To install to a location that requires root privileges:

    R -e 'install.packages(c("package1", "package2"), lib="/usr/local/lib/R/site-library")' 
    

How to push a docker image to a private repository

Just three simple steps:

  1. docker login --username username

    • prompts for password if you omit --password which is recommended as it doesn't store it in your command history
  2. docker tag my-image username/my-repo

  3. docker push username/my-repo

Leave out quotes when copying from cell

First paste it into Word, then you can paste it into notepad and it will appear without the quotes

Trouble Connecting to sql server Login failed. "The login is from an untrusted domain and cannot be used with Windows authentication"

Just adding my suggestion for a resolution, I had a copy of a VM server for developing and testing, I created the database on that with 'sa' having ownership on the db.

I then restored the database onto the live VM server but I was getting the same error mentioned even though the data was still returning correctly. I looked up the 'sa' user mappings and could see it wasn't mapped to the database when I tried to apply the mapping I got a another error "Fix: Cannot use the special principal ‘sa’. Microsoft SQL Server, Error: 15405". so I ran this instead

ALTER AUTHORIZATION ON DATABASE::dbname TO sa

I rechecked the user mappings and it was now assigned to my db and it fixed a lot of access issues for me.

How to get current date time in milliseconds in android

I think leverage this functionality using Java

long time= System.currentTimeMillis();

this will return current time in milliseconds mode . this will surely work

long time= System.currentTimeMillis();
android.util.Log.i("Time Class ", " Time value in millisecinds "+time);

Here is my logcat using the above function

05-13 14:38:03.149: INFO/Time Class(301): Time value in millisecinds 1368436083157

If you got any doubt with millisecond value .Check Here

EDIT : Time Zone I used to demo the code IST(+05:30) ,So if you check milliseconds that mentioned in log to match with time in log you might get a different value based your system timezone

EDIT: This is easy approach .but if you need time zone or any other details I think this won't be enough Also See this approach using android api support

FIFO based Queue implementations?

Queue is an interface that extends Collection in Java. It has all the functions needed to support FIFO architecture.

For concrete implementation you may use LinkedList. LinkedList implements Deque which in turn implements Queue. All of these are a part of java.util package.

For details about method with sample example you can refer FIFO based Queue implementation in Java.

PS: Above link goes to my personal blog that has additional details on this.

How to make Java 6, which fails SSL connection with "SSL peer shut down incorrectly", succeed like Java 7?

update the server arguments from -Dhttps.protocols=SSLv3 to -Dhttps.protocols=TLSv1,SSLv3

How to change dataframe column names in pyspark?

Another way to rename just one column (using import pyspark.sql.functions as F):

df = df.select( '*', F.col('count').alias('new_count') ).drop('count')

When do you use Java's @Override annotation and why?

@Override on interface implementation is inconsistent since there is no such thing as "overriding an interface" in java.

@Override on interface implementation is useless since in practise it catches no bugs that the compilation wouldn't catch anyway. There is only one, far fetched scenario where override on implementers actually does something: If you implement an interface, and the interface REMOVES methods, you will be notified on compile time that you should remove the unused implementations. Notice that if the new version of the interface has NEW or CHANGED methods you'll obviously get a compile error anyways as you're not implementing the new stuff.

@Override on interface implementers should never have been permitted in 1.6, and with eclipse sadly choosing to auto-insert the annotations as default behavior, we get a lot of cluttered source files. When reading 1.6 code, you cannot see from the @Override annotation if a method actually overrides a method in the superclass or just implements an interface.

Using @Override when actually overriding a method in a superclass is fine.

How to find whether a ResultSet is empty or not in Java?

Immediately after your execute statement you can have an if statement. For example

ResultSet rs = statement.execute();
if (!rs.next()){
//ResultSet is empty
}

Error: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported

Ok - for me the source of the problem was in serialisation/deserialisation. The object that was being sent and received was as follows where the code is submitted and the code and maskedPhoneNumber is returned.

@ApiObject(description = "What the object is for.")
@JsonIgnoreProperties(ignoreUnknown = true)
public class CodeVerification {

    @ApiObjectField(description = "The code which is to be verified.")
    @NotBlank(message = "mandatory")
    private final String code;

    @ApiObjectField(description = "The masked mobile phone number to which the code was verfied against.")
    private final String maskedMobileNumber;

    public codeVerification(@JsonProperty("code") String code, String maskedMobileNumber) {
        this.code = code;
        this.maskedMobileNumber = maskedMobileNumber;
    }

    public String getcode() {
        return code;
    }

    public String getMaskedMobileNumber() {
        return maskedMobileNumber;
    }
}

The problem was that I didn't have a JsonProperty defined for the maskedMobileNumber in the constructor. i.e. Constructor should have been

public codeVerification(@JsonProperty("code") String code, @JsonProperty("maskedMobileNumber") String maskedMobileNumber) {
    this.code = code;
    this.maskedMobileNumber = maskedMobileNumber;
}

Print "\n" or newline characters as part of the output on terminal

Another suggestion is to do that way:

string = "abcd\n"
print(string.replace("\n","\\n"))

But be aware that the print function actually print to the terminal the "\n", your terminal interpret that as a newline, that's it. So, my solution just change the newline in \ + n

How to enable remote access of mysql in centos?

so do the following edit my.cnf:

[mysqld]
user = mysql
pid-file = /var/run/mysqld/mysqld.pid
socket = /var/run/mysqld/mysqld.sock
port = 3306
basedir = /usr
datadir = /var/lib/mysql
tmpdir = /tmp
language = /usr/share/mysql/English
bind-address = xxx.xxx.xxx.xxx
# skip-networking

after edit hit service mysqld restart

login into mysql and hit this query:

GRANT ALL ON foo.* TO bar@'xxx.xxx.xxx.xxx' IDENTIFIED BY 'PASSWORD';

thats it make sure your iptables allow connection from 3306 if not put the following:

iptables -A INPUT -i lo -p tcp --dport 3306 -j ACCEPT

iptables -A OUTPUT -p tcp --sport 3306 -j ACCEPT

How to update Git clone

git pull origin master

this will sync your master to the central repo and if new branches are pushed to the central repo it will also update your clone copy.

Failed to resolve: com.android.support:appcompat-v7:28.0

implementation 'com.android.support:appcompat-v7:28.0' implementation 'com.android.support:support-media-compat:28.0.0' implementation 'com.android.support:support-v4:28.0.0' All to add