Programs & Examples On #Mod rails

Android : Capturing HTTP Requests with non-rooted android device

You could install Charles - an HTTP proxy / HTTP monitor / Reverse Proxy that enables a developer to view all of the HTTP and SSL / HTTPS traffic between their machine and the Internet - on your PC or MAC.

Config steps:

  • Let your phone and PC or MAC in a same LAN
  • Launch Charles which you installed (default proxy port is 8888)
  • Setup your phone's wifi configuration: set the ip of delegate to your PC or MAC's ip, port of delegate to 8888
  • Lauch your app in your phone. And monitor http requests on Charles.

Execute command on all files in a directory

The following bash code will pass $file to command where $file will represent every file in /dir

for file in /dir/*
do
  cmd [option] "$file" >> results.out
done

Example

el@defiant ~/foo $ touch foo.txt bar.txt baz.txt
el@defiant ~/foo $ for i in *.txt; do echo "hello $i"; done
hello bar.txt
hello baz.txt
hello foo.txt

How do I write dispatch_after GCD in Swift 3, 4, and 5?

try this

let when = DispatchTime.now() + 1.5
    DispatchQueue.main.asyncAfter(deadline: when) {
        //some code
    }

Spring Boot application can't resolve the org.springframework.boot package

Delete the repository folder from "C:\Users\usename.m2" and create again or update maven project.

Watching variables contents in Eclipse IDE

This video does an excellent job of showing you how to set breakpoints and watch variables in the Eclipse Debugger. http://youtu.be/9gAjIQc4bPU

How can I exclude multiple folders using Get-ChildItem -exclude?

I apologize if this answer seems like duplication of previous answers. I just wanted to show an updated (tested through POSH 5.0) way of solving this. The previous answers were pre-3.0 and not as efficient as modern solutions.

The documentation isn't clear on this, but Get-ChildItem -Recurse -Exclude only matches exclusion on the leaf (Split-Path $_.FullName -Leaf), not the parent path (Split-Path $_.FullName -Parent). Matching the exclusion will just remove the item with the matching leaf; Get-ChildItem will still recurse into that leaf.

In POSH 1.0 or 2.0

Get-ChildItem -Path $folder -Recurse  | 
          ? { $_.PsIsContainer -and $_.FullName -inotmatch 'archive' }

Note: Same answer as @CB.

In POSH 3.0+

Get-ChildItem -Path $folder -Directory -Recurse  | 
          ? { $_.FullName -inotmatch 'archive' }

Note: Updated answer from @CB.

Multiple Excludes

This specifically targets directories while excluding leafs with the Exclude parameter, and parents with the ilike (case-insensitive like) comparison:

#Requires -Version 3.0
[string[]]$Paths = @('C:\Temp', 'D:\Temp')
[string[]]$Excludes = @('*archive*', '*Archive*', '*ARCHIVE*', '*archival*')

$files = Get-ChildItem $Paths -Directory -Recurse -Exclude $Excludes | %{ 
    $allowed = $true
    foreach ($exclude in $Excludes) { 
        if ((Split-Path $_.FullName -Parent) -ilike $exclude) { 
            $allowed = $false
            break
        }
    }
    if ($allowed) {
        $_
    }
}

Note: If you want your $Excludes to be case-sensitive, there are two steps:

  1. Remove the Exclude parameter from Get-ChildItem.
  2. Change the first if condition to:
    • if ($_.FullName -clike $exclude) {

Note: This code has redundancy that I would never implement in production. You should simplify this quite a bit to fit your exact needs. It serves well as a verbose example.

A simple explanation of Naive Bayes Classification

Ram Narasimhan explained the concept very nicely here below is an alternative explanation through the code example of Naive Bayes in action
It uses an example problem from this book on page 351
This is the data set that we will be using
enter image description here
In the above dataset if we give the hypothesis = {"Age":'<=30', "Income":"medium", "Student":'yes' , "Creadit_Rating":'fair'} then what is the probability that he will buy or will not buy a computer.
The code below exactly answers that question.
Just create a file called named new_dataset.csv and paste the following content.

Age,Income,Student,Creadit_Rating,Buys_Computer
<=30,high,no,fair,no
<=30,high,no,excellent,no
31-40,high,no,fair,yes
>40,medium,no,fair,yes
>40,low,yes,fair,yes
>40,low,yes,excellent,no
31-40,low,yes,excellent,yes
<=30,medium,no,fair,no
<=30,low,yes,fair,yes
>40,medium,yes,fair,yes
<=30,medium,yes,excellent,yes
31-40,medium,no,excellent,yes
31-40,high,yes,fair,yes
>40,medium,no,excellent,no

Here is the code the comments explains everything we are doing here! [python]

import pandas as pd 
import pprint 

class Classifier():
    data = None
    class_attr = None
    priori = {}
    cp = {}
    hypothesis = None


    def __init__(self,filename=None, class_attr=None ):
        self.data = pd.read_csv(filename, sep=',', header =(0))
        self.class_attr = class_attr

    '''
        probability(class) =    How many  times it appears in cloumn
                             __________________________________________
                                  count of all class attribute
    '''
    def calculate_priori(self):
        class_values = list(set(self.data[self.class_attr]))
        class_data =  list(self.data[self.class_attr])
        for i in class_values:
            self.priori[i]  = class_data.count(i)/float(len(class_data))
        print "Priori Values: ", self.priori

    '''
        Here we calculate the individual probabilites 
        P(outcome|evidence) =   P(Likelihood of Evidence) x Prior prob of outcome
                               ___________________________________________
                                                    P(Evidence)
    '''
    def get_cp(self, attr, attr_type, class_value):
        data_attr = list(self.data[attr])
        class_data = list(self.data[self.class_attr])
        total =1
        for i in range(0, len(data_attr)):
            if class_data[i] == class_value and data_attr[i] == attr_type:
                total+=1
        return total/float(class_data.count(class_value))

    '''
        Here we calculate Likelihood of Evidence and multiple all individual probabilities with priori
        (Outcome|Multiple Evidence) = P(Evidence1|Outcome) x P(Evidence2|outcome) x ... x P(EvidenceN|outcome) x P(Outcome)
        scaled by P(Multiple Evidence)
    '''
    def calculate_conditional_probabilities(self, hypothesis):
        for i in self.priori:
            self.cp[i] = {}
            for j in hypothesis:
                self.cp[i].update({ hypothesis[j]: self.get_cp(j, hypothesis[j], i)})
        print "\nCalculated Conditional Probabilities: \n"
        pprint.pprint(self.cp)

    def classify(self):
        print "Result: "
        for i in self.cp:
            print i, " ==> ", reduce(lambda x, y: x*y, self.cp[i].values())*self.priori[i]

if __name__ == "__main__":
    c = Classifier(filename="new_dataset.csv", class_attr="Buys_Computer" )
    c.calculate_priori()
    c.hypothesis = {"Age":'<=30', "Income":"medium", "Student":'yes' , "Creadit_Rating":'fair'}

    c.calculate_conditional_probabilities(c.hypothesis)
    c.classify()

output:

Priori Values:  {'yes': 0.6428571428571429, 'no': 0.35714285714285715}

Calculated Conditional Probabilities: 

{
 'no': {
        '<=30': 0.8,
        'fair': 0.6, 
        'medium': 0.6, 
        'yes': 0.4
        },
'yes': {
        '<=30': 0.3333333333333333,
        'fair': 0.7777777777777778,
        'medium': 0.5555555555555556,
        'yes': 0.7777777777777778
      }
}

Result: 
yes  ==>  0.0720164609053
no  ==>  0.0411428571429

Hope it helps in better understanding the problem

peace

What does the Ellipsis object do?

From the Python documentation:

This object is commonly used by slicing (see Slicings). It supports no special operations. There is exactly one ellipsis object, named Ellipsis (a built-in name). type(Ellipsis)() produces the Ellipsis singleton.

It is written as Ellipsis or ....

Return value in a Bash function

The return statement sets the exit code of the function, much the same as exit will do for the entire script.

The exit code for the last command is always available in the $? variable.

function fun1(){
  return 34
}

function fun2(){
  local res=$(fun1)
  echo $? # <-- Always echos 0 since the 'local' command passes.

  res=$(fun1)
  echo $?  #<-- Outputs 34
}

Why does Boolean.ToString output "True" and not "true"

Only people from Microsoft can really answer that question. However, I'd like to offer some fun facts about it ;)

First, this is what it says in MSDN about the Boolean.ToString() method:

Return Value

Type: System.String

TrueString if the value of this instance is true, or FalseString if the value of this instance is false.

Remarks

This method returns the constants "True" or "False". Note that XML is case-sensitive, and that the XML specification recognizes "true" and "false" as the valid set of Boolean values. If the String object returned by the ToString() method is to be written to an XML file, its String.ToLower method should be called first to convert it to lowercase.

Here comes the fun fact #1: it doesn't return TrueString or FalseString at all. It uses hardcoded literals "True" and "False". Wouldn't do you any good if it used the fields, because they're marked as readonly, so there's no changing them.

The alternative method, Boolean.ToString(IFormatProvider) is even funnier:

Remarks

The provider parameter is reserved. It does not participate in the execution of this method. This means that the Boolean.ToString(IFormatProvider) method, unlike most methods with a provider parameter, does not reflect culture-specific settings.

What's the solution? Depends on what exactly you're trying to do. Whatever it is, I bet it will require a hack ;)

How do I render a Word document (.doc, .docx) in the browser using JavaScript?

No browsers currently have the code necessary to render Word Documents, and as far as I know, there are no client-side libraries that currently exist for rendering them either.

However, if you only need to display the Word Document, but don't need to edit it, you can use Google Documents' Viewer via an <iframe> to display a remotely hosted .doc/.docx.

<iframe src="https://docs.google.com/gview?url=http://remote.url.tld/path/to/document.doc&embedded=true"></iframe>

Solution adapted from "How to display a word document using fancybox".

Example:

JSFiddle

However, if you'd rather have native support, in most, if not all browsers, I'd recommend resaving the .doc/.docx as a PDF file Those can also be independently rendered using PDF.js by Mozilla.

Edit:

Huge thanks to fatbotdesigns for posting the Microsoft Office 365 viewer in the comments.

<iframe src='https://view.officeapps.live.com/op/embed.aspx?src=http://remote.url.tld/path/to/document.doc' width='1366px' height='623px' frameborder='0'>This is an embedded <a target='_blank' href='http://office.com'>Microsoft Office</a> document, powered by <a target='_blank' href='http://office.com/webapps'>Office Online</a>.</iframe>

One more important caveat to keep in mind, as pointed out by lightswitch05, is that this will upload your document to a third-party server. If this is unacceptable, then this method of display isn't the proper course of action.

Live Examples:

Google Docs Viewer

Microsoft Office Viewer

JPA: difference between @JoinColumn and @PrimaryKeyJoinColumn?

What happens if I promote the column to be a/the PK, too (a.k.a. identifying relationship)? As the column is now the PK, I must tag it with @Id (...).

This enhanced support of derived identifiers is actually part of the new stuff in JPA 2.0 (see the section 2.4.1 Primary Keys Corresponding to Derived Identities in the JPA 2.0 specification), JPA 1.0 doesn't allow Id on a OneToOne or ManyToOne. With JPA 1.0, you'd have to use PrimaryKeyJoinColumn and also define a Basic Id mapping for the foreign key column.

Now the question is: are @Id + @JoinColumn the same as just @PrimaryKeyJoinColumn?

You can obtain a similar result but using an Id on OneToOne or ManyToOne is much simpler and is the preferred way to map derived identifiers with JPA 2.0. PrimaryKeyJoinColumn might still be used in a JOINED inheritance strategy. Below the relevant section from the JPA 2.0 specification:

11.1.40 PrimaryKeyJoinColumn Annotation

The PrimaryKeyJoinColumn annotation specifies a primary key column that is used as a foreign key to join to another table.

The PrimaryKeyJoinColumn annotation is used to join the primary table of an entity subclass in the JOINED mapping strategy to the primary table of its superclass; it is used within a SecondaryTable annotation to join a secondary table to a primary table; and it may be used in a OneToOne mapping in which the primary key of the referencing entity is used as a foreign key to the referenced entity[108].

...

If no PrimaryKeyJoinColumn annotation is specified for a subclass in the JOINED mapping strategy, the foreign key columns are assumed to have the same names as the primary key columns of the primary table of the superclass.

...

Example: Customer and ValuedCustomer subclass

@Entity
@Table(name="CUST")
@Inheritance(strategy=JOINED)
@DiscriminatorValue("CUST")
public class Customer { ... }

@Entity
@Table(name="VCUST")
@DiscriminatorValue("VCUST")
@PrimaryKeyJoinColumn(name="CUST_ID")
public class ValuedCustomer extends Customer { ... }

[108] The derived id mechanisms described in section 2.4.1.1 are now to be preferred over PrimaryKeyJoinColumn for the OneToOne mapping case.

See also


This source http://weblogs.java.net/blog/felipegaucho/archive/2009/10/24/jpa-join-table-additional-state states that using @ManyToOne and @Id works with JPA 1.x. Who's correct now?

The author is using a pre release JPA 2.0 compliant version of EclipseLink (version 2.0.0-M7 at the time of the article) to write an article about JPA 1.0(!). This article is misleading, the author is using something that is NOT part of JPA 1.0.

For the record, support of Id on OneToOne and ManyToOne has been added in EclipseLink 1.1 (see this message from James Sutherland, EclipseLink comitter and main contributor of the Java Persistence wiki book). But let me insist, this is NOT part of JPA 1.0.

Copying files from server to local computer using SSH

Make sure the scp command is available on both sides - both on the client and on the server.

BOTH Server and Client, otherwise you will encounter this kind of (weird)error message on your client: scp: command not found or something similar even though though you have it all configured locally.

How to Auto resize HTML table cell to fit the text size

Well, me also I was struggling with this issue: this is how I solved it: apply table-layout: auto; to the <table> element.

How can I add to a List's first position?

Of course, Insert or AddFirst will do the trick, but you could always do:

myList.Reverse();
myList.Add(item);
myList.Reverse();

Jquery assiging class to th in a table

You had thead in your selector, but there is no thead in your table. Also you had your selectors backwards. As you mentioned above, you wanted to be adding the tr class to the th, not vice-versa (although your comment seems to contradict what you wrote up above).

$('tr th').each(function(index){     if($('tr td').eq(index).attr('class') != ''){         // get the class of the td         var tdClass = $('tr td').eq(index).attr('class');         // add it to this th         $(this).addClass(tdClass );     } }); 

Fiddle

How do I execute .js files locally in my browser?

If you're using Google Chrome you can use the Chrome Dev Editor: https://github.com/dart-lang/chromedeveditor

Detect change to selected date with bootstrap-datepicker

Try with below code sample.it is working for me

var date_input_field = $('input[name="date"]');
    date_input_field .datepicker({
        dateFormat: '/dd/mm/yyyy',
        container: container,
        todayHighlight: true,
        autoclose: true,
    }).on('change', function(selected){
        alert("startDate..."+selected.timeStamp);
    });

How do I resolve git saying "Commit your changes or stash them before you can merge"?

In my case, I backed up and then deleted the file that Git was complaining about, committed, then I was able to finally check out another branch.

I then replaced the file, copied back in the contents and continued as though nothing happened.

JPA CriteriaBuilder - How to use "IN" comparison operator

If I understand well, you want to Join ScheduleRequest with User and apply the in clause to the userName property of the entity User.

I'd need to work a bit on this schema. But you can try with this trick, that is much more readable than the code you posted, and avoids the Join part (because it handles the Join logic outside the Criteria Query).

List<String> myList = new ArrayList<String> ();
for (User u : usersList) {
    myList.add(u.getUsername());
}
Expression<String> exp = scheduleRequest.get("createdBy");
Predicate predicate = exp.in(myList);
criteria.where(predicate);

In order to write more type-safe code you could also use Metamodel by replacing this line:

Expression<String> exp = scheduleRequest.get("createdBy");

with this:

Expression<String> exp = scheduleRequest.get(ScheduleRequest_.createdBy);

If it works, then you may try to add the Join logic into the Criteria Query. But right now I can't test it, so I prefer to see if somebody else wants to try.


Not a perfect answer though may be code snippets might help.

public <T> List<T> findListWhereInCondition(Class<T> clazz,
            String conditionColumnName, Serializable... conditionColumnValues) {
        QueryBuilder<T> queryBuilder = new QueryBuilder<T>(clazz);
        addWhereInClause(queryBuilder, conditionColumnName,
                conditionColumnValues);
        queryBuilder.select();
        return queryBuilder.getResultList();

    }


private <T> void addWhereInClause(QueryBuilder<T> queryBuilder,
            String conditionColumnName, Serializable... conditionColumnValues) {

        Path<Object> path = queryBuilder.root.get(conditionColumnName);
        In<Object> in = queryBuilder.criteriaBuilder.in(path);
        for (Serializable conditionColumnValue : conditionColumnValues) {
            in.value(conditionColumnValue);
        }
        queryBuilder.criteriaQuery.where(in);

    }

Passing string to a function in C - with or without pointers?

The accepted convention of passing C-strings to functions is to use a pointer:

void function(char* name)

When the function modifies the string you should also pass in the length:

void function(char* name, size_t name_length)

Your first example:

char *functionname(char *string name[256])

passes an array of pointers to strings which is not what you need at all.

Your second example:

char functionname(char string[256])

passes an array of chars. The size of the array here doesn't matter and the parameter will decay to a pointer anyway, so this is equivalent to:

char functionname(char *string)

See also this question for more details on array arguments in C.

Does C have a "foreach" loop construct?

There is no foreach in C.

You can use a for loop to loop through the data but the length needs to be know or the data needs to be terminated by a know value (eg. null).

char* nullTerm;
nullTerm = "Loop through my characters";

for(;nullTerm != NULL;nullTerm++)
{
    //nullTerm will now point to the next character.
}

Using two values for one switch case statement

Java 12 and above

switch (name) {
    case text1, text4 -> // do something ;
    case text2, text3, text 5 -> // do something else ;
    default -> // default case ;
}

You can also assign a value through the switch case expression :

String text = switch (name) {
    case text1, text4 -> "hello" ;
    case text2, text3, text5 -> "world" ;
    default -> "goodbye";
};

"yield" keyword

It allows you to return a value by the switch case expression

String text = switch (name) {
    case text1, text4 ->
        yield "hello";
    case text2, text3, text5 ->
        yield "world";
    default ->
        yield "goodbye";
};

Parsing huge logfiles in Node.js - read in line-by-line

I have made a node module to read large file asynchronously text or JSON. Tested on large files.

var fs = require('fs')
, util = require('util')
, stream = require('stream')
, es = require('event-stream');

module.exports = FileReader;

function FileReader(){

}

FileReader.prototype.read = function(pathToFile, callback){
    var returnTxt = '';
    var s = fs.createReadStream(pathToFile)
    .pipe(es.split())
    .pipe(es.mapSync(function(line){

        // pause the readstream
        s.pause();

        //console.log('reading line: '+line);
        returnTxt += line;        

        // resume the readstream, possibly from a callback
        s.resume();
    })
    .on('error', function(){
        console.log('Error while reading file.');
    })
    .on('end', function(){
        console.log('Read entire file.');
        callback(returnTxt);
    })
);
};

FileReader.prototype.readJSON = function(pathToFile, callback){
    try{
        this.read(pathToFile, function(txt){callback(JSON.parse(txt));});
    }
    catch(err){
        throw new Error('json file is not valid! '+err.stack);
    }
};

Just save the file as file-reader.js, and use it like this:

var FileReader = require('./file-reader');
var fileReader = new FileReader();
fileReader.readJSON(__dirname + '/largeFile.json', function(jsonObj){/*callback logic here*/});

Convert one date format into another in PHP

The Basics

The simplist way to convert one date format into another is to use strtotime() with date(). strtotime() will convert the date into a Unix Timestamp. That Unix Timestamp can then be passed to date() to convert it to the new format.

$timestamp = strtotime('2008-07-01T22:35:17.02');
$new_date_format = date('Y-m-d H:i:s', $timestamp);

Or as a one-liner:

$new_date_format = date('Y-m-d H:i:s', strtotime('2008-07-01T22:35:17.02'));

Keep in mind that strtotime() requires the date to be in a valid format. Failure to provide a valid format will result in strtotime() returning false which will cause your date to be 1969-12-31.

Using DateTime()

As of PHP 5.2, PHP offered the DateTime() class which offers us more powerful tools for working with dates (and time). We can rewrite the above code using DateTime() as so:

$date = new DateTime('2008-07-01T22:35:17.02');
$new_date_format = $date->format('Y-m-d H:i:s');

Working with Unix timestamps

date() takes a Unix timeatamp as its second parameter and returns a formatted date for you:

$new_date_format = date('Y-m-d H:i:s', '1234567890');

DateTime() works with Unix timestamps by adding an @ before the timestamp:

$date = new DateTime('@1234567890');
$new_date_format = $date->format('Y-m-d H:i:s');

If the timestamp you have is in milliseconds (it may end in 000 and/or the timestamp is thirteen characters long) you will need to convert it to seconds before you can can convert it to another format. There's two ways to do this:

  • Trim the last three digits off using substr()

Trimming the last three digits can be acheived several ways, but using substr() is the easiest:

$timestamp = substr('1234567899000', -3);
  • Divide the substr by 1000

You can also convert the timestamp into seconds by dividing by 1000. Because the timestamp is too large for 32 bit systems to do math on you will need to use the BCMath library to do the math as strings:

$timestamp = bcdiv('1234567899000', '1000');

To get a Unix Timestamp you can use strtotime() which returns a Unix Timestamp:

$timestamp = strtotime('1973-04-18');

With DateTime() you can use DateTime::getTimestamp()

$date = new DateTime('2008-07-01T22:35:17.02');
$timestamp = $date->getTimestamp();

If you're running PHP 5.2 you can use the U formatting option instead:

$date = new DateTime('2008-07-01T22:35:17.02');
$timestamp = $date->format('U');

Working with non-standard and ambiguous date formats

Unfortunately not all dates that a developer has to work with are in a standard format. Fortunately PHP 5.3 provided us with a solution for that. DateTime::createFromFormat() allows us to tell PHP what format a date string is in so it can be successfully parsed into a DateTime object for further manipulation.

$date = DateTime::createFromFormat('F-d-Y h:i A', 'April-18-1973 9:48 AM');
$new_date_format = $date->format('Y-m-d H:i:s');

In PHP 5.4 we gained the ability to do class member access on instantiation has been added which allows us to turn our DateTime() code into a one-liner:

$new_date_format = (new DateTime('2008-07-01T22:35:17.02'))->format('Y-m-d H:i:s');

$new_date_format = DateTime::createFromFormat('F-d-Y h:i A', 'April-18-1973 9:48 AM')->format('Y-m-d H:i:s');

selecting rows with id from another table

Try this (subquery):

SELECT * FROM terms WHERE id IN 
   (SELECT term_id FROM terms_relation WHERE taxonomy = "categ")

Or you can try this (JOIN):

SELECT t.* FROM terms AS t 
   INNER JOIN terms_relation AS tr 
   ON t.id = tr.term_id AND tr.taxonomy = "categ"

If you want to receive all fields from two tables:

SELECT t.id, t.name, t.slug, tr.description, tr.created_at, tr.updated_at 
  FROM terms AS t 
   INNER JOIN terms_relation AS tr 
   ON t.id = tr.term_id AND tr.taxonomy = "categ"

MySQL DAYOFWEEK() - my week begins with monday

Could write a udf and take a value to tell it which day of the week should be 1 would look like this (drawing on answer from John to use MOD instead of CASE):

DROP FUNCTION IF EXISTS `reporting`.`udfDayOfWeek`;
DELIMITER |
CREATE FUNCTION `reporting`.`udfDayOfWeek` (
  _date DATETIME,
  _firstDay TINYINT
) RETURNS tinyint(4)
FUNCTION_BLOCK: BEGIN
  DECLARE _dayOfWeek, _offset TINYINT;
  SET _offset = 8 - _firstDay;
  SET _dayOfWeek = (DAYOFWEEK(_date) + _offset) MOD 7;
  IF _dayOfWeek = 0 THEN
    SET _dayOfWeek = 7;
  END IF;
  RETURN _dayOfWeek;
END FUNCTION_BLOCK

To call this function to give you the current day of week value when your week starts on a Tuesday for instance, you'd call:

SELECT udfDayOfWeek(NOW(), 3);

Nice thing about having it as a udf is you could also call it on a result set field like this:

SELECT
  udfDayOfWeek(p.SignupDate, 3) AS SignupDayOfWeek,
  p.FirstName,
  p.LastName
FROM Profile p;

How do I get the scroll position of a document?

To get the actual scrollable height of the areas scrolled by the window scrollbar, I used $('body').prop('scrollHeight'). This seems to be the simplest working solution, but I haven't checked extensively for compatibility. Emanuele Del Grande notes on another solution that this probably won't work for IE below 8.

Most of the other solutions work fine for scrollable elements, but this works for the whole window. Notably, I had the same issue as Michael for Ankit's solution, namely, that $(document).prop('scrollHeight') is returning undefined.

Pandas DataFrame to List of Lists

You could access the underlying array and call its tolist method:

>>> df = pd.DataFrame([[1,2,3],[3,4,5]])
>>> lol = df.values.tolist()
>>> lol
[[1L, 2L, 3L], [3L, 4L, 5L]]

Android Writing Logs to text File

This may be late but hope this may help.. Try this....

public void writefile()
    {
        File externalStorageDir = Environment.getExternalStorageDirectory();
        File myFile = new File(externalStorageDir , "yourfilename.txt");

        if(myFile.exists())
        {
           try
           {

        FileOutputStream fostream = new FileOutputStream(myFile);
        OutputStreamWriter oswriter = new OutputStreamWriter(fostream); 
        BufferedWriter bwriter = new BufferedWriter(oswriter);   
        bwriter.write("Hi welcome ");
        bwriter.newLine();            
        bwriter.close(); 
        oswriter.close(); 
        fostream.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
        else
        {
            try {
                myFile.createNewFile();
            }
            catch (IOException e) 
            {
                e.printStackTrace();
            }
        }

here bfwritter.newline writes your text into the file. And add the permission

 <uses-permission android:name = "android.permission.WRITE_EXTERNAL_STORAGE"/>

in your manifest file without fail.

php foreach with multidimensional array

This would have been a comment under Brad's answer, but I don't have a high enough reputation.

Recently I found that I needed the key of the multidimensional array too, i.e., it wasn't just an index for the array, in the foreach loop.

In order to achieve that, you could use something very similar to the accepted answer, but instead split the key and value as follows

foreach ($mda as $mdaKey => $mdaData) {
    echo $mdaKey . ": " . $mdaData["value"];
}

Hope that helps someone.

Installing R on Mac - Warning messages: Setting LC_CTYPE failed, using "C"

Setting locales in terminal resolved the issue for me. Open the terminal and

  1. Check if locale settings are missing

    > locale
    LANG=
    LC_COLLATE="C"
    LC_CTYPE="UTF-8"
    LC_MESSAGES="C"
    LC_MONETARY="C"
    LC_NUMERIC="C"
    LC_TIME="C"
    LC_ALL=
    
  2. Edit ~/.profile or ~/.bashrc

    export LANG=en_US.UTF-8
    export LC_ALL=en_US.UTF-8
    
  3. Run . ~/.profile or . ~/.bashrc to read from the file.

  4. Open a new terminal window and check that the locales are properly set

    > locale
    LANG="en_US.UTF-8"
    LC_COLLATE="en_US.UTF-8"
    LC_CTYPE="en_US.UTF-8"
    LC_MESSAGES="en_US.UTF-8"
    LC_MONETARY="en_US.UTF-8"
    LC_NUMERIC="en_US.UTF-8"
    LC_TIME="en_US.UTF-8"
    LC_ALL="en_US.UTF-8"
    

When to use the different log levels

I totally agree with the others, and think that GrayWizardx said it best.

All that I can add is that these levels generally correspond to their dictionary definitions, so it can't be that hard. If in doubt, treat it like a puzzle. For your particular project, think of everything that you might want to log.

Now, can you figure out what might be fatal? You know what fatal means, don't you? So, which items on your list are fatal.

Ok, that's fatal dealt with, now let's look at errors ... rinse and repeat.

Below Fatal, or maybe Error, I would suggest that more information is always better than less, so err "upwards". Not sure if it's Info or Warning? Then make it a warning.

I do think that Fatal and error ought to be clear to all of us. The others might be fuzzier, but it is arguably less vital to get them right.

Here are some examples:

Fatal - can't allocate memory, database, etc - can't continue.

Error - no reply to message, transaction aborted, can't save file, etc.

Warning - resource allocation reaches X% (say 80%) - that is a sign that you might want to re-dimension your.

Info - user logged in/out, new transaction, file crated, new d/b field, or field deleted.

Debug - dump of internal data structure, Anything Trace level with file name & line number.
Trace - action succeeded/failed, d/b updated.

Pass multiple parameters to rest API - Spring

Multiple parameters can be given like below,

    @RequestMapping(value = "/mno/{objectKey}", method = RequestMethod.GET, produces = "application/json")
    public List<String> getBook(HttpServletRequest httpServletRequest, @PathVariable(name = "objectKey") String objectKey
      , @RequestParam(value = "id", defaultValue = "false")String id,@RequestParam(value = "name", defaultValue = "false") String name) throws Exception {
               //logic
}

@Autowired and static method

Use AppContext. Make sure you create a bean in your context file.

private final static Foo foo = AppContext.getApplicationContext().getBean(Foo.class);

public static void randomMethod() {
     foo.doStuff();
}

What is an unsigned char?

signed char and unsigned char both represent 1byte, but they have different ranges.

   Type        |      range
-------------------------------
signed char    |  -128 to +127
unsigned char  |     0 to 255

In signed char if we consider char letter = 'A', 'A' is represent binary of 65 in ASCII/Unicode, If 65 can be stored, -65 also can be stored. There are no negative binary values in ASCII/Unicode there for no need to worry about negative values.

Example

#include <stdio.h>

int main()
{
    signed char char1 = 255;
    signed char char2 = -128;
    unsigned char char3 = 255;
    unsigned char char4 = -128;

    printf("Signed char(255) : %d\n",char1);
    printf("Unsigned char(255) : %d\n",char3);

    printf("\nSigned char(-128) : %d\n",char2);
    printf("Unsigned char(-128) : %d\n",char4);

    return 0;
}

Output -:

Signed char(255) : -1
Unsigned char(255) : 255

Signed char(-128) : -128
Unsigned char(-128) : 128

How to change Android version and code version number?

Press Ctrl+Alt+Shift+S in android studio or go to File > Project Structure... Select app on left side and select falvors tab on right side on default config change version code , name and etc... enter image description here

Jquery asp.net Button Click Event via ajax

This is where jQuery really shines for ASP.Net developers. Lets say you have this ASP button:

When that renders, you can look at the source of the page and the id on it won't be btnAwesome, but $ctr001_btnAwesome or something like that. This makes it a pain in the butt to find in javascript. Enter jQuery.

$(document).ready(function() {
  $("input[id$='btnAwesome']").click(function() {
    // Do client side button click stuff here.
  });
});

The id$= is doing a regex match for an id ENDING with btnAwesome.

Edit:

Did you want the ajax call being called from the button click event on the client side? What did you want to call? There are a lot of really good articles on using jQuery to make ajax calls to ASP.Net code behind methods.

The gist of it is you create a static method marked with the WebMethod attribute. You then can make a call to it using jQuery by using $.ajax.

$.ajax({
  type: "POST",
  url: "PageName.aspx/MethodName",
  data: "{}",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(msg) {
    // Do something interesting here.
  }
});

I learned my WebMethod stuff from: http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/

A lot of really good ASP.Net/jQuery stuff there. Make sure you read up about why you have to use msg.d in the return on .Net 3.5 (maybe since 3.0) stuff.

How to find the length of an array in shell?

In the Fish Shell the length of an array can be found with:

$ set a 1 2 3 4
$ count $a
4

syntax error when using command line in python

I faced a similar problem, on my Windows computer, please do check that you have set the Environment Variables correctly.

To check that Environment variable is set correctly:

  1. Open cmd.exe

  2. Type Python and press return

  3. (a) If it outputs the version of python then the environment variables are set correctly.

    (b) If it outputs "no such program or file name" then your environment variable are not set correctly.

To set environment variable:

  1. goto Computer-> System Properties-> Advanced System Settings -> Set Environment Variables
  2. Goto path in the system variables; append ;C:\Python27 in the end.

If you have correct variables already set; then you are calling the file inside the python interpreter.

Where is the .NET Framework 4.5 directory?

The webpage is incorrect and I have pointed this out to MS and they will get it changed.

As already stated above .NET 4.5 is an in-place upgrade of 4.0 so you will only have Microsoft.NET\Framework\v4.0.30319.

The ToolVersion for MSBuild remains at "4.0".

PHP CURL Enable Linux

If anyone else stumbles onto this page from google like I did:

use putty (putty.exe) to sign into your server and install curl using this command :

    sudo apt-get install php5-curl

Make sure curl is enabled in the php.ini file. For me it's in /etc/php5/apache2/php.ini, if you can't find it, this line might be in /etc/php5/conf.d/curl.ini. Make sure the line :

    extension=curl.so

is not commented out then restart apache, so type this into putty:

    sudo /etc/init.d/apache2 restart

Info for install from https://askubuntu.com/questions/9293/how-do-i-install-curl-in-php5, to check if it works this stack overflow might help you: Detect if cURL works?

How to replace specific values in a oracle database column?

In Oracle, there is the concept of schema name, so try using this

update schemname.tablename t
set t.columnname = replace(t.columnname, t.oldvalue, t.newvalue);

MySQL: selecting rows where a column is null

There's also a <=> operator:

SELECT pid FROM planets WHERE userid <=> NULL

Would work. The nice thing is that <=> can also be used with non-NULL values:

SELECT NULL <=> NULL yields 1.

SELECT 42 <=> 42 yields 1 as well.

See here: https://dev.mysql.com/doc/refman/5.7/en/comparison-operators.html#operator_equal-to

Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)

First check your imports, when you use session, transaction it should be org.hibernate and remove @Transactinal annotation. and most important in Entity class if you have used @GeneratedValue(strategy=GenerationType.AUTO) or any other then at the time of model object creation/entity object creation should not create id. final conclusion is if you want pass id filed i.e PK then remove @GeneratedValue from entity class.

Image, saved to sdcard, doesn't appear in Android's Gallery app

there is an app in the emulator that says - ' Dev Tools'

click on that and select ' Media Scanning'.. all the images ll get scanned

PHP form send email to multiple recipients

If i understood correct try this one

$headers = "Bcc: [email protected]";

or

$headers = "Cc: [email protected]";

onKeyPress Vs. onKeyUp and onKeyDown

Updated Answer:

KeyDown

  • Fires multiple times when you hold keys down.
  • Fires meta key.

KeyPress

  • Fires multiple times when you hold keys down.
  • Does not fire meta keys.

KeyUp

  • Fires once at the end when you release key.
  • Fires meta key.

This is the behavior in both addEventListener and jQuery.

https://jsbin.com/vebaholamu/1/edit?js,console,output <-- try example

shows example with holding down for SSS

(answer has been edited with correct response, screenshot & example)

mysql SELECT IF statement with OR

IF(compliment IN('set','Y',1), 'Y', 'N') AS customer_compliment

Will do the job as Buttle Butkus suggested.

WPF loading spinner

CircularProgressBarBlue.xaml

<UserControl 
x:Class="CircularProgressBarBlue"   
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Background="Transparent"
Name="progressBar">
<UserControl.Resources>
    <Storyboard x:Key="spinning" >
        <DoubleAnimation 
            Storyboard.TargetName="SpinnerRotate" 
            Storyboard.TargetProperty="(RotateTransform.Angle)"                 
            From="0" 
            To="360"                 
            RepeatBehavior="Forever"/>
    </Storyboard>
</UserControl.Resources>
<Grid 
    x:Name="LayoutRoot" 
    Background="Transparent" 
    HorizontalAlignment="Center" 
    VerticalAlignment="Center">
    <Image Source="C:\SpinnerImage\BlueSpinner.png" RenderTransformOrigin="0.5,0.5" VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
        <Image.RenderTransform>
            <RotateTransform 
                x:Name="SpinnerRotate"
                Angle="0"/>
        </Image.RenderTransform>
    </Image>


</Grid>

CircularProgressBarBlue.xaml.cs

using System;

using System.Windows;

using System.Windows.Media.Animation;


        /// <summary>
    /// Interaction logic for CircularProgressBarBlue.xaml
    /// </summary>
    public partial class CircularProgressBarBlue
    {
        private Storyboard _sb;

        public CircularProgressBarBlue()
        {
            InitializeComponent();
            StartStoryBoard();
            IsVisibleChanged += CircularProgressBarBlueIsVisibleChanged;
        }

        void CircularProgressBarBlueIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (_sb == null) return;
            if (e != null && e.NewValue != null && (((bool)e.NewValue)))
            {
                _sb.Begin();
                _sb.Resume();
            }
            else
            {
                _sb.Stop();
            }
        }

        void StartStoryBoard()
        {
            try
            {
                _sb = (Storyboard)TryFindResource("spinning");
                if (_sb != null)
                    _sb.Begin();
            }
            catch
            { }
        }
    }

How to convert string to date to string in Swift iOS?

See answer from Gary Makin. And you need change the format or data. Because the data that you have do not fit under the chosen format. For example this code works correct:

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
let dateObj = dateFormatter.dateFromString("10 10 2001")
print("Dateobj: \(dateObj)")

How to post object and List using postman

//backend.

@PostMapping("/")
public List<A> addList(@RequestBody A aObject){
//......ur code
}

class A{
int num;
String name;
List<B> bList;
//getters and setters and default constructor
}
class B{
int d;
//defalut Constructor & gettes&setters
}

// postman

{
"num":value,
"name":value,
"bList":[{
"key":"value",
"key":"value",.....
}]
}
  1. the error is for list there is no default constructor .so we can keep our list of object as a property of another class and pass the list of objects through the postman as the parameter of the another class.

Download image with JavaScript

As @Ian explained, the problem is that jQuery's click() is not the same as the native one.

Therefore, consider using vanilla-js instead of jQuery:

var a = document.createElement('a');
a.href = "img.png";
a.download = "output.png";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);

Demo

How abstraction and encapsulation differ?

Abstraction and Encapsulation are confusing terms and dependent on each other. Let's take it by an example:

public class Person
    {
        private int Id { get; set; }
        private string Name { get; set; }
        private string CustomName()
        {
            return "Name:- " + Name + " and Id is:- " + Id;
        }
    }

When you created Person class, you did encapsulation by writing properties and functions together(Id, Name, CustomName). You perform abstraction when you expose this class to client as

Person p = new Person();
p.CustomName();

Your client doesn't know anything about Id and Name in this function. Now if, your client wants to know the last name as well without disturbing the function call. You do encapsulation by adding one more property into Person class like this.

public class Person
        {
            private int Id { get; set; }
            private string Name { get; set; }
            private string LastName {get; set;}
            public string CustomName()
            {
                return "Name:- " + Name + " and Id is:- " + Id + "last name:- " + LastName;
            }
        }

Look, even after addding an extra property in class, your client doesn't know what you did to your code. This is where you did abstraction.

Configure hibernate (using JPA) to store Y/N for type Boolean instead of 0/1

I used the concept from the answer posted by @marcg and it works great with JPA 2.1. His code wasn't quite right, so I'm posted my working implementation. This will convert Boolean entity fields to a Y/N character column in the database.

From my entity class:

@Convert(converter=BooleanToYNStringConverter.class)
@Column(name="LOADED", length=1)
private Boolean isLoadedSuccessfully;

My converter class:

/**
 * Converts a Boolean entity attribute to a single-character
 * Y/N string that will be stored in the database, and vice-versa
 * 
 * @author jtough
 */
public class BooleanToYNStringConverter 
        implements AttributeConverter<Boolean, String> {

    /**
     * This implementation will return "Y" if the parameter is Boolean.TRUE,
     * otherwise it will return "N" when the parameter is Boolean.FALSE. 
     * A null input value will yield a null return value.
     * @param b Boolean
     */
    @Override
    public String convertToDatabaseColumn(Boolean b) {
        if (b == null) {
            return null;
        }
        if (b.booleanValue()) {
            return "Y";
        }
        return "N";
    }

    /**
     * This implementation will return Boolean.TRUE if the string
     * is "Y" or "y", otherwise it will ignore the value and return
     * Boolean.FALSE (it does not actually look for "N") for any
     * other non-null string. A null input value will yield a null
     * return value.
     * @param s String
     */
    @Override
    public Boolean convertToEntityAttribute(String s) {
        if (s == null) {
            return null;
        }
        if (s.equals("Y") || s.equals("y")) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

}

This variant is also fun if you love emoticons and are just sick and tired of Y/N or T/F in your database. In this case, your database column must be two characters instead of one. Probably not a big deal.

/**
 * Converts a Boolean entity attribute to a happy face or sad face
 * that will be stored in the database, and vice-versa
 * 
 * @author jtough
 */
public class BooleanToHappySadConverter 
        implements AttributeConverter<Boolean, String> {

    public static final String HAPPY = ":)";
    public static final String SAD = ":(";

    /**
     * This implementation will return ":)" if the parameter is Boolean.TRUE,
     * otherwise it will return ":(" when the parameter is Boolean.FALSE. 
     * A null input value will yield a null return value.
     * @param b Boolean
     * @return String or null
     */
    @Override
    public String convertToDatabaseColumn(Boolean b) {
        if (b == null) {
            return null;
        }
        if (b) {
            return HAPPY;
        }
        return SAD;
    }

    /**
     * This implementation will return Boolean.TRUE if the string
     * is ":)", otherwise it will ignore the value and return
     * Boolean.FALSE (it does not actually look for ":(") for any
     * other non-null string. A null input value will yield a null
     * return value.
     * @param s String
     * @return Boolean or null
     */
    @Override
    public Boolean convertToEntityAttribute(String s) {
        if (s == null) {
            return null;
        }
        if (HAPPY.equals(s)) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

}

Execute PHP script in cron job

I had the same problem... I had to run it as a user.

00 * * * * root /usr/bin/php /var/virtual/hostname.nz/public_html/cronjob.php

Including JavaScript class definition from another file in Node.js

If you append this to user.js:

exports.User = User;

then in server.js you can do:

var userFile = require('./user.js');
var User = userFile.User;

http://nodejs.org/docs/v0.4.10/api/globals.html#require

Another way is:

global.User = User;

then this would be enough in server.js:

require('./user.js');

Can I pass a JavaScript variable to another browser window?

Yes, it can be done as long as both windows are on the same domain. The window.open() function will return a handle to the new window. The child window can access the parent window using the DOM element "opener".

wget ssl alert handshake failure

I was having this problem on Ubuntu 12.04.3 LTS (well beyond EOL, I know...) and got around it with:

sudo apt-get update && sudo apt-get install ca-certificates

What does 'corrupted double-linked list' mean

This might be caused due to different reasons, some user have mentioned other possibilities and I add my case:

I got this error when using multi-threading (both std::pthread and std::thread) and the error occurred because I forgot to lock a variable which multi threads may change at the same time. this error comes randomly in some runs but not all because ... you know accident between to threads is random.

That variable in my case was a global std::vector which I tried to push_back() something into it in a function called by threads.. and then I used a std::mutex and never got this error again.

may help some

SQL WHERE.. IN clause multiple columns

You can make a derived table from the subquery, and join table1 to this derived table:

select * from table1 LEFT JOIN 
(
   Select CM_PLAN_ID, Individual_ID
   From CRM_VCM_CURRENT_LEAD_STATUS
   Where Lead_Key = :_Lead_Key
) table2
ON 
   table1.CM_PLAN_ID=table2.CM_PLAN_ID
   AND table1.Individual=table2.Individual
WHERE table2.CM_PLAN_ID IS NOT NULL

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

The following steps are to reset the password for a user in case you forgot, this would also solve your mentioned error.

First, stop your MySQL:

sudo /etc/init.d/mysql stop

Now start up MySQL in safe mode and skip the privileges table:

sudo mysqld_safe --skip-grant-tables &

Login with root:

mysql -uroot

And assign the DB that needs to be used:

use mysql;

Now all you have to do is reset your root password of the MySQL user and restart the MySQL service:

update user set password=PASSWORD("YOURPASSWORDHERE") where User='root';

flush privileges;

quit and restart MySQL:

quit

sudo /etc/init.d/mysql stop sudo /etc/init.d/mysql start Now your root password should be working with the one you just set, check it with:

mysql -u root -p

C# - Making a Process.Start wait until the process has start-up

Like others have already said, it's not immediately obvious what you're asking. I'm going to assume that you want to start a process and then perform another action when the process "is ready".

Of course, the "is ready" is the tricky bit. Depending on what you're needs are, you may find that simply waiting is sufficient. However, if you need a more robust solution, you can consider using a named Mutex to control the control flow between your two processes.

For example, in your main process, you might create a named mutex and start a thread or task which will wait. Then, you can start the 2nd process. When that process decides that "it is ready", it can open the named mutex (you have to use the same name, of course) and signal to the first process.

Youtube iframe wmode issue

If you are using the new asynchronous API, you will need to add the parameter like so:

<!-- YOUTUBE -->
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// 3. This function creates an <iframe> (and YouTube player)
//    after the API code downloads.
var player;
var initialVideo = 'ApkM4t9L5jE'; // YOUR YOUTUBE VIDEO ID
function onYouTubePlayerAPIReady() {
    console.log("onYouTubePlayerAPIReady" + initialVideo);
    player = new YT.Player('player', {
      height: '381',
      width: '681',
      wmode: 'transparent', // SECRET SAUCE HERE
      videoId: initialVideo,      
       playerVars: { 'autoplay': 1, 'rel': 0, 'wmode':'transparent' },
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
}

This is based on the google documentation and example here: http://code.google.com/apis/youtube/iframe_api_reference.html

How to set the opacity/alpha of a UIImage?

Hey hey thanks from Xamarin user! :) Here it goes translated to c#

//***************************************************************************
public static class ImageExtensions
//***************************************************************************
{
    //-------------------------------------------------------------
    public static UIImage WithAlpha(this UIImage image, float alpha)  
    //-------------------------------------------------------------
        {
        UIGraphics.BeginImageContextWithOptions(image.Size,false,image.CurrentScale);
        image.Draw(CGPoint.Empty, CGBlendMode.Normal, alpha);
        var newImage = UIGraphics.GetImageFromCurrentImageContext();
        UIGraphics.EndImageContext();
        return newImage;
        }

}

Usage example:

var MySupaImage = UIImage.FromBundle("opaquestuff.png").WithAlpha(0.15f);

How do I load the contents of a text file into a javascript variable?

here is how I did it in jquery:

jQuery.get('http://localhost/foo.txt', function(data) {
    alert(data);
});

Converting an integer to a hexadecimal string in Ruby

Here's another approach:

sprintf("%02x", 10).upcase

see the documentation for sprintf here: http://www.ruby-doc.org/core/classes/Kernel.html#method-i-sprintf

Why the switch statement cannot be applied on strings?

I think the reason is that in C strings are not primitive types, as tomjen said, think in a string as a char array, so you can not do things like:

switch (char[]) { // ...
switch (int[]) { // ...

How to inflate one view with a layout

With Kotlin, you can use:

val content = LayoutInflater.from(context).inflate(R.layout.[custom_layout_name], null)

[your_main_layout].apply {
    //..
    addView(content)
}

Equivalent of varchar(max) in MySQL?

The max length of a varchar is subject to the max row size in MySQL, which is 64KB (not counting BLOBs):

VARCHAR(65535)

However, note that the limit is lower if you use a multi-byte character set:

VARCHAR(21844) CHARACTER SET utf8

Here are some examples:

The maximum row size is 65535, but a varchar also includes a byte or two to encode the length of a given string. So you actually can't declare a varchar of the maximum row size, even if it's the only column in the table.

mysql> CREATE TABLE foo ( v VARCHAR(65534) );
ERROR 1118 (42000): Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs

But if we try decreasing lengths, we find the greatest length that works:

mysql> CREATE TABLE foo ( v VARCHAR(65532) );
Query OK, 0 rows affected (0.01 sec)

Now if we try to use a multibyte charset at the table level, we find that it counts each character as multiple bytes. UTF8 strings don't necessarily use multiple bytes per string, but MySQL can't assume you'll restrict all your future inserts to single-byte characters.

mysql> CREATE TABLE foo ( v VARCHAR(65532) ) CHARSET=utf8;
ERROR 1074 (42000): Column length too big for column 'v' (max = 21845); use BLOB or TEXT instead

In spite of what the last error told us, InnoDB still doesn't like a length of 21845.

mysql> CREATE TABLE foo ( v VARCHAR(21845) ) CHARSET=utf8;
ERROR 1118 (42000): Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs

This makes perfect sense, if you calculate that 21845*3 = 65535, which wouldn't have worked anyway. Whereas 21844*3 = 65532, which does work.

mysql> CREATE TABLE foo ( v VARCHAR(21844) ) CHARSET=utf8;
Query OK, 0 rows affected (0.32 sec)

How do I download/extract font from chrome developers tools?

It's easy (For Chorme only)

  1. Right click > inspect element
  2. Go to 'Resources' tab and find 'Fonts' in dropdown folders
    • 'Resouces' tab may be called 'Application'
  3. Right click on font (in .woff format) > open link in new tab (this should download the font in .woff format
  4. Find a 'Woff to TTf or Otf' font converter online
  5. Enjoy after conversion!

What does 'stale file handle' in Linux mean?

When the directory is deleted, the inode for that directory (and the inodes for its contents) are recycled. The pointer your shell has to that directory's inode (and its contents's inodes) are now no longer valid. When the directory is restored from backup, the old inodes are not (necessarily) reused; the directory and its contents are stored on random inodes. The only thing that stays the same is that the parent directory reuses the same name for the restored directory (because you told it to).

Now if you attempt to access the contents of the directory that your original shell is still pointing to, it communicates that request to the file system as a request for the original inode, which has since been recycled (and may even be in use for something entirely different now). So you get a stale file handle message because you asked for some nonexistent data.

When you perform a cd operation, the shell reevaluates the inode location of whatever destination you give it. Now that your shell knows the new inode for the directory (and the new inodes for its contents), future requests for its contents will be valid.

What is a bus error?

A specific example of a bus error I just encountered while programming C on OS X:

#include <string.h>
#include <stdio.h>

int main(void)
{
    char buffer[120];
    fgets(buffer, sizeof buffer, stdin);
    strcat("foo", buffer);
    return 0;
}

In case you don't remember the docs strcat appends the second argument to the first by changing the first argument(flip the arguments and it works fine). On linux this gives a segmentation fault(as expected), but on OS X it gives a bus error. Why? I really don't know.

Splitting strings using a delimiter in python

So, your input is 'dan|warrior|54' and you want "warrior". You do this like so:

>>> dan = 'dan|warrior|54'
>>> dan.split('|')[1]
"warrior"

Darken CSS background image?

You can use the CSS3 Linear Gradient property along with your background-image like this:

#landing-wrapper {
    display:table;
    width:100%;
    background: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5) ), url('landingpagepic.jpg');
    background-position:center top;
    height:350px;
}

Here's a demo:

_x000D_
_x000D_
#landing-wrapper {_x000D_
  display: table;_x000D_
  width: 100%;_x000D_
  background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('http://placehold.it/350x150');_x000D_
  background-position: center top;_x000D_
  height: 350px;_x000D_
  color: white;_x000D_
}
_x000D_
<div id="landing-wrapper">Lorem ipsum dolor ismet.</div>
_x000D_
_x000D_
_x000D_

Numpy `ValueError: operands could not be broadcast together with shape ...`

If X and beta do not have the same shape as the second term in the rhs of your last line (i.e. nsample), then you will get this type of error. To add an array to a tuple of arrays, they all must be the same shape.

I would recommend looking at the numpy broadcasting rules.

Draw Circle using css alone

yes it is possible you can use border-radius CSS property. For more info have a look at http://zeeshanmkhan.com/post/2/css-rounded-corner-gradient-drop-shadow-and-opacity

Assembly - JG/JNLE/JL/JNGE after CMP

Wikibooks has a fairly good summary of jump instructions. Basically, there's actually two stages:

cmp_instruction op1, op2

Which sets various flags based on the result, and

jmp_conditional_instruction address

which will execute the jump based on the results of those flags.

Compare (cmp) will basically compute the subtraction op1-op2, however, this is not stored; instead only flag results are set. So if you did cmp eax, ebx that's the same as saying eax-ebx - then deciding based on whether that is positive, negative or zero which flags to set.

More detailed reference here.

How to make an inline element appear on new line, or block element not occupy the whole line?

You can give it a property display block; so it will behave like a div and have its own line

CSS:

.feature_desc {
   display: block;
   ....
}

Is true == 1 and false == 0 in JavaScript?

It's true that true and false don't represent any numerical values in Javascript.

In some languages (e.g. C, VB), the boolean values are defined as actual numerical values, so they are just different names for 1 and 0 (or -1 and 0).

In some other languages (e.g. Pascal, C#), there is a distinct boolean type that is not numerical. It's possible to convert between boolean values and numerical values, but it doesn't happen automatically.

Javascript falls in the category that has a distinct boolean type, but on the other hand Javascript is quite keen to convert values between different data types.

For example, eventhough a number is not a boolean, you can use a numeric value where a boolean value is expected. Using if (1) {...} works just as well as if (true) {...}.

When comparing values, like in your example, there is a difference between the == operator and the === operator. The == equality operator happily converts between types to find a match, so 1 == true evaluates to true because true is converted to 1. The === type equality operator doesn't do type conversions, so 1 === true evaluates to false because the values are of different types.

Why I am getting Cannot pass parameter 2 by reference error when I am using bindParam with a constant value?

When using INTEGER columns (that can be NULL) in MySQL, PDO has some (to me) unexpected behaviour.

If you use $stmt->execute(Array), you have to specify the literal NULL and cannot give NULL by variable reference. So this won't work:

// $val is sometimes null, but sometimes an integer
$stmt->execute(array(
    ':param' => $val
));
// will cause the error 'incorrect integer value' when $val == null

But this will work:

// $val again is sometimes null, but sometimes an integer
$stmt->execute(array(
    ':param' => isset($val) ? $val : null
));
// no errors, inserts NULL when $val == null, inserts the integer otherwise

Tried this on MySQL 5.5.15 with PHP 5.4.1

Ajax success function

It is because Ajax is asynchronous, the success or the error function will be called later, when the server answer the client. So, just move parts depending on the result into your success function like that :

jQuery.ajax({

            type:"post",
            dataType:"json",
            url: myAjax.ajaxurl,
            data: {action: 'submit_data', info: info},
            success: function(data) {
                successmessage = 'Data was succesfully captured';
                $("label#successmessage").text(successmessage);
            },
            error: function(data) {
                successmessage = 'Error';
                $("label#successmessage").text(successmessage);
            },
        });

        $(":input").val('');
        return false;

jQuery autocomplete tagging plug-in like StackOverflow's input tags?

In order of activity, demos/examples available, and simplicity:

Related:

HTML input textbox with a width of 100% overflows table cells

I solved the problem by applying box-sizing:border-box; to the table cells themselves, besides doing the same with the input and the wrapper.

Using an if statement to check if a div is empty

If you want a quick demo how you check for empty divs I'd suggest you to try this link:

http://html-tuts.com/check-if-html-element-is-empty-or-has-children-tags/


Below you have some short examples:

Using CSS

If your div is empty without anything even no white-space, you can use CSS:

.someDiv:empty {
    display: none;
}

Unfortunately there is no CSS selector that selects the previous sibling element. There is only for the next sibling element: x ~ y

.someDiv:empty ~ .anotherDiv {
    display: none;
}

Using jQuery

Checking text length of element with text() function

if ( $('#leftmenu').text().length == 0 ) {
    // length of text is 0
}

Check if element has any children tags inside

if ( $('#leftmenu').children().length == 0 ) {
    // div has no other tags inside it
}

Check for empty elements if they have white-space

if ( $.trim( $('.someDiv').text() ).length == 0 ) {
    // white-space trimmed, div is empty
}

How to disable margin-collapsing?

One neat trick to disable margin collapsing that has no visual impact, as far as I know, is setting the padding of the parent to 0.05px:

.parentClass {
    padding: 0.05px;
}

The padding is no longer 0 so collapsing won't occur anymore but at the same time the padding is small enough that visually it will round down to 0.

If some other padding is desired, then apply padding only to the "direction" in which margin collapsing is not desired, for example padding-top: 0.05px;.

Working example:

_x000D_
_x000D_
.noCollapse {_x000D_
  padding: 0.05px;_x000D_
}_x000D_
_x000D_
.parent {_x000D_
  background-color: red;_x000D_
  width: 150px;_x000D_
}_x000D_
_x000D_
.children {_x000D_
  margin-top: 50px;_x000D_
_x000D_
  background-color: lime;      _x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
}
_x000D_
<h3>Border collapsing</h3>_x000D_
<div class="parent">_x000D_
  <div class="children">_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<h3>No border collapsing</h3>_x000D_
<div class="parent noCollapse">_x000D_
  <div class="children">_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Edit: changed the value from 0.1 to 0.05. As Chris Morgan mentioned in a comment bellow, and from this small test, it seems that indeed Firefox takes the 0.1px padding into consideration. Though, 0.05px seemes to do the trick.

Javascript change date into format of (dd/mm/yyyy)

This will ensure you get a two-digit day and month.

function formattedDate(d = new Date) {
  let month = String(d.getMonth() + 1);
  let day = String(d.getDate());
  const year = String(d.getFullYear());

  if (month.length < 2) month = '0' + month;
  if (day.length < 2) day = '0' + day;

  return `${day}/${month}/${year}`;
}

Or terser:

function formattedDate(d = new Date) {
  return [d.getDate(), d.getMonth()+1, d.getFullYear()]
      .map(n => n < 10 ? `0${n}` : `${n}`).join('/');
}

How can I change Eclipse theme?

enter image description here My Theme plugin provide full featured customization for Eclipse 4. Try it. Visit Plugin Page

ASP.net Repeater get current index, pointer, or counter

To display the item number on the repeater you can use the Container.ItemIndex property.

<asp:repeater id="rptRepeater" runat="server">
    <itemtemplate>
        Item <%# Container.ItemIndex + 1 %>| <%# Eval("Column1") %>
    </itemtemplate>
    <separatortemplate>
        <br />
    </separatortemplate>
</asp:repeater>

Export a graph to .eps file with R

If you are using ggplot2 to generate a figure, then a ggsave(file="name.eps") will also work.

input checkbox true or checked or yes

Only checked and checked="checked" are valid. Your other options depend on error recovery in browsers.

checked="yes" and checked="true" are particularly bad as they imply that checked="no" and checked="false" will set the default state to be unchecked … which they will not.

How to print a dictionary's key?

key_name = '...'
print "the key name is %s and its value is %s"%(key_name, mydic[key_name])

How to resolve compiler warning 'implicit declaration of function memset'

Old question but I had similar issue and I solved it by adding

extern void* memset(void*, int, size_t);

or just

extern void* memset();

at the top of translation unit ( *.c file ).

MVC razor form with multiple different submit buttons?

As well as @Pablo's answer, for newer versions you can also use the asp-page-handler tag helper.

In the page:

<button asp-page-handler="Action1" type="submit">Action 1</button>
<button asp-page-handler="Action2" type="submit">Action 2</button>

then in the controller:

    public async Task OnPostAction1Async() {...}
    public async Task OnPostAction2Async() {...}

How do I skip an iteration of a `foreach` loop?

Use the continue statement:

foreach(object number in mycollection) {
     if( number < 0 ) {
         continue;
     }
  }

Python OpenCV2 (cv2) wrapper to get image size?

cv2 uses numpy for manipulating images, so the proper and best way to get the size of an image is using numpy.shape. Assuming you are working with BGR images, here is an example:

>>> import numpy as np
>>> import cv2
>>> img = cv2.imread('foo.jpg')
>>> height, width, channels = img.shape
>>> print height, width, channels
  600 800 3

In case you were working with binary images, img will have two dimensions, and therefore you must change the code to: height, width = img.shape

Bootstrap 3 2-column form layout

As mentioned earlier, you can use the grid system to layout your inputs and labels anyway that you want. The trick is to remember that you can use rows within your columns to break them into twelfths as well.

The example below is one possible way to accomplish your goal and will put the two text boxes near Label3 on the same line when the screen is small or larger.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
  <head>_x000D_
    <meta charset="utf-8">_x000D_
    <meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->_x000D_
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->_x000D_
    <!--[if lt IE 9]>_x000D_
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>_x000D_
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>_x000D_
    <![endif]-->_x000D_
  </head>_x000D_
  <body>_x000D_
    <div class="row">_x000D_
        <div class="col-xs-6 form-group">_x000D_
            <label>Label1</label>_x000D_
            <input class="form-control" type="text"/>_x000D_
        </div>_x000D_
        <div class="col-xs-6 form-group">_x000D_
            <label>Label2</label>_x000D_
            <input class="form-control" type="text"/>_x000D_
        </div>_x000D_
        <div class="col-xs-6">_x000D_
            <div class="row">_x000D_
                <label class="col-xs-12">Label3</label>_x000D_
            </div>_x000D_
            <div class="row">_x000D_
                <div class="col-xs-12 col-sm-6">_x000D_
                    <input class="form-control" type="text"/>_x000D_
                </div>_x000D_
                <div class="col-xs-12 col-sm-6">_x000D_
                    <input class="form-control" type="text"/>_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>_x000D_
        <div class="col-xs-6 form-group">_x000D_
            <label>Label4</label>_x000D_
            <input class="form-control" type="text"/>_x000D_
        </div>_x000D_
    </div>_x000D_
   _x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/m3u8bjv0/2/

Maven: repository element was not specified in the POM inside distributionManagement?

Review the pom.xml file inside of target/checkout/. Chances are, the pom.xml in your trunk or master branch does not have the distributionManagement tag.

Limitations of SQL Server Express

Another limitation to consider is that SQL Server Express editions go into an idle mode after a period of disuse.

Understanding SQL Express behavior: Idle time resource usage, AUTO_CLOSE and User Instances:

When SQL Express is idle it aggressively trims back the working memory set by writing the cached data back to disk and releasing the memory.

But this is easily worked around: Is there a way to stop SQL Express 2008 from Idling?

How to scp in Python?

You could also check out paramiko. There's no scp module (yet), but it fully supports sftp.

[EDIT] Sorry, missed the line where you mentioned paramiko. The following module is simply an implementation of the scp protocol for paramiko. If you don't want to use paramiko or conch (the only ssh implementations I know of for python), you could rework this to run over a regular ssh session using pipes.

scp.py for paramiko

Double array initialization in Java

double m[][] declares an array of arrays, so called multidimensional array.

m[0] points to an array in the size of four, containing 0*0,1*0,2*0,3*0. Simple math shows the values are actually 0,0,0,0.

Second line is also array in the size of four, containing 0,1,2,3.

And so on...

I guess this mutiple format in you book was to show that 0*0 is row 0 column 0, 0*1 is row 0 column 1, and so on.

How to clear an EditText on click?

Are you looking for behavior similar to the x that shows up on the right side of text fields on an iphone that clears the text when tapped? It's called clearButtonMode there. Here is how to create that same functionality in an Android EditText view:

String value = "";//any text you are pre-filling in the EditText

final EditText et = new EditText(this);
et.setText(value);
final Drawable x = getResources().getDrawable(R.drawable.presence_offline);//your x image, this one from standard android images looks pretty good actually
x.setBounds(0, 0, x.getIntrinsicWidth(), x.getIntrinsicHeight());
et.setCompoundDrawables(null, null, value.equals("") ? null : x, null);
et.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (et.getCompoundDrawables()[2] == null) {
            return false;
        }
        if (event.getAction() != MotionEvent.ACTION_UP) {
            return false;
        }
        if (event.getX() > et.getWidth() - et.getPaddingRight() - x.getIntrinsicWidth()) {
            et.setText("");
            et.setCompoundDrawables(null, null, null, null);
        }
        return false;
    }
});
et.addTextChangedListener(new TextWatcher() {
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        et.setCompoundDrawables(null, null, et.getText().toString().equals("") ? null : x, null);
    }

    @Override
    public void afterTextChanged(Editable arg0) {
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }
});

Error in contrasts when defining a linear model in R

If your independent variable (RHS variable) is a factor or a character taking only one value then that type of error occurs.

Example: iris data in R

(model1 <- lm(Sepal.Length ~ Sepal.Width + Species, data=iris))

# Call:
# lm(formula = Sepal.Length ~ Sepal.Width + Species, data = iris)

# Coefficients:
#       (Intercept)        Sepal.Width  Speciesversicolor   Speciesvirginica  
#            2.2514             0.8036             1.4587             1.9468  

Now, if your data consists of only one species:

(model1 <- lm(Sepal.Length ~ Sepal.Width + Species,
              data=iris[iris$Species == "setosa", ]))
# Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) : 
#   contrasts can be applied only to factors with 2 or more levels

If the variable is numeric (Sepal.Width) but taking only a single value say 3, then the model runs but you will get NA as coefficient of that variable as follows:

(model2 <-lm(Sepal.Length ~ Sepal.Width + Species,
             data=iris[iris$Sepal.Width == 3, ]))

# Call:
# lm(formula = Sepal.Length ~ Sepal.Width + Species, 
#    data = iris[iris$Sepal.Width == 3, ])

# Coefficients:
#       (Intercept)        Sepal.Width  Speciesversicolor   Speciesvirginica  
#             4.700                 NA              1.250              2.017

Solution: There is not enough variation in dependent variable with only one value. So, you need to drop that variable, irrespective of whether that is numeric or character or factor variable.

Updated as per comments: Since you know that the error will only occur with factor/character, you can focus only on those and see whether the length of levels of those factor variables is 1 (DROP) or greater than 1 (NODROP).

To see, whether the variable is a factor or not, use the following code:

(l <- sapply(iris, function(x) is.factor(x)))
# Sepal.Length  Sepal.Width Petal.Length  Petal.Width      Species 
#        FALSE        FALSE        FALSE        FALSE         TRUE 

Then you can get the data frame of factor variables only

m <- iris[, l]

Now, find the number of levels of factor variables, if this is one you need to drop that

ifelse(n <- sapply(m, function(x) length(levels(x))) == 1, "DROP", "NODROP")

Note: If the levels of factor variable is only one then that is the variable, you have to drop.

How to get year and month from a date - PHP

$dateValue = '2012-01-05';
$year = date('Y',strtotime($dateValue));
$month = date('F',strtotime($dateValue));

AWS CLI S3 A client error (403) occurred when calling the HeadObject operation: Forbidden

I was getting this error message due to my EC2 instance's clock being out of sync.

I was able to fix on Ubuntu using this:

sudo ntpdate ntp.ubuntu.com
sudo apt-get install ntp

Configure Log4net to write to multiple files

Vinay is correct. In answer to your comment in his answer, one way you can do it is as follows:

<root>
    <level value="ALL" />
    <appender-ref ref="File1Appender" />
</root>
<logger name="SomeName">
    <level value="ALL" />
    <appender-ref ref="File1Appender2" />
</logger>

This is how I have done it in the past. Then something like this for the other log:

private static readonly ILog otherLog = LogManager.GetLogger("SomeName");

And you can get your normal logger as follows:

private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

Read the loggers and appenders section of the documentation to understand how this works.

How to convert string values from a dictionary, into int/float datatypes?

If you'd decide for a solution acting "in place" you could take a look at this one:

>>> d = [ { 'a':'1' , 'b':'2' , 'c':'3' }, { 'd':'4' , 'e':'5' , 'f':'6' } ]
>>> [dt.update({k: int(v)}) for dt in d for k, v in dt.iteritems()]
[None, None, None, None, None, None]
>>> d
[{'a': 1, 'c': 3, 'b': 2}, {'e': 5, 'd': 4, 'f': 6}]

Btw, key order is not preserved because that's the way standard dictionaries work, ie without the concept of order.

How to retrieve Request Payload

Also you can setup extJs writer with encode: true and it will send data regularly (and, hence, you will be able to retrieve data via $_POST and $_GET).

... the values will be sent as part of the request parameters as opposed to a raw post (via docs for encode config of Ext.data.writer.Json)

UPDATE

Also docs say that:

The encode option should only be set to true when a root is defined

So, probably, writer's root config is required.

Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Add line "arm64" (without quotes) to path: Xcode -> Project -> Build settings -> Architectures -> Excluded architectures Also, do the same for Pods. In both cases for both debug and release fields.

or in detail...

Errors mentioned here while deploying to simulator using Xcode 12 are also one of the things which have affected me. Just right-clicking on each of my projects and showing in finder, opening the .xcodeproj in Atom, then going through the .pbxproj and removing all of the VALIDARCHS settings. This was is what got it working for me. Tried a few of the other suggestions (excluding arm64, Build Active Architecture Only) which seemed to get my build further but ultimately leave me at another error. Having VALIDARCH settings lying around is probably the best thing to check for first.

Get string after character

For the text after the first = and before the next =

cut -d "=" -f2 <<< "$your_str"

or

sed -e 's#.*=\(\)#\1#' <<< "$your_str"

For all text after the first = regardless of if there are multiple =

cut -d "=" -f2- <<< "$your_str"

How to collapse blocks of code in Eclipse?

To collapse all code blocks Ctrl + Shift+ /

To expand all code blocks Ctrl + Shift+ *

pydev:

To collapse all code blocks : Ctrl + 0

To collapse all code blocks : Ctrl + 9

Is there a way to collapse all code blocks in Eclipse?

by @partizanos and @bummi

Stretch child div height to fill parent that has dynamic height

You can do it easily with a bit of jQuery

$(document).ready(function(){
  var parentHeight = $("#parentDiv").parent().height();
  $("#childDiv").height(parentHeight);
});

Save matplotlib file to a directory

You should be able to specify the whole path to the destination of your choice. E.g.:

plt.savefig('E:\New Folder\Name of the graph.jpg')

Failed loading english.pickle with nltk.data.load

This is what worked for me just now:

# Do this in a separate python interpreter session, since you only have to do it once
import nltk
nltk.download('punkt')

# Do this in your ipython notebook or analysis script
from nltk.tokenize import word_tokenize

sentences = [
    "Mr. Green killed Colonel Mustard in the study with the candlestick. Mr. Green is not a very nice fellow.",
    "Professor Plum has a green plant in his study.",
    "Miss Scarlett watered Professor Plum's green plant while he was away from his office last week."
]

sentences_tokenized = []
for s in sentences:
    sentences_tokenized.append(word_tokenize(s))

sentences_tokenized is a list of a list of tokens:

[['Mr.', 'Green', 'killed', 'Colonel', 'Mustard', 'in', 'the', 'study', 'with', 'the', 'candlestick', '.', 'Mr.', 'Green', 'is', 'not', 'a', 'very', 'nice', 'fellow', '.'],
['Professor', 'Plum', 'has', 'a', 'green', 'plant', 'in', 'his', 'study', '.'],
['Miss', 'Scarlett', 'watered', 'Professor', 'Plum', "'s", 'green', 'plant', 'while', 'he', 'was', 'away', 'from', 'his', 'office', 'last', 'week', '.']]

The sentences were taken from the example ipython notebook accompanying the book "Mining the Social Web, 2nd Edition"

Get properties of a class

Some answers are partially wrong, and some facts in them are partially wrong as well.

Answer your question: Yes! You can.

In Typescript

class A {
    private a1;
    private a2;


}

Generates the following code in Javascript:

var A = /** @class */ (function () {
    function A() {
    }
    return A;
}());

as @Erik_Cupal said, you could just do:

let a = new A();
let array = return Object.getOwnPropertyNames(a);

But this is incomplete. What happens if your class has a custom constructor? You need to do a trick with Typescript because it will not compile. You need to assign as any:

let className:any = A;
let a = new className();// the members will have value undefined

A general solution will be:

class A {
    private a1;
    private a2;
    constructor(a1:number, a2:string){
        this.a1 = a1;
        this.a2 = a2;
    }
}

class Describer{

   describeClass( typeOfClass:any){
       let a = new typeOfClass();
       let array = Object.getOwnPropertyNames(a);
       return array;//you can apply any filter here
   }
}

For better understanding this will reference depending on the context.

Using .otf fonts on web browsers

You can implement your OTF font using @font-face like:

@font-face {
    font-family: GraublauWeb;
    src: url("path/GraublauWeb.otf") format("opentype");
}

@font-face {
    font-family: GraublauWeb;
    font-weight: bold;
    src: url("path/GraublauWebBold.otf") format("opentype");
}

// Edit: OTF now works in most browsers, see comments

However if you want to support a wide variety of browsers i would recommend you to switch to WOFF and TTF font types. WOFF type is implemented by every major desktop browser, while the TTF type is a fallback for older Safari, Android and iOS browsers. If your font is a free font, you could convert your font using for example a transfonter.

@font-face {
    font-family: GraublauWeb;
    src: url("path/GraublauWebBold.woff") format("woff"), url("path/GraublauWebBold.ttf")  format("truetype");
}

If you want to support nearly every browser that is still out there (not necessary anymore IMHO), you should add some more font-types like:

@font-face {
    font-family: GraublauWeb;
    src: url("webfont.eot"); /* IE9 Compat Modes */
    src: url("webfont.eot?#iefix") format("embedded-opentype"), /* IE6-IE8 */
         url("webfont.woff") format("woff"), /* Modern Browsers */
         url("webfont.ttf")  format("truetype"), /* Safari, Android, iOS */
         url("webfont.svg#svgFontName") format("svg"); /* Legacy iOS */
}

You can read more about why all these types are implemented and their hacks here. To get a detailed view of which file-types are supported by which browsers, see:

@font-face Browser Support

EOT Browser Support

WOFF Browser Support

TTF Browser Support

SVG-Fonts Browser Support

hope this helps

Is a new line = \n OR \r\n?

The given answer is far from complete. In fact, it is so far from complete that it tends to lead the reader to believe that this answer is OS dependent when it isn't. It also isn't something which is programming language dependent (as some commentators have suggested). I'm going to add more information in order to make this more clear. First, lets give the list of current new line variations (as in, what they've been since 1999):

  • \r\n is only used on Windows Notepad, the DOS command line, most of the Windows API and in some (older) Windows apps.
  • \n is used for all other systems, applications and the Internet.

You'll notice that I've put most Windows apps in the \n group which may be slightly controversial but before you disagree with this statement, please grab a UNIX formatted text file and try it in 10 web friendly Windows applications of your choice (which aren't listed in my exceptions above). What percentage of them handled it just fine? You'll find that they (practically) all implement auto detection of line endings or just use \n because, while Windows may use \r\n, the Internet uses \n. Therefore, it is best practice for applications to use \n alone if you want your output to be Internet friendly.

PHP also defines a newline character called PHP_EOL. This constant is set to the OS specific newline string for the machine PHP is running on (\r\n for Windows and \n for everything else). This constant is not very useful for webpages and should be avoided for HTML output or for writing most text to files. It becomes VERY useful when we move to command line output from PHP applications because it will allow your application to output to a terminal Window in a consistent manner across all supported OSes.

If you want your PHP applications to work from any server they are placed on, the two biggest things to remember are that you should always just use \n unless it is terminal output (in which case you use PHP_EOL) and you should also ALWAYS use / for your path separator (not \).

The even longer explanation:

An application may choose to use whatever line endings it likes regardless of the default OS line ending style. If I want my text editor to print a newline every time it encounters a period that is no harder than using the \n to represent a newline because I'm interpreting the text as I display it anyway. IOW, I'm fiddling around with measuring the width of each character so it knows where to display the next so it is very simple to add a statement saying that if the current char is a period then perform a newline action (or if it is a \n then display a period).

Aside from the null terminator, no character code is sacred and when you write a text editor or viewer you are in charge of translating the bits in your file into glyphs (or carriage returns) on the screen. The only thing that distinguishes a control character such as the newline from other characters is that most font sets don't include them (meaning they don't have a visual representation available).

That being said, if you are working at a higher level of abstraction then you probably aren't making your own textbox controls. If this is the case then you're stuck with whatever line ending that control makes available to you. Even in this case it is a simple matter to automatically detect the line ending style of any string and make the conversion before you load your text into the control and then undo it when you read from that control. Meaning, that if you're a desktop application dev and your application doesn't recognize \n as a newline then it isn't a very friendly application and you really have no excuse because it isn't hard to make it the right way. It also means that whomever wrote Notepad should be ashamed of himself because it really is very easy to do much better and so many people suffer through using it every day.

Setting CSS pseudo-class rules from JavaScript

My trick is using an attribute selector. Attributes are easier to set up by javascript.

css

.class{ /*normal css... */}
.class[special]:after{ content: 'what you want'}

javascript

  function setSpecial(id){ document.getElementById(id).setAttribute('special', '1'); }

html

<element id='x' onclick="setSpecial(this.id)"> ...  

Mongoose (mongodb) batch insert?

It seems that using mongoose there is a limit of more than 1000 documents, when using

Potato.collection.insert(potatoBag, onInsert);

You can use:

var bulk = Model.collection.initializeOrderedBulkOp();

async.each(users, function (user, callback) {
    bulk.insert(hash);
}, function (err) {
    var bulkStart = Date.now();
    bulk.execute(function(err, res){
        if (err) console.log (" gameResult.js > err " , err);
        console.log (" gameResult.js > BULK TIME  " , Date.now() - bulkStart );
        console.log (" gameResult.js > BULK INSERT " , res.nInserted)
      });
});

But this is almost twice as fast when testing with 10000 documents:

function fastInsert(arrOfResults) {
var startTime = Date.now();
    var count = 0;
    var c = Math.round( arrOfResults.length / 990);

    var fakeArr = [];
    fakeArr.length = c;
    var docsSaved = 0

    async.each(fakeArr, function (item, callback) {

            var sliced = arrOfResults.slice(count, count+999);
            sliced.length)
            count = count +999;
            if(sliced.length != 0 ){
                    GameResultModel.collection.insert(sliced, function (err, docs) {
                            docsSaved += docs.ops.length
                            callback();
                    });
            }else {
                    callback()
            }
    }, function (err) {
            console.log (" gameResult.js > BULK INSERT AMOUNT: ", arrOfResults.length, "docsSaved  " , docsSaved, " DIFF TIME:",Date.now() - startTime);
    });
}

String replacement in Objective-C

If you want multiple string replacement:

NSString *s = @"foo/bar:baz.foo";
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@"/:."];
s = [[s componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: @""];
NSLog(@"%@", s); // => foobarbazfoo

How to uninstall an older PHP version from centOS7

Subscribing to the IUS Community Project Repository

cd ~
curl 'https://setup.ius.io/' -o setup-ius.sh

Run the script:

sudo bash setup-ius.sh

Upgrading mod_php with Apache

This section describes the upgrade process for a system using Apache as the web server and mod_php to execute PHP code. If, instead, you are running Nginx and PHP-FPM, skip ahead to the next section.

Begin by removing existing PHP packages. Press y and hit Enter to continue when prompted.

sudo yum remove php-cli mod_php php-common

Install the new PHP 7 packages from IUS. Again, press y and Enter when prompted.

sudo yum install mod_php70u php70u-cli php70u-mysqlnd

Finally, restart Apache to load the new version of mod_php:

sudo apachectl restart

You can check on the status of Apache, which is managed by the httpd systemd unit, using systemctl:

systemctl status httpd

Forgot Oracle username and password, how to retrieve?

  1. Open Command Prompt/Terminal and type:

    sqlplus / as SYSDBA

  2. SQL prompt will turn up. Now type:

    ALTER USER existing_account_name IDENTIFIED BY new_password ACCOUNT UNLOCK;

  3. Voila! You've unlocked your account.

How to not wrap contents of a div?

I don't know the reasoning behind this, but I set my parent container to display:flex and the child containers to display:inline-block and they stayed inline despite the combined width of the children exceeding the parent.

Didn't need to toy with max-width, max-height, white-space, or anything else.

Hope that helps someone.

I want to align the text in a <td> to the top

I was facing such a problem, look at the picture below

enter image description here

and here is its HTML

<tr class="li1">
    <td valign="top">1.</td>
    <td colspan="5" valign="top">
        <p>How to build e-book learning environment</p>
    </td>
</tr>

so I fix it by changing valign Attribute in both td tags to baseline

and it worked

here is the result enter image description here

hope this help you

Python debugging tips

PDB

You can use the pdb module, insert pdb.set_trace() anywhere and it will function as a breakpoint.

>>> import pdb
>>> a="a string"
>>> pdb.set_trace()
--Return--
> <stdin>(1)<module>()->None
(Pdb) p a
'a string'
(Pdb)

To continue execution use c (or cont or continue).

It is possible to execute arbitrary Python expressions using pdb. For example, if you find a mistake, you can correct the code, then type a type expression to have the same effect in the running code

ipdb is a version of pdb for IPython. It allows the use of pdb with all the IPython features including tab completion.

It is also possible to set pdb to automatically run on an uncaught exception.

Pydb was written to be an enhanced version of Pdb. Benefits?

Date Comparison using Java

If you're set on using Java Dates rather than, say, JodaTime, use a java.text.DateFormat to convert the string to a Date, then compare the two using .equals:

I almost forgot: You need to zero out the hours, minutes, seconds, and milliseconds on the current date before comparing them. I used a Calendar object below to do it.

import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;

// Other code here
    String toDate;
    //toDate = "05/11/2010";

    // Value assigned to toDate somewhere in here

    DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
    Calendar currDtCal = Calendar.getInstance();

    // Zero out the hour, minute, second, and millisecond
    currDtCal.set(Calendar.HOUR_OF_DAY, 0);
    currDtCal.set(Calendar.MINUTE, 0);
    currDtCal.set(Calendar.SECOND, 0);
    currDtCal.set(Calendar.MILLISECOND, 0);

    Date currDt = currDtCal.getTime();

    Date toDt;
    try {
        toDt = df.parse(toDate);
    } catch (ParseException e) {
        toDt = null;
        // Print some error message back to the user
    }

    if (currDt.equals(toDt)) {
        // They're the same date
    }

How to check if a variable exists in a FreeMarker template?

To check if the value exists:

[#if userName??]
   Hi ${userName}, How are you?
[/#if]

Or with the standard freemarker syntax:

<#if userName??>
   Hi ${userName}, How are you?
</#if>

To check if the value exists and is not empty:

<#if userName?has_content>
    Hi ${userName}, How are you?
</#if>

Node.js Best Practice Exception Handling

I wrote about this recently at http://snmaynard.com/2012/12/21/node-error-handling/. A new feature of node in version 0.8 is domains and allow you to combine all the forms of error handling into one easier manage form. You can read about them in my post.

You can also use something like Bugsnag to track your uncaught exceptions and be notified via email, chatroom or have a ticket created for an uncaught exception (I am the co-founder of Bugsnag).

Create whole path automatically when writing to a new file

Something like:

File file = new File("C:\\user\\Desktop\\dir1\\dir2\\filename.txt");
file.getParentFile().mkdirs();
FileWriter writer = new FileWriter(file);

How to set headers in http get request?

The Header field of the Request is public. You may do this :

req.Header.Set("name", "value")

Change key pair for ec2 instance

This is for them who has two different pem file and for any security purpose want to discard one of the two. Let's say we want to discard 1.pem

  1. Connect with server 2 and copy ssh key from ~/.ssh/authorized_keys
  2. Connect with server 1 in another terminal and paste the key in ~/.ssh/authorized_keys. You will have now two public ssh key here
  3. Now, just for your confidence, try to connect with server 1 with 2.pem. You will be able to connect server 1 with both 1.pem and 2.pem
  4. Now, comment the 1.pem ssh and connect using ssh -i 2.pem user@server1

Unable to call the built in mb_internal_encoding method?

For OpenSUse (zypper package manager):

zypper install php5-mbstring

and:

zyper install php7-mbstring

In the other hand, you can search them through YaST Software manager.

Note that, you must restart apache http server:

systemctl restart apache2.service

Is SQL syntax case sensitive?

I found this blog post to be very helpful (I am not the author). Summarizing (please read, though):

...delimited identifiers are case sensitive ("table_name" != "Table_Name"), while non quoted identifiers are not, and are transformed to upper case (table_name => TABLE_NAME).

He found DB2, Oracle and Interbase/Firebird are 100% compliant:

PostgreSQL ... lowercases every unquoted identifier, instead of uppercasing it. MySQL ... file system dependent. SQLite and SQL Server ... case of the table and field names are preserved on creation, but they are completely ignored afterwards.

Is it possible to style a mouseover on an image map using CSS?

Sorry to jump on this question late in the game but I have an answer for irregular (non-rectangular) shapes. I solved it using SVGs to generate masks of where I want to have the event attached.

The idea is to attach events to inlined SVGs, super cheap and even user friendly because there are plenty of programs for generating SVGs. The SVG can have a layer of the image as a background.

http://jcrogel.com/code/2015/03/18/mapping-images-using-javascript-events/

Set language for syntax highlighting in Visual Studio Code

In the very right bottom corner, left to the smiley there was the icon saying "Plain Text". When you click it, the menu with all languages appears where you can choose your desired language.

VSCode

DateTime.TryParse issue with dates of yyyy-dd-MM format

If you give the user the opportunity to change the date/time format, then you'll have to create a corresponding format string to use for parsing. If you know the possible date formats (i.e. the user has to select from a list), then this is much easier because you can create those format strings at compile time.

If you let the user do free-format design of the date/time format, then you'll have to create the corresponding DateTime format strings at runtime.

Convert a JSON String to a HashMap

You can use Jackson API as well for this :

    final String json = "....your json...";
    final ObjectMapper mapper = new ObjectMapper();
    final MapType type = mapper.getTypeFactory().constructMapType(
        Map.class, String.class, Object.class);
    final Map<String, Object> data = mapper.readValue(json, type);

How to Alter Constraint

No. We cannot alter the constraint, only thing we can do is drop and recreate it

ALTER TABLE [TABLENAME] DROP CONSTRAINT [CONSTRAINTNAME]

Foreign Key Constraint

Alter Table Table1 Add Constraint [CONSTRAINTNAME] Foreign Key (Column) References Table2 (Column) On Update Cascade On Delete Cascade

Primary Key constraint

Alter Table Table add constraint [Primary Key] Primary key(Column1,Column2,.....)

Error: Selection does not contain a main type

I ran into the same problem. I fixed by right click on the package -> properties -> Java Build Path -> Add folder (select the folder your code reside in).

URL for public Amazon S3 bucket

The URL structure you're referring to is called the REST endpoint, as opposed to the Web Site Endpoint.


Note: Since this answer was originally written, S3 has rolled out dualstack support on REST endpoints, using new hostnames, while leaving the existing hostnames in place. This is now integrated into the information provided, below.


If your bucket is really in the us-east-1 region of AWS -- which the S3 documentation formerly referred to as the "US Standard" region, but was subsequently officially renamed to the "U.S. East (N. Virginia) Region" -- then http://s3-us-east-1.amazonaws.com/bucket/ is not the correct form for that endpoint, even though it looks like it should be. The correct format for that region is either http://s3.amazonaws.com/bucket/ or http://s3-external-1.amazonaws.com/bucket/

The format you're using is applicable to all the other S3 regions, but not US Standard US East (N. Virginia) [us-east-1].

S3 now also has dual-stack endpoint hostnames for the REST endpoints, and unlike the original endpoint hostnames, the names of these have a consistent format across regions, for example s3.dualstack.us-east-1.amazonaws.com. These endpoints support both IPv4 and IPv6 connectivity and DNS resolution, but are otherwise functionally equivalent to the existing REST endpoints.

If your permissions and configuration are set up such that the web site endpoint works, then the REST endpoint should work, too.

However... the two endpoints do not offer the same functionality.

Roughly speaking, the REST endpoint is better-suited for machine access and the web site endpoint is better suited for human access, since the web site endpoint offers friendly error messages, index documents, and redirects, while the REST endpoint doesn't. On the other hand, the REST endpoint offers HTTPS and support for signed URLs, while the web site endpoint doesn't.

Choose the correct type of endpoint (REST or web site) for your application:

http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteEndpoints.html#WebsiteRestEndpointDiff


¹ s3-external-1.amazonaws.com has been referred to as the "Northern Virginia endpoint," in contrast to the "Global endpoint" s3.amazonaws.com. It was unofficially possible to get read-after-write consistency on new objects in this region if the "s3-external-1" hostname was used, because this would send you to a subset of possible physical endpoints that could provide that functionality. This behavior is now officially supported on this endpoint, so this is probably the better choice in many applications. Previously, s3-external-2 had been referred to as the "Pacific Northwest endpoint" for US-Standard, though it is now a CNAME in DNS for s3-external-1 so s3-external-2 appears to have no purpose except backwards-compatibility.

Reordering Chart Data Series

Right-click any series on the chart. In the "Format Data Series" dialog, there is a "Series Order" tab, in which you can move series up and down. I find this much easier than fiddling with the last argument of the series formula.

This is in Excel 2003 in Windows. There is a similar dialog in Excel 2011 for Mac:

enter image description here

How Can I Truncate A String In jQuery?

From: jQuery text truncation (read more style)

Try this:

var title = "This is your title";

var shortText = jQuery.trim(title).substring(0, 10)
    .split(" ").slice(0, -1).join(" ") + "...";

And you can also use a plugin:

As a extension of String

String.prototype.trimToLength = function(m) {
  return (this.length > m) 
    ? jQuery.trim(this).substring(0, m).split(" ").slice(0, -1).join(" ") + "..."
    : this;
};

Use as

"This is your title".trimToLength(10);

Node.js Logging

The "logger.setLevel('ERROR');" is causing the problem. I do not understand why, but when I set it to anything other than "ALL", nothing gets printed in the file. I poked around a little bit and modified your code. It is working fine for me. I created two files.

logger.js

var log4js = require('log4js');
log4js.clearAppenders()
log4js.loadAppender('file');
log4js.addAppender(log4js.appenders.file('test.log'), 'test');
var logger = log4js.getLogger('test');
logger.setLevel('ERROR');

var getLogger = function() {
   return logger;
};

exports.logger = getLogger();

logger.test.js

var logger = require('./logger.js')

var log = logger.logger;

log.error("ERROR message");
log.trace("TRACE message");

When I run "node logger.test.js", I see only "ERROR message" in test.log file. If I change the level to "TRACE" then both lines are printed on test.log.

How to always show scrollbar

Simple and easy. Add this attribute to the ScrollBar:

android:fadeScrollbars="false"

Or you can do this in :

scrollView.setScrollbarFadingEnabled(false);

Or in :

scrollView.isScrollbarFadingEnabled = false

How do you make sure email you send programmatically is not automatically marked as spam?

First of all, you need to ensure the required email authentication mechanisms like SPF and DKIM are in place. These two are prominent ways of proving that you were the actual sender of an email and it's not really spoofed. This reduces the chances of emails getting filtered as spam.

Second thing is, you can check the reverse DNS output of your domain name against different DNSBLs. Use below simple command on terminal:

  **dig a +short (domain-name).(blacklist-domain-name)**

  ie.  dig a +short example.com.dsn.rfc-clueless.org
  > 127.0.0.2

In the above examples, this means your domain "example.com" is listed in blacklist but due to Domain Setting Compliance(rfc-clueless.org list domain which has compliance issue )

note: I prefer multivalley and pepipost tool for checking the domain listings.

The from address/reply-to-id should be proper, always use visible unsubscribe button within your email body (this will help your users to sign out from your email-list without killing your domain reputation)

Pandas unstack problems: ValueError: Index contains duplicate entries, cannot reshape

Here's an example DataFrame which show this, it has duplicate values with the same index. The question is, do you want to aggregate these or keep them as multiple rows?

In [11]: df
Out[11]:
   0  1  2      3
0  1  2  a  16.86
1  1  2  a  17.18
2  1  4  a  17.03
3  2  5  b  17.28

In [12]: df.pivot_table(values=3, index=[0, 1], columns=2, aggfunc='mean')  # desired?
Out[12]:
2        a      b
0 1
1 2  17.02    NaN
  4  17.03    NaN
2 5    NaN  17.28

In [13]: df1 = df.set_index([0, 1, 2])

In [14]: df1
Out[14]:
           3
0 1 2
1 2 a  16.86
    a  17.18
  4 a  17.03
2 5 b  17.28

In [15]: df1.unstack(2)
ValueError: Index contains duplicate entries, cannot reshape

One solution is to reset_index (and get back to df) and use pivot_table.

In [16]: df1.reset_index().pivot_table(values=3, index=[0, 1], columns=2, aggfunc='mean')
Out[16]:
2        a      b
0 1
1 2  17.02    NaN
  4  17.03    NaN
2 5    NaN  17.28

Another option (if you don't want to aggregate) is to append a dummy level, unstack it, then drop the dummy level...

javascript - pass selected value from popup window to parent window input box

use: opener.document.<id of document>.innerHTML = xmlhttp.responseText;

jQuery ajax success callback function definition

Try rewriting your success handler to:

success : handleData

The success property of the ajax method only requires a reference to a function.

In your handleData function you can take up to 3 parameters:

object data
string textStatus
jqXHR jqXHR

How to read a file in other directory in python

i found this way useful also.

import tkinter.filedialog
from_filename = tkinter.filedialog.askopenfilename()  

here a window will appear so you can browse till you find the file , you click on it then you can continue using open , and read .

from_file = open(from_filename, 'r')
contents = from_file.read()
contents

Missing XML comment for publicly visible type or member

This is because an XML documentation file has been specified in your Project Properties and Your Method/Class is public and lack documentation.
You can either :

  1. Disable XML documentation:

    Right Click on your Project -> Properties -> 'Build' tab -> uncheck XML Documentation File.

  2. Sit and write the documentation yourself!

Summary of XML documentation goes like this:

/// <summary>
/// Description of the class/method/variable
/// </summary>
..declaration goes here..

CSS display: inline vs inline-block

Inline elements:

  1. respect left & right margins and padding, but not top & bottom
  2. cannot have a width and height set
  3. allow other elements to sit to their left and right.
  4. see very important side notes on this here.

Block elements:

  1. respect all of those
  2. force a line break after the block element
  3. acquires full-width if width not defined

Inline-block elements:

  1. allow other elements to sit to their left and right
  2. respect top & bottom margins and padding
  3. respect height and width

From W3Schools:

  • An inline element has no line break before or after it, and it tolerates HTML elements next to it.

  • A block element has some whitespace above and below it and does not tolerate any HTML elements next to it.

  • An inline-block element is placed as an inline element (on the same line as adjacent content), but it behaves as a block element.

When you visualize this, it looks like this:

CSS block vs inline vs inline-block

The image is taken from this page, which also talks some more about this subject.

Detect key input in Python

Key input is a predefined event. You can catch events by attaching event_sequence(s) to event_handle(s) by using one or multiple of the existing binding methods(bind, bind_class, tag_bind, bind_all). In order to do that:

  1. define an event_handle method
  2. pick an event(event_sequence) that fits your case from an events list

When an event happens, all of those binding methods implicitly calls the event_handle method while passing an Event object, which includes information about specifics of the event that happened, as the argument.

In order to detect the key input, one could first catch all the '<KeyPress>' or '<KeyRelease>' events and then find out the particular key used by making use of event.keysym attribute.

Below is an example using bind to catch both '<KeyPress>' and '<KeyRelease>' events on a particular widget(root):

try:                        # In order to be able to import tkinter for
    import tkinter as tk    # either in python 2 or in python 3
except ImportError:
    import Tkinter as tk


def event_handle(event):
    # Replace the window's title with event.type: input key
    root.title("{}: {}".format(str(event.type), event.keysym))


if __name__ == '__main__':
    root = tk.Tk()
    event_sequence = '<KeyPress>'
    root.bind(event_sequence, event_handle)
    root.bind('<KeyRelease>', event_handle)
    root.mainloop()

Where does mysql store data?

In version 5.6 at least, the Management tab in MySQL Workbench shows that it's in a hidden folder called ProgramData in the C:\ drive. My default data directory is

C:\ProgramData\MySQL\MySQL Server 5.6\data

. Each database has a folder and each table has a file here.

Last Key in Python Dictionary

There are absolutely very good reason to want the last key of an OrderedDict. I use an ordered dict to list my users when I edit them. I am using AJAX calls to update user permissions and to add new users. Since the AJAX fires when a permission is checked, I want my new user to stay in the same position in the displayed list (last) for convenience until I reload the page. Each time the script runs, it re-orders the user dictionary.

That's all good, why need the last entry? So that when I'm writing unit tests for my software, I would like to confirm that the user remains in the last position until the page is reloaded.

dict.keys()[-1]

Performs this function perfectly (Python 2.7).

Accessing members of items in a JSONArray with Java

An org.json.JSONArray is not iterable.
Here's how I process elements in a net.sf.json.JSONArray:

    JSONArray lineItems = jsonObject.getJSONArray("lineItems");
    for (Object o : lineItems) {
        JSONObject jsonLineItem = (JSONObject) o;
        String key = jsonLineItem.getString("key");
        String value = jsonLineItem.getString("value");
        ...
    }

Works great... :)

How do I add multiple conditions to "ng-disabled"?

There is maybe a bit of a gotcha in the phrasing of the original question:

I need to check that two conditions are both true before enabling a button

The first thing to remember that the ng-disabled directive is evaluating a condition under which the button should be, well, disabled, but the original question is referring to the conditions under which it should en enabled. It will be enabled under any circumstances where the ng-disabled expression is not "truthy".

So, the first consideration is how to rephrase the logic of the question to be closer to the logical requirements of ng-disabled. The logical inverse of checking that two conditions are true in order to enable a button is that if either condition is false then the button should be disabled.

Thus, in the case of the original question, the pseudo-expression for ng-disabled is "disable the button if condition1 is false or condition2 is false". Translating into the Javascript-like code snippet required by Angular (https://docs.angularjs.org/guide/expression), we get:

!condition1 || !condition2

Zoomlar has it right!

Selenium WebDriver How to Resolve Stale Element Reference Exception?

StaleElementReferenceException is due to unavailability of an element being accessed by findelement method.

You need make sure before performing any operations on an element(If you have a doubt on availability of that element)

Waiting for an element's visibility

(new WebDriverWait(driver, 10)).until(new ExpectedCondition()
    {
           public Boolean apply(WebDriver d) {
              return d.findElement(By.name("createForm:dateInput_input")).isDisplayed();
     }});

Or else Use this logic to verify whether the element is present or not.

How to view an HTML file in the browser with Visual Studio Code

For Windows - Open your Default Browser - Tested on VS Code v 1.1.0

Answer to both opening a specific file (name is hard-coded) OR opening ANY other file.

Steps:

  1. Use ctrl + shift + p (or F1) to open the Command Palette.

  2. Type in Tasks: Configure Task or on older versions Configure Task Runner. Selecting it will open the tasks.json file. Delete the script displayed and replace it by the following:

    {
        "version": "0.1.0",
        "command": "explorer",    
        "windows": {
            "command": "explorer.exe"
        },
        "args": ["test.html"]
    }
    

    Remember to change the "args" section of the tasks.json file to the name of your file. This will always open that specific file when you hit F5.

    You may also set the this to open whichever file you have open at the time by using ["${file}"] as the value for "args". Note that the $ goes outside the {...}, so ["{$file}"] is incorrect.

  3. Save the file.

  4. Switch back to your html file (in this example it's "text.html"), and press ctrl + shift + b to view your page in your Web Browser.

enter image description here

How do I hide the PHP explode delimiter from submitted form results?

<select name="FakeName" id="Fake-ID" aria-required="true" required>  <?php $options=nl2br(file_get_contents("employees.txt")); $options=explode("<br />",$options);  foreach ($options as $item_array) { echo "<option value='".$item_array"'>".$item_array"</option>";  } ?> </select> 

D3.js: How to get the computed width and height for an arbitrary element?

.getBoundingClientRect() returns the size of an element and its position relative to the viewport.We can easily get following

  • left, right
  • top, bottom
  • height, width

Example :

var element = d3.select('.elementClassName').node();
element.getBoundingClientRect().width;

How to run Spring Boot web application in Eclipse itself?

If you are doing code in STS you just need to add the devtools dependency in your maven file. After that it will run itself whenever you will do some change.

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

Numpy first occurrence of value greater than existing value

This is a little faster (and looks nicer)

np.argmax(aa>5)

Since argmax will stop at the first True ("In case of multiple occurrences of the maximum values, the indices corresponding to the first occurrence are returned.") and doesn't save another list.

In [2]: N = 10000

In [3]: aa = np.arange(-N,N)

In [4]: timeit np.argmax(aa>N/2)
100000 loops, best of 3: 52.3 us per loop

In [5]: timeit np.where(aa>N/2)[0][0]
10000 loops, best of 3: 141 us per loop

In [6]: timeit np.nonzero(aa>N/2)[0][0]
10000 loops, best of 3: 142 us per loop

How to create the most compact mapping n ? isprime(n) up to a limit N?

When I have to do a fast verification, I write this simple code based on the basic division between numbers lower than square root of input.

def isprime(n):
    if n%2==0:
        return n==2
    else:
        cota = int(n**0.5)+1
        for ind in range(3,2,cota):
            if n%ind==0:
                print(ind)
                return False
    is_one = n==1
    return True != is_one

isprime(22783)
  • The last True != n==1 is to avoid the case n=1.

Install Android App Bundle on device

No, if you are debugging an app without other users use the Build > Build APK(s) menu in Android Studio or execute it in your device/emulator them the debug release apk will install automatically. If you are debugging an app with others use Build > Generate Signed APK... menu. If you want to publish the beta version use the Google Play Store. Your APK(s) will be in app\build\outputs\apk\debug and app\release folders.

How to add background-image using ngStyle (angular2)?

I think you could try this:

<div [ngStyle]="{'background-image': 'url(' + photo + ')'}"></div>

From reading your ngStyle expression, I guess that you missed some "'"...

How to check if keras tensorflow backend is GPU or CPU version?

According to the documentation.

If you are running on the TensorFlow or CNTK backends, your code will automatically run on GPU if any available GPU is detected.

You can check what all devices are used by tensorflow by -

from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())

Also as suggested in this answer

import tensorflow as tf
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))

This will print whether your tensorflow is using a CPU or a GPU backend. If you are running this command in jupyter notebook, check out the console from where you have launched the notebook.

If you are sceptic whether you have installed the tensorflow gpu version or not. You can install the gpu version via pip.

pip install tensorflow-gpu

How to get key names from JSON using jq

In combination with the above answer, you want to ask jq for raw output, so your last filter should be eg.:

     cat input.json | jq -r 'keys'

From jq help:

     -r     output raw strings, not JSON texts;

From inside of a Docker container, how do I connect to the localhost of the machine?

I doing a hack similar to above posts of get the local IP to map to a alias name (DNS) in the container. The major problem is to get dynamically with a simple script that works both in Linux and OSX the host IP address. I did this script that works in both environments (even in Linux distribution with "$LANG" != "en_*" configured):

ifconfig | grep -E "([0-9]{1,3}\.){3}[0-9]{1,3}" | grep -v 127.0.0.1 | awk '{ print $2 }' | cut -f2 -d: | head -n1

So, using Docker Compose, the full configuration will be:

Startup script (docker-run.sh):

export DOCKERHOST=$(ifconfig | grep -E "([0-9]{1,3}\.){3}[0-9]{1,3}" | grep -v 127.0.0.1 | awk '{ print $2 }' | cut -f2 -d: | head -n1)
docker-compose -f docker-compose.yml up

docker-compose.yml:

myapp:
  build: .
  ports:
    - "80:80"
  extra_hosts:
    - "dockerhost:$DOCKERHOST"

Then change http://localhost to http://dockerhost in your code.

For a more advance guide of how to customize the DOCKERHOST script, take a look at this post with a explanation of how it works.

HTTP could not register URL http://+:8000/HelloWCF/. Your process does not have access rights to this namespace

Right Click on Visual Studio > Run as Administrator > Open your project and run the service. This is a privilege related issue.

In java how to get substring from a string till a character c?

If your project already uses commons-lang, StringUtils provide a nice method for this purpose:

String filename = "abc.def.ghi";

String start = StringUtils.substringBefore(filename, "."); // returns "abc"

see javadoc [2.6] [3.1]

How exactly does the android:onClick XML attribute differ from setOnClickListener?

android:onClick is for API level 4 onwards, so if you're targeting < 1.6, then you can't use it.

Java JRE 64-bit download for Windows?

I believe the link below will always give you the latest version of the 64-bit JRE http://javadl.sun.com/webapps/download/AutoDL?BundleId=43883

Map implementation with duplicate keys

This problem can be solved with a list of map entry List<Map.Entry<K,V>>. We don't need to use neither external libraries nor new implementation of Map. A map entry can be created like this: Map.Entry<String, Integer> entry = new AbstractMap.SimpleEntry<String, Integer>("key", 1);

Javascript - Get Image height

Do you want to adjust the images themselves, or just the way they display? If the former, you want something on the server side. If the latter, you just need to change image.height and image.width.

What are the RGB codes for the Conditional Formatting 'Styles' in Excel?

For anyone who stumbles across this in the future, this is how you do it:

xl.Range("A1:A1").Style := "Bad"
xl.Range("A1:A1").Style := "Good"
xl.Range("A1:A1").Style := "Neutral"

An easy way to check on things like this is to open excel and record a macro. In this case I recorded a macro where I just formatted the cell to "Bad". Once you've recorded the macro, just go in and edit it and it will essentially give you the code. It will require a little translation on your part, but here is what the macro looks like when I edit it:

 Selection.Style = "Bad"

As you can see, it's pretty easy to make the jump to AHK from what excel provides.

With arrays, why is it the case that a[5] == 5[a]?

Nice question/answers.

Just want to point out that C pointers and arrays are not the same, although in this case the difference is not essential.

Consider the following declarations:

int a[10];
int* p = a;

In a.out, the symbol a is at an address that's the beginning of the array, and symbol p is at an address where a pointer is stored, and the value of the pointer at that memory location is the beginning of the array.

Python, print all floats to 2 decimal places in output

Not directly in the way you want to write that, no. One of the design tenets of Python is "Explicit is better than implicit" (see import this). This means that it's better to describe what you want rather than having the output format depend on some global formatting setting or something. You could of course format your code differently to make it look nicer:

print         '%.2f' % var1, \
      'kg =' ,'%.2f' % var2, \
      'lb =' ,'%.2f' % var3, \
      'gal =','%.2f' % var4, \
      'l'

Subprocess changing directory

just use os.chdir
Example:

>>> import os
>>> import subprocess
>>> # Lets Just Say WE want To List The User Folders
>>> os.chdir("/home/")
>>> subprocess.run("ls")
user1 user2 user3 user4

Simple PHP calculator

<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Calculator</title>
    </head>
    <body>
    HTML Code is here:

         <form method="post">
            <input type="text" name="numb1">
            <input type="text" name="numb2">
            <select name="operator" id="">
               <option>None</option>
               <option>Add</option>
               <option>Subtract</option>
               <option>Multiply</option>
               <option>Divide</option>
               <option>Square</option>
            </select>
            <button type="submit" name="submit" value="submit">Calculate</button>
         </form>

    PHP Code:

        <?php 

            if (isset($_POST['submit'])) {
                $result1 = $_POST['numb1'];
                $result2 = $_POST['numb2'];
                $operator = $_POST['operator'];
                switch ($operator) {
                    case 'None':
                        echo "You need to select any operator";
                        break;
                    case 'Add':
                        echo $result1 + $result2;
                        break;
                    case 'Subtract':
                        echo $result1 - $result2;
                        break;
                    case 'Multiply':
                        echo $result1 * $result2;
                        break;
                    case 'Divide':
                        echo $result1 / $result2;
                        break;
                    case 'Square':
                        echo $result1 ** $result2;
                        break;
                }
            }


         ?>
        enter code here

    </body>
    </html>

How do I get the directory of the PowerShell script I execute?

PowerShell 3 has the $PSScriptRoot automatic variable:

Contains the directory from which a script is being run.

In Windows PowerShell 2.0, this variable is valid only in script modules (.psm1). Beginning in Windows PowerShell 3.0, it is valid in all scripts.

Don't be fooled by the poor wording. PSScriptRoot is the directory of the current file.

In PowerShell 2, you can calculate the value of $PSScriptRoot yourself:

# PowerShell v2
$PSScriptRoot = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition

Entity Framework: table without primary key

Having a useless identity key is pointless at times. I find if the ID isn't used, why add it? However, Entity is not so forgiving about it, so adding an ID field would be best. Even in the case it's not used, it's better than dealing with Entity's incessive errors about the missing identity key.

Can't find file executable in your configured search path for gnc gcc compiler

For that you need to install binary of GNU GCC compiler, which comes with MinGW package. You can download MinGW( and put it under C:/ ) and later you have to download gnu -c, c++ related Binaries, so select required package and install them(in the MinGW ). Then in the Code::Blocks, go to Setting, Compiler, ToolChain Executable. In that you will find Path, there set C:/MinGW. Then mentioned error will be vanished.

CSS: how to position element in lower right?

Lets say your HTML looks something like this:

<div class="box">
    <!-- stuff -->
    <p class="bet_time">Bet 5 days ago</p>
</div>

Then, with CSS, you can make that text appear in the bottom right like so:

.box {
    position:relative;
}
.bet_time {
    position:absolute;
    bottom:0;
    right:0;
}

The way this works is that absolutely positioned elements are always positioned with respect to the first relatively positioned parent element, or the window. Because we set the box's position to relative, .bet_time positions its right edge to the right edge of .box and its bottom edge to the bottom edge of .box

How to create a database from shell command?

cat filename.sql | mysql -u username -p # type mysql password when asked for it

Where filename.sql holds all the sql to create your database. Or...

echo "create database `database-name`" | mysql -u username -p

If you really only want to create a database.

Action bar navigation modes are deprecated in Android L

It seems like they added a new Class named android.widget.Toolbar that extends ViewGroup. Also they added a new method setActionBar(Toolbar) in Activity. I haven't tested it yet, but it looks like you can wrap all kinds of TabWidgets, Spinners or custom views into a Toolbar and use it as your Actionbar.

Insert default value when parameter is null

Don't specify the column or value when inserting and the DEFAULT constaint's value will be substituted for the missing value.

I don't know how this would work in a single column table. I mean: it would, but it wouldn't be very useful.

Declaring and using MySQL varchar variables

I ran into the same problem using MySQL Workbench. According to the MySQL documentation, the DECLARE "statement declares local variables within stored programs." That apparently means it is only guaranteed to work with stored procedures/functions.

The solution for me was to simply remove the DECLARE statement, and introduce the variable in the SET statement. For your code that would mean:

-- DECLARE FOO varchar(7); 
-- DECLARE oldFOO varchar(7);

-- the @ symbol is required
SET @FOO = '138'; 
SET @oldFOO = CONCAT('0', FOO);

UPDATE mypermits SET person = FOO WHERE person = oldFOO;

When to use RabbitMQ over Kafka?

RabbitMQ is a solid, general-purpose message broker that supports several protocols such as AMQP, MQTT, STOMP, etc. It can handle high throughput. A common use case for RabbitMQ is to handle background jobs or long-running task, such as file scanning, image scaling or PDF conversion. RabbitMQ is also used between microservices, where it serves as a means of communicating between applications, avoiding bottlenecks passing messages.

Kafka is a message bus optimized for high-throughput ingestion data streams and replay. Use Kafka when you have the need to move a large amount of data, process data in real-time or analyze data over a time period. In other words, where data need to be collected, stored, and handled. An example is when you want to track user activity on a webshop and generate suggested items to buy. Another example is data analysis for tracking, ingestion, logging or security.

Kafka can be seen as a durable message broker where applications can process and re-process streamed data on disk. Kafka has a very simple routing approach. RabbitMQ has better options if you need to route your messages in complex ways to your consumers. Use Kafka if you need to support batch consumers that could be offline or consumers that want messages at low latency. 

In order to understand how to read data from Kafka, we first need to understand its consumers and consumer groups. Partitions allow you to parallelize a topic by splitting the data across multiple nodes. Each record in a partition is assigned and identified by its unique offset. This offset points to the record in a partition. In the latest version of Kafka, Kafka maintains a numerical offset for each record in a partition. A consumer in Kafka can either automatically commit offsets periodically, or it can choose to control this committed position manually. RabbitMQ will keep all states about consumed/acknowledged/unacknowledged messages. I find Kafka more complex to understand than the case of RabbitMQ, where the message is simply removed from the queue once it's acked.

RabbitMQ's queues are fastest when they're empty, while Kafka retains large amounts of data with very little overhead - Kafka is designed for holding and distributing large volumes of messages. (If you plan to have very long queues in RabbitMQ you could have a look at lazy queues.)

Kafka is built from the ground up with horizontal scaling (scale by adding more machines) in mind, while RabbitMQ is mostly designed for vertical scaling (scale by adding more power).

RabbitMQ has a built-in user-friendly interface that lets you monitor and handle your RabbitMQ server from a web browser. Among other things, queues, connections, channels, exchanges, users and user permissions can be handled - created, deleted and listed in the browser and you can monitor message rates and send/receive messages manually. Kafka has a number of open-source tools, and also some commercial once, offering the administration and monitoring functionalities. I would say that it's easier/gets faster to get a good understanding of RabbitMQ.

In general, if you want a simple/traditional pub-sub message broker, the obvious choice is RabbitMQ, as it will most probably scale more than you will ever need it to scale. I would have chosen RabbitMQ if my requirements were simple enough to deal with system communication through channels/queues, and where retention and streaming is not a requirement.

There are two main situations where I would choose RabbitMQ; For long-running tasks, when I need to run reliable background jobs. And for communication and integration within, and between applications, i.e as middleman between microservices; where a system simply needs to notify another part of the system to start to work on a task, like ordering handling in a webshop (order placed, update order status, send order, payment, etc.).

In general, if you want a framework for storing, reading (re-reading), and analyzing streaming data, use Apache Kafka. It’s ideal for systems that are audited or those that need to store messages permanently. These can also be broken down into two main use cases for analyzing data (tracking, ingestion, logging, security etc.) or real-time processing.

More reading, use cases and some comparison data can be found here: https://www.cloudamqp.com/blog/2019-12-12-when-to-use-rabbitmq-or-apache-kafka.html

Also recommending the industry paper: "Kafka versus RabbitMQ: A comparative study of two industry reference publish/subscribe implementations": http://dl.acm.org/citation.cfm?id=3093908

I do work at a company providing both Apache Kafka and RabbitMQ as a Service.

Please help me convert this script to a simple image slider

Problems only surface when I am I trying to give the first loaded content an active state

Does this mean that you want to add a class to the first button?

$('.o-links').click(function(e) {   // ... }).first().addClass('O_Nav_Current'); 

instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:

CSS:

.image-area {     width: 100%;     height: auto;     display: none; }  .image-area:first-of-type {     display: block; } 

JavaScript:

var $slides = $('.image-area'),     $btns = $('a.o-links');  $btns.on('click', function (e) {     var i = $btns.removeClass('O_Nav_Current').index(this);     $(this).addClass('O_Nav_Current');      $slides.filter(':visible').fadeOut(1000, function () {         $slides.eq(i).fadeIn(1000);     });      e.preventDefault();  }).first().addClass('O_Nav_Current'); 

http://jsfiddle.net/RmF57/

Replace first occurrence of string in Python

string replace() function perfectly solves this problem:

string.replace(s, old, new[, maxreplace])

Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.

>>> u'longlongTESTstringTEST'.replace('TEST', '?', 1)
u'longlong?stringTEST'

Angular 4 - Observable catch error

If you want to use the catch() of the Observable you need to use Observable.throw() method before delegating the error response to a method

_x000D_
_x000D_
import { Injectable } from '@angular/core';_x000D_
import { Headers, Http, ResponseOptions} from '@angular/http';_x000D_
import { AuthHttp } from 'angular2-jwt';_x000D_
_x000D_
import { MEAT_API } from '../app.api';_x000D_
_x000D_
import { Observable } from 'rxjs/Observable';_x000D_
import 'rxjs/add/operator/map';_x000D_
import 'rxjs/add/operator/catch';_x000D_
_x000D_
@Injectable()_x000D_
export class CompareNfeService {_x000D_
_x000D_
_x000D_
  constructor(private http: AuthHttp) {}_x000D_
_x000D_
  envirArquivos(order): Observable < any > {_x000D_
    const headers = new Headers();_x000D_
    return this.http.post(`${MEAT_API}compare/arquivo`, order,_x000D_
        new ResponseOptions({_x000D_
          headers: headers_x000D_
        }))_x000D_
      .map(response => response.json())_x000D_
      .catch((e: any) => Observable.throw(this.errorHandler(e)));_x000D_
  }_x000D_
_x000D_
  errorHandler(error: any): void {_x000D_
    console.log(error)_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

Using Observable.throw() worked for me

Javascript setInterval not working

Change setInterval("func",10000) to either setInterval(funcName, 10000) or setInterval("funcName()",10000). The former is the recommended method.

Passing a Bundle on startActivity()?

Passing data from one Activity to Activity in android

An intent contains the action and optionally additional data. The data can be passed to other activity using intent putExtra() method. Data is passed as extras and are key/value pairs. The key is always a String. As value you can use the primitive data types int, float, chars, etc. We can also pass Parceable and Serializable objects from one activity to other.

Intent intent = new Intent(context, YourActivity.class);
intent.putExtra(KEY, <your value here>);
startActivity(intent);

Retrieving bundle data from android activity

You can retrieve the information using getData() methods on the Intent object. The Intent object can be retrieved via the getIntent() method.

 Intent intent = getIntent();
  if (null != intent) { //Null Checking
    String StrData= intent.getStringExtra(KEY);
    int NoOfData = intent.getIntExtra(KEY, defaultValue);
    boolean booleanData = intent.getBooleanExtra(KEY, defaultValue);
    char charData = intent.getCharExtra(KEY, defaultValue); 
  }

gpg decryption fails with no secret key error

You can also be interested at the top answer in here: https://askubuntu.com/questions/1080204/gpg-problem-with-the-agent-permission-denied

basically the solution that worked for me too is:

gpg --decrypt --pinentry-mode=loopback <file>

What is the JUnit XML format specification that Hudson supports?

The top answer of the question Anders Lindahl refers to an xsd file.

Personally I found this xsd file also very useful (I don't remember how I found that one). It looks a bit less intimidating, and as far as I used it, all the elements and attributes seem to be recognized by Jenkins (v1.451)

One thing though: when adding multiple <failure ... elements, only one was retained in Jenkins. When creating the xml file, I now concatenate all the failures in one.


Update 2016-11 The link is broken now. A better alternative is this page from cubic.org: JUnit XML reporting file format, where a nice effort has been taken to provide a sensible documented example. Example and xsd are copied below, but their page looks waay nicer.


sample JUnit XML file

<?xml version="1.0" encoding="UTF-8"?>
<!-- a description of the JUnit XML format and how Jenkins parses it. See also junit.xsd -->

<!-- if only a single testsuite element is present, the testsuites
     element can be omitted. All attributes are optional. -->
<testsuites disabled="" <!-- total number of disabled tests from all testsuites. -->
            errors=""   <!-- total number of tests with error result from all testsuites. -->
            failures="" <!-- total number of failed tests from all testsuites. -->
            name=""
            tests=""    <!-- total number of successful tests from all testsuites. -->
            time=""     <!-- time in seconds to execute all test suites. -->
        >

  <!-- testsuite can appear multiple times, if contained in a testsuites element.
       It can also be the root element. -->
  <testsuite name=""      <!-- Full (class) name of the test for non-aggregated testsuite documents.
                               Class name without the package for aggregated testsuites documents. Required -->
         tests=""     <!-- The total number of tests in the suite, required. -->
         disabled=""  <!-- the total number of disabled tests in the suite. optional -->
             errors=""    <!-- The total number of tests in the suite that errored. An errored test is one that had an unanticipated problem,
                               for example an unchecked throwable; or a problem with the implementation of the test. optional -->
             failures=""  <!-- The total number of tests in the suite that failed. A failure is a test which the code has explicitly failed
                               by using the mechanisms for that purpose. e.g., via an assertEquals. optional -->
             hostname=""  <!-- Host on which the tests were executed. 'localhost' should be used if the hostname cannot be determined. optional -->
         id=""        <!-- Starts at 0 for the first testsuite and is incremented by 1 for each following testsuite -->
         package=""   <!-- Derived from testsuite/@name in the non-aggregated documents. optional -->
         skipped=""   <!-- The total number of skipped tests. optional -->
         time=""      <!-- Time taken (in seconds) to execute the tests in the suite. optional -->
         timestamp="" <!-- when the test was executed in ISO 8601 format (2014-01-21T16:17:18). Timezone may not be specified. optional -->
         >

    <!-- Properties (e.g., environment settings) set during test
     execution. The properties element can appear 0 or once. -->
    <properties>
      <!-- property can appear multiple times. The name and value attributres are required. -->
      <property name="" value=""/>
    </properties>

    <!-- testcase can appear multiple times, see /testsuites/testsuite@tests -->
    <testcase name=""       <!-- Name of the test method, required. -->
          assertions="" <!-- number of assertions in the test case. optional -->
          classname=""  <!-- Full class name for the class the test method is in. required -->
          status=""
          time=""       <!-- Time taken (in seconds) to execute the test. optional -->
          >

      <!-- If the test was not executed or failed, you can specify one
           the skipped, error or failure elements. -->

      <!-- skipped can appear 0 or once. optional -->
      <skipped/>

      <!-- Indicates that the test errored. An errored test is one
           that had an unanticipated problem. For example an unchecked
           throwable or a problem with the implementation of the
           test. Contains as a text node relevant data for the error,
           for example a stack trace. optional -->
      <error message="" <!-- The error message. e.g., if a java exception is thrown, the return value of getMessage() -->
         type=""    <!-- The type of error that occured. e.g., if a java execption is thrown the full class name of the exception. -->
         ></error>

      <!-- Indicates that the test failed. A failure is a test which
       the code has explicitly failed by using the mechanisms for
       that purpose. For example via an assertEquals. Contains as
       a text node relevant data for the failure, e.g., a stack
       trace. optional -->
      <failure message="" <!-- The message specified in the assert. -->
           type=""    <!-- The type of the assert. -->
           ></failure>

      <!-- Data that was written to standard out while the test was executed. optional -->
      <system-out></system-out>

      <!-- Data that was written to standard error while the test was executed. optional -->
      <system-err></system-err>
    </testcase>

    <!-- Data that was written to standard out while the test suite was executed. optional -->
    <system-out></system-out>
    <!-- Data that was written to standard error while the test suite was executed. optional -->
    <system-err></system-err>
  </testsuite>
</testsuites>

JUnit XSD file

<?xml version="1.0" encoding="UTF-8" ?>
<!-- from https://svn.jenkins-ci.org/trunk/hudson/dtkit/dtkit-format/dtkit-junit-model/src/main/resources/com/thalesgroup/dtkit/junit/model/xsd/junit-4.xsd -->
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

    <xs:element name="failure">
        <xs:complexType mixed="true">
            <xs:attribute name="type" type="xs:string" use="optional"/>
            <xs:attribute name="message" type="xs:string" use="optional"/>
        </xs:complexType>
    </xs:element>

    <xs:element name="error">
        <xs:complexType mixed="true">
            <xs:attribute name="type" type="xs:string" use="optional"/>
            <xs:attribute name="message" type="xs:string" use="optional"/>
        </xs:complexType>
    </xs:element>

    <xs:element name="properties">
        <xs:complexType>
            <xs:sequence>
                <xs:element ref="property" maxOccurs="unbounded"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>

    <xs:element name="property">
        <xs:complexType>
            <xs:attribute name="name" type="xs:string" use="required"/>
            <xs:attribute name="value" type="xs:string" use="required"/>
        </xs:complexType>
    </xs:element>

    <xs:element name="skipped" type="xs:string"/>
    <xs:element name="system-err" type="xs:string"/>
    <xs:element name="system-out" type="xs:string"/>

    <xs:element name="testcase">
        <xs:complexType>
            <xs:sequence>
                <xs:element ref="skipped" minOccurs="0" maxOccurs="1"/>
                <xs:element ref="error" minOccurs="0" maxOccurs="unbounded"/>
                <xs:element ref="failure" minOccurs="0" maxOccurs="unbounded"/>
                <xs:element ref="system-out" minOccurs="0" maxOccurs="unbounded"/>
                <xs:element ref="system-err" minOccurs="0" maxOccurs="unbounded"/>
            </xs:sequence>
            <xs:attribute name="name" type="xs:string" use="required"/>
            <xs:attribute name="assertions" type="xs:string" use="optional"/>
            <xs:attribute name="time" type="xs:string" use="optional"/>
            <xs:attribute name="classname" type="xs:string" use="optional"/>
            <xs:attribute name="status" type="xs:string" use="optional"/>
        </xs:complexType>
    </xs:element>

    <xs:element name="testsuite">
        <xs:complexType>
            <xs:sequence>
                <xs:element ref="properties" minOccurs="0" maxOccurs="1"/>
                <xs:element ref="testcase" minOccurs="0" maxOccurs="unbounded"/>
                <xs:element ref="system-out" minOccurs="0" maxOccurs="1"/>
                <xs:element ref="system-err" minOccurs="0" maxOccurs="1"/>
            </xs:sequence>
            <xs:attribute name="name" type="xs:string" use="required"/>
            <xs:attribute name="tests" type="xs:string" use="required"/>
            <xs:attribute name="failures" type="xs:string" use="optional"/>
            <xs:attribute name="errors" type="xs:string" use="optional"/>
            <xs:attribute name="time" type="xs:string" use="optional"/>
            <xs:attribute name="disabled" type="xs:string" use="optional"/>
            <xs:attribute name="skipped" type="xs:string" use="optional"/>
            <xs:attribute name="timestamp" type="xs:string" use="optional"/>
            <xs:attribute name="hostname" type="xs:string" use="optional"/>
            <xs:attribute name="id" type="xs:string" use="optional"/>
            <xs:attribute name="package" type="xs:string" use="optional"/>
        </xs:complexType>
    </xs:element>

    <xs:element name="testsuites">
        <xs:complexType>
            <xs:sequence>
                <xs:element ref="testsuite" minOccurs="0" maxOccurs="unbounded"/>
            </xs:sequence>
            <xs:attribute name="name" type="xs:string" use="optional"/>
            <xs:attribute name="time" type="xs:string" use="optional"/>
            <xs:attribute name="tests" type="xs:string" use="optional"/>
            <xs:attribute name="failures" type="xs:string" use="optional"/>
            <xs:attribute name="disabled" type="xs:string" use="optional"/>
            <xs:attribute name="errors" type="xs:string" use="optional"/>
        </xs:complexType>
    </xs:element>

</xs:schema>

Filter values only if not null using lambda in Java8

You just need to filter the cars that have a null name:

requiredCars = cars.stream()
                   .filter(c -> c.getName() != null)
                   .filter(c -> c.getName().startsWith("M"));

Attempt by security transparent method 'WebMatrix.WebData.PreApplicationStartCode.Start()'

You may also get :

Could not load file or assembly 'WebMatrix.Data, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

This has moved to this package

 Install-Package Microsoft.AspNet.WebPages.Data

You should probably do a clean build before attempting any of the answers to this question and after updating packages

How to select rows with no matching entry in another table?

Let we have the following 2 tables(salary and employee) enter image description here

Now i want those records from employee table which are not in salary. We can do this in 3 ways:

  1. Using inner Join
select * from employee
where id not in(select e.id from employee e inner join salary s on e.id=s.id)

enter image description here

  1. Using Left outer join
select * from employee e 
left outer join salary s on e.id=s.id  where s.id is null

enter image description here

  1. Using Full Join
select * from employee e
full outer join salary s on e.id=s.id where e.id not in(select id from salary)

enter image description here

uint8_t vs unsigned char

Just to be pedantic, some systems may not have an 8 bit type. According to Wikipedia:

An implementation is required to define exact-width integer types for N = 8, 16, 32, or 64 if and only if it has any type that meets the requirements. It is not required to define them for any other N, even if it supports the appropriate types.

So uint8_t isn't guaranteed to exist, though it will for all platforms where 8 bits = 1 byte. Some embedded platforms may be different, but that's getting very rare. Some systems may define char types to be 16 bits, in which case there probably won't be an 8-bit type of any kind.

Other than that (minor) issue, @Mark Ransom's answer is the best in my opinion. Use the one that most clearly shows what you're using the data for.

Also, I'm assuming you meant uint8_t (the standard typedef from C99 provided in the stdint.h header) rather than uint_8 (not part of any standard).