Programs & Examples On #Average

In mathematics, an average is a measure of the "middle" or "typical" value of a data set. Different types of averages include the arithmetic mean, the median, and the mode.

Finding the average of a list

If you wanted to get more than just the mean (aka average) you might check out scipy stats

from scipy import stats
l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
print(stats.describe(l))

# DescribeResult(nobs=9, minmax=(2, 78), mean=20.11111111111111, 
# variance=572.3611111111111, skewness=1.7791785448425341, 
# kurtosis=1.9422716419666397)

Take a list of numbers and return the average

You want to iterate through the list, sum all the numbers, and then divide the sum by the number of elements in the list. You can use a for loop to accomplish this.

average = 0
sum = 0    
for n in numbers:
    sum = sum + n
average = sum / len(numbers)

The for loop looks at each element in the list, and then adds it to the current sum. You then divide by the length of the list (or the number of elements in the list) to find the average.

I would recommend googling a python reference to find out how to use common programming concepts like loops and conditionals so that you feel comfortable when starting out. There are lots of great resources online that you could look up.

Good luck!

SQL query with avg and group by

If I understand what you need, try this:

SELECT id, pass, AVG(val) AS val_1 
FROM data_r1 
GROUP BY id, pass;

Or, if you want just one row for every id, this:

SELECT d1.id,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 1) as val_1,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 2) as val_2,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 3) as val_3,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 4) as val_4,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 5) as val_5,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 6) as val_6,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 7) as val_7
from data_r1 d1
GROUP BY d1.id

Trying to get the average of a count resultset

You just can put your query as a subquery:

SELECT avg(count)
  FROM 
    (
    SELECT COUNT (*) AS Count
      FROM Table T
     WHERE T.Update_time =
               (SELECT MAX (B.Update_time )
                  FROM Table B
                 WHERE (B.Id = T.Id))
    GROUP BY T.Grouping
    ) as counts

Edit: I think this should be the same:

SELECT count(*) / count(distinct T.Grouping)
  FROM Table T
 WHERE T.Update_time =
           (SELECT MAX (B.Update_time)
              FROM Table B
             WHERE (B.Id = T.Id))

Calculate average in java

Instead of:

int count = 0;
for (int i = 0; i<args.length -1; ++i)
    count++;
System.out.println(count);

 }

you can just

int count = args.length;

The average is the sum of your args divided by the number of your args.

int res = 0;
int count = args.lenght;

for (int a : args)
{
res += a;
}
res /= count;

you can make this code shorter too, i'll let you try and ask if you need help!

This is my first answerso tell me if something wrong!

Calculating arithmetic mean (one type of average) in Python

NumPy has a numpy.mean which is an arithmetic mean. Usage is as simple as this:

>>> import numpy
>>> a = [1, 2, 4]
>>> numpy.mean(a)
2.3333333333333335

How to manipulate arrays. Find the average. Beginner Java

If we want to add numbers of an Array and find the average of them follow this easy way! .....

public class Array {

    public static void main(String[] args) {

        int[]array = {1,3,5,7,9,6,3};
        int i=0;
        int sum=0;
        double average=0;
        for( i=0;i<array.length;i++){
            System.out.println(array[i]);
            sum=sum+array[i];
        }
        System.out.println("sum is:"+sum);
        System.out.println("average is: "+(double)sum/vargu.length);



    }

}

Calculating average of an array list?

You can use standard looping constructs or iterator/listiterator for the same :

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
double sum = 0;
Iterator<Integer> iter1 = list.iterator();
while (iter1.hasNext()) {
    sum += iter1.next();
}
double average = sum / list.size();
System.out.println("Average = " + average);

If using Java 8, you could use Stream or IntSream operations for the same :

OptionalDouble avg = list.stream().mapToInt(Integer::intValue).average();
System.out.println("Average = " + avg.getAsDouble());

Reference : Calculating average of arraylist

Finding moving average from data points in Python

ravgs = [sum(data[i:i+5])/5. for i in range(len(data)-4)]

This isn't the most efficient approach but it will give your answer and I'm unclear if your window is 5 points or 10. If its 10, replace each 5 with 10 and the 4 with 9.

How to compute the sum and average of elements in an array?

Here is my rookie way of simply finding the avg. Hope this helps somebody.

function numAvg(num){
    var total = 0;
    for(var i = 0;i < num.length; i++) { 
        total+=num[i];
    }
    return total/num.length;
}

np.mean() vs np.average() in Python NumPy?

In addition to the differences already noted, there's another extremely important difference that I just now discovered the hard way: unlike np.mean, np.average doesn't allow the dtype keyword, which is essential for getting correct results in some cases. I have a very large single-precision array that is accessed from an h5 file. If I take the mean along axes 0 and 1, I get wildly incorrect results unless I specify dtype='float64':

>T.shape
(4096, 4096, 720)
>T.dtype
dtype('<f4')

m1 = np.average(T, axis=(0,1))                #  garbage
m2 = np.mean(T, axis=(0,1))                   #  the same garbage
m3 = np.mean(T, axis=(0,1), dtype='float64')  # correct results

Unfortunately, unless you know what to look for, you can't necessarily tell your results are wrong. I will never use np.average again for this reason but will always use np.mean(.., dtype='float64') on any large array. If I want a weighted average, I'll compute it explicitly using the product of the weight vector and the target array and then either np.sum or np.mean, as appropriate (with appropriate precision as well).

How to change working directory in Jupyter Notebook?

  1. list all magic command %lsmagic
  2. show current directory %pwd

Why can't static methods be abstract in Java?

Regular methods can be abstract when they are meant to be overridden by subclasses and provided with functionality. Imagine the class Foo is extended by Bar1, Bar2, Bar3 etc. So, each will have their own version of the abstract class according to their needs.

Now, static methods by definition belong to the class, they have nothing to do with the objects of the class or the objects of its subclasses. They don't even need them to exist, they can be used without instantiating the classes. Hence, they need to be ready-to-go and cannot depend on the subclasses to add functionality to them.

Using the RUN instruction in a Dockerfile with 'source' does not work

If you have SHELL available you should go with this answer -- don't use the accepted one, which forces you to put the rest of the dockerfile in one command per this comment.

If you are using an old Docker version and don't have access to SHELL, this will work so long as you don't need anything from .bashrc (which is a rare case in Dockerfiles):

ENTRYPOINT ["bash", "--rcfile", "/usr/local/bin/virtualenvwrapper.sh", "-ci"]

Note the -i is needed to make bash read the rcfile at all.

this.getClass().getClassLoader().getResource("...") and NullPointerException

When you use

this.getClass().getResource("myFile.ext")

getResource will try to find the resource relative to the package. If you use:

this.getClass().getResource("/myFile.ext")

getResource will treat it as an absolute path and simply call the classloader like you would have if you'd done.

this.getClass().getClassLoader().getResource("myFile.ext")

The reason you can't use a leading / in the ClassLoader path is because all ClassLoader paths are absolute and so / is not a valid first character in the path.

How do I remove the height style from a DIV using jQuery?

$('div#someDiv').height('auto');

I like using this, because it's symmetric with how you explicitly used .height(val) to set it in the first place, and works across browsers.

Determine a string's encoding in C#

Check out Utf8Checker it is simple class that does exactly this in pure managed code. http://utf8checker.codeplex.com

Notice: as already pointed out "determine encoding" makes sense only for byte streams. If you have a string it is already encoded from someone along the way who already knew or guessed the encoding to get the string in the first place.

CSS selector for text input fields?

I usually use selectors in my main stylesheet, then make an ie6 specific .js (jquery) file that adds a class to all of the input types. Example:

$(document).ready(function(){
  $("input[type='text']").addClass('text');
)};

And then just duplicate my styles in the ie6 specific stylesheet using the classes. That way the actual markup is a little bit cleaner.

Using "like" wildcard in prepared statement

String fname = "Sam\u0025";

PreparedStatement ps= conn.prepareStatement("SELECT * FROM Users WHERE User_FirstName LIKE ? ");

ps.setString(1, fname);

How to open every file in a folder

You can actually just use os module to do both:

  1. list all files in a folder
  2. sort files by file type, file name etc.

Here's a simple example:

import os #os module imported here
location = os.getcwd() # get present working directory location here
counter = 0 #keep a count of all files found
csvfiles = [] #list to store all csv files found at location
filebeginwithhello = [] # list to keep all files that begin with 'hello'
otherfiles = [] #list to keep any other file that do not match the criteria

for file in os.listdir(location):
    try:
        if file.endswith(".csv"):
            print "csv file found:\t", file
            csvfiles.append(str(file))
            counter = counter+1

        elif file.startswith("hello") and file.endswith(".csv"): #because some files may start with hello and also be a csv file
            print "csv file found:\t", file
            csvfiles.append(str(file))
            counter = counter+1

        elif file.startswith("hello"):
            print "hello files found: \t", file
            filebeginwithhello.append(file)
            counter = counter+1

        else:
            otherfiles.append(file)
            counter = counter+1
    except Exception as e:
        raise e
        print "No files found here!"

print "Total files found:\t", counter

Now you have not only listed all the files in a folder but also have them (optionally) sorted by starting name, file type and others. Just now iterate over each list and do your stuff.

SQL Sum Multiple rows into one

You should group by the field you want the SUM apply to, and not include in SELECT any field other than multiple rows values, like COUNT, SUM, AVE, etc, because if you include Bill field like in this case, only the first value in the set of rows will be displayed, being almost meaningless and confusing.

This will return the sum of bills per account number:

SELECT SUM(Bill) FROM Table1 GROUP BY AccountNumber

You could add more clauses like WHERE, ORDER BY etc as needed.

Android, Java: HTTP POST Request

You can reuse the implementation I added to ACRA: http://code.google.com/p/acra/source/browse/tags/REL-3_1_0/CrashReport/src/org/acra/HttpUtils.java?r=236

(See the doPost(Map, Url) method, working over http and https even with self signed certs)

Why is "using namespace std;" considered bad practice?

It's case by case. We want to minimize the "total cost of ownership" of the software over its lifespan. Stating "using namespace std" has some costs, but not using it also has a cost in legibility.

People correctly point out that when using it, when the standard library introduces new symbols and definitions, your code ceases to compile, and you may be forced to rename variables. And yet this is probably good long-term, since future maintainers will be momentarily confused or distracted if you're using a keyword for some surprising purpose.

You don't want to have a template called vector, say, which isn't the vector known by everyone else. And the number of new definitions thus introduced in the C++ library is small enough it may simply not come up. There is a cost to having to do this kind of change, but the cost is not high and is offset by the clarity gained by not using std symbol names for other purposes.

Given the number of classes, variables, and functions, stating std:: on every one might fluff up your code by 50% and make it harder to get your head around. An algorithm or step in a method that could be taken in on one screenful of code now requires scrolling back and forth to follow. This is a real cost. Arguably it may not be a high cost, but people who deny it even exists are inexperienced, dogmatic, or simply wrong.

I'd offer the following rules:

  1. std is different from all other libraries. It is the one library everyone basically needs to know, and in my view is best thought of as part of the language. Generally speaking there is an excellent case for using namespace std even if there isn't for other libraries.

  2. Never force the decision onto the author of a compilation unit (a .cpp file) by putting this using in a header. Always defer the decision to the compilation unit author. Even in a project that has decided to use using namespace std everywhere may fine a few modules that are best handled as exceptions to that rule.

  3. Even though the namespace feature lets you have many modules with symbols defined the same, it's going to be confusing to do so. Keep the names different to the extent possible. Even if not using the namespace feature, if you have a class named foo and std introduces a class named foo, it's probably better long-run to rename your class anyway.

  4. An alternative to using namespaces is to manually namespace symbols by prefixing them. I have two libraries I've used for decades, both starting as C libraries, actually, where every symbol is prefixed with "AK" or "SCWin". Generally speaking, this is like avoiding the "using" construct, but you don't write the twin colons. AK::foo() is instead AKFoo(). It makes code 5-10% denser and less verbose, and the only downside is that you'll be in big trouble if you have to use two such libraries that have the same prefixing. Note the X Window libraries are excellent in this regard, except they forgot to do so with a few #defines: TRUE and FALSE should have been XTRUE and XFALSE, and this set up a namespace clash with Sybase or Oracle that likewise used TRUE and FALSE with different values! (ASCII 0 and 1 in the case of the database!) One special advantage of this is that it applies seemlessly to preprocessor definitions, whereas the C++ using/namespace system doesn't handle them. A nice benefit of this is that it gives an organic slope from being part of a project to eventually being a library. In a large application of mine, all window classes are prefixed Win, all signal-processing modules Mod, and so on. There's little chance of any of these being reused so there's no practical benefit to making each group into a library, but it makes obvious in a few seconds how the project breaks into sub-projects.

Difference between filter and filter_by in SQLAlchemy

It is a syntax sugar for faster query writing. Its implementation in pseudocode:

def filter_by(self, **kwargs):
    return self.filter(sql.and_(**kwargs))

For AND you can simply write:

session.query(db.users).filter_by(name='Joe', surname='Dodson')

btw

session.query(db.users).filter(or_(db.users.name=='Ryan', db.users.country=='England'))

can be written as

session.query(db.users).filter((db.users.name=='Ryan') | (db.users.country=='England'))

Also you can get object directly by PK via get method:

Users.query.get(123)
# And even by a composite PK
Users.query.get(123, 321)

When using get case its important that object can be returned without database request from identity map which can be used as cache(associated with transaction)

How to convert Moment.js date to users local timezone?

var dateFormat = 'YYYY-DD-MM HH:mm:ss';
var testDateUtc = moment.utc('2015-01-30 10:00:00');
var localDate = testDateUtc.local();
console.log(localDate.format(dateFormat)); // 2015-30-01 02:00:00
  1. Define your date format.
  2. Create a moment object and set the UTC flag to true on the object.
  3. Create a localized moment object converted from the original moment object.
  4. Return a formatted string from the localized moment object.

See: http://momentjs.com/docs/#/manipulating/local/

How to set a background image in Xcode using swift?

Swift 5.3 in XCode 12.2 Playgrounds

Place the cursor wherever in the code the #insertLiteral would have been in earlier versions. Select from the top-menu Editor->Insert Image Literal... and navigate to the file. Click Open.

The file is added to a playground Resource folder and will then appear when the playground is run in whichever view it was positioned when selected.

If a file is already in the playground Bundle, e.g. in /Resources, it can be dragged directly to the required position in the code (where it will be represented by an icon).

cf. Apple help docs give details of this and how to place other colour and file literals.

How can I reference a dll in the GAC from Visual Studio?

The relevant files and references can be found here:

http://msdn.microsoft.com/en-us/library/cc283981.aspx

Note the links off it about implementation/etc.

Check whether $_POST-value is empty

$username = filter_input(INPUT_POST, 'userName', FILTER_SANITIZE_STRING);
if ($username == '') {$username = 'Anonymous';}

Best practice - always filter inputs, sanitize string is ok, but you're better off using a custom callback function to really filter out what's not acceptable. Then check the now-safe variable if it is null/empty and if it is, set to Anonymous. Does not require 'else' statement as it was set if it existed on the first line.

Why do I have ORA-00904 even when the column is present?

Have you compared the table definitions in Prod and Dev?

And when you are running it in SQL Developer, are you running the query in Prod (same database as the application) and with the same user?

If there are some additional columns that you are adding (using an alter command) and these changes are not yet promoted to prod, this issue is possible.

Can you post the definition of the table and your actual Query?

EOFError: end of file reached issue with Net::HTTP

I had the same problem, ruby-1.8.7-p357, and tried loads of things in vain...

I finally realised that it happens only on multiple calls using the same XMLRPC::Client instance!

So now I'm re-instantiating my client at each call and it just works:|

Deleting array elements in JavaScript - delete vs splice

delete Vs splice

when you delete an item from an array

_x000D_
_x000D_
var arr = [1,2,3,4]; delete arr[2]; //result [1, 2, 3:, 4]_x000D_
console.log(arr)
_x000D_
_x000D_
_x000D_

when you splice

_x000D_
_x000D_
var arr = [1,2,3,4]; arr.splice(1,1); //result [1, 3, 4]_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_

in case of delete the element is deleted but the index remains empty

while in case of splice element is deleted and the index of rest elements is reduced accordingly

C pointers and arrays: [Warning] assignment makes pointer from integer without a cast

int[] and int* are represented the same way, except int[] allocates (IIRC).

ap is a pointer, therefore giving it the value of an integer is dangerous, as you have no idea what's at address 45.

when you try to access it (x = *ap), you try to access address 45, which causes the crash, as it probably is not a part of the memory you can access.

How do I change the font size of a UILabel in Swift?

label.font = UIFont.systemFontOfSize(20)

Controlling Maven final name of jar artifact

This works for me

mvn jar:jar -Djar.finalName=custom-jar-name

How can I define a composite primary key in SQL?

CREATE TABLE `voting` (
  `QuestionID` int(10) unsigned NOT NULL,
  `MemberId` int(10) unsigned NOT NULL,
  `vote` int(10) unsigned NOT NULL,
  PRIMARY KEY  (`QuestionID`,`MemberId`)
);

How to import local packages without gopath

Go dependency management summary:

  • vgo if your go version is: x >= go 1.11
  • dep or vendor if your go version is: go 1.6 >= x < go 1.11
  • Manually if your go version is: x < go 1.6

Edit 3: Go 1.11 has a feature vgo which will replace dep.

To use vgo, see Modules documentation. TLDR below:

export GO111MODULE=on
go mod init
go mod vendor # if you have vendor/ folder, will automatically integrate
go build

This method creates a file called go.mod in your projects directory. You can then build your project with go build. If GO111MODULE=auto is set, then your project cannot be in $GOPATH.


Edit 2: The vendoring method is still valid and works without issue. vendor is largely a manual process, because of this dep and vgo were created.


Edit 1: While my old way works it's not longer the "correct" way to do it. You should be using vendor capabilities, vgo, or dep (for now) that are enabled by default in Go 1.6; see. You basically add your "external" or "dependent" packages within a vendor directory; upon compilation the compiler will use these packages first.


Found. I was able import local package with GOPATH by creating a subfolder of package1 and then importing with import "./package1" in binary1.go and binary2.go scripts like this :

binary1.go

...
import (
        "./package1"
      )
...

So my current directory structure looks like this:

myproject/
+-- binary1.go
+-- binary2.go
+-- package1/
¦   +-- package1.go
+-- package2.go

I should also note that relative paths (at least in go 1.5) also work; for example:

import "../packageX"

What is a daemon thread in Java?

Here is an example to test behavior of daemon threads in case of jvm exit due to non existence of user threads.

Please note second last line in the output below, when main thread exited, daemon thread also died and did not print finally executed9 statement within finally block. This means that any i/o resources closed within finally block of a daemon thread will not be closed if JVM exits due to non existence of user threads.

public class DeamonTreadExample {

public static void main(String[] args) throws InterruptedException {

    Thread t = new Thread(() -> {
        int count = 0;
        while (true) {
            count++;
            try {
                System.out.println("inside try"+ count);
                Thread.currentThread().sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                System.out.println("finally executed"+ count);
            }
        }
    });
    t.setDaemon(true);
    t.start();

    Thread.currentThread().sleep(10000);
    System.out.println("main thread exited");
  }
}

Output

inside try1
finally executed1
inside try2
finally executed2
inside try3
finally executed3
inside try4
finally executed4
inside try5
finally executed5
inside try6
finally executed6
inside try7
finally executed7
inside try8
finally executed8
inside try9
finally executed9
inside try10
main thread exited

How to simulate a touch event in Android?

MotionEvent is generated only by touching the screen.

Rotation of 3D vector?

Using pyquaternion is extremely simple; to install it (while still in python), run in your console:

import pip;
pip.main(['install','pyquaternion'])

Once installed:

  from pyquaternion import Quaternion
  v = [3,5,0]
  axis = [4,4,1]
  theta = 1.2 #radian
  rotated_v = Quaternion(axis=axis,angle=theta).rotate(v)

How are echo and print different in PHP?

From: http://web.archive.org/web/20090221144611/http://faqts.com/knowledge_base/view.phtml/aid/1/fid/40

  1. Speed. There is a difference between the two, but speed-wise it should be irrelevant which one you use. echo is marginally faster since it doesn't set a return value if you really want to get down to the nitty gritty.

  2. Expression. print() behaves like a function in that you can do: $ret = print "Hello World"; And $ret will be 1. That means that print can be used as part of a more complex expression where echo cannot. An example from the PHP Manual:

$b ? print "true" : print "false";

print is also part of the precedence table which it needs to be if it is to be used within a complex expression. It is just about at the bottom of the precedence list though. Only , AND OR XOR are lower.

  1. Parameter(s). The grammar is: echo expression [, expression[, expression] ... ] But echo ( expression, expression ) is not valid. This would be valid: echo ("howdy"),("partner"); the same as: echo "howdy","partner"; (Putting the brackets in that simple example serves no purpose since there is no operator precedence issue with a single term like that.)

So, echo without parentheses can take multiple parameters, which get concatenated:

   echo  "and a ", 1, 2, 3;   // comma-separated without parentheses
   echo ("and a 123");        // just one parameter with parentheses

print() can only take one parameter:

   print ("and a 123");
   print  "and a 123";

How do I get currency exchange rates via an API such as Google Finance?

I got this content from http://www.scriptarticle.com/2012/05/03/get-live-currency-rates-and-currency-conversion-using-php-and-apis/

<?php

function get_currency($from_Currency, $to_Currency, $amount) {
    $amount = urlencode($amount);
    $from_Currency = urlencode($from_Currency);
    $to_Currency = urlencode($to_Currency);

    $url = "http://www.google.com/finance/converter?a=$amount&from=$from_Currency&to=$to_Currency";

    $ch = curl_init();
    $timeout = 0;
    curl_setopt ($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);

    curl_setopt ($ch, CURLOPT_USERAGENT,
                 "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $rawdata = curl_exec($ch);
    curl_close($ch);
    $data = explode('bld>', $rawdata);
    $data = explode($to_Currency, $data[1]);

    return round($data[0], 2);
}

// Call the function to get the currency converted
echo get_currency('USD', 'INR', 1);

?>

How can I Remove .DS_Store files from a Git repository?

create a .gitignore file using command touch .gitignore

and add the following lines in it

.DS_Store

save the .gitignore file and then push it in to your git repo.

Set HTTP header for one request

There's a headers parameter in the config object you pass to $http for per-call headers:

$http({method: 'GET', url: 'www.google.com/someapi', headers: {
    'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});

Or with the shortcut method:

$http.get('www.google.com/someapi', {
    headers: {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});

The list of the valid parameters is available in the $http service documentation.

How can I add 1 day to current date?

Inspired by jpmottin in this question, here's the one line code:

_x000D_
_x000D_
var dateStr = '2019-01-01';_x000D_
var days = 1;_x000D_
_x000D_
var result = new Date(new Date(dateStr).setDate(new Date(dateStr).getDate() + days));_x000D_
_x000D_
document.write('Date: ', result); // Wed Jan 02 2019 09:00:00 GMT+0900 (Japan Standard Time)_x000D_
document.write('<br />');_x000D_
document.write('Trimmed Date: ', result.toISOString().substr(0, 10)); // 2019-01-02
_x000D_
_x000D_
_x000D_

Hope this helps

How do I convert datetime to ISO 8601 in PHP

If you try set a value in datetime-local

date("Y-m-d\TH:i",strtotime('2010-12-30 23:21:46'));

//output : 2010-12-30T23:21

Adding a regression line on a ggplot

If you want to fit other type of models, like a dose-response curve using logistic models you would also need to create more data points with the function predict if you want to have a smoother regression line:

fit: your fit of a logistic regression curve

#Create a range of doses:
mm <- data.frame(DOSE = seq(0, max(data$DOSE), length.out = 100))
#Create a new data frame for ggplot using predict and your range of new 
#doses:
fit.ggplot=data.frame(y=predict(fit, newdata=mm),x=mm$DOSE)

ggplot(data=data,aes(x=log10(DOSE),y=log(viability)))+geom_point()+
geom_line(data=fit.ggplot,aes(x=log10(x),y=log(y)))

Camera access through browser

I think this one is working. Recording a video or audio;

<input type="file" accept="video/*;capture=camcorder">
<input type="file" accept="audio/*;capture=microphone">

or (new method)

<device type="media" onchange="update(this.data)"></device>
<video autoplay></video>
<script>
  function update(stream) {
    document.querySelector('video').src = stream.url;
  }
</script>

If it is not, probably will work on ios6, more detail can be found at get user media

How to clear the logs properly for a Docker container?

On my Ubuntu servers even as sudo I would get Cannot open ‘/var/lib/docker/containers/*/*-json.log’ for writing: No such file or directory

But combing the docker inspect and truncate answers worked :

sudo truncate -s 0 `docker inspect --format='{{.LogPath}}' <container>`

WCF error: The caller was not authenticated by the service

Why can't you just remove the security setting altogether for wsHttpBinding ("none" instead of "message" or "transport")?

How can I create C header files

  1. Open your favorite text editor
  2. Create a new file named whatever.h
  3. Put your function prototypes in it

DONE.

Example whatever.h

#ifndef WHATEVER_H_INCLUDED
#define WHATEVER_H_INCLUDED
int f(int a);
#endif

Note: include guards (preprocessor commands) added thanks to luke. They avoid including the same header file twice in the same compilation. Another possibility (also mentioned on the comments) is to add #pragma once but it is not guaranteed to be supported on every compiler.

Example whatever.c

#include "whatever.h"

int f(int a) { return a + 1; }

And then you can include "whatever.h" into any other .c file, and link it with whatever.c's object file.

Like this:

sample.c

#include "whatever.h"

int main(int argc, char **argv)
{
    printf("%d\n", f(2)); /* prints 3 */
    return 0;
}

To compile it (if you use GCC):

$ gcc -c whatever.c -o whatever.o
$ gcc -c sample.c -o sample.o

To link the files to create an executable file:

$ gcc sample.o whatever.o -o sample

You can test sample:

$ ./sample
3
$

Floating point comparison functions for C#

I translated the sample from Michael Borgwardt. This is the result:

public static bool NearlyEqual(float a, float b, float epsilon){
    float absA = Math.Abs (a);
    float absB = Math.Abs (b);
    float diff = Math.Abs (a - b);

    if (a == b) {
        return true;
    } else if (a == 0 || b == 0 || diff < float.Epsilon) {
        // a or b is zero or both are extremely close to it
        // relative error is less meaningful here
        return diff < epsilon;
    } else { // use relative error
        return diff / (absA + absB) < epsilon;
    }
}

Feel free to improve this answer.

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

Another way of doing this, in code only, is to detect if the process is running as admin like in the answer by @NG.. And then open the application again and close the current one.

I use this code when an application only needs admin privileges when run under certain conditions, such as when installing itself as a service. So it doesn't need to run as admin all the time like the other answers force it too.

Note in the below code NeedsToRunAsAdmin is a method that detects if under current conditions admin privileges are required. If this returns false the code will not elevate itself. This is a major advantage of this approach over the others.

Although this code has the advantages stated above, it does need to re-launch itself as a new process which isn't always what you want.

private static void Main(string[] args)
{
    if (NeedsToRunAsAdmin() && !IsRunAsAdmin())
    {
        ProcessStartInfo proc = new ProcessStartInfo();
        proc.UseShellExecute = true;
        proc.WorkingDirectory = Environment.CurrentDirectory;
        proc.FileName = Assembly.GetEntryAssembly().CodeBase;

        foreach (string arg in args)
        {
            proc.Arguments += String.Format("\"{0}\" ", arg);
        }

        proc.Verb = "runas";

        try
        {
            Process.Start(proc);
        }
        catch
        {
            Console.WriteLine("This application requires elevated credentials in order to operate correctly!");
        }
    }
    else
    {
        //Normal program logic...
    }
}

private static bool IsRunAsAdmin()
{
    WindowsIdentity id = WindowsIdentity.GetCurrent();
    WindowsPrincipal principal = new WindowsPrincipal(id);

    return principal.IsInRole(WindowsBuiltInRole.Administrator);
}

PostgreSQL: FOREIGN KEY/ON DELETE CASCADE

Excerpt from PostgreSQL documentation:

Restricting and cascading deletes are the two most common options. [...] CASCADE specifies that when a referenced row is deleted, row(s) referencing it should be automatically deleted as well.

This means that if you delete a category – referenced by books – the referencing book will also be deleted by ON DELETE CASCADE.

Example:

CREATE SCHEMA shire;

CREATE TABLE shire.clans (
    id serial PRIMARY KEY,
    clan varchar
);

CREATE TABLE shire.hobbits (
    id serial PRIMARY KEY,
    hobbit varchar,
    clan_id integer REFERENCES shire.clans (id) ON DELETE CASCADE
);

DELETE FROM clans will CASCADE to hobbits by REFERENCES.

sauron@mordor> psql
sauron=# SELECT * FROM shire.clans;
 id |    clan    
----+------------
  1 | Baggins
  2 | Gamgi
(2 rows)

sauron=# SELECT * FROM shire.hobbits;
 id |  hobbit  | clan_id 
----+----------+---------
  1 | Bilbo    |       1
  2 | Frodo    |       1
  3 | Samwise  |       2
(3 rows)

sauron=# DELETE FROM shire.clans WHERE id = 1 RETURNING *;
 id |  clan   
----+---------
  1 | Baggins
(1 row)

DELETE 1
sauron=# SELECT * FROM shire.hobbits;
 id |  hobbit  | clan_id 
----+----------+---------
  3 | Samwise  |       2
(1 row)

If you really need the opposite (checked by the database), you will have to write a trigger!

Send POST data using XMLHttpRequest

Minimal use of FormData to submit an AJAX request

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge, chrome=1"/>
<script>
"use strict";
function submitForm(oFormElement)
{
  var xhr = new XMLHttpRequest();
  xhr.onload = function(){ alert (xhr.responseText); } // success case
  xhr.onerror = function(){ alert (xhr.responseText); } // failure case
  xhr.open (oFormElement.method, oFormElement.action, true);
  xhr.send (new FormData (oFormElement));
  return false;
}
</script>
</head>

<body>
<form method="post" action="somewhere" onsubmit="return submitForm(this);">
  <input type="hidden" value="person"   name="user" />
  <input type="hidden" value="password" name="pwd" />
  <input type="hidden" value="place"    name="organization" />
  <input type="hidden" value="key"      name="requiredkey" />
  <input type="submit" value="post request"/>
</form>
</body>
</html>

Remarks

  1. This does not fully answer the OP question because it requires the user to click in order to submit the request. But this may be useful to people searching for this kind of simple solution.

  2. This example is very simple and does not support the GET method. If you are interesting by more sophisticated examples, please have a look at the excellent MDN documentation. See also similar answer about XMLHttpRequest to Post HTML Form.

  3. Limitation of this solution: As pointed out by Justin Blank and Thomas Munk (see their comments), FormData is not supported by IE9 and lower, and default browser on Android 2.3.

Node.js - How to send data from html to express

I'd like to expand on Obertklep's answer. In his example it is an NPM module called body-parser which is doing most of the work. Where he puts req.body.name, I believe he/she is using body-parser to get the contents of the name attribute(s) received when the form is submitted.

If you do not want to use Express, use querystring which is a built-in Node module. See the answers in the link below for an example of how to use querystring.

It might help to look at this answer, which is very similar to your quest.

Add a new column to existing table in a migration

this things is worked on laravel 5.1.

first, on your terminal execute this code

php artisan make:migration add_paid_to_users --table=users

after that go to your project directory and expand directory database - migration and edit file add_paid_to_users.php, add this code

public function up()
{
    Schema::table('users', function (Blueprint $table) {
         $table->string('paid'); //just add this line
    });
}

after that go back to your terminal and execute this command

php artisan migrate

hope this help.

How do I make a Mac Terminal pop-up/alert? Applescript?

If you're using any Mac OS X version which has Notification Center, you can use the terminal-notifier gem. First install it (you may need sudo):

gem install terminal-notifier

and then simply:

terminal-notifier -message "Hello, this is my message" -title "Message Title"

See also this OS X Daily post.

Updating state on props change in React Form

// store the startTime prop in local state
const [startTime, setStartTime] = useState(props.startTime)
// 
useEffect(() => {
  if (props.startTime !== startTime) {
    setStartTime(props.startTime);
  }
}, [props.startTime]);

Can this method be migrated to class components?

how to select rows based on distinct values of A COLUMN only

Try this - you need a CTE (Common Table Expression) that partitions (groups) your data by distinct e-mail address, and sorts each group by ID - smallest first. Then you just select the first entry for each group - that should give you what you're looking for:

;WITH DistinctMails AS
(
    SELECT ID, MailID, EMailAddress, NAME,
        ROW_NUMBER() OVER(PARTITION BY EMailAddress ORDER BY ID) AS 'RowNum'
    FROM dbo.YourMailTable
)
SELECT *
FROM DistinctMails
WHERE RowNum = 1

This works on SQL Server 2005 and newer (you didn't mention what version you're using...)

Apply function to all elements of collection through LINQ

I found some way to perform in on dictionary contain my custom class methods

foreach (var item in this.Values.Where(p => p.IsActive == false))
            item.Refresh();

Where 'this' derived from : Dictionary<string, MyCustomClass>

class MyCustomClass 
{
   public void Refresh(){}
}

How to strip comma in Python string

You want to replace it, not strip it:

s = s.replace(',', '')

Execute command without keeping it in history

There are several ways you can achieve this. This sets the size of the history file to 0:

export HISTFILESIZE=0

This sets the history file to /dev/null, effectively disabling it:

export HISTFILE=/dev/null

For individual commands, you can prefix the command with a space and it won't be saved in the history file. Note that this requires you have the ignorespace value included in the $HISTCONTROL environment variable (man bash and search for ignorespace for more details).

How to list installed packages from a given repo using yum

Try

yum list installed | grep reponame

On one of my servers:

yum list installed | grep remi
ImageMagick2.x86_64                       6.6.5.10-1.el5.remi          installed
memcache.x86_64                          1.4.5-2.el5.remi             installed
mysql.x86_64                              5.1.54-1.el5.remi            installed
mysql-devel.x86_64                        5.1.54-1.el5.remi            installed
mysql-libs.x86_64                         5.1.54-1.el5.remi            installed
mysql-server.x86_64                       5.1.54-1.el5.remi            installed
mysqlclient15.x86_64                      5.0.67-1.el5.remi            installed
php.x86_64                                5.3.5-1.el5.remi             installed
php-cli.x86_64                            5.3.5-1.el5.remi             installed
php-common.x86_64                         5.3.5-1.el5.remi             installed
php-domxml-php4-php5.noarch               1.21.2-1.el5.remi            installed
php-fpm.x86_64                            5.3.5-1.el5.remi             installed
php-gd.x86_64                             5.3.5-1.el5.remi             installed
php-mbstring.x86_64                       5.3.5-1.el5.remi             installed
php-mcrypt.x86_64                         5.3.5-1.el5.remi             installed
php-mysql.x86_64                          5.3.5-1.el5.remi             installed
php-pdo.x86_64                            5.3.5-1.el5.remi             installed
php-pear.noarch                           1:1.9.1-6.el5.remi           installed
php-pecl-apc.x86_64                       3.1.6-1.el5.remi             installed
php-pecl-imagick.x86_64                   3.0.1-1.el5.remi.1           installed
php-pecl-memcache.x86_64                  3.0.5-1.el5.remi             installed
php-pecl-xdebug.x86_64                    2.1.0-1.el5.remi             installed
php-soap.x86_64                           5.3.5-1.el5.remi             installed
php-xml.x86_64                            5.3.5-1.el5.remi             installed
remi-release.noarch                       5-8.el5.remi                 installed

It works.

if variable contains

The fastest way to check if a string contains another string is using indexOf:

if (code.indexOf('ST1') !== -1) {
    // string code has "ST1" in it
} else {
    // string code does not have "ST1" in it
}

Read file content from S3 bucket with boto3

You might also consider the smart_open module, which supports iterators:

from smart_open import smart_open

# stream lines from an S3 object
for line in smart_open('s3://mybucket/mykey.txt', 'rb'):
    print(line.decode('utf8'))

and context managers:

with smart_open('s3://mybucket/mykey.txt', 'rb') as s3_source:
    for line in s3_source:
         print(line.decode('utf8'))

    s3_source.seek(0)  # seek to the beginning
    b1000 = s3_source.read(1000)  # read 1000 bytes

Find smart_open at https://pypi.org/project/smart_open/

Java file path in Linux

Looks like you are missing a leading slash. Perhaps try:

Scanner s = new Scanner(new File("/home/me/java/ex.txt"));

(as to where it looks for files by default, it is where the JVM is run from for relative paths like the one you have in your question)

Xcode 4: create IPA file instead of .xcarchive

I had the same problem... Had to recreate the project from scratch.

Note: my project was created in XCode 3.1 and was linking against a static library that was being built as a subproject (to a common destination). I changed this to build the source instead when I recreated the XCode project in XCode 4.

Now doing a Product/Archive/Share... gets the option of "iOS App Store Package (.ipa)" directly above "Application" (which is now greyed out) and "Archive" (which exports the .xcarchive).

Locate current file in IntelliJ

Alt + F1 (or Alt + Shift + 1 for linux) almost does what you want. You need to hit Enter afterwards as IDEA allows multiple "targets" for navigation (project structure, file structure etc).

(Note you can also set AutoScroll to Source and AutoScroll from source using the two "boxes with arrows" buttons above the project structure view but this can get annoying when it shoves you into the JDK source because you followed a reference to java.io.File.

The keymap defines it as Select current file or symbol in any view.

Jquery: Find Text and replace

$("#id1 p:contains('dog')").html("doll");

that'll do it.

http://jsfiddle.net/pgDFQ/

Two way sync with rsync

Rclone is what you are looking for. Rclone ("rsync for cloud storage") is a command line program to sync files and directories to and from different cloud storage providers including local filesystems. Rclone was previously known as Swiftsync and has been available since 2013.

Apache won't start in wamp

I had the same problem. My port 80 was not in use.

After thorough research, all I did was to download Update for Universal C Runtime.

Once installed and my PC restarted, all was OK.

git rebase fatal: Needed a single revision

I ran into this and realized I didn't fetch the upstream before trying to rebase. All I needed was to git fetch upstream

Edittext change border color with shape.xml

selector is used for applying multiple alternate drawables for different status of the view, so in this case, there is no need for selector

instead use shape

<?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#ffffff" />
    <stroke android:width="1dip" android:color="#ff9900" />
</shape>

FontAwesome icons not showing. Why?

I solved this problem by putting the Fonts directory at the same level as my CSS files.

What can <f:metadata>, <f:viewParam> and <f:viewAction> be used for?

Process GET parameters

The <f:viewParam> manages the setting, conversion and validation of GET parameters. It's like the <h:inputText>, but then for GET parameters.

The following example

<f:metadata>
    <f:viewParam name="id" value="#{bean.id}" />
</f:metadata>

does basically the following:

  • Get the request parameter value by name id.
  • Convert and validate it if necessary (you can use required, validator and converter attributes and nest a <f:converter> and <f:validator> in it like as with <h:inputText>)
  • If conversion and validation succeeds, then set it as a bean property represented by #{bean.id} value, or if the value attribute is absent, then set it as request attribtue on name id so that it's available by #{id} in the view.

So when you open the page as foo.xhtml?id=10 then the parameter value 10 get set in the bean this way, right before the view is rendered.

As to validation, the following example sets the param to required="true" and allows only values between 10 and 20. Any validation failure will result in a message being displayed.

<f:metadata>
    <f:viewParam id="id" name="id" value="#{bean.id}" required="true">
        <f:validateLongRange minimum="10" maximum="20" />
    </f:viewParam>
</f:metadata>
<h:message for="id" />

Performing business action on GET parameters

You can use the <f:viewAction> for this.

<f:metadata>
    <f:viewParam id="id" name="id" value="#{bean.id}" required="true">
        <f:validateLongRange minimum="10" maximum="20" />
    </f:viewParam>
    <f:viewAction action="#{bean.onload}" />
</f:metadata>
<h:message for="id" />

with

public void onload() {
    // ...
}

The <f:viewAction> is however new since JSF 2.2 (the <f:viewParam> already exists since JSF 2.0). If you can't upgrade, then your best bet is using <f:event> instead.

<f:event type="preRenderView" listener="#{bean.onload}" />

This is however invoked on every request. You need to explicitly check if the request isn't a postback:

public void onload() {
    if (!FacesContext.getCurrentInstance().isPostback()) {
        // ...
    }
}

When you would like to skip "Conversion/Validation failed" cases as well, then do as follows:

public void onload() {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    if (!facesContext.isPostback() && !facesContext.isValidationFailed()) {
        // ...
    }
}

Using <f:event> this way is in essence a workaround/hack, that's exactly why the <f:viewAction> was introduced in JSF 2.2.


Pass view parameters to next view

You can "pass-through" the view parameters in navigation links by setting includeViewParams attribute to true or by adding includeViewParams=true request parameter.

<h:link outcome="next" includeViewParams="true">
<!-- Or -->
<h:link outcome="next?includeViewParams=true">

which generates with the above <f:metadata> example basically the following link

<a href="next.xhtml?id=10">

with the original parameter value.

This approach only requires that next.xhtml has also a <f:viewParam> on the very same parameter, otherwise it won't be passed through.


Use GET forms in JSF

The <f:viewParam> can also be used in combination with "plain HTML" GET forms.

<f:metadata>
    <f:viewParam id="query" name="query" value="#{bean.query}" />
    <f:viewAction action="#{bean.search}" />
</f:metadata>
...
<form>
    <label for="query">Query</label>
    <input type="text" name="query" value="#{empty bean.query ? param.query : bean.query}" />
    <input type="submit" value="Search" />
    <h:message for="query" />
</form>
...
<h:dataTable value="#{bean.results}" var="result" rendered="#{not empty bean.results}">
     ...
</h:dataTable>

With basically this @RequestScoped bean:

private String query;
private List<Result> results;

public void search() {
    results = service.search(query);
}

Note that the <h:message> is for the <f:viewParam>, not the plain HTML <input type="text">! Also note that the input value displays #{param.query} when #{bean.query} is empty, because the submitted value would otherwise not show up at all when there's a validation or conversion error. Please note that this construct is invalid for JSF input components (it is doing that "under the covers" already).


See also:

jquery change button color onclick

You have to include the jquery framework in your document head from a cdn for example:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>

Then you have to include a own script for example:

(function( $ ) {

  $(document).ready(function(){
      $('input').click(function() {
          $(this).css('background-color', 'green');
      }
  });


  $(window).load(function() { 
  });

})( jQuery );

This part is a mapping of the $ to jQuery, so actually it is jQuery('selector').function();

(function( $ ) {

})( jQuery );

Here you can find die api of jquery where all functions are listed with examples and explanation: http://api.jquery.com/

Append values to query string

The following solution works for ASP.NET 5 (vNext) and it uses QueryHelpers class to build a URI with parameters.

    public Uri GetUri()
    {
        var location = _config.Get("http://iberia.com");
        Dictionary<string, string> values = GetDictionaryParameters();

        var uri = Microsoft.AspNetCore.WebUtilities.QueryHelpers.AddQueryString(location, values);
        return new Uri(uri);
    }

    private Dictionary<string,string> GetDictionaryParameters()
    {
        Dictionary<string, string> values = new Dictionary<string, string>
        {
            { "param1", "value1" },
            { "param2", "value2"},
            { "param3", "value3"}
        };
        return values;
    }

The result URI would have http://iberia.com?param1=value1&param2=value2&param3=value3

How to reset index in a pandas dataframe?

DataFrame.reset_index is what you're looking for. If you don't want it saved as a column, then do:

df = df.reset_index(drop=True)

If you don't want to reassign:

df.reset_index(drop=True, inplace=True)

Build Step Progress Bar (css and jquery)

What I would do is use the same trick often use for hovering on buttons. Prepare an image that has 2 parts: (1) a top half which is greyed out, meaning incomplete, and (2) a bottom half which is colored in, meaning completed. Use the same image 4 times to make up the 4 steps of the progress bar, and align top for incomplete steps, and align bottom for incomplete steps.

In order to take advantage of image alignment, you'd have to use the image as the background for 4 divs, rather than using the img element.

This is the CSS for background image alignment:

div.progress-incomplete {
  background-position: top;
}
div.progress-finished {
  background-position: bottom;
}

Ascending and Descending Number Order in java

you can make two function one for Ascending and another for Descending the next two functions work after convert array to List

public List<Integer> sortDescending(List<Integer> arr){
    Comparator<Integer> c = Collections.reverseOrder();
    Collections.sort(arr,c);
    return arr;
  }

next function

public List<Integer> sortAscending(List<Integer> arr){   
    Collections.sort(arr);
    return arr;
  }

How can I remove a button or make it invisible in Android?

First make the button invisible in xml file.Then set button visible in java code if needed.

Button resetButton=(Button)findViewById(R.id.my_button_del);
resetButton.setVisibility(View.VISIBLE); //To set visible

Xml:

<Button
android:text="Delete"
android:id="@+id/my_button_del"
android:layout_width="72dp" 
android:layout_height="40dp"
android:visibility="invisible"/>

Compute mean and standard deviation by group for multiple variables in a data.frame

The updated dplyr solution, as for 2020

1: summarise_each_() is deprecated as of dplyr 0.7.0. and 2: funs() is deprecated as of dplyr 0.8.0.

ag.dplyr <- DF %>% group_by(ID) %>% summarise(across(.cols = everything(),list(mean = mean, sd = sd)))

Use <Image> with a local file

It works exactly as you expect it to work. There's a bug https://github.com/facebook/react-native/issues/282 that prevents it from working correctly.

If you have node_modules (with react_native) in the same folder as the xcode project, you can edit node_modules/react-native/packager/packager.js and make this change: https://github.com/facebook/react-native/pull/286/files . It'll work magically :)

If your react_native is installed somewhere else and the patch doesn't work, comment on https://github.com/facebook/react-native/issues/282 to let them know about your setup.

How to merge 2 JSON objects from 2 files using jq?

Here's a version that works recursively (using *) on an arbitrary number of objects:

echo '{"A": {"a": 1}}' '{"A": {"b": 2}}' '{"B": 3}' |\
  jq --slurp 'reduce .[] as $item ({}; . * $item)'

{
  "A": {
    "a": 1,
    "b": 2
  },
  "B": 3
}

Node.js: Python not found exception due to node-sass and node-gyp

so this happened to me on windows recently. I fix it by following the following steps using a PowerShell with admin privileges:

  1. delete node_modulesfolder
  2. running npm install --global windows-build-tools
  3. reinstalling node modules or node-sass with npm install

Understanding Bootstrap's clearfix class

When a clearfix is used in a parent container, it automatically wraps around all the child elements.

It is usually used after floating elements to clear the float layout.

When float layout is used, it will horizontally align the child elements. Clearfix clears this behaviour.

Example - Bootstrap Panels

In bootstrap, when the class panel is used, there are 3 child types: panel-header, panel-body, panel-footer. All of which have display:block layout but panel-body has a clearfix pre-applied. panel-body is a main container type whereas panel-header & panel-footer isn't intended to be a container, it is just intended to hold some basic text.

If floating elements are added, the parent container does not get wrapped around those elements because the height of floating elements is not inherited by the parent container.

So for panel-header & panel-footer, clearfix is needed to clear the float layout of elements: Clearfix class gives a visual appearance that the height of the parent container has been increased to accommodate all of its child elements.

 <div class="container">
    <div class="panel panel-default">
        <div class="panel-footer">
            <div class="col-xs-6">
                <input type="button" class="btn btn-primary"   value="Button1">
                <input type="button" class="btn btn-primary"   value="Button2">
                <input type="button" class="btn btn-primary"   value="Button3">
            </div>
        </div>
    </div>

    <div class="panel panel-default">
        <div class="panel-footer">
            <div class="col-xs-6">
                <input type="button" class="btn btn-primary"   value="Button1">
                <input type="button" class="btn btn-primary"   value="Button2">
                <input type="button" class="btn btn-primary"   value="Button3">
            </div>
            <div class="clearfix"/>
        </div>
    </div>
</div>

see an example photo here

How to make GREP select only numeric values?

Don't use more commands than necessary, leave away tail, grep and cut. You can do this with only (a simple) awk

PS: giving a block-size en print only de persentage is a bit silly ;-) So leave also away the "-B MB"

df . |awk -F'[multiple field seperators]' '$NF=="Last field must be exactly --> mounted patition" {print $(NF-number from last field)}'

in your case, use:

df . |awk -F'[ %]' '$NF=="/" {print $(NF-2)}'

output: 81

If you want to show the percent symbol, you can leave the -F'[ %]' away and your print field will move 1 field further back

df . |awk '$NF=="/" {print $(NF-1)}'

output: 81%

How can I strip first X characters from string using sed?

Cut first two characters from string:

$ string="1234567890"; echo "${string:2}"
34567890

Detect network connection type on Android

You can make custom Method to accomplish this task.

  public String getNetworkClass(Context context) {
        TelephonyManager mTelephonyManager = (TelephonyManager)
                context.getSystemService(Context.TELEPHONY_SERVICE);
        int networkType = mTelephonyManager.getNetworkType();
        switch (networkType) {
            case TelephonyManager.NETWORK_TYPE_GPRS:
            case TelephonyManager.NETWORK_TYPE_EDGE:
            case TelephonyManager.NETWORK_TYPE_CDMA:
            case TelephonyManager.NETWORK_TYPE_1xRTT:
            case TelephonyManager.NETWORK_TYPE_IDEN:
                return "2G";
            case TelephonyManager.NETWORK_TYPE_UMTS:
            case TelephonyManager.NETWORK_TYPE_EVDO_0:
            case TelephonyManager.NETWORK_TYPE_EVDO_A:
            case TelephonyManager.NETWORK_TYPE_HSDPA:
            case TelephonyManager.NETWORK_TYPE_HSUPA:
            case TelephonyManager.NETWORK_TYPE_HSPA:
            case TelephonyManager.NETWORK_TYPE_EVDO_B:
            case TelephonyManager.NETWORK_TYPE_EHRPD:
            case TelephonyManager.NETWORK_TYPE_HSPAP:
                return "3G";
            case TelephonyManager.NETWORK_TYPE_LTE:
                return "4G";
            default:
                return "Unknown";
        }
    }

Error: Cannot find module 'webpack'

Installing both webpack and CLI globally worked for me.

npm i -g webpack webpack-cli

How to fix: "UnicodeDecodeError: 'ascii' codec can't decode byte"

tl;dr / quick fix

  • Don't decode/encode willy nilly
  • Don't assume your strings are UTF-8 encoded
  • Try to convert strings to Unicode strings as soon as possible in your code
  • Fix your locale: How to solve UnicodeDecodeError in Python 3.6?
  • Don't be tempted to use quick reload hacks

Unicode Zen in Python 2.x - The Long Version

Without seeing the source it's difficult to know the root cause, so I'll have to speak generally.

UnicodeDecodeError: 'ascii' codec can't decode byte generally happens when you try to convert a Python 2.x str that contains non-ASCII to a Unicode string without specifying the encoding of the original string.

In brief, Unicode strings are an entirely separate type of Python string that does not contain any encoding. They only hold Unicode point codes and therefore can hold any Unicode point from across the entire spectrum. Strings contain encoded text, beit UTF-8, UTF-16, ISO-8895-1, GBK, Big5 etc. Strings are decoded to Unicode and Unicodes are encoded to strings. Files and text data are always transferred in encoded strings.

The Markdown module authors probably use unicode() (where the exception is thrown) as a quality gate to the rest of the code - it will convert ASCII or re-wrap existing Unicodes strings to a new Unicode string. The Markdown authors can't know the encoding of the incoming string so will rely on you to decode strings to Unicode strings before passing to Markdown.

Unicode strings can be declared in your code using the u prefix to strings. E.g.

>>> my_u = u'my ünicôdé string'
>>> type(my_u)
<type 'unicode'>

Unicode strings may also come from file, databases and network modules. When this happens, you don't need to worry about the encoding.

Gotchas

Conversion from str to Unicode can happen even when you don't explicitly call unicode().

The following scenarios cause UnicodeDecodeError exceptions:

# Explicit conversion without encoding
unicode('€')

# New style format string into Unicode string
# Python will try to convert value string to Unicode first
u"The currency is: {}".format('€')

# Old style format string into Unicode string
# Python will try to convert value string to Unicode first
u'The currency is: %s' % '€'

# Append string to Unicode
# Python will try to convert string to Unicode first
u'The currency is: ' + '€'         

Examples

In the following diagram, you can see how the word café has been encoded in either "UTF-8" or "Cp1252" encoding depending on the terminal type. In both examples, caf is just regular ascii. In UTF-8, é is encoded using two bytes. In "Cp1252", é is 0xE9 (which is also happens to be the Unicode point value (it's no coincidence)). The correct decode() is invoked and conversion to a Python Unicode is successfull: Diagram of a string being converted to a Python Unicode string

In this diagram, decode() is called with ascii (which is the same as calling unicode() without an encoding given). As ASCII can't contain bytes greater than 0x7F, this will throw a UnicodeDecodeError exception:

Diagram of a string being converted to a Python Unicode string with the wrong encoding

The Unicode Sandwich

It's good practice to form a Unicode sandwich in your code, where you decode all incoming data to Unicode strings, work with Unicodes, then encode to strs on the way out. This saves you from worrying about the encoding of strings in the middle of your code.

Input / Decode

Source code

If you need to bake non-ASCII into your source code, just create Unicode strings by prefixing the string with a u. E.g.

u'Zürich'

To allow Python to decode your source code, you will need to add an encoding header to match the actual encoding of your file. For example, if your file was encoded as 'UTF-8', you would use:

# encoding: utf-8

This is only necessary when you have non-ASCII in your source code.

Files

Usually non-ASCII data is received from a file. The io module provides a TextWrapper that decodes your file on the fly, using a given encoding. You must use the correct encoding for the file - it can't be easily guessed. For example, for a UTF-8 file:

import io
with io.open("my_utf8_file.txt", "r", encoding="utf-8") as my_file:
     my_unicode_string = my_file.read() 

my_unicode_string would then be suitable for passing to Markdown. If a UnicodeDecodeError from the read() line, then you've probably used the wrong encoding value.

CSV Files

The Python 2.7 CSV module does not support non-ASCII characters . Help is at hand, however, with https://pypi.python.org/pypi/backports.csv.

Use it like above but pass the opened file to it:

from backports import csv
import io
with io.open("my_utf8_file.txt", "r", encoding="utf-8") as my_file:
    for row in csv.reader(my_file):
        yield row

Databases

Most Python database drivers can return data in Unicode, but usually require a little configuration. Always use Unicode strings for SQL queries.

MySQL

In the connection string add:

charset='utf8',
use_unicode=True

E.g.

>>> db = MySQLdb.connect(host="localhost", user='root', passwd='passwd', db='sandbox', use_unicode=True, charset="utf8")
PostgreSQL

Add:

psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY)

HTTP

Web pages can be encoded in just about any encoding. The Content-type header should contain a charset field to hint at the encoding. The content can then be decoded manually against this value. Alternatively, Python-Requests returns Unicodes in response.text.

Manually

If you must decode strings manually, you can simply do my_string.decode(encoding), where encoding is the appropriate encoding. Python 2.x supported codecs are given here: Standard Encodings. Again, if you get UnicodeDecodeError then you've probably got the wrong encoding.

The meat of the sandwich

Work with Unicodes as you would normal strs.

Output

stdout / printing

print writes through the stdout stream. Python tries to configure an encoder on stdout so that Unicodes are encoded to the console's encoding. For example, if a Linux shell's locale is en_GB.UTF-8, the output will be encoded to UTF-8. On Windows, you will be limited to an 8bit code page.

An incorrectly configured console, such as corrupt locale, can lead to unexpected print errors. PYTHONIOENCODING environment variable can force the encoding for stdout.

Files

Just like input, io.open can be used to transparently convert Unicodes to encoded byte strings.

Database

The same configuration for reading will allow Unicodes to be written directly.

Python 3

Python 3 is no more Unicode capable than Python 2.x is, however it is slightly less confused on the topic. E.g the regular str is now a Unicode string and the old str is now bytes.

The default encoding is UTF-8, so if you .decode() a byte string without giving an encoding, Python 3 uses UTF-8 encoding. This probably fixes 50% of people's Unicode problems.

Further, open() operates in text mode by default, so returns decoded str (Unicode ones). The encoding is derived from your locale, which tends to be UTF-8 on Un*x systems or an 8-bit code page, such as windows-1251, on Windows boxes.

Why you shouldn't use sys.setdefaultencoding('utf8')

It's a nasty hack (there's a reason you have to use reload) that will only mask problems and hinder your migration to Python 3.x. Understand the problem, fix the root cause and enjoy Unicode zen. See Why should we NOT use sys.setdefaultencoding("utf-8") in a py script? for further details

How to enable Google Play App Signing

This guide is oriented to developers who already have an application in the Play Store. If you are starting with a new app the process it's much easier and you can follow the guidelines of paragraph "New apps" from here

Prerequisites that 99% of developers already have :

  1. Android Studio

  2. JDK 8 and after installation you need to setup an environment variable in your user space to simplify terminal commands. In Windows x64 you need to add this : C:\Program Files\Java\{JDK_VERSION}\bin to the Path environment variable. (If you don't know how to do this you can read my guide to add a folder to the Windows 10 Path environment variable).

Step 0: Open Google Play developer console, then go to Release Management -> App Signing.

enter image description here

Accept the App Signing TOS.

enter image description here

Step 1: Download PEPK Tool clicking the button identical to the image below

enter image description here

Step 2: Open a terminal and type:

java -jar PATH_TO_PEPK --keystore=PATH_TO_KEYSTORE --alias=ALIAS_YOU_USE_TO_SIGN_APK --output=PATH_TO_OUTPUT_FILE --encryptionkey=GOOGLE_ENCRYPTION_KEY

Legend:

  • PATH_TO_PEPK = Path to the pepk.jar you downloaded in Step 1, could be something like C:\Users\YourName\Downloads\pepk.jar for Windows users.
  • PATH_TO_KEYSTORE = Path to keystore which you use to sign your release APK. Could be a file of type *.keystore or *.jks or without extension. Something like C:\Android\mykeystore or C:\Android\mykeystore.keystore etc...
  • ALIAS_YOU_USE_TO_SIGN_APK = The name of the alias you use to sign the release APK.
  • PATH_TO_OUTPUT_FILE = The path of the output file with .pem extension, something like C:\Android\private_key.pem
  • GOOGLE_ENCRYPTION_KEY = This encryption key should be always the same. You can find it in the App Signing page, copy and paste it. Should be in this form: eb10fe8f7c7c9df715022017b00c6471f8ba8170b13049a11e6c09ffe3056a104a3bbe4ac5a955f4ba4fe93fc8cef27558a3eb9d2a529a2092761fb833b656cd48b9de6a

Example:

java -jar "C:\Users\YourName\Downloads\pepk.jar" --keystore="C:\Android\mykeystore" --alias=myalias --output="C:\Android\private_key.pem" --encryptionkey=eb10fe8f7c7c9df715022017b00c6471f8ba8170b13049a11e6c09ffe3056a104a3bbe4ac5a955f4ba4fe93fc8cef27558a3eb9d2a529a2092761fb833b656cd48b9de6a

Press Enter and you will need to provide in order:

  1. The keystore password
  2. The alias password

If everything has gone OK, you now will have a file in PATH_TO_OUTPUT_FILE folder called private_key.pem.

Step 3: Upload the private_key.pem file clicking the button identical to the image below

enter image description here

Step 4: Create a new keystore file using Android Studio.

YOU WILL NEED THIS KEYSTORE IN THE FUTURE TO SIGN THE NEXT RELEASES OF YOUR APP, DON'T FORGET THE PASSWORDS

Open one of your Android projects (choose one at random). Go to Build -> Generate Signed APK and press Create new.

enter image description here

Now you should fill the required fields.

Key store path represent the new keystore you will create, choose a folder and a name using the 3 dots icon on the right, i choosed C:\Android\upload_key.jks (.jks extension will be added automatically)

NOTE: I used upload as the new alias name but if you previously used the same keystore with different aliases to sign different apps, you should choose the same aliases name you had previously in the original keystore.

enter image description here

Press OK when finished, and now you will have a new upload_key.jks keystore. You can close Android Studio now.

Step 5: We need to extract the upload certificate from the newly created upload_key.jks keystore. Open a terminal and type:

keytool -export -rfc -keystore UPLOAD_KEYSTORE_PATH -alias UPLOAD_KEYSTORE_ALIAS -file PATH_TO_OUTPUT_FILE

Legend:

  • UPLOAD_KEYSTORE_PATH = The path of the upload keystore you just created. In this case was C:\Android\upload_key.jks.
  • UPLOAD_KEYSTORE_ALIAS = The new alias associated with the upload keystore. In this case was upload.
  • PATH_TO_OUTPUT_FILE = The path to the output file with .pem extension. Something like C:\Android\upload_key_public_certificate.pem.

Example:

keytool -export -rfc -keystore "C:\Android\upload_key.jks" -alias upload -file "C:\Android\upload_key_public_certificate.pem"

Press Enter and you will need to provide the keystore password.

Now if everything has gone OK, you will have a file in the folder PATH_TO_OUTPUT_FILE called upload_key_public_certificate.pem.

Step 6: Upload the upload_key_public_certificate.pem file clicking the button identical to the image below

enter image description here

Step 7: Click ENROLL button at the end of the App Signing page.

enter image description here

Now every new release APK must be signed with the upload_key.jks keystore and aliases created in Step 4, prior to be uploaded in the Google Play Developer console.

More Resources:

Q&A

Q: When i upload the APK signed with the new upload_key keystore, Google Play show an error like : You uploaded an unsigned APK. You need to create a signed APK.

A: Check to sign the APK with both signatures (V1 and V2) while building the release APK. Read here for more details.

UPDATED

The step 4,5,6 are to create upload key which is optional for existing apps

"Upload key (optional for existing apps): A new key you generate during your enrollment in the program. You will use the upload key to sign all future APKs prior to uploading them to the Play Console." https://support.google.com/googleplay/android-developer/answer/7384423

Change a Git remote HEAD to point to something besides master

Simple just log into your GitHub account and on the far right side in the navigation menu choose Settings, in the Settings Tab choose Default Branch and return back to main page of your repository that did the trick for me.

How can I use "e" (Euler's number) and power operation in python 2.7

Python's power operator is ** and Euler's number is math.e, so:

 from math import e
 x.append(1-e**(-value1**2/2*value2**2))

How can the size of an input text box be defined in HTML?

You can set the width in pixels via inline styling:

<input type="text" name="text" style="width: 195px;">

You can also set the width with a visible character length:

<input type="text" name="text" size="35">

How to configure port for a Spring Boot application

put this code in u applicatop.properties file
enter image description here

Django error - matching query does not exist

Maybe you have no Comments record with such primary key, then you should use this code:

try:
    comment = Comment.objects.get(pk=comment_id)
except Comment.DoesNotExist:
    comment = None

Filter element based on .data() key/value

Sounds like more work than its worth.

1) Why not just have a single JavaScript variable that stores a reference to the currently selected element\jQuery object.

2) Why not add a class to the currently selected element. Then you could query the DOM for the ".active" class or something.

Troubleshooting "Illegal mix of collations" error in mysql

If you have phpMyAdmin installed, you can follow the instructions given in the following link: https://mediatemple.net/community/products/dv/204403914/default-mysql-character-set-and-collation You have to match the collate of the database with that of all the tables, as well as the fields of the tables and then recompile all the stored procedures and functions. With that everything should work again.

Single Form Hide on Startup

You're going to want to set the window state to minimized, and show in taskbar to false. Then at the end of your forms Load set window state to maximized and show in taskbar to true

    public frmMain()
    {
        Program.MainForm = this;
        InitializeComponent();

        this.WindowState = FormWindowState.Minimized;
        this.ShowInTaskbar = false;
    }

private void frmMain_Load(object sender, EventArgs e)
    {
        //Do heavy things here

        //At the end do this
        this.WindowState = FormWindowState.Maximized;
        this.ShowInTaskbar = true;
    }

Nested classes' scope?

Easiest solution:

class OuterClass:
    outer_var = 1
    class InnerClass:
        def __init__(self):
            self.inner_var = OuterClass.outer_var

It requires you to be explicit, but doesn't take much effort.

ExecuteNonQuery: Connection property has not been initialized.

double click on your form to create form_load event.Then inside that event write command.connection = "your connection name";

How to URL encode in Python 3?

For Python 3 you could try using quote instead of quote_plus:

import urllib.parse

print(urllib.parse.quote("http://www.sample.com/"))

Result:

http%3A%2F%2Fwww.sample.com%2F

Or:

from requests.utils import requote_uri
requote_uri("http://www.sample.com/?id=123 abc")

Result:

'https://www.sample.com/?id=123%20abc'

Why does .json() return a promise?

Also, what helped me understand this particular scenario that you described is the Promise API documentation, specifically where it explains how the promised returned by the then method will be resolved differently depending on what the handler fn returns:

if the handler function:

  • returns a value, the promise returned by then gets resolved with the returned value as its value;
  • throws an error, the promise returned by then gets rejected with the thrown error as its value;
  • returns an already resolved promise, the promise returned by then gets resolved with that promise's value as its value;
  • returns an already rejected promise, the promise returned by then gets rejected with that promise's value as its value.
  • returns another pending promise object, the resolution/rejection of the promise returned by then will be subsequent to the resolution/rejection of the promise returned by the handler. Also, the value of the promise returned by then will be the same as the value of the promise returned by the handler.

Example for boost shared_mutex (multiple reads/one write)?

It looks like you would do something like this:

boost::shared_mutex _access;
void reader()
{
  // get shared access
  boost::shared_lock<boost::shared_mutex> lock(_access);

  // now we have shared access
}

void writer()
{
  // get upgradable access
  boost::upgrade_lock<boost::shared_mutex> lock(_access);

  // get exclusive access
  boost::upgrade_to_unique_lock<boost::shared_mutex> uniqueLock(lock);
  // now we have exclusive access
}

Update records in table from CTE

WITH CTE_DocTotal (DocTotal, InvoiceNumber)
AS
(
    SELECT  InvoiceNumber,
            SUM(Sale + VAT) AS DocTotal
    FROM    PEDI_InvoiceDetail
    GROUP BY InvoiceNumber
)    
UPDATE PEDI_InvoiceDetail
SET PEDI_InvoiceDetail.DocTotal = CTE_DocTotal.DocTotal
FROM CTE_DocTotal
INNER JOIN PEDI_InvoiceDetail ON ...

How do I count a JavaScript object's attributes?

For those which will read this question/answers, here is a JavaScript implementation of Dictionary collection very similar as functionality as .NET one: JavaScript Dictionary

How to find what code is run by a button or element in Chrome using Developer Tools

Solution 1: Framework blackboxing

Works great, minimal setup and no third parties.

According to Chrome's documentation:

What happens when you blackbox a script?

Exceptions thrown from library code will not pause (if Pause on exceptions is enabled), Stepping into/out/over bypasses the library code, Event listener breakpoints don't break in library code, The debugger will not pause on any breakpoints set in library code. The end result is you are debugging your application code instead of third party resources.

Here's the updated workflow:
  1. Pop open Chrome Developer Tools (F12 or ?+?+i), go to settings (upper right, or F1). Find a tab on the left called "Blackboxing"

enter image description here

  1. This is where you put the RegEx pattern of the files you want Chrome to ignore while debugging. For example: jquery\..*\.js (glob pattern/human translation: jquery.*.js)
  2. If you want to skip files with multiple patterns you can add them using the pipe character, |, like so: jquery\..*\.js|include\.postload\.js (which acts like an "or this pattern", so to speak. Or keep adding them with the "Add" button.
  3. Now continue to Solution 3 described down below.

Bonus tip! I use Regex101 regularly (but there are many others: ) to quickly test my rusty regex patterns and find out where I'm wrong with the step-by-step regex debugger. If you are not yet "fluent" in Regular Expressions I recommend you start using sites that help you write and visualize them such as http://buildregex.com/ and https://www.debuggex.com/

You can also use the context menu when working in the Sources panel. When viewing a file, you can right-click in the editor and choose Blackbox Script. This will add the file to the list in the Settings panel:

enter image description here


Solution 2: Visual Event

enter image description here

It's an excellent tool to have:

Visual Event is an open-source Javascript bookmarklet which provides debugging information about events that have been attached to DOM elements. Visual Event shows:

  • Which elements have events attached to them
  • The type of events attached to an element
  • The code that will be run with the event is triggered
  • The source file and line number for where the attached function was defined (Webkit browsers and Opera only)


Solution 3: Debugging

You can pause the code when you click somewhere in the page, or when the DOM is modified... and other kinds of JS breakpoints that will be useful to know. You should apply blackboxing here to avoid a nightmare.

In this instance, I want to know what exactly goes on when I click the button.

  1. Open Dev Tools -> Sources tab, and on the right find Event Listener Breakpoints:

    enter image description here

  2. Expand Mouse and select click

  3. Now click the element (execution should pause), and you are now debugging the code. You can go through all code pressing F11 (which is Step in). Or go back a few jumps in the stack. There can be a ton of jumps


Solution 4: Fishing keywords

With Dev Tools activated, you can search the whole codebase (all code in all files) with ?+?+F or:

enter image description here

and searching #envio or whatever the tag/class/id you think starts the party and you may get somewhere faster than anticipated.

Be aware sometimes there's not only an img but lots of elements stacked, and you may not know which one triggers the code.


If this is a bit out of your knowledge, take a look at Chrome's tutorial on debugging.

How do I test a website using XAMPP?

The webpages on an online server reside in a location which looks somewhat like this: http://www.somerandomsite.com/index.php

Since xampp is Offline, it sets up a local server whose address is like this http://localhost/

Basically, xampp sets up a server (apache and others) in your system. And all the files such as index.php, somethingelse.php, etc., reside in the xampp\htdocs\ folder.

The browser locates the server in localhost and will search through the above folder for any resources available in there.

So create any number of folders inside the "xampp\htdocs\" each folder thus forming a website (as you build it).

Sometimes apache won't even start. This is due to the clashing of ports with some applications. Some of them I commonly encounter is Skype. See to that it is killed completely and restart apache

Android emulator failed to allocate memory 8

In the AVD setup: Change the CPU/ABI option to MIPS. It worked for me

How to display a PDF via Android web browser without "downloading" first

  • Download the acrobat reader .apk file for android to display pdf file
  • Put your pdf files on an sd card
  • Use the snippet of code below

    File file= new File("/sdcard/test.pdf");
    Uri path=Uri.fromFile(file);
    Intent i =new Intent(Intent.ACTION_VIEW);
    i.setDataAndType(path,"application/pdf");
    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(i);
    

program cant start because php5.dll is missing

In case this might help someone, after installing the thread safe version of PHP 5.5.1, everything was working under apache for my dev sites, but I ran into the same "php5.dll is missing" problem installing Composer using the Composer-Setup.exe - or, as I soon discovered, just running something as simple as php -v from the command line. I made a copy of php5ts.dll and named it php5.dll and everything worked. I assume the Composer installer was specifically looking for "php5.dll" and I knew that the thread safe code would be run by the renamed .dll. I also assume something is wrong with my setup to screw up the command line functionality, but with everything working, I have more important issues to deal with than to try and find the problem.

HTTP Request in Kotlin

import java.io.IOException
import java.net.URL

fun main(vararg args: String) {
    val response = try {
        URL("http://seznam.cz")
                .openStream()
                .bufferedReader()
                .use { it.readText() }
    } catch (e: IOException) {
        "Error with ${e.message}."
    }
    println(response)
}

Making an API call in Python with an API that requires a bearer token

The token has to be placed in an Authorization header according to the following format:

Authorization: Bearer [Token_Value]

Code below:

import urllib2
import json

def get_auth_token():
    """
    get an auth token
    """
    req=urllib2.Request("https://xforce-api.mybluemix.net/auth/anonymousToken")
    response=urllib2.urlopen(req)
    html=response.read()
    json_obj=json.loads(html)
    token_string=json_obj["token"].encode("ascii","ignore")
    return token_string

def get_response_json_object(url, auth_token):
    """
    returns json object with info
    """
    auth_token=get_auth_token()
    req=urllib2.Request(url, None, {"Authorization": "Bearer %s" %auth_token})
    response=urllib2.urlopen(req)
    html=response.read()
    json_obj=json.loads(html)
    return json_obj

Call to undefined method mysqli_stmt::get_result

Please read the user notes for this method:

http://php.net/manual/en/mysqli-stmt.get-result.php

It requires the mysqlnd driver... if it isn't installed on your webspace you will have to work with BIND_RESULT & FETCH!

https://secure.php.net/manual/en/mysqli-stmt.bind-result.php

https://secure.php.net/manual/en/mysqli-stmt.fetch.php

setTimeout / clearTimeout problems

You need to declare timer outside the function. Otherwise, you get a brand new variable on each function invocation.

var timer;
function endAndStartTimer() {
  window.clearTimeout(timer);
  //var millisecBeforeRedirect = 10000; 
  timer = window.setTimeout(function(){alert('Hello!');},10000); 
}

pass post data with window.location.href

As it was said in other answers there is no way to make a POST request using window.location.href, to do it you can create a form and submit it immediately.

You can use this function:

function postForm(path, params, method) {
    method = method || 'post';

    var form = document.createElement('form');
    form.setAttribute('method', method);
    form.setAttribute('action', path);

    for (var key in params) {
        if (params.hasOwnProperty(key)) {
            var hiddenField = document.createElement('input');
            hiddenField.setAttribute('type', 'hidden');
            hiddenField.setAttribute('name', key);
            hiddenField.setAttribute('value', params[key]);

            form.appendChild(hiddenField);
        }
    }

    document.body.appendChild(form);
    form.submit();
}

postForm('mysite.com/form', {arg1: 'value1', arg2: 'value2'});

https://stackoverflow.com/a/133997/2965158

How to describe table in SQL Server 2008?

The sp_help built-in procedure is the SQL Server's closest thing to Oracle's DESC function IMHO

sp_help MyTable

Use

sp_help "[SchemaName].[TableName]" 

or

sp_help "[InstanceName].[SchemaName].[TableName]"

in case you need to qualify the table name further

MongoDB what are the default user and password?

For MongoDB earlier than 2.6, the command to add a root user is addUser (e.g.)

db.addUser({user:'admin',pwd:'<password>',roles:["root"]})

Shortest way to check for null and assign another value if not

You are looking for the C# coalesce operator: ??. This operator takes a left and right argument. If the left hand side of the operator is null or a nullable with no value it will return the right argument. Otherwise it will return the left.

var x = somePossiblyNullValue ?? valueIfNull;

What is HTML5 ARIA?

What is it?

WAI-ARIA stands for “Web Accessibility Initiative – Accessible Rich Internet Applications”. It is a set of attributes to help enhance the semantics of a web site or web application to help assistive technologies, such as screen readers for the blind, make sense of certain things that are not native to HTML. The information exposed can range from something as simple as telling a screen reader that activating a link or button just showed or hid more items, to widgets as complex as whole menu systems or hierarchical tree views.

This is achieved by applying roles and state attributes to HTML 4.01 or later markup that has no bearing on layout or browser functionality, but provides additional information for assistive technologies.

One corner stone of WAI-ARIA is the role attribute. It tells the browser to tell the assistive technology that the HTML element used is not actually what the element name suggests, but something else. While it originally is only a div element, this div element may be the container to a list of auto-complete items, in which case a role of “listbox” would be appropriate to use. Likewise, another div that is a child of that container div, and which contains a single option item, should then get a role of “option”. Two divs, but through the roles, totally different meaning. The roles are modeled after commonly used desktop application counterparts.

An exception to this are document landmark roles, which don’t change the actual meaning of the element in question, but provide information about this particular place in a document.

The second corner stone are WAI-ARIA states and properties. They define the state of certain native or WAI-ARIA elements such as if something is collapsed or expanded, a form element is required, something has a popup menu attached to it or the like. These are often dynamic and change their values throughout the lifecycle of a web application, and are usually manipulated via JavaScript.

What is it not?

WAI-ARIA is not intended to influence browser behavior. Unlike a real button element, for example, a div which you pour the role of “button” onto does not give you keyboard focusability, an automatic click handler when Space or Enter are being pressed on it, and other properties that are indiginous to a button. The browser itself does not know that a div with role of “button” is a button, only its accessibility API portion does.

As a consequence, this means that you absolutely have to implement keyboard navigation, focusability and other behavioural patterns known from desktop applications yourself. You can find some Advanced ARIA techniques Here.

When should I not use it?

Yes, that’s correct, this section comes first! Because the first rule of using WAI-ARIA is: Don’t use it unless you absolutely have to! The less WAI-ARIA you have, and the more you can count on using native HTML widgets, the better! There are some more rules to follow, you can check them out here.

Set variable in jinja

Just Set it up like this

{% set active_link = recordtype -%}

What's the difference between Visual Studio Community and other, paid versions?

All these answers are partially wrong.

Microsoft has clarified that Community is for ANY USE as long as your revenue is under $1 Million US dollars. That is literally the only difference between Pro and Community. Corporate or free or not, irrelevant.

Even the lack of TFS support is not true. I can verify it is present and works perfectly.

EDIT: Here is an MSDN post regarding the $1M limit: MSDN (hint: it's in the VS 2017 license)

EDIT: Even over the revenue limit, open source is still free.

how to set cursor style to pointer for links without hrefs

This worked for me:

<a onClick={this.openPopupbox} style={{cursor: 'pointer'}}>

How to get last inserted id?

After this:

INSERT INTO aspnet_GameProfiles(UserId, GameId) OUTPUT INSERTED.ID VALUES(@UserId, @GameId)

Execute this

int id = (int)command.ExecuteScalar;

It will work

Plot correlation matrix using pandas

You can use pyplot.matshow() from matplotlib:

import matplotlib.pyplot as plt

plt.matshow(dataframe.corr())
plt.show()

Edit:

In the comments was a request for how to change the axis tick labels. Here's a deluxe version that is drawn on a bigger figure size, has axis labels to match the dataframe, and a colorbar legend to interpret the color scale.

I'm including how to adjust the size and rotation of the labels, and I'm using a figure ratio that makes the colorbar and the main figure come out the same height.


EDIT 2: As the df.corr() method ignores non-numerical columns, .select_dtypes(['number']) should be used when defining the x and y labels to avoid an unwanted shift of the labels (included in the code below).

f = plt.figure(figsize=(19, 15))
plt.matshow(df.corr(), fignum=f.number)
plt.xticks(range(df.select_dtypes(['number']).shape[1]), df.select_dtypes(['number']).columns, fontsize=14, rotation=45)
plt.yticks(range(df.select_dtypes(['number']).shape[1]), df.select_dtypes(['number']).columns, fontsize=14)
cb = plt.colorbar()
cb.ax.tick_params(labelsize=14)
plt.title('Correlation Matrix', fontsize=16);

correlation plot example

How can I convert a string to boolean in JavaScript?

I'm using this one when I get value from URL/Form or other source.

It is pretty universal one line piece of code.

Maybe not the best for performance, if you need to run it millions times let me know, we can check how to optimize it, otherwise is pretty good and customizable.

boolResult = !(['false', '0', '', 'undefined'].indexOf(String(myVar).toLowerCase().trim()) + 1);

Result:

myVar = true;  // true
myVar = 'true';  // true
myVar = 'TRUE';  // true
myVar = '1';  // true
myVar = 'any other value not related to false';  // true

myVar = false; // false
myVar = 'false';  // false
myVar = 'FALSE';  // false
myVar = '0';  // false

How do I declare class-level properties in Objective-C?

properties have a specific meaning in Objective-C, but I think you mean something that's equivalent to a static variable? E.g. only one instance for all types of Foo?

To declare class functions in Objective-C you use the + prefix instead of - so your implementation would look something like:

// Foo.h
@interface Foo {
}

+ (NSDictionary *)dictionary;

// Foo.m
+ (NSDictionary *)dictionary {
  static NSDictionary *fooDict = nil;
  if (fooDict == nil) {
    // create dict
  }
  return fooDict;
}

Clearing a text field on button click

Something like this will add a button and let you use it to clear the values

<div>           
<input type="text" id="textfield1" size="5"/>         
</div>

<div>          
<input type="text" id="textfield2" size="5"/>           
</div>

<div>
    <input type="button" onclick="clearFields()" value="Clear">
</div>


<script type="text/javascript">
function clearFields() {
    document.getElementById("textfield1").value=""
    document.getElementById("textfield2").value=""
}
</script>

Why doesn't "System.out.println" work in Android?

System.out.println("...") is displayed on the Android Monitor in Android Studio

What is a stack pointer used for in microprocessors?

A stack is a LIFO (last in, first out - the last entry you push on to the stack is the first one you get back when you pop) data structure that is typically used to hold stack frames (bits of the stack that belong to the current function).

This includes, but is not limited to:

  • the return address.
  • a place for a return value.
  • passed parameters.
  • local variables.

You push items onto the stack and pop them off. In a microprocessor, the stack can be used for both user data (such as local variables and passed parameters) and CPU data (such as return addresses when calling subroutines).

The actual implementation of a stack depends on the microprocessor architecture. It can grow up or down in memory and can move either before or after the push/pop operations.

Operation which typically affect the stack are:

  • subroutine calls and returns.
  • interrupt calls and returns.
  • code explicitly pushing and popping entries.
  • direct manipulation of the SP register.

Consider the following program in my (fictional) assembly language:

Addr  Opcodes   Instructions    ; Comments
----  --------  --------------  ----------
                                ; 1: pc<-0000, sp<-8000
0000  01 00 07  load r0,7       ; 2: pc<-0003, r0<-7
0003  02 00     push r0         ; 3: pc<-0005, sp<-7ffe, (sp:7ffe)<-0007
0005  03 00 00  call 000b       ; 4: pc<-000b, sp<-7ffc, (sp:7ffc)<-0008
0008  04 00     pop r0          ; 7: pc<-000a, r0<-(sp:7ffe[0007]), sp<-8000
000a  05        halt            ; 8: pc<-000a
000b  06 01 02  load r1,[sp+2]  ; 5: pc<-000e, r1<-(sp+2:7ffe[0007])
000e  07        ret             ; 6: pc<-(sp:7ffc[0008]), sp<-7ffe

Now let's follow the execution, describing the steps shown in the comments above:

  1. This is the starting condition where the program counter is zero and the stack pointer is 8000 (all these numbers are hexadecimal).
  2. This simply loads register r0 with the immediate value 7 and moves to the next step (I'll assume that you understand the default behavior will be to move to the next step unless otherwise specified).
  3. This pushes r0 onto the stack by reducing the stack pointer by two then storing the value of the register to that location.
  4. This calls a subroutine. What would have been the program counter is pushed on to the stack in a similar fashion to r0 in the previous step and then the program counter is set to its new value. This is no different to a user-level push other than the fact it's done more as a system-level thing.
  5. This loads r1 from a memory location calculated from the stack pointer - it shows a way to pass parameters to functions.
  6. The return statement extracts the value from where the stack pointer points and loads it into the program counter, adjusting the stack pointer up at the same time. This is like a system-level pop (see next step).
  7. Popping r0 off the stack involves extracting the value from where the stack pointer points then adjusting that stack pointer up.
  8. Halt instruction simply leaves program counter where it is, an infinite loop of sorts.

Hopefully from that description, it will become clear. Bottom line is: a stack is useful for storing state in a LIFO way and this is generally ideal for the way most microprocessors do subroutine calls.

Unless you're a SPARC of course, in which case you use a circular buffer for your stack :-)

Update: Just to clarify the steps taken when pushing and popping values in the above example (whether explicitly or by call/return), see the following examples:

LOAD R0,7
PUSH R0
                     Adjust sp       Store val
sp-> +--------+      +--------+      +--------+
     |  xxxx  |  sp->|  xxxx  |  sp->|  0007  |
     |        |      |        |      |        |
     |        |      |        |      |        |
     |        |      |        |      |        |
     +--------+      +--------+      +--------+

POP R0
                     Get value       Adjust sp
     +--------+      +--------+  sp->+--------+
sp-> |  0007  |  sp->|  0007  |      |  0007  |
     |        |      |        |      |        |
     |        |      |        |      |        |
     |        |      |        |      |        |
     +--------+      +--------+      +--------+

How can you use php in a javascript function

Simply, your question sounded wrong because the JavaScript variables need to be echoed.

_x000D_
_x000D_
<?php_x000D_
        $num = 1;_x000D_
        echo $num;_x000D_
        echo "<input type='button' value='Click' onclick='readmore()' />";_x000D_
     echo "<script> function readmore() { document.write('";_x000D_
        $num = 2;_x000D_
        echo $num;_x000D_
        echo "'); } </script>";_x000D_
?>
_x000D_
_x000D_
_x000D_

Is it possible to install Xcode 10.2 on High Sierra (10.13.6)?

You don't need to run Xcode 10.2 for iOS 12.2 support. You just need access to the appropriate folder in DeviceSupport.

A possible solution is

  • Download Xcode 10.2 from a direkt link (not from App Store).
  • Rename it for example to Xcode102.
  • Put it into /Applications. It's possible to have multiple Xcode versions in the same directory.
  • Create a symbolic link in Terminal.app to have access to the 12.2 device support folder in Xcode 10.2

    ln -s /Applications/Xcode102.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/12.2\ \(16E226\) /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport
    

You can move Xcode 10.2 to somewhere else but then you have to adjust the path.

Now Xcode 10.1 supports devices running iOS 12.2

How to fix Uncaught InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number?

I had the same problem with exactly the same error message. In the end the error was, that I still called the maps v2 javascript. I had to replace:

<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=####################" type="text/javascript"></script>

with

<script src="http://maps.googleapis.com/maps/api/js?key=####################&sensor=false" type="text/javascript"></script>

after this, it worked fine. took me a while ;-)

How do I create a link to add an entry to a calendar?

UPDATE (free for personal use):
HTTPS IS NOW SUPPORTED

While my answer below detailing how-to for each service WILL work, IMO it's much easier now to go with a third-party like AddThisEvent [https://addthisevent.com]. It lets you customize lots of options as well as add to Facebook and more. Unfortunately, they've now made it a paid service for anything other than personal use and do enforce this.

I assume there are other third-party solutions like this one, but I can only speak to this one, and it has worked great for us so far.


For an "Add to my Google Calendar", they used to have a code generator form you could use, but have since taken it down. For more details on Google Calendar links, see squarecandy's answer below.

For Outlook, it's a BIT more complicated, but basically you need to create a .vcs file with the event's data, and just make a link to that file. Step-by-step instructions here.

For an iCal link, you could use a PHP class like this one, or follow this page's instructions on how to create an ics file (iCal file).

Spring Boot: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean

use this one in your pom.xml :

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
</dependency>

or this one :

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>

How do I get a YouTube video thumbnail from the YouTube API?

I have used YouTube thumbnails in this way:

$url = 'http://img.youtube.com/vi/' . $youtubeId . '/0.jpg';
$img = dirname(__FILE__) . '/youtubeThumbnail_'  . $youtubeId . '.jpg';
file_put_contents($img, file_get_contents($url));

Remember YouTube prevents to include images directly from their server.

Convert DataFrame column type from string to datetime, dd/mm/yyyy format

You can use the following if you want to specify tricky formats:

df['date_col'] =  pd.to_datetime(df['date_col'], format='%d/%m/%Y')

More details on format here:

Javascript: Load an Image from url and display

Add a div with ID imgDiv and make your script

 document.getElementById('imgDiv').innerHTML='<img src=\'http://webpage.com/images/'+document.getElementById('imagename').value +'.png\'>'

I tried to stay as close to your original as tp not overwhelm you with jQuery and such

How to write a CSS hack for IE 11?

You can use js and add a class in html to maintain the standard of conditional comments:

  var ua = navigator.userAgent,
      doc = document.documentElement;

  if ((ua.match(/MSIE 10.0/i))) {
    doc.className = doc.className + " ie10";

  } else if((ua.match(/rv:11.0/i))){
    doc.className = doc.className + " ie11";
  }

Or use a lib like bowser:

https://github.com/ded/bowser

Or modernizr for feature detection:

http://modernizr.com/

How to properly add cross-site request forgery (CSRF) token using PHP

Security Warning: md5(uniqid(rand(), TRUE)) is not a secure way to generate random numbers. See this answer for more information and a solution that leverages a cryptographically secure random number generator.

Looks like you need an else with your if.

if (!isset($_SESSION['token'])) {
    $token = md5(uniqid(rand(), TRUE));
    $_SESSION['token'] = $token;
    $_SESSION['token_time'] = time();
}
else
{
    $token = $_SESSION['token'];
}

How do I make a <div> move up and down when I'm scrolling the page?

You want to apply the fixed property to the position style of the element.

position: fixed;

What browser are you working with? Not all browsers support the fixed property. Read more about who supports it, who doesn't and some work around here

http://webreflection.blogspot.com/2009/09/css-position-fixed-solution.html

Getting the first index of an object

My solution:

Object.prototype.__index = function(index)
{
    var i = -1;
    for (var key in this)
    {
        if (this.hasOwnProperty(key) && typeof(this[key])!=='function')
            ++i;
        if (i >= index)
            return this[key];
    }
    return null;
}
aObj = {'jack':3, 'peter':4, '5':'col', 'kk':function(){alert('hell');}, 'till':'ding'};
alert(aObj.__index(4));

Fatal error: iostream: No such file or directory in compiling C program using GCC

Seems like you posted a new question after you realized that you were dealing with a simpler problem related to size_t. I am glad that you did.

Anyways, You have a .c source file, and most of the code looks as per C standards, except that #include <iostream> and using namespace std;

C equivalent for the built-in functions of C++ standard #include<iostream> can be availed through #include<stdio.h>

  1. Replace #include <iostream> with #include <stdio.h>, delete using namespace std;
  2. With #include <iostream> taken off, you would need a C standard alternative for cout << endl;, which can be done by printf("\n"); or putchar('\n');
    Out of the two options, printf("\n"); works the faster as I observed.

    When used printf("\n"); in the code above in place of cout<<endl;

    $ time ./thread.exe
    1 2 3 4 5 6 7 8 9 10
    
    real    0m0.031s
    user    0m0.030s
    sys     0m0.030s
    

    When used putchar('\n'); in the code above in place of cout<<endl;

    $ time ./thread.exe
    1 2 3 4 5 6 7 8 9 10
    
    real    0m0.047s
    user    0m0.030s
    sys     0m0.030s
    

Compiled with Cygwin gcc (GCC) 4.8.3 version. results averaged over 10 samples. (Took me 15 mins)

How to redirect to a route in laravel 5 by using href tag if I'm not using blade or any template?

In you app config file change the url to localhost/example/public

Then when you want to link to something

<a href="{{ url('page') }}">Some Text</a>

without blade

<a href="<?php echo url('page') ?>">Some Text</a>

Can I dynamically add HTML within a div tag from C# on load event?

You can add a div with runat="server" to the page:

<div runat="server" id="myDiv">
</div>

and then set its InnerHtml property from the code-behind:

myDiv.InnerHtml = "your html here";

If you want to modify the DIV's contents on the client side, then you can use javascript code similar to this:

<script type="text/javascript">
    Sys.Application.add_load(MyLoad);
    function MyLoad(sender) {
        $get('<%= div.ClientID %>').innerHTML += " - text added on client";
    }
</script>

UndefinedMetricWarning: F-score is ill-defined and being set to 0.0 in labels with no predicted samples

According to @Shovalt's answer, but in short:

Alternatively you could use the following lines of code

    from sklearn.metrics import f1_score
    metrics.f1_score(y_test, y_pred, labels=np.unique(y_pred))

This should remove your warning and give you the result you wanted, because it no longer considers the difference between the sets, by using the unique mode.

Perl - Multiple condition if statement without duplicating code?

if (   ($name eq "tom" and $password eq "123!")
    or ($name eq "frank" and $password eq "321!")) {

    print "You have gained access.";
}
else {
    print "Access denied!";
}

append multiple values for one key in a dictionary

It's easier if you get these values into a list of tuples. To do this, you can use list slicing and the zip function.

data_in = [2010,2,2009,4,1989,8,2009,7]
data_pairs = zip(data_in[::2],data_in[1::2])

Zip takes an arbitrary number of lists, in this case the even and odd entries of data_in, and puts them together into a tuple.

Now we can use the setdefault method.

data_dict = {}
for x in data_pairs:
    data_dict.setdefault(x[0],[]).append(x[1])

setdefault takes a key and a default value, and returns either associated value, or if there is no current value, the default value. In this case, we will either get an empty or populated list, which we then append the current value to.

What's is the difference between include and extend in use case diagram?

Both <include> and <extend> are dependent on the base class but <extend> is optional i.e., it is derived from the base class but in the point of users view it may be used or may not be used.

<include> is incorporated in base class i.e., it is compulsary to use <include> in your use case or else it would be considered incomplete.

eg:

In ATM machine construction (according to users point of view):

1: Withdrawal,deposit of cash and checking the account comes under <extend> because it depends on the user whether to withdraw or deposit or check. These are optional things the user does.

2: "Enter the pin, placing card, removal of card" these are the things that come under <include> because the user must, and should, place a card and enter a valid pin for verification.

How to view log output using docker-compose run?

  1. use the command to start containers in detached mode: docker-compose up -d
  2. to view the containers use: docker ps
  3. to view logs for a container: docker logs <containerid>

How do you add a JToken to an JObject?

TL;DR: You should add a JProperty to a JObject. Simple. The index query returns a JValue, so figure out how to get the JProperty instead :)


The accepted answer is not answering the question as it seems. What if I want to specifically add a JProperty after a specific one? First, lets start with terminologies which really had my head worked up.

  • JToken = The mother of all other types. It can be A JValue, JProperty, JArray, or JObject. This is to provide a modular design to the parsing mechanism.
  • JValue = any Json value type (string, int, boolean).
  • JProperty = any JValue or JContainer (see below) paired with a name (identifier). For example "name":"value".
  • JContainer = The mother of all types which contain other types (JObject, JValue).
  • JObject = a JContainer type that holds a collection of JProperties
  • JArray = a JContainer type that holds a collection JValue or JContainer.

Now, when you query Json item using the index [], you are getting the JToken without the identifier, which might be a JContainer or a JValue (requires casting), but you cannot add anything after it, because it is only a value. You can change it itself, query more deep values, but you cannot add anything after it for example.

What you actually want to get is the property as whole, and then add another property after it as desired. For this, you use JOjbect.Property("name"), and then create another JProperty of your desire and then add it after this using AddAfterSelf method. You are done then.

For more info: http://www.newtonsoft.com/json/help/html/ModifyJson.htm

This is the code I modified.

public class Program
{
  public static void Main()
  {
    try
    {
      string jsonText = @"
      {
        ""food"": {
          ""fruit"": {
            ""apple"": {
              ""colour"": ""red"",
              ""size"": ""small""
            },
            ""orange"": {
              ""colour"": ""orange"",
              ""size"": ""large""
            }
          }
        }
      }";

      var foodJsonObj = JObject.Parse(jsonText);
      var bananaJson = JObject.Parse(@"{ ""banana"" : { ""colour"": ""yellow"", ""size"": ""medium""}}");

      var fruitJObject = foodJsonObj["food"]["fruit"] as JObject;
      fruitJObject.Property("orange").AddAfterSelf(new JProperty("banana", fruitJObject));

      Console.WriteLine(foodJsonObj.ToString());
    }
    catch (Exception ex)
    {
      Console.WriteLine(ex.GetType().Name + ": " + ex.Message);
    }
  }
}

(Mac) -bash: __git_ps1: command not found

I know it's not a real answer...

I had some strange issues with sourcing git-prompt.sh in my .bashrc so I started to look for other solution. This one: http://www.jqno.nl/post/2012/04/02/howto-display-the-current-git-branch-in-your-prompt/ doesn't use __git_ps1 and author claims it works also on Mac (for now it works perfectly on my Ubuntu and it's easy to tweak).

I hope it helps!

How to submit a form on enter when the textarea has focus?

You can't do this without JavaScript. Stackoverflow is using the jQuery JavaScript library which attachs functions to HTML elements on page load.

Here's how you could do it with vanilla JavaScript:

<textarea onkeydown="if (event.keyCode == 13) { this.form.submit(); return false; }"></textarea>

Keycode 13 is the enter key.

Here's how you could do it with jQuery like as Stackoverflow does:

<textarea class="commentarea"></textarea>

with

$(document).ready(function() {
    $('.commentarea').keydown(function(event) {
        if (event.which == 13) {
            this.form.submit();
            event.preventDefault();
         }
    });
});

Why is the minidlna database not being refreshed?

Resolved with crontab root

10 * * * * /usr/bin/minidlnad -r

Groovy - Convert object to JSON string

I couldn't get the other answers to work within the evaluate console in Intellij so...

groovy.json.JsonOutput.toJson(myObject)

This works quite well, but unfortunately

groovy.json.JsonOutput.prettyString(myObject)

didn't work for me.

To get it pretty printed I had to do this...

groovy.json.JsonOutput.prettyPrint(groovy.json.JsonOutput.toJson(myObject))

Is there a C++ gdb GUI for Linux?

Latest version of Geany supports it (only on Linux, though)

Is it possible to display inline images from html in an Android TextView?

I have implemented in my app ,taken referece from the pskink.thanx a lot

package com.example.htmltagimg;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LevelListDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.text.Spanned;
import android.util.Log;
import android.widget.TextView;

public class MainActivity extends Activity implements ImageGetter {
private final static String TAG = "TestImageGetter";
private TextView mTv;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    String source = "this is a test of <b>ImageGetter</b> it contains " +
            "two images: <br/>" +
            "<img src=\"http://developer.android.com/assets/images/dac_logo.png\"><br/>and<br/>" +
            "<img src=\"http://www.hdwallpapersimages.com/wp-content/uploads/2014/01/Winter-Tiger-Wild-Cat-Images.jpg\">";
    String imgs="<p><img alt=\"\" src=\"http://images.visitcanberra.com.au/images/canberra_hero_image.jpg\" style=\"height:50px; width:100px\" />Test Article, Test Article, Test Article, Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,v</p>";
    String src="<p><img alt=\"\" src=\"http://stylonica.com/wp-content/uploads/2014/02/Beauty-of-nature-random-4884759-1280-800.jpg\" />Test Attractions Test Attractions Test Attractions Test Attractions</p>";
    String img="<p><img alt=\"\" src=\"/site_media/photos/gallery/75b3fb14-3be6-4d14-88fd-1b9d979e716f.jpg\" style=\"height:508px; width:640px\" />Test Article, Test Article, Test Article, Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,v</p>";
    Spanned spanned = Html.fromHtml(imgs, this, null);
    mTv = (TextView) findViewById(R.id.text);
    mTv.setText(spanned);
}

@Override
public Drawable getDrawable(String source) {
    LevelListDrawable d = new LevelListDrawable();
    Drawable empty = getResources().getDrawable(R.drawable.ic_launcher);
    d.addLevel(0, 0, empty);
    d.setBounds(0, 0, empty.getIntrinsicWidth(), empty.getIntrinsicHeight());

    new LoadImage().execute(source, d);

    return d;
}

class LoadImage extends AsyncTask<Object, Void, Bitmap> {

    private LevelListDrawable mDrawable;

    @Override
    protected Bitmap doInBackground(Object... params) {
        String source = (String) params[0];
        mDrawable = (LevelListDrawable) params[1];
        Log.d(TAG, "doInBackground " + source);
        try {
            InputStream is = new URL(source).openStream();
            return BitmapFactory.decodeStream(is);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Bitmap bitmap) {
        Log.d(TAG, "onPostExecute drawable " + mDrawable);
        Log.d(TAG, "onPostExecute bitmap " + bitmap);
        if (bitmap != null) {
            BitmapDrawable d = new BitmapDrawable(bitmap);
            mDrawable.addLevel(1, 1, d);
            mDrawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight());
            mDrawable.setLevel(1);
            // i don't know yet a better way to refresh TextView
            // mTv.invalidate() doesn't work as expected
            CharSequence t = mTv.getText();
            mTv.setText(t);
        }
    }
}
}

As per below @rpgmaker comment i added this answer

yes you can do using ResolveInfo class

check your file is supported with already installed apps or not

using below code:

private boolean isSupportedFile(File file) throws PackageManager.NameNotFoundException {
    PackageManager pm = mContext.getPackageManager();
    java.io.File mFile = new java.io.File(file.getFileName());
    Uri data = Uri.fromFile(mFile);
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(data, file.getMimeType());
    List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);

    if (resolveInfos != null && resolveInfos.size() > 0) {
        Drawable icon = mContext.getPackageManager().getApplicationIcon(resolveInfos.get(0).activityInfo.packageName);
        Glide.with(mContext).load("").placeholder(icon).into(binding.fileAvatar);
        return true;
    } else {
        Glide.with(mContext).load("").placeholder(R.drawable.avatar_defaultworkspace).into(binding.fileAvatar);
        return false;
    }
}

Rename Pandas DataFrame Index

If you want to use the same mapping for renaming both columns and index you can do:

mapping = {0:'Date', 1:'SM'}
df.index.names = list(map(lambda name: mapping.get(name, name), df.index.names))
df.rename(columns=mapping, inplace=True)

Java - JPA - @Version annotation

Version used to ensure that only one update in a time. JPA provider will check the version, if the expected version already increase then someone else already update the entity so an exception will be thrown.

So updating entity value would be more secure, more optimist.

If the value changes frequent, then you might consider not to use version field. For an example "an entity that has counter field, that will increased everytime a web page accessed"

How to use target in location.href

Why not have a hidden anchor tag on the page with the target set as you need, then simulate clicking it when you need the pop out?

How can I simulate a click to an anchor tag?

This would work in the cases where the window.open did not work

VBA - Run Time Error 1004 'Application Defined or Object Defined Error'

Assgining a value that starts with a "=" will kick in formula evaluation and gave in my case the above mentioned error #1004. Prepending it with a space was the ticket for me.

Big O, how do you calculate/approximate it?

Big O notation is useful because it's easy to work with and hides unnecessary complications and details (for some definition of unnecessary). One nice way of working out the complexity of divide and conquer algorithms is the tree method. Let's say you have a version of quicksort with the median procedure, so you split the array into perfectly balanced subarrays every time.

Now build a tree corresponding to all the arrays you work with. At the root you have the original array, the root has two children which are the subarrays. Repeat this until you have single element arrays at the bottom.

Since we can find the median in O(n) time and split the array in two parts in O(n) time, the work done at each node is O(k) where k is the size of the array. Each level of the tree contains (at most) the entire array so the work per level is O(n) (the sizes of the subarrays add up to n, and since we have O(k) per level we can add this up). There are only log(n) levels in the tree since each time we halve the input.

Therefore we can upper bound the amount of work by O(n*log(n)).

However, Big O hides some details which we sometimes can't ignore. Consider computing the Fibonacci sequence with

a=0;
b=1;
for (i = 0; i <n; i++) {
    tmp = b;
    b = a + b;
    a = tmp;
}

and lets just assume the a and b are BigIntegers in Java or something that can handle arbitrarily large numbers. Most people would say this is an O(n) algorithm without flinching. The reasoning is that you have n iterations in the for loop and O(1) work in side the loop.

But Fibonacci numbers are large, the n-th Fibonacci number is exponential in n so just storing it will take on the order of n bytes. Performing addition with big integers will take O(n) amount of work. So the total amount of work done in this procedure is

1 + 2 + 3 + ... + n = n(n-1)/2 = O(n^2)

So this algorithm runs in quadradic time!

Is there a way to add a gif to a Markdown file?

just upload the .gif file into your base folder of GitHub and edit README.md just use this code

![](name-of-giphy.gif)

Current Subversion revision command

There is also a more convenient (for some) svnversion command.

Output might be a single revision number or something like this (from -h):

  4123:4168     mixed revision working copy
  4168M         modified working copy
  4123S         switched working copy
  4123:4168MS   mixed revision, modified, switched working copy

I use this python code snippet to extract revision information:

import re
import subprocess

p = subprocess.Popen(["svnversion"], stdout = subprocess.PIPE, 
    stderr = subprocess.PIPE)
p.wait()
m = re.match(r'(|\d+M?S?):?(\d+)(M?)S?', p.stdout.read())
rev = int(m.group(2))
if m.group(3) == 'M':
    rev += 1

bind/unbind service example (android)

You can try using this code:

protected ServiceConnection mServerConn = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder binder) {
        Log.d(LOG_TAG, "onServiceConnected");
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        Log.d(LOG_TAG, "onServiceDisconnected");
    }
}

public void start() {
    // mContext is defined upper in code, I think it is not necessary to explain what is it 
    mContext.bindService(intent, mServerConn, Context.BIND_AUTO_CREATE);
    mContext.startService(intent);
}

public void stop() {
    mContext.stopService(new Intent(mContext, ServiceRemote.class));
    mContext.unbindService(mServerConn);
}

Insert entire DataTable into database at once instead of row by row?

I would prefer user defined data type : it is super fast.

Step 1 : Create User Defined Table in Sql Server DB

CREATE TYPE [dbo].[udtProduct] AS TABLE(
  [ProductID] [int] NULL,
  [ProductName] [varchar](50) NULL,
  [ProductCode] [varchar](10) NULL
)
GO

Step 2 : Create Stored Procedure with User Defined Type

CREATE PROCEDURE ProductBulkInsertion 
@product udtProduct readonly
AS
BEGIN
    INSERT INTO Product
    (ProductID,ProductName,ProductCode)
    SELECT ProductID,ProductName,ProductCode
    FROM @product
END

Step 3 : Execute Stored Procedure from c#

SqlCommand sqlcmd = new SqlCommand("ProductBulkInsertion", sqlcon);
sqlcmd.CommandType = CommandType.StoredProcedure;
sqlcmd.Parameters.AddWithValue("@product", productTable);
sqlcmd.ExecuteNonQuery();

Possible Issue : Alter User Defined Table

Actually there is no sql server command to alter user defined type But in management studio you can achieve this from following steps

1.generate script for the type.(in new query window or as a file) 2.delete user defied table. 3.modify the create script and then execute.

how can I copy a conditional formatting in Excel 2010 to other cells, which is based on a other cells content?

I had this problem too and couldn't solve it without using VBA.

In my case I had a table with numbers that I wanted to be formatted and a corresponding table next to it with the desired formatting values.

i.e. While column F contains the values I want to format, the desired formatting for each cell is captured in column Z, expressed as "RED", "AMBER" or "GREEN."

Quick solution below. Manually select the range to which to apply the conditional formatting and then run the macro.

   Sub ConditionalFormatting()
For Each Cell In Selection.Cells
With Cell
    'clean
    .FormatConditions.Delete

    'green rule
    .FormatConditions.Add Type:=xlExpression, Formula1:= _
        "=$Z" & Cell.Row & "=""GREEN"""
    .FormatConditions(.FormatConditions.Count).SetFirstPriority
    With .FormatConditions(1).Font
        .Color = -11489280
        .TintAndShade = 0
    End With
    .FormatConditions(1).StopIfTrue = False

    'amber rule
    .FormatConditions.Add Type:=xlExpression, Formula1:= _
        "=$Z" & Cell.Row & "=""AMBER"""
    .FormatConditions(.FormatConditions.Count).SetFirstPriority
    With .FormatConditions(1).Font
        .ThemeColor = xlThemeColorAccent6
        .TintAndShade = -0.249946592608417
    End With
    .FormatConditions(1).StopIfTrue = False

    'red rule
    .FormatConditions.Add Type:=xlExpression, Formula1:= _
        "=$Z" & Cell.Row & "=""RED"""
    .FormatConditions(.FormatConditions.Count).SetFirstPriority
    With .FormatConditions(1).Font
        .Color = -16776961
        .TintAndShade = 0
    End With
    .FormatConditions(1).StopIfTrue = False
End With

Next Cell

End Sub

How to convert a PNG image to a SVG?

To my surprise, potrace it turns out, can only process black and white. That may be fine for you use case, but some may consider lack of color tracing to be problematic.

Personally, I've had satisfactory results with Vector Magic

Still it's not perfect.

How to get javax.comm API?

you can find Java Communications API 2.0 in below link

http://www.java2s.com/Code/Jar/c/Downloadcomm20jar.htm

Writing html form data to a txt file without the use of a webserver

i made a little change to this code to save entry of a radio button but unable to save the text which appears in text box after selecting the radio button.

the code is below:-

    <!DOCTYPE html>
<html>
<head>
<style>
form * {
  display: block;
  margin: 10px;
}
</style>
<script language="Javascript" >
function download(filename, text) {
  var pom = document.createElement('a');
  pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + 

encodeURIComponent(text));
  pom.setAttribute('download', filename);

  pom.style.display = 'none';
  document.body.appendChild(pom);

  pom.click();

  document.body.removeChild(pom);
}
</script>
</head>
<body>

<form onsubmit="download(this['name'].value, this['text'].value)">
  <input type="text" name="name" value="test.txt">
  <textarea rows=3 cols=50 name="text">PLEASE WRITE ANSWER HERE. </textarea>
<input type="radio" name="radio" value="Option 1" onclick="getElementById('problem').value=this.value;"> Option 1<br>
<input type="radio" name="radio" value="Option 2" onclick="getElementById('problem').value=this.value;"> Option 2<br>
<form onsubmit="download(this['name'].value, this['text'].value)">
<input type="text" name="problem" id="problem">
  <input type="submit" value="SAVE">
</form>
</body>
</html>

What are best practices that you use when writing Objective-C and Cocoa?

Use NSAssert and friends. I use nil as valid object all the time ... especially sending messages to nil is perfectly valid in Obj-C. However if I really want to make sure about the state of a variable, I use NSAssert and NSParameterAssert, which helps to track down problems easily.

How to use Servlets and Ajax?

$.ajax({
type: "POST",
url: "url to hit on servelet",
data:   JSON.stringify(json),
dataType: "json",
success: function(response){
    // we have the response
    if(response.status == "SUCCESS"){
        $('#info').html("Info  has been added to the list successfully.<br>"+
        "The  Details are as follws : <br> Name : ");

    }else{
        $('#info').html("Sorry, there is some thing wrong with the data provided.");
    }
},
 error: function(e){
   alert('Error: ' + e);
 }
});

No Spring WebApplicationInitializer types detected on classpath

I faced this problem and finally resolved. Please make sure that your web.xml and Servlet.xml file should present in web/inf folder.

Also Please add spring jars into Web Deployment assembly in project properties

We might missed out this when setting up the project from beginning.

How do I convert between big-endian and little-endian values in C++?

Here is a basic function to swap to/from little and big endian. It's basic but it doesn't require supplementary libraries.

void endianness_swap(uint32_t& val) {
    uint8_t a, b, c;
    a = (val & 0xFF000000) >> 24;
    b = (val & 0x00FF0000) >> 16;
    c = (val & 0x0000FF00) >> 8;
    val=(val & 0x000000FF) << 24;
    val = val + (c << 16) + (b << 8) + (a);
}

Getting each individual digit from a whole integer

Usually, this problem resolve with using the modulo of a number in a loop or convert a number to a string. For convert a number to a string, you may can use the function itoa, so considering the variant with the modulo of a number in a loop.


Content of a file get_digits.c

$ cat get_digits.c 

#include <stdio.h>
#include <stdlib.h>
#include <math.h>


// return a length of integer
unsigned long int get_number_count_digits(long int number);

// get digits from an integer number into an array
int number_get_digits(long int number, int **digits, unsigned int *len);

// for demo features
void demo_number_get_digits(long int number);


int
main()
{
    demo_number_get_digits(-9999999999999);
    demo_number_get_digits(-10000000000);
    demo_number_get_digits(-1000);
    demo_number_get_digits(-9);
    demo_number_get_digits(0);
    demo_number_get_digits(9);
    demo_number_get_digits(1000);
    demo_number_get_digits(10000000000);
    demo_number_get_digits(9999999999999);
    return EXIT_SUCCESS;
}


unsigned long int
get_number_count_digits(long int number)
{
    if (number < 0)
        number = llabs(number);
    else if (number == 0)
        return 1;

    if (number < 999999999999997)
        return floor(log10(number)) + 1;

    unsigned long int count = 0;
    while (number > 0) {
        ++count;
        number /= 10;
    }
    return count;
}


int
number_get_digits(long int number, int **digits, unsigned int *len)
{
    number = labs(number);

    // termination count digits and size of a array as well as
    *len = get_number_count_digits(number);

    *digits = realloc(*digits, *len * sizeof(int));

    // fill up the array
    unsigned int index = 0;
    while (number > 0) {
        (*digits)[index] = (int)(number % 10);
        number /= 10;
        ++index;
    }

    // reverse the array
    unsigned long int i = 0, half_len = (*len / 2);
    int swap;
    while (i < half_len) {
        swap = (*digits)[i];
        (*digits)[i] = (*digits)[*len - i - 1];
        (*digits)[*len - i - 1] = swap;
         ++i;
    }

    return 0;
}


void
demo_number_get_digits(long int number)
{
    int *digits;
    unsigned int len;

    digits = malloc(sizeof(int));

    number_get_digits(number, &digits, &len);

    printf("%ld --> [", number);
    for (unsigned int i = 0; i < len; ++i) {
        if (i == len - 1)
            printf("%d", digits[i]);
        else
            printf("%d, ", digits[i]);
    }
    printf("]\n");

    free(digits);
}

Demo with the GNU GCC

$~/Downloads/temp$ cc -Wall -Wextra -std=c11 -o run get_digits.c -lm
$~/Downloads/temp$ ./run
-9999999999999 --> [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9]
-10000000000 --> [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
-1000 --> [1, 0, 0, 0]
-9 --> [9]
0 --> [0]
9 --> [9]
1000 --> [1, 0, 0, 0]
10000000000 --> [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
9999999999999 --> [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9]

Demo with the LLVM/Clang

$~/Downloads/temp$ rm run
$~/Downloads/temp$ clang -std=c11 -Wall -Wextra get_digits.c -o run -lm
setivolkylany$~/Downloads/temp$ ./run
-9999999999999 --> [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9]
-10000000000 --> [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
-1000 --> [1, 0, 0, 0]
-9 --> [9]
0 --> [0]
9 --> [9]
1000 --> [1, 0, 0, 0]
10000000000 --> [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
9999999999999 --> [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9]

Testing environment

$~/Downloads/temp$ cc --version | head -n 1
cc (Debian 4.9.2-10) 4.9.2
$~/Downloads/temp$ clang --version
Debian clang version 3.5.0-10 (tags/RELEASE_350/final) (based on LLVM 3.5.0)
Target: x86_64-pc-linux-gnu
Thread model: posix

How to add \newpage in Rmarkdown in a smart way?

Simply \newpage or \pagebreak will work, e.g.

hello world
\newpage
```{r, echo=FALSE}
1+1
```
\pagebreak
```{r, echo=FALSE}
plot(1:10)
```

This solution assumes you are knitting PDF. For HTML, you can achieve a similar effect by adding a tag <P style="page-break-before: always">. Note that you likely won't see a page break in your browser (HTMLs don't have pages per se), but the printing layout will have it.

java.io.FileNotFoundException: (Access is denied)

Also, in some cases is important to check the target folder permissions. To give write permission for the user might be the solution. That worked for me.

set height of imageview as matchparent programmatically

You can use the MATCH_PARENT constant or its numeric value -1.

How to output HTML from JSP <%! ... %> block?

You can do something like this:

<%!
String myMethod(String input) {
    return "test " + input;
}
%>

<%= myMethod("1 2 3") %>

This will output test 1 2 3 to the page.

Android Studio Gradle DSL method not found: 'android()' -- Error(17,0)

I went ahead and downloaded the project from the link you provided: http://javapapers.com/android/android-chat-bubble/

Since this is an old tutorial, you simply need to upgrade the software, gradle, the android build tools and plugin.

Make sure you have the latest Gradle and Android Studio:

build.gradle:

buildscript {
    repositories {
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.2'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

app/build.gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion '23.0.3'

    defaultConfig {
        minSdkVersion 9
        targetSdkVersion 23
        versionCode 1
        versionName '1.0'
    }
}

dependencies {
    compile 'com.android.support:appcompat-v7:23.2.1'
}

Then run gradle:

gradle installDebug

No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization

When I used policy before I set the default authentication scheme into it as well. I had modified the DefaultPolicy so it was slightly different. However the same should work for add policy as well.

services.AddAuthorization(options =>
        {
            options.AddPolicy(DefaultAuthorizedPolicy, policy =>
            {
                policy.Requirements.Add(new TokenAuthRequirement());
                policy.AuthenticationSchemes = new List<string>()
                                {
                                    CookieAuthenticationDefaults.AuthenticationScheme
                                }
            });
        });

Do take into consideration that by Default AuthenticationSchemes property uses a read only list. I think it would be better to implement that instead of List as well.

How to deal with INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES without uninstall?

For what it is worth, I ran into this problem after adding a new plugin to my Cordova project. I had been having cordova do builds and install directly on the device via USB.

I fixed it by uninstalling the app from the device and on the next deploy there were no problems.

Laravel Soft Delete posts

In Laravel 5.5 Soft Deleted works ( for me ).

Data Base

deleted_at Field, default NULL value

Model

use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Model {
    use SoftDeletes;
}

Controller

public function destroy($id)
{
    User::find($id)->delete();
}

ALTER TABLE on dependent column

you can drop the Constraint which is restricting you. If the column has access to other table. suppose a view is accessing the column which you are altering then it wont let you alter the column unless you drop the view. and after making changes you can recreate the view.

enter image description here

What is the syntax for an inner join in LINQ to SQL?

var q=(from pd in dataContext.tblProducts join od in dataContext.tblOrders on pd.ProductID equals od.ProductID orderby od.OrderID select new { od.OrderID,
 pd.ProductID,
 pd.Name,
 pd.UnitPrice,
 od.Quantity,
 od.Price,
 }).ToList(); 

Add Legend to Seaborn point plot

Old question, but there's an easier way.

sns.pointplot(x=x_col,y=y_col,data=df_1,color='blue')
sns.pointplot(x=x_col,y=y_col,data=df_2,color='green')
sns.pointplot(x=x_col,y=y_col,data=df_3,color='red')
plt.legend(labels=['legendEntry1', 'legendEntry2', 'legendEntry3'])

This lets you add the plots sequentially, and not have to worry about any of the matplotlib crap besides defining the legend items.

How can I get browser to prompt to save password?

This work much better for me, because it's 100% ajaxed and the browser detects the login.

<form id="loginform" action="javascript:login(this);" >
 <label for="username">Username</label>
 <input name="username" type="text" value="" required="required" />
 <label for="password">Password</label>
 <input name="password" type="password" value="" required="required" />
 <a href="#" onclick="document.getElementById("loginform").submit();"  >Login</a>
</form>

How to avoid soft keyboard pushing up my layout?

Solved it by setting the naughty EditText:

etSearch = (EditText) view.findViewById(R.id.etSearch);

etSearch.setInputType(InputType.TYPE_NULL);

etSearch.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        etSearch.setInputType(InputType.TYPE_CLASS_TEXT);
        return false;
    }
});

How to know if other threads have finished?

I would suggest looking at the javadoc for Thread class.

You have multiple mechanisms for thread manipulation.

  • Your main thread could join() the three threads serially, and would then not proceed until all three are done.

  • Poll the thread state of the spawned threads at intervals.

  • Put all of the spawned threads into a separate ThreadGroup and poll the activeCount() on the ThreadGroup and wait for it to get to 0.

  • Setup a custom callback or listener type of interface for inter-thread communication.

I'm sure there are plenty of other ways I'm still missing.

What is path of JDK on Mac ?

On my Mac:

/System/Library/Frameworks/JavaVM.framework/Home/

btw, did you tried which java?

How do I turn off autocommit for a MySQL client?

Instead of switching autocommit off manually at restore time you can already dump your MySQL data in a way that includes all necessary statements right into your SQL file.

The command line parameter for mysqldump is --no-autocommit. You might also consider to add --opt which sets a combination of other parameters to speed up restore operations.

Here is an example for a complete mysqldump command line as I use it, containing --no-autocommit and --opt:

mysqldump -hlocalhost -uMyUser -p'MyPassword' --no-autocommit --opt --default-character-set=utf8 --quote-names  MyDbName  >  dump.sql

For details of these parameters see the reference of mysqldump

SQL Server Restore Error - Access is Denied

Got problem like this. Error caused by enabled compression on SQL Server folders.

how to merge 200 csv files in Python

You could import csv then loop through all the CSV files reading them into a list. Then write the list back out to disk.

import csv

rows = []

for f in (file1, file2, ...):
    reader = csv.reader(open("f", "rb"))

    for row in reader:
        rows.append(row)

writer = csv.writer(open("some.csv", "wb"))
writer.writerows("\n".join(rows))

The above is not very robust as it has no error handling nor does it close any open files. This should work whether or not the the individual files have one or more rows of CSV data in them. Also I did not run this code, but it should give you an idea of what to do.

ORA-12516, TNS:listener could not find available handler

You opened a lot of connections and that's the issue. I think in your code, you did not close the opened connection.

A database bounce could temporarily solve, but will re-appear when you do consecutive execution. Also, it should be verified the number of concurrent connections to the database. If maximum DB processes parameter has been reached this is a common symptom.

Courtesy of this thread: https://community.oracle.com/thread/362226?tstart=-1

Delete with Join in MySQL

One solution is to use subquery

DELETE FROM posts WHERE post_id in (SELECT post_id FROM posts p
INNER JOIN projects prj ON p.project_id = prj.project_id 
INNER JOIN clients c on prj.client_id = c.client_id WHERE c.client_id = :client_id 
);

The subquery returns the ID that need to be deleted; all three tables are connected using joins and only those records are deleted that meets the filter condition (in yours case i.e. client_id in the where clause).

Javascript negative number

This is an old question but it has a lot of views so I think that is important to update it.

ECMAScript 6 brought the function Math.sign(), which returns the sign of a number (1 if it's positive, -1 if it's negative) or NaN if it is not a number. Reference

You could use it as:

var number = 1;

if(Math.sign(number) === 1){
    alert("I'm positive");
}else if(Math.sign(number) === -1){
    alert("I'm negative");
}else{
    alert("I'm not a number");
}

How can I put the current running linux process in background?

Suspend the process with CTRL+Z then use the command bg to resume it in background. For example:

sleep 60
^Z  #Suspend character shown after hitting CTRL+Z
[1]+  Stopped  sleep 60  #Message showing stopped process info
bg  #Resume current job (last job stopped)

More about job control and bg usage in bash manual page:

JOB CONTROL
Typing the suspend character (typically ^Z, Control-Z) while a process is running causes that process to be stopped and returns control to bash. [...] The user may then manipulate the state of this job, using the bg command to continue it in the background, [...]. A ^Z takes effect immediately, and has the additional side effect of causing pending output and typeahead to be discarded.

bg [jobspec ...]
Resume each suspended job jobspec in the background, as if it had been started with &. If jobspec is not present, the shell's notion of the current job is used.

EDIT

To start a process where you can even kill the terminal and it still carries on running

nohup [command] [-args] > [filename] 2>&1 &

e.g.

nohup /home/edheal/myprog -arg1 -arg2 > /home/edheal/output.txt 2>&1 &

To just ignore the output (not very wise) change the filename to /dev/null

To get the error message set to a different file change the &1 to a filename.

In addition: You can use the jobs command to see an indexed list of those backgrounded processes. And you can kill a backgrounded process by running kill %1 or kill %2 with the number being the index of the process.

Implement a simple factory pattern with Spring 3 annotations

Following answer of DruidKuma

Litte refactor of his factory with autowired constructor:

@Service
public class MyServiceFactory {

    private static final Map<String, MyService> myServiceCache = new HashMap<>();

    @Autowired
    private MyServiceFactory(List<MyService> services) {
        for(MyService service : services) {
            myServiceCache.put(service.getType(), service);
        }
    }

    public static MyService getService(String type) {
        MyService service = myServiceCache.get(type);
        if(service == null) throw new RuntimeException("Unknown service type: " + type);
        return service;
    }
}

IEnumerable vs List - What to Use? How do they work?

Nobody mentioned one crucial difference, ironically answered on a question closed as a duplicated of this.

IEnumerable is read-only and List is not.

See Practical difference between List and IEnumerable

What is the difference between the dot (.) operator and -> in C++?

Note that the -> operator cannot be used for certain things, for instance, accessing operator[].

#include <vector>

int main()
{
   std::vector<int> iVec;
   iVec.push_back(42);
   std::vector<int>* iVecPtr = &iVec;

   //int i = iVecPtr->[0]; // Does not compile
   int i = (*iVecPtr)[0]; // Compiles.
}

How to change cursor from pointer to finger using jQuery?

$('selector').css('cursor', 'pointer'); // 'default' to revert

I know that may be confusing per your original question, but the "finger" cursor is actually called "pointer".

The normal arrow cursor is just "default".

all possible default pointer looks DEMO

String formatting: % vs. .format vs. string literal

Assuming you're using Python's logging module, you can pass the string formatting arguments as arguments to the .debug() method rather than doing the formatting yourself:

log.debug("some debug info: %s", some_info)

which avoids doing the formatting unless the logger actually logs something.

How to get the fragment instance from the FragmentActivity?

To get the fragment instance in a class that extends FragmentActivity:

MyclassFragment instanceFragment=
    (MyclassFragment)getSupportFragmentManager().findFragmentById(R.id.idFragment);

To get the fragment instance in a class that extends Fragment:

MyclassFragment instanceFragment =  
    (MyclassFragment)getFragmentManager().findFragmentById(R.id.idFragment);

Java ArrayList for integers

you should not use Integer[] array inside the list as arraylist itself is a kind of array. Just leave the [] and it should work