Programs & Examples On #Count

Count refers to the number of objects in a collection. It's also a commonly-used SQL function that counts the number of rows.

Fast way to discover the row count of a table in PostgreSQL

You can get the count by the below query (without * or any column names).

select from table_name;

Select count(*) from multiple tables

For a bit of completeness - this query will create a query to give you a count of all of the tables for a given owner.

select 
  DECODE(rownum, 1, '', ' UNION ALL ') || 
  'SELECT ''' || table_name || ''' AS TABLE_NAME, COUNT(*) ' ||
  ' FROM ' || table_name  as query_string 
 from all_tables 
where owner = :owner;

The output is something like

SELECT 'TAB1' AS TABLE_NAME, COUNT(*) FROM TAB1
 UNION ALL SELECT 'TAB2' AS TABLE_NAME, COUNT(*) FROM TAB2
 UNION ALL SELECT 'TAB3' AS TABLE_NAME, COUNT(*) FROM TAB3
 UNION ALL SELECT 'TAB4' AS TABLE_NAME, COUNT(*) FROM TAB4

Which you can then run to get your counts. It's just a handy script to have around sometimes.

Count words in a string method?

import java.util.; import java.io.;

public class Main {

public static void main(String[] args) {

    File f=new File("src/MyFrame.java");
    String value=null;
    int i=0;
    int j=0;
    int k=0;
try {
    Scanner  in =new Scanner(f);
    while(in.hasNextLine())
    {
    String a=in.nextLine();
    k++; 
    char chars[]=a.toCharArray();
    i +=chars.length;
    }
    in.close();
    Scanner in2=new Scanner(f);
    while(in2.hasNext())
            {

        String b=in2.next();
        System.out.println(b);
        j++;
            }
   in2.close();

    System.out.println("the number of chars is :"+i);
    System.out.println("the number of words is :"+j);
    System.out.println("the number of lines is :"+k);





}
catch (Exception e) {
    e.printStackTrace();

}


}

}

Extend contigency table with proportions (percentages)

Here is another example using the lapply and table functions in base R.

freqList = lapply(select_if(tips, is.factor), 
              function(x) {
                  df = data.frame(table(x))

                  df = data.frame(fct = df[, 1], 
                                  n = sapply(df[, 2], function(y) {
                                      round(y / nrow(dat), 2)
                                    }
                                )
                            )
                  return(df) 
                    }
                )

Use print(freqList) to see the proportion tables (percent of frequencies) for each column/feature/variable (depending on your tradecraft) that is labeled as a factor.

SQLite Query in Android to count rows

Another way would be using:

myCursor.getCount();

on a Cursor like:

Cursor myCursor = db.query(table_Name, new String[] { row_Username }, 
row_Username + " =? AND " + row_Password + " =?",
new String[] { entered_Password, entered_Password }, 
null, null, null);

If you can think of getting away from the raw query.

count distinct values in spreadsheet

Not exactly what the user asked, but an easy way to just count unique values:

Google introduced a new function to count unique values in just one step, and you can use this as an input for other formulas:

=COUNTUNIQUE(A1:B10)

Count number of tables in Oracle

These documents describe data dictionary views:

all_tables: http://docs.oracle.com/cd/B19306_01/server.102/b14237/statviews_4473.htm#REFRN26286

user_tables: http://docs.oracle.com/cd/B19306_01/server.102/b14237/statviews_2105.htm#i1592091

dba_tables: http://docs.oracle.com/cd/B19306_01/server.102/b14237/statviews_4155.htm#i1627762

You can run queries on these views to count what you need.

To add something more to @Anurag Thakre's answer:

Use this query which will give you the actual no of counts respect to the owners

SELECT COUNT(*),tablespace_name  FROM USER_TABLES group by tablespace_name;

Or by table owners:

SELECT COUNT(*), owner  FROM ALL_TABLES group by owner;

Tablespace itself does not identify an unique object owner. Multiple users can create objects in the same tablespace and a single user can create objects in various tablespaces. It is a common practice to separate tables and indexes into different tablespaces.

SQL query for finding records where count > 1

Use the HAVING clause and GROUP By the fields that make the row unique

The below will find

all users that have more than one payment per day with the same account number

SELECT 
 user_id ,
 COUNT(*) count
FROM 
 PAYMENT
GROUP BY
 account,
 user_id ,
 date
HAVING
COUNT(*) > 1

Update If you want to only include those that have a distinct ZIP you can get a distinct set first and then perform you HAVING/GROUP BY

 SELECT 
    user_id,
    account_no , 
    date,
        COUNT(*)
 FROM
    (SELECT DISTINCT
            user_id,
            account_no , 
            zip, 
            date
         FROM
            payment 
    
        ) 
        payment
 GROUP BY
    
    user_id,
    account_no , 
    
    date
HAVING COUNT(*) > 1

Powershell: count members of a AD group

Something I'd like to share..

$adinfo.members actually give twice the number of actual members. $adinfo.member (without the "s") returns the correct amount. Even when dumping $adinfo.members & $adinfo.member to screen outputs the lower amount of members.

No idea how to explain this!

SQL to Entity Framework Count Group-By

Query syntax

var query = from p in context.People
            group p by p.name into g
            select new
            {
              name = g.Key,
              count = g.Count()
            };

Method syntax

var query = context.People
                   .GroupBy(p => p.name)
                   .Select(g => new { name = g.Key, count = g.Count() });

Conditional Count on a field

Using COUNT instead of SUM removes the requirement for an ELSE statement:

SELECT jobId, jobName,
    COUNT(CASE WHEN Priority=1 THEN 1 END) AS Priority1,
    COUNT(CASE WHEN Priority=2 THEN 1 END) AS Priority2,
    COUNT(CASE WHEN Priority=3 THEN 1 END) AS Priority3,
    COUNT(CASE WHEN Priority=4 THEN 1 END) AS Priority4,
    COUNT(CASE WHEN Priority=5 THEN 1 END) AS Priority5
FROM TableName
GROUP BY jobId, jobName

How to count items in JSON data

You're close. A really simple solution is just to get the length from the 'run' objects returned. No need to bother with 'load' or 'loads':

len(data['result'][0]['run'])

Count the number occurrences of a character in a string

Regular expressions are very useful if you want case-insensitivity (and of course all the power of regex).

my_string = "Mary had a little lamb"
# simplest solution, using count, is case-sensitive
my_string.count("m")   # yields 1
import re
# case-sensitive with regex
len(re.findall("m", my_string))
# three ways to get case insensitivity - all yield 2
len(re.findall("(?i)m", my_string))
len(re.findall("m|M", my_string))
len(re.findall(re.compile("m",re.IGNORECASE), my_string))

Be aware that the regex version takes on the order of ten times as long to run, which will likely be an issue only if my_string is tremendously long, or the code is inside a deep loop.

PHP: Count a stdClass object

The count function is meant to be used on

  1. Arrays
  2. Objects that are derived from classes that implement the countable interface

A stdClass is neither of these. The easier/quickest way to accomplish what you're after is

$count = count(get_object_vars($some_std_class_object));

This uses PHP's get_object_vars function, which will return the properties of an object as an array. You can then use this array with PHP's count function.

SQL Query with Join, Count and Where

You have to use GROUP BY so you will have multiple records returned,

SELECT  COUNT(*) TotalCount, 
        b.category_id, 
        b.category_name 
FROM    table1 a
        INNER JOIN table2 b
            ON a.category_id = b.category_id 
WHERE   a.colour <> 'red'
GROUP   BY b.category_id, b.category_name

Which command in VBA can count the number of characters in a string variable?

Len(word)

Although that's not what your question title asks =)

Laravel Eloquent - distinct() and count() not working properly together

try this

$ad->getcodes()->groupby('pid')->distinct()->count('pid')

Count the Number of Tables in a SQL Server Database

Try this:

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

How can I count the number of elements of a given value in a matrix?

this would be perfect cause we are doing operation on matrix, and the answer should be a single number

sum(sum(matrix==value))

COUNT(*) vs. COUNT(1) vs. COUNT(pk): which is better?

Asked and answered before...

Books on line says "COUNT ( { [ [ ALL | DISTINCT ] expression ] | * } )"

"1" is a non-null expression so it's the same as COUNT(*). The optimiser recognises it as trivial so gives the same plan. A PK is unique and non-null (in SQL Server at least) so COUNT(PK) = COUNT(*)

This is a similar myth to EXISTS (SELECT * ... or EXISTS (SELECT 1 ...

And see the ANSI 92 spec, section 6.5, General Rules, case 1

        a) If COUNT(*) is specified, then the result is the cardinality
          of T.

        b) Otherwise, let TX be the single-column table that is the
          result of applying the <value expression> to each row of T
          and eliminating null values. If one or more null values are
          eliminated, then a completion condition is raised: warning-
          null value eliminated in set function.

SQL: How to get the count of each distinct value in a column?

SELECT
  category,
  COUNT(*) AS `num`
FROM
  posts
GROUP BY
  category

Counting the number of elements with the values of x in a vector

I would probably do something like this

length(which(numbers==x))

But really, a better way is

table(numbers)

postgresql COUNT(DISTINCT ...) very slow

You can use this:

SELECT COUNT(*) FROM (SELECT DISTINCT column_name FROM table_name) AS temp;

This is much faster than:

COUNT(DISTINCT column_name)

How to count the number of occurrences of a character in an Oracle varchar value?

SELECT {FN LENGTH('123-345-566')} - {FN LENGTH({FN REPLACE('123-345-566', '#', '')})} FROM DUAL

Count number of rows per group and add result to original data frame

Another way that generalizes more:

df$count <- unsplit(lapply(split(df, df[c("name","type")]), nrow), df[c("name","type")])

Count indexes using "for" in Python

If you have some given list, and want to iterate over its items and indices, you can use enumerate():

for index, item in enumerate(my_list):
    print index, item

If you only need the indices, you can use range():

for i in range(len(my_list)):
    print i

How to count number of records per day?

You could also try this:

SELECT DISTINCT (DATE(dateadded)) AS unique_date, COUNT(*) AS amount
FROM table
GROUP BY unique_date
ORDER BY unique_date ASC

Counting array elements in Perl

It sounds like you want a sparse array. A normal array would have 24 items in it, but a sparse array would have 3. In Perl we emulate sparse arrays with hashes:

#!/usr/bin/perl

use strict;
use warnings;

my %sparse;

@sparse{0, 5, 23} = (1 .. 3);

print "there are ", scalar keys %sparse, " items in the sparse array\n",
    map { "\t$sparse{$_}\n" } sort { $a <=> $b } keys %sparse;

The keys function in scalar context will return the number of items in the sparse array. The only downside to using a hash to emulate a sparse array is that you must sort the keys before iterating over them if their order is important.

You must also remember to use the delete function to remove items from the sparse array (just setting their value to undef is not enough).

Java count occurrence of each item in an array

Using HashMap it is walk in the park.

main(){
    String[] array ={"a","ab","a","abc","abc","a","ab","ab","a"};
    Map<String,Integer> hm = new HashMap();

    for(String x:array){

        if(!hm.containsKey(x)){
            hm.put(x,1);
        }else{
            hm.put(x, hm.get(x)+1);
        }
    }
    System.out.println(hm);
}

Pandas count(distinct) equivalent

I believe this is what you want:

table.groupby('YEARMONTH').CLIENTCODE.nunique()

Example:

In [2]: table
Out[2]: 
   CLIENTCODE  YEARMONTH
0           1     201301
1           1     201301
2           2     201301
3           1     201302
4           2     201302
5           2     201302
6           3     201302

In [3]: table.groupby('YEARMONTH').CLIENTCODE.nunique()
Out[3]: 
YEARMONTH
201301       2
201302       3

C++ - how to find the length of an integer

How about (works also for 0 and negatives):

int digits( int x ) { 
    return ( (bool) x * (int) log10( abs( x ) ) + 1 );
}

How can I divide one column of a data frame through another?

Hadley Wickham

dplyr

packages is always a saver in case of data wrangling. To add the desired division as a third variable I would use mutate()

d <- mutate(d, new = min / count2.freq)

Getting the size of an array in an object

Arrays have a property .length that returns the number of elements.

var st =
    {
        "itema":{},
        "itemb":
        [
            {"id":"s01","cd":"c01","dd":"d01"},
            {"id":"s02","cd":"c02","dd":"d02"}
        ]
    };

st.itemb.length // 2

jQuery: count number of rows in a table

Use a selector that will select all the rows and take the length.

var rowCount = $('#myTable tr').length;

Note: this approach also counts all trs of every nested table!

jQuery count number of divs with a certain class?

And for the plain js answer if anyone might be interested;

var count = document.getElementsByClassName("item");

Cheers.

Reference: https://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp

How do you access the value of an SQL count () query in a Java program

I would expect this query to work with your program:

"SELECT COUNT(*) AS count FROM "+lastTempTable+")"

(You need to alias the column, not the table)

Sum values in foreach loop php

In your case IF you want to go with foreach loop than

$sum = 0;
foreach($group as $key => $value) {
   $sum += $value; 
}
echo $sum;

But if you want to go with direct sum of array than look on below for your solution :

$total = array_sum($group);

for only sum of array looping is time wasting.

http://php.net/manual/en/function.array-sum.php

array_sum — Calculate the sum of values in an array

<?php
$a = array(2, 4, 6, 8);
echo "sum(a) = " . array_sum($a) . "\n";

$b = array("a" => 1.2, "b" => 2.3, "c" => 3.4);
echo "sum(b) = " . array_sum($b) . "\n";
?>

The above example will output:

sum(a) = 20
sum(b) = 6.9

MySQL joins and COUNT(*) from another table

Your groups_main table has a key column named id. I believe you can only use the USING syntax for the join if the groups_fans table has a key column with the same name, which it probably does not. So instead, try this:

LEFT JOIN groups_fans AS m ON m.group_id = g.id

Or replace group_id with whatever the appropriate column name is in the groups_fans table.

How to count days between two dates in PHP?

You can use date_diff to calculate the difference between two dates:

$date1 = date_create("2013-03-15");
$date2 = date_create("2013-12-12");
$diff =  date_diff($date1 , $date2);
echo  $diff->format("%R%a days");

A method to count occurrences in a list

Your outer loop is looping over all the words in the list. It's unnecessary and will cause you problems. Remove it and it should work properly.

Count number of occurrences of a pattern in a file (even on same line)

Hack grep's color function, and count how many color tags it prints out:

echo -e "a\nb  b b\nc\ndef\nb e brb\nr" \
| GREP_COLOR="033" grep --color=always  b \
| perl -e 'undef $/; $_=<>; s/\n//g; s/\x1b\x5b\x30\x33\x33/\n/g; print $_' \
| wc -l

(How) can I count the items in an enum?

I really do not see any way to really get to the number of values in an enumeration in C++. Any of the before mention solution work as long as you do not define the value of your enumerations if you define you value that you might run into situations where you either create arrays too big or too small

enum example{ test1 = -2, test2 = -1, test3 = 0, test4 = 1, test5 = 2 }

in this about examples the result would create a array of 3 items when you need an array of 5 items

enum example2{ test1 , test2 , test3 , test4 , test5 = 301 }

in this about examples the result would create a array of 301 items when you need an array of 5 items

The best way to solve this problem in the general case would be to iterate through your enumerations but that is not in the standard yet as far as I know

pandas python how to count the number of records or rows in a dataframe

The Nan example above misses one piece, which makes it less generic. To do this more "generically" use df['column_name'].value_counts() This will give you the counts of each value in that column.

d=['A','A','A','B','C','C'," " ," "," "," "," ","-1"] # for simplicity

df=pd.DataFrame(d)
df.columns=["col1"]
df["col1"].value_counts() 
      5
A     3
C     2
-1    1
B     1
dtype: int64
"""len(df) give you 12, so we know the rest must be Nan's of some form, while also having a peek into other invalid entries, especially when you might want to ignore them like -1, 0 , "", also"""

Get number of digits with JavaScript

`You can do it by simple loop using Math.trunc() function. if in interview interviewer ask to do it without converting it into string`
    let num = 555194154234 ;
    let len = 0 ;
    const numLen = (num) => {
     for(let i = 0; i < num ||  num == 1 ; i++){
        num = Math.trunc(num/10);
        len++ ;
     }
      return len + 1 ;
    }
    console.log(numLen(num));

How to use count and group by at the same select statement

if You Want to use Select All Query With Count Option, try this...

 select a.*, (Select count(b.name) from table_name as b where Condition) as totCount from table_name  as a where where Condition

In Firebase, is there a way to get the number of children of a node without loading all the node data?

write a cloud function to and update the node count.

// below function to get the given node count.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.userscount = functions.database.ref('/users/')
    .onWrite(event => {

      console.log('users number : ', event.data.numChildren());


      return event.data.ref.parent.child('count/users').set(event.data.numChildren());
    }); 

Refer :https://firebase.google.com/docs/functions/database-events

root--| |-users ( this node contains all users list) |
|-count |-userscount : (this node added dynamically by cloud function with the user count)

Fastest way to determine if record exists

Below is the simplest and fastest way to determine if a record exists in database or not Good thing is it works in all Relational DB's

SELECT distinct 1 products.id FROM products WHERE products.id = ?;

Performing a query on a result from another query?

Usually you can plug a Query's result (which is basically a table) as the FROM clause source of another query, so something like this will be written:

SELECT COUNT(*), SUM(SUBQUERY.AGE) from
(
  SELECT availables.bookdate AS Date, DATEDIFF(now(),availables.updated_at) as Age
  FROM availables
  INNER JOIN rooms
  ON availables.room_id=rooms.id
  WHERE availables.bookdate BETWEEN '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094
  GROUP BY availables.bookdate
) AS SUBQUERY

SQL count rows in a table

Use This Query :

Select
    S.name + '.' + T.name As TableName ,
    SUM( P.rows ) As RowCont 

From sys.tables As T
    Inner Join sys.partitions As P On ( P.OBJECT_ID = T.OBJECT_ID )
    Inner Join sys.schemas As S On ( T.schema_id = S.schema_id )
Where
    ( T.is_ms_shipped = 0 )
    AND 
    ( P.index_id IN (1,0) )
    And
    ( T.type = 'U' )

Group By S.name , T.name 

Order By SUM( P.rows ) Desc

Linq with group by having count

Below solution may help you.

var unmanagedDownloadcountwithfilter = from count in unmanagedDownloadCount.Where(d =>d.downloaddate >= startDate && d.downloaddate <= endDate)
group count by count.unmanagedassetregistryid into grouped
where grouped.Count() > request.Download
select new
{
   UnmanagedAssetRegistryID = grouped.Key,
   Count = grouped.Count()
};

Getting a count of rows in a datatable that meet certain criteria

int numberOfRecords = DTb.Rows.Count;
int numberOfColumns = DTb.Columns.Count;

Counting the occurrences / frequency of array elements

I think this is the simplest way how to count occurrences with same value in array.

var a = [true, false, false, false];
a.filter(function(value){
    return value === false;
}).length

How do we count rows using older versions of Hibernate (~2009)?

This works in Hibernate 4(Tested).

String hql="select count(*) from  Book";
Query query= getCurrentSession().createQuery(hql);
Long count=(Long) query.uniqueResult();
return count;

Where getCurrentSession() is:

@Autowired
private SessionFactory sessionFactory;


private Session getCurrentSession(){
return sessionFactory.getCurrentSession();
}

COUNT / GROUP BY with active record?

I think you should count the results with FOUND_ROWS() and SQL_CALC_FOUND_ROWS. You'll need two queries: select, group_by, etc. You'll add a plus select: SQL_CALC_FOUND_ROWS user_id. After this query run a query: SELECT FOUND_ROWS(). This will return the desired number.

Count multiple columns with group by in one query

One solution is to wrap it in a subquery

SELECT *
FROM
(
    SELECT COUNT(column1),column1 FROM table GROUP BY column1
    UNION ALL
    SELECT COUNT(column2),column2 FROM table GROUP BY column2
    UNION ALL
    SELECT COUNT(column3),column3 FROM table GROUP BY column3
) s

How to find length of digits in an integer?

def length(i):
  return len(str(i))

Inner join with count() on three tables

One needs to understand what a JOIN or a series of JOINs does to a set of data. With strae's post, a pe_id of 1 joined with corresponding order and items on pe_id = 1 will give you the following data to "select" from:

[ table people portion ] [ table orders portion ] [ table items portion ]

| people.pe_id | people.pe_name | orders.ord_id | orders.pe_id | orders.ord_title | item.item_id | item.ord_id | item.pe_id | item.title |

| 1 | Foo | 1 | 1 | First order | 1 | 1 | 1 | Apple |
| 1 | Foo | 1 | 1 | First order | 2 | 1 | 1 | Pear |

The joins essentially come up with a cartesian product of all the tables. You basically have that data set to select from and that's why you need a distinct count on orders.ord_id and items.item_id. Otherwise both counts will result in 2 - because you effectively have 2 rows to select from.

How to make use of SQL (Oracle) to count the size of a string?

You can use LENGTH() for CHAR / VARCHAR2 and DBMS_LOB.GETLENGTH() for CLOB. Both functions will count actual characters (not bytes).

See the linked documentation if you do need bytes.

count (non-blank) lines-of-code in bash

Script to recursively count all non-blank lines with a certain file extension in the current directory:

#!/usr/bin/env bash
(
echo 0;
for ext in "$@"; do
    for i in $(find . -name "*$ext"); do
        sed '/^\s*$/d' $i | wc -l ## skip blank lines
        #cat $i | wc -l; ## count all lines
        echo +;
    done
done
echo p q;
) | dc;

Sample usage:

./countlines.sh .py .java .html

Count number of occurrences for each unique value

You should change the query to:

SELECT time_col, COUNT(time_col) As Count
FROM time_table
WHERE activity_col = 3
GROUP BY time_col

This vl works correctly.

count of entries in data frame in R

You could use table:

R> x <- read.table(textConnection('
   Believe Age Gender Presents Behaviour
1    FALSE   9   male       25   naughty
2     TRUE   5   male       20      nice
3     TRUE   4 female       30      nice
4     TRUE   4   male       34   naughty'
), header=TRUE)

R> table(x$Believe)

FALSE  TRUE 
    1     3 

Oracle row count of table by count(*) vs NUM_ROWS from DBA_TABLES

According to the documentation NUM_ROWS is the "Number of rows in the table", so I can see how this might be confusing. There, however, is a major difference between these two methods.

This query selects the number of rows in MY_TABLE from a system view. This is data that Oracle has previously collected and stored.

select num_rows from all_tables where table_name = 'MY_TABLE'

This query counts the current number of rows in MY_TABLE

select count(*) from my_table

By definition they are difference pieces of data. There are two additional pieces of information you need about NUM_ROWS.

  1. In the documentation there's an asterisk by the column name, which leads to this note:

    Columns marked with an asterisk (*) are populated only if you collect statistics on the table with the ANALYZE statement or the DBMS_STATS package.

    This means that unless you have gathered statistics on the table then this column will not have any data.

  2. Statistics gathered in 11g+ with the default estimate_percent, or with a 100% estimate, will return an accurate number for that point in time. But statistics gathered before 11g, or with a custom estimate_percent less than 100%, uses dynamic sampling and may be incorrect. If you gather 99.999% a single row may be missed, which in turn means that the answer you get is incorrect.

If your table is never updated then it is certainly possible to use ALL_TABLES.NUM_ROWS to find out the number of rows in a table. However, and it's a big however, if any process inserts or deletes rows from your table it will be at best a good approximation and depending on whether your database gathers statistics automatically could be horribly wrong.

Generally speaking, it is always better to actually count the number of rows in the table rather then relying on the system tables.

Count the number of times a string appears within a string

Probably not the most efficient, but think it's a neat way to do it.

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(CountAllTheTimesThisStringAppearsInThatString("7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false", "true"));
        Console.WriteLine(CountAllTheTimesThisStringAppearsInThatString("7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false", "false"));

    }

    static Int32 CountAllTheTimesThisStringAppearsInThatString(string orig, string find)
    {
        var s2 = orig.Replace(find,"");
        return (orig.Length - s2.Length) / find.Length;
    }
}

Find duplicate lines in a file and count how many time each line was duplicated?

To find and count duplicate lines in multiple files, you can try the following command:

sort <files> | uniq -c | sort -nr

or:

cat <files> | sort | uniq -c | sort -nr

Count number of records returned by group by

You can do both in one query using the OVER clause on another COUNT

select
    count(*) RecordsPerGroup,
    COUNT(*) OVER () AS TotalRecords
from temptable
group by column_1, column_2, column_3, column_4

Count number of rows by group using dplyr

Another option, not necesarily more elegant, but does not require to refer to a specific column:

mtcars %>% 
  group_by(cyl, gear) %>%
  do(data.frame(nrow=nrow(.)))

Trying to get the average of a count resultset

You just can put your query as a subquery:

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

Edit: I think this should be the same:

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

Most efficient way to get table row count

If you do not have privilege for "Show Status" then, The best option is to, create two triggers and a new table which keeps the row count of your billion records table.

Example:

TableA >> Billion Records
TableB >> 1 Column and 1 Row

Whenever there is insert query on TableA(InsertTrigger), Increment the row value by 1 TableB
Whenever there is delete query on TableA(DeleteTrigger), Decrement the row value by 1 in TableB

How to count the number of files in a directory using Python

import os
print len(os.listdir(os.getcwd()))

How to obtain the total numbers of rows from a CSV file in Python?

To do it you need to have a bit of code like my example here:

file = open("Task1.csv")
numline = len(file.readlines())
print (numline)

I hope this helps everyone.

How to count instances of character in SQL Column

DECLARE @StringToFind VARCHAR(100) = "Text To Count"

SELECT (LEN([Field To Search]) - LEN(REPLACE([Field To Search],@StringToFind,'')))/COALESCE(NULLIF(LEN(@StringToFind), 0), 1) --protect division from zero
FROM [Table To Search]

mysql: get record count between two date-time

for speed you can do this

WHERE date(created_at) ='2019-10-21'

Faster alternative in Oracle to SELECT COUNT(*) FROM sometable

Option 1: Have an index on a non-null column present that can be used for the scan. Or create a function-based index as:

create index idx on t(0);

this can then be scanned to give the count.

Option 2: If you have monitoring turned on then check the monitoring view USER_TAB_MODIFICATIONS and add/subtract the relevant values to the table statistics.

Option 3: For a quick estimate on large tables invoke the SAMPLE clause ... for example ...

SELECT 1000*COUNT(*) FROM sometable SAMPLE(0.1); 

Option 4: Use a materialized view to maintain the count(*). Powerful medicine though.

um ...

Count distinct value pairs in multiple columns in SQL

Get all distinct id, name and address columns and count the resulting rows.

SELECT COUNT(*) FROM mytable GROUP BY id, name, address

Lists: Count vs Count()

myList.Count is a method on the list object, it just returns the value of a field so is very fast. As it is a small method it is very likely to be inlined by the compiler (or runtime), they may then allow other optimization to be done by the compiler.

myList.Count() is calling an extension method (introduced by LINQ) that loops over all the items in an IEnumerable, so should be a lot slower.

However (In the Microsoft implementation) the Count extension method has a “special case” for Lists that allows it to use the list’s Count property, this means the Count() method is only a little slower than the Count property.

It is unlikely you will be able to tell the difference in speed in most applications.

So if you know you are dealing with a List use the Count property, otherwise if you have a "unknown" IEnumerabl, use the Count() method and let it optimise for you.

PHP - count specific array values

array_count_values only works for integers and strings. If you happen to want counts for float/numeric values (and you are heedless of small variations in precision or representation), this works:

function arrayCountValues($arr) {
  $vals = [];
  foreach ($arr as $val) { array_push($vals,strval($val)); }
  $cnts = array_count_values($vals);
  arsort($cnts);
  return $cnts;
}

Note that I return $cnts with the keys as strings. It would be easy to reconvert them, but I'm trying to determine the mode for the values, so I only need to re-convert the first (several) values.

I tested a version which looped, creating an array of counts rather than using array_count_values, and this turned out to be more efficient (by maybe 8-10%)!

Javascript counting number of objects in object

In recent browsers you can use:

Object.keys(obj.Data).length

See MDN

For older browsers, use the for-in loop in Michael Geary's answer.

JPA COUNT with composite primary key query not working

Use count(d.ertek) or count(d.id) instead of count(d). This can be happen when you have composite primary key at your entity.

Using GroupBy, Count and Sum in LINQ Lambda Expressions

var boxSummary = from b in boxes
                 group b by b.Owner into g
                 let nrBoxes = g.Count()
                 let totalWeight = g.Sum(w => w.Weight)
                 let totalVolume = g.Sum(v => v.Volume)
                 select new { Owner = g.Key, Boxes = nrBoxes,
                              TotalWeight = totalWeight,
                              TotalVolume = totalVolume }

Search for string and get count in vi editor

:g/xxxx/d

This will delete all the lines with pattern, and report how many deleted. Undo to get them back after.

Count how many files in directory PHP

Maybe usefull to someone. On a Windows system, you can let Windows do the job by calling the dir-command. I use an absolute path, like E:/mydir/mysubdir.

<?php 
$mydir='E:/mydir/mysubdir';
$dir=str_replace('/','\\',$mydir);
$total = exec('dir '.$dir.' /b/a-d | find /v /c "::"');

How can I count the occurrences of a list item?

Counting the occurrences of one item in a list

For counting the occurrences of just one list item you can use count()

>>> l = ["a","b","b"]
>>> l.count("a")
1
>>> l.count("b")
2

Counting the occurrences of all items in a list is also known as "tallying" a list, or creating a tally counter.

Counting all items with count()

To count the occurrences of items in l one can simply use a list comprehension and the count() method

[[x,l.count(x)] for x in set(l)]

(or similarly with a dictionary dict((x,l.count(x)) for x in set(l)))

Example:

>>> l = ["a","b","b"]
>>> [[x,l.count(x)] for x in set(l)]
[['a', 1], ['b', 2]]
>>> dict((x,l.count(x)) for x in set(l))
{'a': 1, 'b': 2}

Counting all items with Counter()

Alternatively, there's the faster Counter class from the collections library

Counter(l)

Example:

>>> l = ["a","b","b"]
>>> from collections import Counter
>>> Counter(l)
Counter({'b': 2, 'a': 1})

How much faster is Counter?

I checked how much faster Counter is for tallying lists. I tried both methods out with a few values of n and it appears that Counter is faster by a constant factor of approximately 2.

Here is the script I used:

from __future__ import print_function
import timeit

t1=timeit.Timer('Counter(l)', \
                'import random;import string;from collections import Counter;n=1000;l=[random.choice(string.ascii_letters) for x in range(n)]'
                )

t2=timeit.Timer('[[x,l.count(x)] for x in set(l)]',
                'import random;import string;n=1000;l=[random.choice(string.ascii_letters) for x in range(n)]'
                )

print("Counter(): ", t1.repeat(repeat=3,number=10000))
print("count():   ", t2.repeat(repeat=3,number=10000)

And the output:

Counter():  [0.46062711701961234, 0.4022796869976446, 0.3974247490405105]
count():    [7.779430688009597, 7.962715800967999, 8.420845870045014]

How to count check-boxes using jQuery?

There are multiple methods to do that:

Method 1:

alert($('.checkbox_class_here:checked').size());

Method 2:

alert($('input[name=checkbox_name]').attr('checked'));

Method 3:

alert($(":checkbox:checked").length);

Count number of occurences for each unique value

I know there are many other answers, but here is another way to do it using the sort and rle functions. The function rle stands for Run Length Encoding. It can be used for counts of runs of numbers (see the R man docs on rle), but can also be applied here.

test.data = rep(c(1, 2, 2, 2), 25)
rle(sort(test.data))
## Run Length Encoding
##   lengths: int [1:2] 25 75
##   values : num [1:2] 1 2

If you capture the result, you can access the lengths and values as follows:

## rle returns a list with two items.
result.counts <- rle(sort(test.data))
result.counts$lengths
## [1] 25 75
result.counts$values
## [1] 1 2

Count number of objects in list

You can also use unlist(), which is often useful for handling lists:

> mylist <- list(A = c(1:3), B = c(4:6), C = c(7:9))

> mylist
$A
[1] 1 2 3

$B
[1] 4 5 6

$C
[1] 7 8 9

> unlist(mylist)
A1 A2 A3 B1 B2 B3 C1 C2 C3 
 1  2  3  4  5  6  7  8  9 

> length(unlist(mylist))
[1] 9

unlist() is a simple way of executing other functions on lists as well, such as:

> sum(mylist)
Error in sum(mylist) : invalid 'type' (list) of argument

> sum(unlist(mylist))
[1] 45

How can I tell how many objects I've stored in an S3 bucket?

None of the APIs will give you a count because there really isn't any Amazon specific API to do that. You have to just run a list-contents and count the number of results that are returned.

How to sort a list of objects based on an attribute of the objects?

Add rich comparison operators to the object class, then use sort() method of the list.
See rich comparison in python.


Update: Although this method would work, I think solution from Triptych is better suited to your case because way simpler.

Counting the Number of keywords in a dictionary in python

Calling len() directly on your dictionary works, and is faster than building an iterator, d.keys(), and calling len() on it, but the speed of either will negligible in comparison to whatever else your program is doing.

d = {x: x**2 for x in range(1000)}

len(d)
# 1000

len(d.keys())
# 1000

%timeit len(d)
# 41.9 ns ± 0.244 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

%timeit len(d.keys())
# 83.3 ns ± 0.41 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

How do you find the row count for all your tables in Postgres

This worked for me

SELECT schemaname,relname,n_live_tup FROM pg_stat_user_tables ORDER BY n_live_tup DESC;

Item frequency count in Python

The answer below takes some extra cycles, but it is another method

def func(tup):
    return tup[-1]


def print_words(filename):
    f = open("small.txt",'r')
    whole_content = (f.read()).lower()
    print whole_content
    list_content = whole_content.split()
    dict = {}
    for one_word in list_content:
        dict[one_word] = 0
    for one_word in list_content:
        dict[one_word] += 1
    print dict.items()
    print sorted(dict.items(),key=func)

select count(*) from table of mysql in php

$result = mysql_query("SELECT COUNT(*) AS `count` FROM `Students`");
$row = mysql_fetch_assoc($result);
$count = $row['count'];

Try this code.

How do I count occurrence of duplicate items in array

Count duplicate element of an array in PHP without using in-built function

$arraychars=array("or","red","yellow","green","red","yellow","yellow");
$arrCount=array();
        for($i=0;$i<$arrlength-1;$i++)
        {
          $key=$arraychars[$i];
          if($arrCount[$key]>=1)
            {
              $arrCount[$key]++;
            } else{
              $arrCount[$key]=1;
        }
        echo $arraychars[$i]."<br>";
     }
        echo "<pre>";
        print_r($arrCount);

GROUP BY and COUNT in PostgreSQL

There is also EXISTS:

SELECT count(*) AS post_ct
FROM   posts p
WHERE  EXISTS (SELECT FROM votes v WHERE v.post_id = p.id);

In Postgres and with multiple entries on the n-side like you probably have, it's generally faster than count(DISTINCT post_id):

SELECT count(DISTINCT p.id) AS post_ct
FROM   posts p
JOIN   votes v ON v.post_id = p.id;

The more rows per post there are in votes, the bigger the difference in performance. Test with EXPLAIN ANALYZE.

count(DISTINCT post_id) has to read all rows, sort or hash them, and then only consider the first per identical set. EXISTS will only scan votes (or, preferably, an index on post_id) until the first match is found.

If every post_id in votes is guaranteed to be present in the table posts (referential integrity enforced with a foreign key constraint), this short form is equivalent to the longer form:

SELECT count(DISTINCT post_id) AS post_ct
FROM   votes;

May actually be faster than the EXISTS query with no or few entries per post.

The query you had works in simpler form, too:

SELECT count(*) AS post_ct
FROM  (
    SELECT FROM posts 
    JOIN   votes ON votes.post_id = posts.id 
    GROUP  BY posts.id
    ) sub;

Benchmark

To verify my claims I ran a benchmark on my test server with limited resources. All in a separate schema:

Test setup

Fake a typical post / vote situation:

CREATE SCHEMA y;
SET search_path = y;

CREATE TABLE posts (
  id   int PRIMARY KEY
, post text
);

INSERT INTO posts
SELECT g, repeat(chr(g%100 + 32), (random()* 500)::int)  -- random text
FROM   generate_series(1,10000) g;

DELETE FROM posts WHERE random() > 0.9;  -- create ~ 10 % dead tuples

CREATE TABLE votes (
  vote_id serial PRIMARY KEY
, post_id int REFERENCES posts(id)
, up_down bool
);

INSERT INTO votes (post_id, up_down)
SELECT g.* 
FROM  (
   SELECT ((random()* 21)^3)::int + 1111 AS post_id  -- uneven distribution
        , random()::int::bool AS up_down
   FROM   generate_series(1,70000)
   ) g
JOIN   posts p ON p.id = g.post_id;

All of the following queries returned the same result (8093 of 9107 posts had votes).
I ran 4 tests with EXPLAIN ANALYZE ant took the best of five on Postgres 9.1.4 with each of the three queries and appended the resulting total runtimes.

  1. As is.

  2. After ..

    ANALYZE posts;
    ANALYZE votes;
    
  3. After ..

    CREATE INDEX foo on votes(post_id);
    
  4. After ..

    VACUUM FULL ANALYZE posts;
    CLUSTER votes using foo;
    

count(*) ... WHERE EXISTS

  1. 253 ms
  2. 220 ms
  3. 85 ms -- winner (seq scan on posts, index scan on votes, nested loop)
  4. 85 ms

count(DISTINCT x) - long form with join

  1. 354 ms
  2. 358 ms
  3. 373 ms -- (index scan on posts, index scan on votes, merge join)
  4. 330 ms

count(DISTINCT x) - short form without join

  1. 164 ms
  2. 164 ms
  3. 164 ms -- (always seq scan)
  4. 142 ms

Best time for original query in question:

  • 353 ms

For simplified version:

  • 348 ms

@wildplasser's query with a CTE uses the same plan as the long form (index scan on posts, index scan on votes, merge join) plus a little overhead for the CTE. Best time:

  • 366 ms

Index-only scans in the upcoming PostgreSQL 9.2 can improve the result for each of these queries, most of all for EXISTS.

Related, more detailed benchmark for Postgres 9.5 (actually retrieving distinct rows, not just counting):

Multiple aggregate functions in HAVING clause

For your example query, the only possible value greater than 2 and less than 4 is 3, so we simplify:

GROUP BY meetingID
HAVING COUNT(caseID) = 3

In your general case:

GROUP BY meetingID
HAVING COUNT(caseID) > x AND COUNT(caseID) < 7

Or (possibly easier to read?),

GROUP BY meetingID
HAVING COUNT(caseID) BETWEEN x+1 AND 6

Calculate average in java

I'm going to show you 2 ways. If you don't need a lot of stats in your project simply implement following.

public double average(ArrayList<Double> x) {
    double sum = 0;
    for (double aX : x) sum += aX;
    return (sum / x.size());
}

If you plan on doing a lot of stats might as well not reinvent the wheel. So why not check out http://commons.apache.org/proper/commons-math/userguide/stat.html

You'll fall into true luv!

XSLT counting elements with a given value

This XPath:

count(//Property[long = '11007'])

returns the same value as:

count(//Property/long[text() = '11007'])

...except that the first counts Property nodes that match the criterion and the second counts long child nodes that match the criterion.

As per your comment and reading your question a couple of times, I believe that you want to find uniqueness based on a combination of criteria. Therefore, in actuality, I think you are actually checking multiple conditions. The following would work as well:

count(//Property[@Name = 'Alive'][long = '11007'])

because it means the same thing as:

count(//Property[@Name = 'Alive' and long = '11007'])

Of course, you would substitute the values for parameters in your template. The above code only illustrates the point.

EDIT (after question edit)


You were quite right about the XML being horrible. In fact, this is a downright CodingHorror candidate! I had to keep recounting to keep track of the "Property" node I was on presently. I feel your pain!

Here you go:

count(/root/ac/Properties/Property[Properties/Property/Properties/Property/long = $parPropId])

Note that I have removed all the other checks (for ID and Value). They appear not to be required since you are able to arrive at the relevant node using the hierarchy in the XML. Also, you already mentioned that the check for uniqueness is based only on the contents of the long element.

How to count the occurrence of certain item in an ndarray?

dict(zip(*numpy.unique(y, return_counts=True)))

Just copied Seppo Enarvi's comment here which deserves to be a proper answer

Group by & count function in sqlalchemy

You can also count on multiple groups and their intersection:

self.session.query(func.count(Table.column1),Table.column1, Table.column2).group_by(Table.column1, Table.column2).all()

The query above will return counts for all possible combinations of values from both columns.

Count with IF condition in MySQL query

Replace this line:

count(if(ccc_news_comments.id = 'approved', ccc_news_comments.id, 0)) AS comments

With this one:

coalesce(sum(ccc_news_comments.id = 'approved'), 0) comments

SHA512 vs. Blowfish and Bcrypt

Blowfish is not a hashing algorithm. It's an encryption algorithm. What that means is that you can encrypt something using blowfish, and then later on you can decrypt it back to plain text.

SHA512 is a hashing algorithm. That means that (in theory) once you hash the input you can't get the original input back again.

They're 2 different things, designed to be used for different tasks. There is no 'correct' answer to "is blowfish better than SHA512?" You might as well ask "are apples better than kangaroos?"

If you want to read some more on the topic here's some links:

How do I make the first letter of a string uppercase in JavaScript?

There are already so many good answers, but you can also use a simple CSS transform:

text-transform: capitalize;

_x000D_
_x000D_
div.c {
  text-transform: capitalize;
}
_x000D_
<h2>text-transform: capitalize:</h2>
<div class="c">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
_x000D_
_x000D_
_x000D_

When should I use "this" in a class?

this is useful in the builder pattern.

public class User {

    private String firstName;
    private String surname;

    public User(Builder builder){
        firstName = builder.firstName;
        surname = builder.surname;
    }

    public String getFirstName(){
        return firstName;
    }

    public String getSurname(){
        return surname;
    }

    public static class Builder {
        private String firstName;
        private String surname;

        public Builder setFirstName(String firstName) {
            this.firstName = firstName;
            return this;
        }

        public Builder setSurname(String surname) {
            this.surname = surname;
            return this;
        }

        public User build(){
            return new User(this);
        }

    }

    public static void main(String[] args) {
        User.Builder builder = new User.Builder();
        User user = builder.setFirstName("John").setSurname("Doe").build();
    }

}

Change default timeout for mocha

In current versions of Mocha, the timeout can be changed globally like this:

mocha.timeout(5000);

Just add the line above anywhere in your test suite, preferably at the top of your spec or in a separate test helper.


In older versions, and only in a browser, you could change the global configuration using mocha.setup.

mocha.setup({ timeout: 5000 });

The documentation does not cover the global timeout setting, but offers a few examples on how to change the timeout in other common scenarios.

How to use setprecision in C++

#include <iostream>
#include <iomanip>
 
int main(void) 
{
    float value;
    cin >> value;
    cout << setprecision(4) << value;
    return 0;
}

How to set a DateTime variable in SQL Server 2008?

You Should Try This Way :

  DECLARE @TEST DATE
  SET @TEST =  '05/09/2013'
  PRINT @TEST

Why Does OAuth v2 Have Both Access and Refresh Tokens?

This answer is from Justin Richer via the OAuth 2 standard body email list. This is posted with his permission.


The lifetime of a refresh token is up to the (AS) authorization server — they can expire, be revoked, etc. The difference between a refresh token and an access token is the audience: the refresh token only goes back to the authorization server, the access token goes to the (RS) resource server.

Also, just getting an access token doesn’t mean the user’s logged in. In fact, the user might not even be there anymore, which is actually the intended use case of the refresh token. Refreshing the access token will give you access to an API on the user’s behalf, it will not tell you if the user’s there.

OpenID Connect doesn’t just give you user information from an access token, it also gives you an ID token. This is a separate piece of data that’s directed at the client itself, not the AS or the RS. In OIDC, you should only consider someone actually “logged in” by the protocol if you can get a fresh ID token. Refreshing it is not likely to be enough.

For more information please read http://oauth.net/articles/authentication/

How do I create an array of strings in C?

Here are some of your options:

char a1[][14] = { "blah", "hmm" };
char* a2[] = { "blah", "hmm" };
char (*a3[])[] = { &"blah", &"hmm" };  // only since you brought up the syntax -

printf(a1[0]); // prints blah
printf(a2[0]); // prints blah
printf(*a3[0]); // prints blah

The advantage of a2 is that you can then do the following with string literals

a2[0] = "hmm";
a2[1] = "blah";

And for a3 you may do the following:

a3[0] = &"hmm";
a3[1] = &"blah";

For a1 you will have to use strcpy() (better yet strncpy()) even when assigning string literals. The reason is that a2, and a3 are arrays of pointers and you can make their elements (i.e. pointers) point to any storage, whereas a1 is an array of 'array of chars' and so each element is an array that "owns" its own storage (which means it gets destroyed when it goes out of scope) - you can only copy stuff into its storage.

This also brings us to the disadvantage of using a2 and a3 - since they point to static storage (where string literals are stored) the contents of which cannot be reliably changed (viz. undefined behavior), if you want to assign non-string literals to the elements of a2 or a3 - you will first have to dynamically allocate enough memory and then have their elements point to this memory, and then copy the characters into it - and then you have to be sure to deallocate the memory when done.

Bah - I miss C++ already ;)

p.s. Let me know if you need examples.

How do I make a delay in Java?

If you want to pause then use java.util.concurrent.TimeUnit:

TimeUnit.SECONDS.sleep(1);

To sleep for one second or

TimeUnit.MINUTES.sleep(1);

To sleep for a minute.

As this is a loop, this presents an inherent problem - drift. Every time you run code and then sleep you will be drifting a little bit from running, say, every second. If this is an issue then don't use sleep.

Further, sleep isn't very flexible when it comes to control.

For running a task every second or at a one second delay I would strongly recommend a ScheduledExecutorService and either scheduleAtFixedRate or scheduleWithFixedDelay.

For example, to run the method myTask every second (Java 8):

public static void main(String[] args) {
    final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    executorService.scheduleAtFixedRate(App::myTask, 0, 1, TimeUnit.SECONDS);
}

private static void myTask() {
    System.out.println("Running");
}

And in Java 7:

public static void main(String[] args) {
    final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    executorService.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            myTask();
        }
    }, 0, 1, TimeUnit.SECONDS);
}

private static void myTask() {
    System.out.println("Running");
}

How to debug heap corruption errors?

What type of allocation functions are you using? I recently hit a similar error using the Heap* style allocation functions.

It turned out that I was mistakenly creating the heap with the HEAP_NO_SERIALIZE option. This essentially makes the Heap functions run without thread safety. It's a performance improvement if used properly but shouldn't ever be used if you are using HeapAlloc in a multi-threaded program [1]. I only mention this because your post mentions you have a multi-threaded app. If you are using HEAP_NO_SERIALIZE anywhere, delete that and it will likely fix your problem.

[1] There are certain situations where this is legal, but it requires you to serialize calls to Heap* and is typically not the case for multi-threaded programs.

Why don't Java's +=, -=, *=, /= compound assignment operators require casting?

Java Language Specification defines E1 op= E2 to be equivalent to E1 = (T) ((E1) op (E2)) where T is a type of E1 and E1 is evaluated once.

That's a technical answer, but you may be wondering why that's a case. Well, let's consider the following program.

public class PlusEquals {
    public static void main(String[] args) {
        byte a = 1;
        byte b = 2;
        a = a + b;
        System.out.println(a);
    }
}

What does this program print?

Did you guess 3? Too bad, this program won't compile. Why? Well, it so happens that addition of bytes in Java is defined to return an int. This, I believe was because the Java Virtual Machine doesn't define byte operations to save on bytecodes (there is a limited number of those, after all), using integer operations instead is an implementation detail exposed in a language.

But if a = a + b doesn't work, that would mean a += b would never work for bytes if it E1 += E2 was defined to be E1 = E1 + E2. As the previous example shows, that would be indeed the case. As a hack to make += operator work for bytes and shorts, there is an implicit cast involved. It's not that great of a hack, but back during the Java 1.0 work, the focus was on getting the language released to begin with. Now, because of backwards compatibility, this hack introduced in Java 1.0 couldn't be removed.

Automatic HTTPS connection/redirect with node.js/express

The idea is to check if the incoming request is made with https, if so simply don't redirect it again to https but continue as usual. Else, if it is http, redirect it with appending https.

app.use (function (req, res, next) {
  if (req.secure) {
          next();
  } else {
          res.redirect('https://' + req.headers.host + req.url);
  }
});

Max value of Xmx and Xms in Eclipse?

The maximum values do not depend on Eclipse, it depends on your OS (and obviously on the physical memory available).

You may want to take a look at this question: Max amount of memory per java process in Windows?

How can I enable Assembly binding logging?

For me the 'Bla' file was System.Net.http dll which was missing from my BIN folder. I just added it and it worked fine. Didn't change any registry key or anything of that sort.

React onClick and preventDefault() link refresh/redirect?

I didn't find any of the mentioned options to be correct or work for me when I came to this page. They did give me ideas to test things out and I found that this worked for me.

dontGoToLink(e) {
  e.preventDefault();
 }

render() {
  return (<a href="test.com" onClick={this.dontGoToLink} />});
}

Build fat static library (device + simulator) using Xcode and SDK 4+

I have spent many hours trying to build a fat static library that will work on armv7, armv7s, and the simulator. Finally found a solution.

The gist is to build the two libraries (one for the device and then one for the simulator) separately, rename them to distinguish from each other, and then lipo -create them into one library.

lipo -create libPhone.a libSimulator.a -output libUniversal.a

I tried it and it works!

Set specific precision of a BigDecimal

 BigDecimal decPrec = (BigDecimal)yo.get("Avg");
 decPrec = decPrec.setScale(5, RoundingMode.CEILING);
 String value= String.valueOf(decPrec);

This way you can set specific precision of a BigDecimal.

The value of decPrec was 1.5726903423607562595809913132345426 which is rounded off to 1.57267.

How to set a cookie for another domain

see RFC6265:

The user agent will reject cookies unless the Domain attribute specifies a scope for the cookie that would include the origin server. For example, the user agent will accept a cookie with a Domain attribute of "example.com" or of "foo.example.com" from foo.example.com, but the user agent will not accept a cookie with a Domain attribute of "bar.example.com" or of "baz.foo.example.com".

NOTE: For security reasons, many user agents are configured to reject Domain attributes that correspond to "public suffixes". For example, some user agents will reject Domain attributes of "com" or "co.uk". (See Section 5.3 for more information.)

But the above mentioned workaround with image/iframe works, though it's not recommended due to its insecurity.

How to delete rows from a pandas DataFrame based on a conditional expression

You can assign the DataFrame to a filtered version of itself:

df = df[df.score > 50]

This is faster than drop:

%%timeit
test = pd.DataFrame({'x': np.random.randn(int(1e6))})
test = test[test.x < 0]
# 54.5 ms ± 2.02 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%%timeit
test = pd.DataFrame({'x': np.random.randn(int(1e6))})
test.drop(test[test.x > 0].index, inplace=True)
# 201 ms ± 17.9 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%%timeit
test = pd.DataFrame({'x': np.random.randn(int(1e6))})
test = test.drop(test[test.x > 0].index)
# 194 ms ± 7.03 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

How to Increase Import Size Limit in phpMyAdmin

Sharky's answer was spot on. The phpMyAdmin upload file size displayed is NOT managed by the php.ini settings, which you can see when you run a phpinfo.php containing:

<?php
// Show all information, defaults to INFO_ALL
phpinfo();
?>

It is good practice to increase your php.ini settings for:

post_max_size upload_max_filesize max_execution_time max_input_time memory_limit

You may use the settings example that Sujiraj R shared. Once you have made all of the changes to both your php.ini AND in the"Tweak Settings" area of WHM, when you launch phpMyAdmin and go to the import screen, you will see the size you selected for "cPanel PHP max upload size" field.

There were a lot of good answers on this post, but you had to look back and forth to get the right answer. I hope that by encapsulating those previous answers in this post I have helped just a bit. All of the answers I refer to on this post were derived by others that posted here, so please do not credit me with any of the answers posted herein.

Deep copy, shallow copy, clone

  • Deep copy: Clone this object and every reference to every other object it has
  • Shallow copy: Clone this object and keep its references
  • Object clone() throws CloneNotSupportedException: It is not specified whether this should return a deep or shallow copy, but at the very least: o.clone() != o

How to run a cronjob every X minutes?

Your CRON should look like this:

*/5 * * * *

CronWTF is really usefull when you need to test out your CRON settings.

Might be a good idea to pipe the output into a log file so you can see if your script is throwing any errors too - since you wont see them in your terminal.

Also try using a shebang at the top of your PHP file, so the system knows where to find PHP. Such as:

#!/usr/bin/php

that way you can call the whole thing like this

*/5 * * * * php /path/to/script.php > /path/to/logfile.log

Android : change button text and background color

Here is an example of a drawable that will be white by default, black when pressed:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape>
            <solid
                android:color="#1E669B"/>
            <stroke
                android:width="2dp"
                android:color="#1B5E91"/>
            <corners
                android:radius="6dp"/>
            <padding
                android:bottom="10dp"
                android:left="10dp"
                android:right="10dp"
                android:top="10dp"/>
        </shape>

    </item>
    <item>
        <shape>
            <gradient
                android:angle="270"
                android:endColor="#1E669B"
                android:startColor="#1E669B"/>
            <stroke
                android:width="4dp"
                android:color="#1B5E91"/>
            <corners
                android:radius="7dp"/>
            <padding
                android:bottom="10dp"
                android:left="10dp"
                android:right="10dp"
                android:top="10dp"/>
        </shape>
    </item>
</selector>

Proper usage of Java -D command-line parameters

You're giving parameters to your program instead to Java. Use

java -Dtest="true" -jar myApplication.jar 

instead.

Consider using

"true".equalsIgnoreCase(System.getProperty("test"))

to avoid the NPE. But do not use "Yoda conditions" always without thinking, sometimes throwing the NPE is the right behavior and sometimes something like

System.getProperty("test") == null || System.getProperty("test").equalsIgnoreCase("true")

is right (providing default true). A shorter possibility is

!"false".equalsIgnoreCase(System.getProperty("test"))

but not using double negation doesn't make it less hard to misunderstand.

Prevent BODY from scrolling when a modal is opened

This issue is fixed, Solution: Just open your bootstap.css and change as below

body.modal-open,
.modal-open .navbar-fixed-top,
.modal-open .navbar-fixed-bottom {
  margin-right: 15px;
}

to

 body.modal-open,
.modal-open .navbar-fixed-top,
.modal-open .navbar-fixed-bottom {
  /*margin-right: 15px;*/
}

Please view the below youtube video only less than 3min your issue will fix... https://www.youtube.com/watch?v=kX7wPNMob_E

React Native: Getting the position of an element

I needed to find the position of an element inside a ListView and used this snippet that works kind of like .offset:

const UIManager = require('NativeModules').UIManager;
const handle = React.findNodeHandle(this.refs.myElement);
UIManager.measureLayoutRelativeToParent(
  handle, 
  (e) => {console.error(e)}, 
  (x, y, w, h) => {
    console.log('offset', x, y, w, h);
  });

This assumes I had a ref='myElement' on my component.

JavaScript dictionary with names

You may be trying to use a JSON object:

var myMappings = { "name": "10%", "phone": "10%", "address": "50%", etc.. }

To access:

myMappings.name;
myMappings.phone;
etc..

What is the difference between Python's list methods append and extend?

append appends a single element. extend appends a list of elements.

Note that if you pass a list to append, it still adds one element:

>>> a = [1, 2, 3]
>>> a.append([4, 5, 6])
>>> a
[1, 2, 3, [4, 5, 6]]

get DATEDIFF excluding weekends using sql server

BEGIN 
DECLARE @totaldays INT; 
DECLARE @weekenddays INT;

SET @totaldays = DATEDIFF(DAY, @startDate, @endDate) 
SET @weekenddays = ((DATEDIFF(WEEK, @startDate, @endDate) * 2) + -- get the number of weekend days in between
                       CASE WHEN DATEPART(WEEKDAY, @startDate) = 1 THEN 1 ELSE 0 END + -- if selection was Sunday, won't add to weekends
                       CASE WHEN DATEPART(WEEKDAY, @endDate) = 6 THEN 1 ELSE 0 END)  -- if selection was Saturday, won't add to weekends

Return (@totaldays - @weekenddays)

END

This is on SQL Server 2014

How do you check if a string is not equal to an object or other string value in java?

you'll want to use && to see that it is not equal to "AM" AND not equal to "PM"

if(!TimeOfDayStringQ.equals("AM") && !TimeOfDayStringQ.equals("PM")) {
    System.out.println("Sorry, incorrect input.");
    System.exit(1);
}

to be clear you can also do

if(!(TimeOfDayStringQ.equals("AM") || TimeOfDayStringQ.equals("PM"))){
    System.out.println("Sorry, incorrect input.");
    System.exit(1);
}

to have the not (one or the other) phrase in the code (remember the (silent) brackets)

Can someone explain __all__ in Python?

It also changes what pydoc will show:

module1.py

a = "A"
b = "B"
c = "C"

module2.py

__all__ = ['a', 'b']

a = "A"
b = "B"
c = "C"

$ pydoc module1

Help on module module1:

NAME
    module1

FILE
    module1.py

DATA
    a = 'A'
    b = 'B'
    c = 'C'

$ pydoc module2

Help on module module2:

NAME
    module2

FILE
    module2.py

DATA
    __all__ = ['a', 'b']
    a = 'A'
    b = 'B'

I declare __all__ in all my modules, as well as underscore internal details, these really help when using things you've never used before in live interpreter sessions.

"Series objects are mutable and cannot be hashed" error

Shortly: gene_name[x] is a mutable object so it cannot be hashed. To use an object as a key in a dictionary, python needs to use its hash value, and that's why you get an error.

Further explanation:

Mutable objects are objects which value can be changed. For example, list is a mutable object, since you can append to it. int is an immutable object, because you can't change it. When you do:

a = 5;
a = 3;

You don't change the value of a, you create a new object and make a point to its value.

Mutable objects cannot be hashed. See this answer.

To solve your problem, you should use immutable objects as keys in your dictionary. For example: tuple, string, int.

Read HttpContent in WebApi controller

You can keep your CONTACT parameter with the following approach:

using (var stream = new MemoryStream())
{
    var context = (HttpContextBase)Request.Properties["MS_HttpContext"];
    context.Request.InputStream.Seek(0, SeekOrigin.Begin);
    context.Request.InputStream.CopyTo(stream);
    string requestBody = Encoding.UTF8.GetString(stream.ToArray());
}

Returned for me the json representation of my parameter object, so I could use it for exception handling and logging.

Found as accepted answer here

#ifdef in C#

I would recommend you using the Conditional Attribute!

Update: 3.5 years later

You can use #if like this (example copied from MSDN):

// preprocessor_if.cs
#define DEBUG
#define VC_V7
using System;
public class MyClass 
{
    static void Main() 
    {
#if (DEBUG && !VC_V7)
        Console.WriteLine("DEBUG is defined");
#elif (!DEBUG && VC_V7)
        Console.WriteLine("VC_V7 is defined");
#elif (DEBUG && VC_V7)
        Console.WriteLine("DEBUG and VC_V7 are defined");
#else
        Console.WriteLine("DEBUG and VC_V7 are not defined");
#endif
    }
}

Only useful for excluding parts of methods.

If you use #if to exclude some method from compilation then you will have to exclude from compilation all pieces of code which call that method as well (sometimes you may load some classes at runtime and you cannot find the caller with "Find all references"). Otherwise there will be errors.

If you use conditional compilation on the other hand you can still leave all pieces of code that call the method. All parameters will still be validated by the compiler. The method just won't be called at runtime. I think that it is way better to hide the method just once and not have to remove all the code that calls it as well. You are not allowed to use the conditional attribute on methods which return value - only on void methods. But I don't think this is a big limitation because if you use #if with a method that returns a value you have to hide all pieces of code that call it too.

Here is an example:


    // calling Class1.ConditionalMethod() will be ignored at runtime 
    // unless the DEBUG constant is defined


    using System.Diagnostics;
    class Class1 
    {
       [Conditional("DEBUG")]
       public static void ConditionalMethod() {
          Console.WriteLine("Executed Class1.ConditionalMethod");
       }
    }

Summary:

I would use #ifdef in C++ but with C#/VB I would use Conditional attribute. This way you hide the method definition without having to hide the pieces of code that call it. The calling code is still compiled and validated by the compiler, the method is not called at runtime though. You may want to use #if to avoid dependencies because with Conditional attribute your code is still compiled.

ASP.NET Web Api: The requested resource does not support http method 'GET'

Although this isn't an answer to the OP, I had the exact same error from a completely different root cause; so in case this helps anybody else...

The problem for me was an incorrectly named method parameter which caused WebAPI to route the request unexpectedly. I have the following methods in my ProgrammesController:

[HttpGet]
public Programme GetProgrammeById(int id)
{
    ...
}

[HttpDelete]
public bool DeleteProgramme(int programmeId)
{
    ...
}

DELETE requests to .../api/programmes/3 were not getting routed to DeleteProgramme as I expected, but to GetProgrammeById, because DeleteProgramme didn't have a parameter name of id. GetProgrammeById was then of course rejecting the DELETE as it is marked as only accepting GETs.

So the fix was simple:

[HttpDelete]
public bool DeleteProgramme(int id)
{
    ...
}

And all is well. Silly mistake really but hard to debug.

RestSharp JSON Parameter Posting

In the current version of RestSharp (105.2.3.0) you can add a JSON object to the request body with:

request.AddJsonBody(new { A = "foo", B = "bar" });

This method sets content type to application/json and serializes the object to a JSON string.

How to change resolution (DPI) of an image?

It's simply a matter of scaling the image width and height up by the correct ratio. Not all images formats support a DPI metatag, and when they do, all they're telling your graphics software to do is divide the image by the ratio supplied.

For example, if you export a 300dpi image from Photoshop to a JPEG, the image will appear to be very large when viewed in your picture viewing software. This is because the DPI information isn't supported in JPEG and is discarded when saved. This means your picture viewer doesn't know what ratio to divide the image by and instead displays the image at at 1:1 ratio.

To get the ratio you need to scale the image by, see the code below. Just remember, this will stretch the image, just like it would in Photoshop. You're essentially quadrupling the size of the image so it's going to stretch and may produce artifacts.

Pseudo code

ratio = 300.0 / 72.0   // 4.167
image.width * ratio
image.height * ratio

Rails create or update magic?

Add this to your model:

def self.update_or_create_by(args, attributes)
  obj = self.find_or_create_by(args)
  obj.update(attributes)
  return obj
end

With that, you can:

User.update_or_create_by({name: 'Joe'}, attributes)

C++11 thread-safe queue

According to the standard condition_variables are allowed to wakeup spuriously, even if the event hasn't occured. In case of a spurious wakeup it will return cv_status::no_timeout (since it woke up instead of timing out), even though it hasn't been notified. The correct solution for this is of course to check if the wakeup was actually legit before proceding.

The details are specified in the standard §30.5.1 [thread.condition.condvar]:

—The function will unblock when signaled by a call to notify_one(), a call to notify_all(), expiration of the absolute timeout (30.2.4) speci?ed by abs_time, or spuriously.

...

Returns: cv_status::timeout if the absolute timeout (30.2.4) speci?edby abs_time expired, other-ise cv_status::no_timeout.

Remove spaces from a string in VB.NET

You can also use a small function that will loop through and remove any spaces.

This is very clean and simple.

Public Shared Function RemoveXtraSpaces(strVal As String) As String
     Dim iCount As Integer = 1
     Dim sTempstrVal As String

     sTempstrVal = ""

     For iCount = 1 To Len(strVal)
        sTempstrVal = sTempstrVal + Mid(strVal, iCount, 1).Trim
     Next

     RemoveXtraSpaces = sTempstrVal

     Return RemoveXtraSpaces

End Function

C# Get a control's position on a form

I usually do it like this.. Works every time..

var loc = ctrl.PointToScreen(Point.Empty);

Force drop mysql bypassing foreign key constraint

You can use the following steps, its worked for me to drop table with constraint,solution already explained in the above comment, i just added screen shot for that -enter image description here

Android Whatsapp/Chat Examples

Check out yowsup
https://github.com/tgalal/yowsup

Yowsup is a python library that allows you to do all the previous in your own app. Yowsup allows you to login and use the Whatsapp service and provides you with all capabilities of an official Whatsapp client, allowing you to create a full-fledged custom Whatsapp client.

A solid example of Yowsup's usage is Wazapp. Wazapp is full featured Whatsapp client that is being used by hundreds of thousands of people around the world. Yowsup is born out of the Wazapp project. Before becoming a separate project, it was only the engine powering Wazapp. Now that it matured enough, it was separated into a separate project, allowing anyone to build their own Whatsapp client on top of it. Having such a popular client as Wazapp, built on Yowsup, helped bring the project into a much advanced, stable and mature level, and ensures its continuous development and maintaince.

Yowsup also comes with a cross platform command-line frontend called yowsup-cli. yowsup-cli allows you to jump into connecting and using Whatsapp service directly from command line.

How do I include the string header?

You want to include <string> and use std::string:

#include <string>
#include <iostream>

int main()
{
    std::string s = "a string";
    std::cout << s << std::endl;
}

But what you really need to do is get an introductory level book. You aren't going to learn properly any other way, certainly not scrapping for information online.

How to change background Opacity when bootstrap modal is open

you can set the opacity by the last parameter of rgb function.

the opacity is 0.5 in the example

.modal-backdrop {
    background-color: rgb(0, 0, 0, 0.5);
}

Convert JSON String to JSON Object c#

This works for me using JsonConvert

var result = JsonConvert.DeserializeObject<Class>(responseString);

Aren't Python strings immutable? Then why does a + " " + b work?

Python strings are immutable. However, a is not a string: it is a variable with a string value. You can't mutate the string, but can change what value of the variable to a new string.

Firebase (FCM) how to get token

for those who land here, up to now FirebaseInstanceIdService is deprecated now, use instead:

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    @Override
    public void onNewToken(String token) {
        Log.d("MY_TOKEN", "Refreshed token: " + token);

        // If you want to send messages to this application instance or
        // manage this apps subscriptions on the server side, send the
        // Instance ID token to your app server.
        // sendRegistrationToServer(token);
    }
}

and declare in AndroidManifest

<application... >

<service android:name=".fcm.MyFirebaseMessagingService">
    <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>
</application>

How to remove an iOS app from the App Store

Minor change in iTunes Connect,

  • Login to iTunes Connect
  • Select your app from My Apps section
  • Select App Store tab, Then select Pricing & Availability section
  • Under Availability section you will see two options 1) Available in all territories 2) Remove from sale, Kindly refer below screenshot for the same.
  • Select remove from sale if you would like to remove from all territories, if you would like to remove from specific territory then click on edit & remove from selected territory.

enter image description here

Show div #id on click with jQuery

This is simple way to Display Div using:-

$("#musicinfo").show();  //or
$("#musicinfo").css({'display':'block'});  //or
$("#musicinfo").toggle("slow");   //or
$("#musicinfo").fadeToggle();    //or

How can I transform string to UTF-8 in C#?

string utf8String = "Acción";
string propEncodeString = string.Empty;

byte[] utf8_Bytes = new byte[utf8String.Length];
for (int i = 0; i < utf8String.Length; ++i)
{
   utf8_Bytes[i] = (byte)utf8String[i];
}

propEncodeString = Encoding.UTF8.GetString(utf8_Bytes, 0, utf8_Bytes.Length);

Output should look like

Acción

day’s displays day's

call DecodeFromUtf8();

private static void DecodeFromUtf8()
{
    string utf8_String = "day’s";
    byte[] bytes = Encoding.Default.GetBytes(utf8_String);
    utf8_String = Encoding.UTF8.GetString(bytes);
}

"Auth Failed" error with EGit and GitHub

For *nix users who are using SSH:

Make sure the username for your account on your local machine does not differ from the username for the account on the server. Apparently, eGit does not seem to be able to handle this. For example, if your username on your local machine is 'john', and the account you are using on the server is named 'git', egit simply fails to connect (for me anyways). The only work around I have found is to make sure you have identical usernames in both the local machine and the server.

Flutter Countdown Timer

If all you need is a simple countdown timer, this is a good alternative instead of installing a package. Happy coding!

countDownTimer() async {
 int timerCount;
 for (int x = 5; x > 0; x--) {
   await Future.delayed(Duration(seconds: 1)).then((_) {
     setState(() {
       timerCount -= 1;
    });
  });
 }
}

How do you subtract Dates in Java?

You can use the following approach:

SimpleDateFormat formater=new SimpleDateFormat("yyyy-MM-dd");

long d1=formater.parse("2001-1-1").getTime();
long d2=formater.parse("2001-1-2").getTime();

System.out.println(Math.abs((d1-d2)/(1000*60*60*24)));

NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference

This issue is due to ArrayList variable not being instantiated. Need to declare "recordings" variable like following, that should solve the issue;

ArrayList<String> recordings = new ArrayList<String>();

this calls default constructor and assigns empty string to the recordings variable so that it is not null anymore.

Getting multiple selected checkbox values in a string in javascript and PHP

This is a variation to get all checked checkboxes in all_location_id without using an "if" statement

var all_location_id = document.querySelectorAll('input[name="location[]"]:checked');

var aIds = [];

for(var x = 0, l = all_location_id.length; x < l;  x++)
{
    aIds.push(all_location_id[x].value);
}

var str = aIds.join(', ');

console.log(str);

How do I call a JavaScript function on page load?

Another way to do this is by using event listeners, here how you use them:

document.addEventListener("DOMContentLoaded", function() {
  you_function(...);
});

Explanation:

DOMContentLoaded It means when the DOM Objects of the document are fully loaded and seen by JavaScript, also this could have been "click", "focus"...

function() Anonymous function, will be invoked when the event occurs.

How to install a package inside virtualenv?

Avoiding Headaches and Best Practices:

  • Virtual Environments are not part of your git project (they don't need to be versioned) !

  • They can reside on the project folder (locally), but, ignored on your .gitignore.

  • After activating the virtual environment of your project, never "sudo pip install package".
  • After finishing your work, always "deactivate" your environment.
  • Avoid renaming your project folder.


For a better representation, here's a simulation:

creating a folder for your projects/environments

$ mkdir venv

creating environment

$ cd venv/ 

$ virtualenv google_drive
New python executable in google_drive/bin/python
Installing setuptools, pip...done.

activating environment

$ source google_drive/bin/activate

installing packages

(google_drive) $ pip install PyDrive
Downloading/unpacking PyDrive
Downloading PyDrive-1.3.1-py2-none-any.whl
...
...
...    
Successfully installed PyDrive PyYAML google-api-python-client oauth2client six uritemplate httplib2 pyasn1 rsa pyasn1-modules
Cleaning up...

package available inside the environment

(google_drive) $ python
Python 2.7.6 (default, Oct 26 2016, 20:30:19) 
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> import pydrive.auth
>>>  
>>> gdrive = pydrive.auth.GoogleAuth()
>>>

deactivate environment

(google_drive) $ deactivate 

$ 

package NOT AVAILABLE outside the environment

$ python
Python 2.7.6 (default, Oct 26 2016, 20:32:10) 
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> import pydrive.auth
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named pydrive.auth
>>> 

Notes:

Why not sudo?

Virtualenv creates a whole new environment for you, defining $PATH and some other variables and settings. When you use sudo pip install package, you are running Virtualenv as root, escaping the whole environment which was created, and then, installing the package on global site-packages, and not inside the project folder where you have a Virtual Environment, although you have activated the environment.

If you rename the folder of your project...

...you'll have to adjust some variables from some files inside the bin directory of your project.

For example:

bin/pip, line 1 (She Bang)

bin/activate, line 42 (VIRTUAL_ENV)

Adding rows dynamically with jQuery

Building on the other answers, I simplified things a bit. By cloning the last element, we get the "add new" button for free (you have to change the ID to a class because of the cloning) and also reduce DOM operations. I had to use filter() instead of find() to get only the last element.

$('.js-addNew').on('click', function(e) {
   e.preventDefault();
   var $rows   = $('.person'),
       $last   = $rows.filter(':last'),
       $newRow = $last.clone().insertAfter($last);

   $last.find($('.js-addNew')).remove(); // remove old button
   $newRow.hide().find('input').val('');
   $newRow.slideDown(500);
});

postgresql - replace all instances of a string within text field

You want to use postgresql's replace function:

replace(string text, from text, to text)

for instance :

UPDATE <table> SET <field> = replace(<field>, 'cat', 'dog')

Be aware, though, that this will be a string-to-string replacement, so 'category' will become 'dogegory'. the regexp_replace function may help you define a stricter match pattern for what you want to replace.

AngularJS view not updating on model change

setTimout executes outside of angular. You need to use $timeout service for this to work:

var app = angular.module('test', []);

    app.controller('TestCtrl', function ($scope, $timeout) {
       $scope.testValue = 0;

        $timeout(function() {
            console.log($scope.testValue++);
        }, 500);
    });

The reason is that two-way binding in angular uses dirty checking. This is a good article to read about angular's dirty checking. $scope.$apply() kicks off a $digest cycle. This will apply the binding. $timeout handles the $apply for you so it is the recommended service to use when using timeouts.

Essentially, binding happens during the $digest cycle (if the value is seen to be different).

how to convert date to a format `mm/dd/yyyy`

Use CONVERT with the Value specifier of 101, whilst casting your data to date:

CONVERT(VARCHAR(10), CAST(Created_TS AS DATE), 101)

Difference between static and shared libraries?

-------------------------------------------------------------------------
|  +-  |    Shared(dynamic)       |   Static Library (Linkages)         |
-------------------------------------------------------------------------
|Pros: | less memory use          |   an executable, using own libraries|
|      |                          |     ,coming with the program,       |
|      |                          |   doesn't need to worry about its   |
|      |                          |   compilebility subject to libraries|
-------------------------------------------------------------------------
|Cons: | implementations of       |   bigger memory uses                |
|      | libraries may be altered |                                     |
|      | subject to OS  and its   |                                     |
|      | version, which may affect|                                     |
|      | the compilebility and    |                                     |
|      | runnability of the code  |                                     |
-------------------------------------------------------------------------

cast class into another class or convert class to another

There are some great answers here, I just wanted to add a little bit of type checking here as we cannot assume that if properties exist with the same name, that they are of the same type. Here is my offering, which extends on the previous, very excellent answer as I had a few little glitches with it.

In this version I have allowed for the consumer to specify fields to be excluded, and also by default to exclude any database / model specific related properties.

    public static T Transform<T>(this object myobj, string excludeFields = null)
    {
        // Compose a list of unwanted members
        if (string.IsNullOrWhiteSpace(excludeFields))
            excludeFields = string.Empty;
        excludeFields = !string.IsNullOrEmpty(excludeFields) ? excludeFields + "," : excludeFields;
        excludeFields += $"{nameof(DBTable.ID)},{nameof(DBTable.InstanceID)},{nameof(AuditableBase.CreatedBy)},{nameof(AuditableBase.CreatedByID)},{nameof(AuditableBase.CreatedOn)}";

        var objectType = myobj.GetType();
        var targetType = typeof(T);
        var targetInstance = Activator.CreateInstance(targetType, false);

        // Find common members by name
        var sourceMembers = from source in objectType.GetMembers().ToList()
                                  where source.MemberType == MemberTypes.Property
                                  select source;
        var targetMembers = from source in targetType.GetMembers().ToList()
                                  where source.MemberType == MemberTypes.Property
                                  select source;
        var commonMembers = targetMembers.Where(memberInfo => sourceMembers.Select(c => c.Name)
            .ToList().Contains(memberInfo.Name)).ToList();

        // Remove unwanted members
        commonMembers.RemoveWhere(x => x.Name.InList(excludeFields));

        foreach (var memberInfo in commonMembers)
        {
            if (!((PropertyInfo)memberInfo).CanWrite) continue;

            var targetProperty = typeof(T).GetProperty(memberInfo.Name);
            if (targetProperty == null) continue;

            var sourceProperty = myobj.GetType().GetProperty(memberInfo.Name);
            if (sourceProperty == null) continue;

            // Check source and target types are the same
            if (sourceProperty.PropertyType.Name != targetProperty.PropertyType.Name) continue;

            var value = myobj.GetType().GetProperty(memberInfo.Name)?.GetValue(myobj, null);
            if (value == null) continue;

            // Set the value
            targetProperty.SetValue(targetInstance, value, null);
        }
        return (T)targetInstance;
    }

How do I sort an NSMutableArray with custom objects in it?

Swift's protocols and functional programming makes that very easy you just have to make your class conform to the Comparable protocol, implement the methods required by the protocol and then use the sorted(by: ) high order function to create a sorted array without need to use mutable arrays by the way.

class Person: Comparable {
    var birthDate: NSDate?
    let name: String

    init(name: String) {
        self.name = name
    }

    static func ==(lhs: Person, rhs: Person) -> Bool {
        return lhs.birthDate === rhs.birthDate || lhs.birthDate?.compare(rhs.birthDate as! Date) == .orderedSame
    }

    static func <(lhs: Person, rhs: Person) -> Bool {
        return lhs.birthDate?.compare(rhs.birthDate as! Date) == .orderedAscending
    }

    static func >(lhs: Person, rhs: Person) -> Bool {
        return lhs.birthDate?.compare(rhs.birthDate as! Date) == .orderedDescending
    }

}

let p1 = Person(name: "Sasha")
p1.birthDate = NSDate() 

let p2 = Person(name: "James")
p2.birthDate = NSDate()//he is older by miliseconds

if p1 == p2 {
    print("they are the same") //they are not
}

let persons = [p1, p2]

//sort the array based on who is older
let sortedPersons = persons.sorted(by: {$0 > $1})

//print sasha which is p1
print(persons.first?.name)
//print James which is the "older"
print(sortedPersons.first?.name)

How to reset Jenkins security settings from the command line?

Easy way out of this is to use the admin psw to login with your admin user:

  • Change to root user: sudo su -
  • Copy the password: xclip -sel clip < /var/lib/jenkins/secrets/initialAdminPassword
  • Login with admin and press ctrl + v on password input box.

Install xclip if you don't have it:

  • $ sudo apt-get install xclip

HTML email with Javascript

I don't think that is possible in an email, nor should it be. There would be major security ramifications.

If file exists then delete the file

fileExists() is a method of FileSystemObject, not a global scope function.

You also have an issue with the delete, DeleteFile() is also a method of FileSystemObject.

Furthermore, it seems you are moving the file and then attempting to deal with the overwrite issue, which is out of order. First you must detect the name collision, so you can choose the rename the file or delete the collision first. I am assuming for some reason you want to keep deleting the new files until you get to the last one, which seemed implied in your question.

So you could use the block:

if NOT fso.FileExists(newname) Then  

    file.move fso.buildpath(OUT_PATH, newname)           

else

    fso.DeleteFile newname
    file.move fso.buildpath(OUT_PATH, newname)  

end if 

Also be careful that your string comparison with the = sign is case sensitive. Use strCmp with vbText compare option for case insensitive string comparison.

Run PHP function on html button click

Use an AJAX Request on your PHP file, then display the result on your page, without any reloading.

http://api.jquery.com/load/ This is a simple solution if you don't need any POST data.

Show spinner GIF during an $http request in AngularJS?

Here's a version using a directive and ng-hide.

This will show the loader during all calls via angular's $http service.

In the template:

<div class="loader" data-loading></div>

directive:

angular.module('app')
  .directive('loading', ['$http', function ($http) {
    return {
      restrict: 'A',
      link: function (scope, element, attrs) {
        scope.isLoading = function () {
          return $http.pendingRequests.length > 0;
        };
        scope.$watch(scope.isLoading, function (value) {
          if (value) {
            element.removeClass('ng-hide');
          } else {
            element.addClass('ng-hide');
          }
        });
      }
    };
}]);

by using the ng-hide class on the element, you can avoid jquery.


Customize: add an interceptor

If you create a loading-interceptor, you can show/hide the loader based on a condition.

directive:

var loadingDirective = function ($rootScope) {
  return function ($scope, element, attrs) {
      $scope.$on("loader_show", function () {
          return element.removeClass('ng-hide');
      });
      return $scope.$on("loader_hide", function () {
          return element.addClass('ng-hide');
      });
  };
};

interceptor:

  • for example: don't show spinner when response.background === true;
  • Intercept request and/or response to set $rootScope.$broadcast("loader_show"); or $rootScope.$broadcast("loader_hide");

more info on writing an interceptor

Measuring Query Performance : "Execution Plan Query Cost" vs "Time Taken"

Query Execution Time:

DECLARE @EndTime datetime
DECLARE @StartTime datetime 
SELECT @StartTime=GETDATE() 


` -- Write Your Query`

SELECT @EndTime=GETDATE()
--This will return execution time of your query
SELECT DATEDIFF(MILLISECOND,@StartTime,@EndTime) AS [Duration in millisecs] 

Query Out Put Will be Like:

enter image description here

To Optimize Query Cost :

Click on your SQL Management Studio

enter image description here

Run your query and click on Execution plan beside the Messages tab of your query result. you will see like

enter image description here

psql: server closed the connection unexepectedly

If your Postgres was working and suddenly you encountered with this error, my problem was resolved just by restarting Postgres service or container.

Crop image in android

hope you are doing well. you can use my code to crop image.you just have to make a class and use this class into your XMl and java classes. Crop image. you can crop your selected image into circle and square into many of option. hope fully it will works for you.because this is totally manageable for you and you can change it according to you.

enjoy your work :)

Using File.listFiles with FileNameExtensionFilter

Duh.... listFiles requires java.io.FileFilter. FileNameExtensionFilter extends javax.swing.filechooser.FileFilter. I solved my problem by implementing an instance of java.io.FileFilter

Edit: I did use something similar to @cFreiner's answer. I was trying to use a Java API method instead of writing my own implementation which is why I was trying to use FileNameExtensionFilter. I have many FileChoosers in my application and have used FileNameExtensionFilters for that and I mistakenly assumed that it was also extending java.io.FileFilter.

When do Java generics require <? extends T> instead of <T> and is there any downside of switching?

First - I have to direct you to http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html -- she does an amazing job.

The basic idea is that you use

<T extends SomeClass>

when the actual parameter can be SomeClass or any subtype of it.

In your example,

Map<String, Class<? extends Serializable>> expected = null;
Map<String, Class<java.util.Date>> result = null;
assertThat(result, is(expected));

You're saying that expected can contain Class objects that represent any class that implements Serializable. Your result map says it can only hold Date class objects.

When you pass in result, you're setting T to exactly Map of String to Date class objects, which doesn't match Map of String to anything that's Serializable.

One thing to check -- are you sure you want Class<Date> and not Date? A map of String to Class<Date> doesn't sound terribly useful in general (all it can hold is Date.class as values rather than instances of Date)

As for genericizing assertThat, the idea is that the method can ensure that a Matcher that fits the result type is passed in.

What’s the difference between Response.Write() andResponse.Output.Write()?

Response.write() is used to display the normal text and Response.output.write() is used to display the formated text.

What is the purpose of using WHERE 1=1 in SQL statements?

Yeah, it's typically because it starts out as 'where 1 = 0', to force the statement to fail.

It's a more naive way of wrapping it up in a transaction and not committing it at the end, to test your query. (This is the preferred method).

How to detect page zoom level in all modern browsers?

In Internet Explorer 7, 8 & 9, this works:

function getZoom() {
    var screen;

    screen = document.frames.screen;
    return ((screen.deviceXDPI / screen.systemXDPI) * 100 + 0.9).toFixed();
}

The "+0.9" is added to prevent rounding errors (otherwise, you would get 104% and 109% when the browser zoom is set to 105% and 110% respectively).

In IE6 zoom doesn't exists, so it is unnecessary to check the zoom.

pass post data with window.location.href

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

You can use this function:

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

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

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

            form.appendChild(hiddenField);
        }
    }

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

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

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

Write-back vs Write-Through caching?

Write-back and write-through describe policies when a write hit occurs, that is when the cache has the requested information. In these examples, we assume a single processor is writing to main memory with a cache.

Write-through: The information is written to the cache and memory, and the write finishes when both have finished. This has the advantage of being simpler to implement, and the main memory is always consistent (in sync) with the cache (for the uniprocessor case - if some other device modifies main memory, then this policy is not enough), and a read miss never results in writes to main memory. The obvious disadvantage is that every write hit has to do two writes, one of which accesses slower main memory.

Write-back: The information is written to a block in the cache. The modified cache block is only written to memory when it is replaced (in effect, a lazy write). A special bit for each cache block, the dirty bit, marks whether or not the cache block has been modified while in the cache. If the dirty bit is not set, the cache block is "clean" and a write miss does not have to write the block to memory.

The advantage is that writes can occur at the speed of the cache, and if writing within the same block only one write to main memory is needed (when the previous block is being replaced). The disadvantages are that this protocol is harder to implement, main memory can be not consistent (not in sync) with the cache, and reads that result in replacement may cause writes of dirty blocks to main memory.

The policies for a write miss are detailed in my first link.

These protocols don't take care of the cases with multiple processors and multiple caches, as is common in modern processors. For this, more complicated cache coherence mechanisms are required. Write-through caches have simpler protocols since a write to the cache is immediately reflected in memory.

Good resources:

Java getting the Enum name given the Enum Value

Try, the following code..

    @Override
    public String toString() {
    return this.name();
    }

Eclipse "cannot find the tag library descriptor" for custom tags (not JSTL!)

I'm using Spring STS plugin and a Spring webmvc template project. I had to install the Maven m2e plugin first: http://www.eclipse.org/m2e/

And then clean the project. Under Project -> Clean...

ASP.Net MVC 4 Form with 2 submit buttons/actions

That's what we have in our applications:
Attribute

public class HttpParamActionAttribute : ActionNameSelectorAttribute
{
    public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
    {
        if (actionName.Equals(methodInfo.Name, StringComparison.InvariantCultureIgnoreCase))
            return true;

        var request = controllerContext.RequestContext.HttpContext.Request;
        return request[methodInfo.Name] != null;
    }
}

Actions decorated with it:


[HttpParamAction]
public ActionResult Save(MyModel model)
{
    // ...
}

[HttpParamAction]
public ActionResult Publish(MyModel model)
{
    // ...
}

HTML/Razor

@using (@Html.BeginForm())
{
    <!-- form content here -->
    <input type="submit" name="Save" value="Save" />
    <input type="submit" name="Publish" value="Publish" />
}

name attribute of submit button should match action/method name

This way you do not have to hard-code urls in javascript

Catching errors in Angular HttpClient

If you find yourself unable to catch errors with any of the solutions provided here, it may be that the server isn't handling CORS requests.

In that event, Javascript, much less Angular, can access the error information.

Look for warnings in your console that include CORB or Cross-Origin Read Blocking.

Also, the syntax has changed for handling errors (as described in every other answer). You now use pipe-able operators, like so:

this.service.requestsMyInfo(payload).pipe(
    catcheError(err => {
        // handle the error here.
    })
);

NULL vs nullptr (Why was it replaced?)

One reason: the literal 0 has a bad tendency to acquire the type int, e.g. in perfect argument forwarding or more in general as argument with templated type.

Another reason: readability and clarity of code.

How to find substring from string?

If you are utilizing arrays too much then you should include cstring.h because it has too many functions including finding substrings.

datetime.parse and making it work with a specific format

DateTime.ParseExact(input,"yyyyMMdd HH:mm",null);

assuming you meant to say that minutes followed the hours, not seconds - your example is a little confusing.

The ParseExact documentation details other overloads, in case you want to have the parse automatically convert to Universal Time or something like that.

As @Joel Coehoorn mentions, there's also the option of using TryParseExact, which will return a Boolean value indicating success or failure of the operation - I'm still on .Net 1.1, so I often forget this one.

If you need to parse other formats, you can check out the Standard DateTime Format Strings.

How do I set hostname in docker-compose?

As of docker-compose version 3 and later, you can just use the hostname key:

version: '3'
services:
  dns:
    hostname: 'your-name'

Dataset - Vehicle make/model/year (free)

These guys have an API that will give the results. It's also free to use.

http://www.carqueryapi.com

Note: they also provide data source download in xls or sql format at a premium price. but these data also provides technical specifications for all the make model and trim options.

Best Practice: Software Versioning

We follow a.b.c approach like:

increament 'a' if there is some major changes happened in application. Like we upgrade .NET 1.1 application to .NET 3.5

increament 'b' if there is some minor changes like any new CR or Enhancement is implemented.

increament 'c' if there is some defects fixes in the code.

ActionBarActivity is deprecated

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

Read here and here for more information.

How can I create a dynamic button click event on a dynamic button?

Let's say you have 25 objects and want one process to handle any one objects click event. You could write 25 delegates or use a loop to handle the click event.

public form1()
{
    foreach (Panel pl  in Container.Components)
    {
        pl.Click += Panel_Click;
    }
}

private void Panel_Click(object sender, EventArgs e)
{
    // Process the panel clicks here
    int index = Panels.FindIndex(a => a == sender);
    ...
}

Missing visible-** and hidden-** in Bootstrap v4

Unfortunately these new bootstrap 4 classes do not work like the old ones on a div using collapse as they set the visible div to block which starts out visible rather than hidden and if you add an extra div around the collapse functionality no longer works.

How to declare global variables in Android?

The suggested by Soonil way of keeping a state for the application is good, however it has one weak point - there are cases when OS kills the entire application process. Here is the documentation on this - Processes and lifecycles.

Consider a case - your app goes into the background because somebody is calling you (Phone app is in the foreground now). In this case && under some other conditions (check the above link for what they could be) the OS may kill your application process, including the Application subclass instance. As a result the state is lost. When you later return to the application, then the OS will restore its activity stack and Application subclass instance, however the myState field will be null.

AFAIK, the only way to guarantee state safety is to use any sort of persisting the state, e.g. using a private for the application file or SharedPrefernces (it eventually uses a private for the application file in the internal filesystem).

How can I inject a property value into a Spring Bean which was configured using annotations?

For me, it was @Lucky's answer, and specifically, the line

AutowiredFakaSource fakeDataSource = ctx.getBean(AutowiredFakaSource.class);

from the Captain Debug page

that fixed my problem. I have an ApplicationContext-based app running from the command-line, and judging by a number of the comments on SO, Spring wires up these differently to MVC-based apps.

Print <div id="printarea"></div> only?

I have a better solution with minimal code.

Place your printable part inside a div with an id like this:

<div id="printableArea">
      <h1>Print me</h1>
</div>

<input type="button" onclick="printDiv('printableArea')" value="print a div!" />

Then add an event like an onclick (as shown above), and pass the id of the div like I did above.

Now let's create a really simple javascript:

function printDiv(divName) {
     var printContents = document.getElementById(divName).innerHTML;
     var originalContents = document.body.innerHTML;

     document.body.innerHTML = printContents;

     window.print();

     document.body.innerHTML = originalContents;
}

Notice how simple this is? No popups, no new windows, no crazy styling, no JS libraries like jquery. The problem with really complicated solutions (the answer isn't complicated and not what I'm referring to) is the fact that it will NEVER translate across all browsers, ever! If you want to make the styles different, do as shown in the checked answer by adding the media attribute to a stylesheet link (media="print").

No fluff, lightweight, it just works.

How do I get JSON data from RESTful service using Python?

If you desire to use Python 3, you can use the following:

import json
import urllib.request
req = urllib.request.Request('url')
with urllib.request.urlopen(req) as response:
    result = json.loads(response.readall().decode('utf-8'))

Index of element in NumPy array

You can convert a numpy array to list and get its index .

for example:

tmp = [1,2,3,4,5] #python list
a = numpy.array(tmp) #numpy array
i = list(a).index(2) # i will return index of 2, which is 1

this is just what you wanted.

AngularJS - get element attributes values

If you are using Angular2+ following code will help

You can use following syntax to get attribute value from html element

//to retrieve html element

const element = fixture.debugElement.nativeElement.querySelector('name of element'); // example a, h1, p

//get attribute value from that element

  const attributeValue = element.attributeName // like textContent/href

How to Deserialize XML document

You can just change one attribute for you Cars car property from XmlArrayItem to XmlElment. That is, from

[System.Xml.Serialization.XmlRootAttribute("Cars", Namespace = "", IsNullable = false)]
public class Cars
{
    [XmlArrayItem(typeof(Car))]
    public Car[] Car { get; set; }
}

to

[System.Xml.Serialization.XmlRootAttribute("Cars", Namespace = "", IsNullable = false)]
public class Cars
{
    [XmlElement("Car")]
    public Car[] Car { get; set; }
}

Accessing JSON object keys having spaces

The answer of Pardeep Jain can be useful for static data, but what if we have an array in JSON?

For example, we have i values and get the value of id field

alert(obj[i].id); //works!

But what if we need key with spaces?

In this case, the following construction can help (without point between [] blocks):

alert(obj[i]["No. of interfaces"]); //works too!

"An attempt was made to access a socket in a way forbidden by its access permissions" while using SMTP

Do this if you are using GoDaddy, I'm using Lets Encrypt SSL if you want you can get it.

Here is the code - The code is in asp.net core 2.0 but should work in above versions.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MailKit.Net.Smtp;
using MimeKit;

namespace UnityAssets.Website.Services
{
    public class EmailSender : IEmailSender
    {
        public async Task SendEmailAsync(string toEmailAddress, string subject, string htmlMessage)
        {
            var email = new MimeMessage();
            email.From.Add(new MailboxAddress("Application Name", "[email protected]"));
            email.To.Add(new MailboxAddress(toEmailAddress, toEmailAddress));
            email.Subject = subject;

            var body = new BodyBuilder
            {
                HtmlBody = htmlMessage
            };

            email.Body = body.ToMessageBody();

            using (var client = new SmtpClient())
            {
                //provider specific settings
                await client.ConnectAsync("smtp.gmail.com", 465, true).ConfigureAwait(false);
                await client.AuthenticateAsync("[email protected]", "sketchunity").ConfigureAwait(false);

                await client.SendAsync(email).ConfigureAwait(false);
                await client.DisconnectAsync(true).ConfigureAwait(false);
            }
        }
    }
}

Pandas rename column by position?

You can do this:

df.rename(columns={ df.columns[1]: "whatever" })

How do you change the document font in LaTeX?

This article might be helpful with changing fonts.

From the article:

The commands to change font attributes are illustrated by the following example:

  \fontencoding{T1}
  \fontfamily{garamond}
  \fontseries{m}
  \fontshape{it}
  \fontsize{12}{15}
  \selectfont

This series of commands set the current font to medium weight italic garamond 12pt type with 15pt leading in the T1 encoding scheme, and the \selectfont command causes LaTeX to look in its mapping scheme for a metric corresponding to these attributes.

Where can I find documentation on formatting a date in JavaScript?

Personally, because I use both PHP and jQuery/javascript in equal measures, I use the date function from php.js http://phpjs.org/functions/date/

Using a library that uses the same format strings as something I already know is easier for me, and the manual containing all of the format string possibilities for the date function is of course online at php.net

You simply include the date.js file in your HTML using your preferred method then call it like this:

var d1=new Date();
var datestring = date('Y-m-d', d1.valueOf()/1000);

You can use d1.getTime() instead of valueOf() if you want, they do the same thing.

The divide by 1000 of the javascript timestamp is because a javascript timestamp is in miliseconds but a PHP timestamp is in seconds.

Edit a text file on the console using Powershell

You could install Far Manager (a great OFM, by the way) and call its editor like that:

Far /e filename.txt

Android TabLayout Android Design

I am facing some issue with menu change when fragment changes in ViewPager. I ended up implemented below code.

DashboardFragment

public class DashboardFragment extends BaseFragment {

    private Context mContext;
    private TabLayout mTabLayout;
    private ViewPager mViewPager;
    private DashboardPagerAdapter mAdapter;
    private OnModuleChangeListener onModuleChangeListener;
    private NavDashBoardActivity activityInstance;

    public void setOnModuleChangeListener(OnModuleChangeListener onModuleChangeListener) {
        this.onModuleChangeListener = onModuleChangeListener;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.dashboard_fragment, container, false);
    }

    //pass -1 if you want to get it via pager
    public Fragment getFragmentFromViewpager(int position) {
        if (position == -1)
            position = mViewPager.getCurrentItem();
        return ((Fragment) (mAdapter.instantiateItem(mViewPager, position)));
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mContext = getActivity();

        activityInstance = (NavDashBoardActivity) getActivity();

        mTabLayout = (TabLayout) view.findViewById(R.id.tab_layout);
        mViewPager = (ViewPager) view.findViewById(R.id.view_pager);

        final List<EnumUtils.Module> moduleToShow = getModuleToShowList();
        mViewPager.setOffscreenPageLimit(moduleToShow.size());

        for(EnumUtils.Module module :moduleToShow)
            mTabLayout.addTab(mTabLayout.newTab().setText(EnumUtils.Module.getTabText(module)));

        updateTabPagerAndMenu(0 , moduleToShow);

        mAdapter = new DashboardPagerAdapter(getFragmentManager(),moduleToShow);
        mViewPager.setOffscreenPageLimit(mAdapter.getCount());

        mViewPager.setAdapter(mAdapter);

        mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(final TabLayout.Tab tab) {
                    mViewPager.post(new Runnable() {
                    @Override
                    public void run() {
                        mViewPager.setCurrentItem(tab.getPosition());
                    }
                });
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });

        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                //added to redraw menu on scroll
            }

            @Override
            public void onPageSelected(int position) {
                updateTabPagerAndMenu(position , moduleToShow);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    //also validate other checks and this method should be in SharedPrefs...
    public static List<EnumUtils.Module> getModuleToShowList(){
        List<EnumUtils.Module> moduleToShow = new ArrayList<>();

        moduleToShow.add(EnumUtils.Module.HOME);
        moduleToShow.add(EnumUtils.Module.ABOUT);

        return moduleToShow;
    }

    public void setCurrentTab(final int position){
        if(mViewPager != null){
            mViewPager.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mViewPager.setCurrentItem(position);
                }
            },100);
        }
    }

    private Fragment getCurrentFragment(){
        return mAdapter.getCurrentFragment();
    }

    private void updateTabPagerAndMenu(int position , List<EnumUtils.Module> moduleToShow){
        //it helps to change menu on scroll
        //http://stackoverflow.com/a/27984263/3496570
        //No effect after changing below statement
        ActivityCompat.invalidateOptionsMenu(getActivity());
        if(mTabLayout != null)
            mTabLayout.getTabAt(position).select();

        if(onModuleChangeListener != null){

            if(activityInstance != null){
                activityInstance.updateStatusBarColor(
                        EnumUtils.Module.getStatusBarColor(moduleToShow.get(position)));
            }
            onModuleChangeListener.onModuleChanged(moduleToShow.get(position));

            mTabLayout.setSelectedTabIndicatorColor(EnumUtils.Module.getModuleColor(moduleToShow.get(position)));
            mTabLayout.setTabTextColors(ContextCompat.getColor(mContext,android.R.color.black)
                    , EnumUtils.Module.getModuleColor(moduleToShow.get(position)));
        }
    }
}

dashboardfragment.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <!-- our tablayout to display tabs  -->
    <android.support.design.widget.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:tabBackground="@android:color/white"
        app:tabGravity="fill"
        app:tabIndicatorHeight="4dp"
        app:tabMode="scrollable"
        app:tabSelectedTextColor="@android:color/black"
        app:tabTextColor="@android:color/black" />

    <!-- View pager to swipe views -->
    <android.support.v4.view.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</LinearLayout>

DashboardPagerAdapter

public class DashboardPagerAdapter extends FragmentPagerAdapter {

private List<EnumUtils.Module> moduleList;
private Fragment mCurrentFragment = null;

public DashboardPagerAdapter(FragmentManager fm, List<EnumUtils.Module> moduleList){
    super(fm);
    this.moduleList = moduleList;
}

@Override
public Fragment getItem(int position) {
    return EnumUtils.Module.getDashboardFragment(moduleList.get(position));
}

@Override
public int getCount() {
    return moduleList.size();
}

@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
    if (getCurrentFragment() != object) {
        mCurrentFragment = ((Fragment) object);
    }
    super.setPrimaryItem(container, position, object);
}

public Fragment getCurrentFragment() {
    return mCurrentFragment;
}

public int getModulePosition(EnumUtils.Module moduleName){
    for(int x = 0 ; x < moduleList.size() ; x++){
        if(moduleList.get(x).equals(moduleName))
            return x;
    }
    return -1;
}

}

And in each page of Fragment setHasOptionMenu(true) in onCreate and implement onCreateOptionMenu. then it will work properly.

dASHaCTIVITY

public class NavDashBoardActivity extends BaseActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private Context mContext;
    private DashboardFragment dashboardFragment;
    private Toolbar mToolbar;
    private DrawerLayout drawer;
    private ActionBarDrawerToggle toggle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_nav_dash_board);

        mContext = NavDashBoardActivity.this;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().setStatusBarColor(ContextCompat.getColor(mContext,R.color.yellow_action_bar));
        }

        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);

        updateToolbarText(new ToolbarTextBO("NCompass " ,""));

        drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        toggle = new ActionBarDrawerToggle(
                this, drawer, mToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        //onclick of back button on Navigation it will popUp fragment...
        toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!toggle.isDrawerIndicatorEnabled()) {
                    getSupportFragmentManager().popBackStack();
                }
            }
        });

        final NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setItemIconTintList(null);//It helps to show icon on Navigation
        updateNavigationMenuItem(navigationView);

        navigationView.setNavigationItemSelectedListener(this);

        //Left Drawer Upper Section
        View headerLayout = navigationView.getHeaderView(0); // 0-index header

        TextView userNameTv = (TextView) headerLayout.findViewById(R.id.tv_user_name);
        userNameTv.setText(AuthSharePref.readUserLoggedIn().getFullName());
        RoundedImageView ivUserPic = (RoundedImageView) headerLayout.findViewById(R.id.iv_user_pic);

        ivUserPic.setImageResource(R.drawable.profile_img);

        headerLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //close drawer and add a fragment to it
                drawer.closeDrawers();//also try other methods..
            }
        });

        //ZA code starts...
        dashboardFragment = new DashboardFragment();
        dashboardFragment.setOnModuleChangeListener(new OnModuleChangeListener() {
            @Override
            public void onModuleChanged(EnumUtils.Module module) {
                if(mToolbar != null){
                    mToolbar.setBackgroundColor(EnumUtils.Module.getModuleColor(module));

                    if(EnumUtils.Module.getMenuID(module) != -1)
                        navigationView.getMenu().findItem(EnumUtils.Module.getMenuID(module)).setChecked(true);
                }
            }
        });

        addBaseFragment(dashboardFragment);
        backStackListener();
    }



    public void updateStatusBarColor(int colorResourceID){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().setStatusBarColor(colorResourceID);
        }
    }

    private void updateNavigationMenuItem(NavigationView navigationView){
        List<EnumUtils.Module> modules =  DashboardFragment.getModuleToShowList();

        if(!modules.contains(EnumUtils.Module.MyStores)){
            navigationView.getMenu().findItem(R.id.nav_my_store).setVisible(false);
        }
        if(!modules.contains(EnumUtils.Module.Livewall)){
            navigationView.getMenu().findItem(R.id.nav_live_wall).setVisible(false);
        }
    }

    private void backStackListener(){
        getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
            @Override
            public void onBackStackChanged() {

                if(getSupportFragmentManager().getBackStackEntryCount() >= 1)
                {
                    toggle.setDrawerIndicatorEnabled(false); //disable "hamburger to arrow" drawable
                    toggle.setHomeAsUpIndicator(R.drawable.ic_arrow_back_black_24dp); //set your own
                    ///toggle.setDrawerArrowDrawable();
                    ///toggle.setDrawerIndicatorEnabled(false); // this will hide hamburger image
                    ///Toast.makeText(mContext,"Update to Arrow",Toast.LENGTH_SHORT).show();
                }
                else{
                    toggle.setDrawerIndicatorEnabled(true);
                }
                if(getSupportFragmentManager().getBackStackEntryCount() >0){
                    if(getCurrentFragment() instanceof DashboardFragment){
                        Fragment subFragment = ((DashboardFragment) getCurrentFragment())
                                .getViewpager(-1);
                    }
                }
                else{

                }
            }
        });
    }

    private void updateToolBarTitle(String title){
        getSupportActionBar().setTitle(title);
    }
    public void updateToolBarColor(String hexColor){
        if(mToolbar != null)
            mToolbar.setBackgroundColor(Color.parseColor(hexColor));
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (drawer.isDrawerOpen(GravityCompat.START))
            getMenuInflater().inflate(R.menu.empty, menu);

        return super.onCreateOptionsMenu(menu);//true is wriiten first..
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == android.R.id.home)
        {
            if (drawer.isDrawerOpen(GravityCompat.START))
                drawer.closeDrawer(GravityCompat.START);
            else {
                if (getSupportFragmentManager().getBackStackEntryCount() > 0) {

                } else
                    drawer.openDrawer(GravityCompat.START);
            }

            return false;///true;
        }

        return false;// false so that fragment can also handle the menu event. Otherwise it is handled their
        ///return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_my_store) {
            // Handle the camera action
            dashboardFragment.setCurrentTab(EnumUtils.Module.MyStores);
        } 
        }else if  (id == R.id.nav_log_out)  {
            Dialogs.logOut(mContext);
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }


    public void updateToolbarText(ToolbarTextBO toolbarTextBO){
        mToolbar.setTitle("");
        mToolbar.setSubtitle("");
        if(toolbarTextBO.getTitle() != null && !toolbarTextBO.getTitle().isEmpty())
            mToolbar.setTitle(toolbarTextBO.getTitle());
        if(toolbarTextBO.getDescription() != null && !toolbarTextBO.getDescription().isEmpty())
            mToolbar.setSubtitle(toolbarTextBO.getDescription());*/

    }

    @Override
    public void onPostCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onPostCreate(savedInstanceState, persistentState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        toggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        toggle.onConfigurationChanged(newConfig);
    }
}

Richtextbox wpf binding

This VB.Net version works for my situation. I removed thread collection semaphore, instead using RemoveHandler and AddHandler. Also, since a FlowDocument can only be bound to one RichTextBox at a time, I put in a check that the RichTextBox's IsLoaded=True. Let's begin with how I used the class in a MVVM app which uses ResourceDictionary instead of Window.

    ' Loaded and Unloaded events seems to be the only way to initialize a control created from a Resource Dictionary
' Loading document here because Loaded is the last available event to create a document
Private Sub Rtb_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
    ' only good place to initialize RichTextBox.Document with DependencyProperty
    Dim rtb As RichTextBox = DirectCast(sender, RichTextBox)
    Try
        rtb.Document = RichTextBoxHelper.GetDocumentXaml(rtb)
    Catch ex As Exception
        Debug.WriteLine("Rtb_Loaded: Message:" & ex.Message)
    End Try
End Sub

' Loaded and Unloaded events seems to be the only way to initialize a control created from a Resource Dictionary
' Free document being held by RichTextBox.Document by assigning New FlowDocument to RichTextBox.Document. Otherwise we'll see an of "Document belongs to another RichTextBox"
Private Sub Rtb_Unloaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
    Dim rtb As RichTextBox = DirectCast(sender, RichTextBox)
    Dim fd As New FlowDocument
    RichTextBoxHelper.SetDocumentXaml(rtb, fd)
    Try
        rtb.Document = fd
    Catch ex As Exception
        Debug.WriteLine("PoemDocument.PoemDocumentView.PoemRtb_Unloaded: Message:" & ex.Message)
    End Try
End Sub

Public Class RichTextBoxHelper
    Inherits DependencyObject

    Public Shared Function GetDocumentXaml(ByVal depObj As DependencyObject) As FlowDocument
        Return depObj.GetValue(DocumentXamlProperty)
    End Function

    Public Shared Sub SetDocumentXaml(ByVal depObj As DependencyObject, ByVal value As FlowDocument)
        depObj.SetValue(DocumentXamlProperty, value)
    End Sub

    Public Shared ReadOnly DocumentXamlProperty As DependencyProperty = DependencyProperty.RegisterAttached("DocumentXaml", GetType(FlowDocument), GetType(RichTextBoxHelper), New FrameworkPropertyMetadata(Nothing, FrameworkPropertyMetadataOptions.AffectsRender Or FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, Sub(depObj, e)
                                                                                                                                                                                                                                                                                                                                   RegisterIt(depObj, e)
                                                                                                                                                                                                                                                                                                                               End Sub))


    Private Shared Sub RegisterIt(ByVal depObj As System.Windows.DependencyObject, ByVal e As System.Windows.DependencyPropertyChangedEventArgs)
        Dim rtb As RichTextBox = DirectCast(depObj, RichTextBox)
        If rtb.IsLoaded Then
            RemoveHandler rtb.TextChanged, AddressOf TextChanged
            Try
                rtb.Document = GetDocumentXaml(rtb)
            Catch ex As Exception
                Debug.WriteLine("RichTextBoxHelper.RegisterIt: ex:" & ex.Message)
                rtb.Document = New FlowDocument()
            End Try
            AddHandler rtb.TextChanged, AddressOf TextChanged
        Else
            Debug.WriteLine("RichTextBoxHelper: Unloaded control ignored:" & rtb.Name)
        End If
    End Sub

    ' When a RichTextBox Document changes, update the DependencyProperty so they're in sync.
    Private Shared Sub TextChanged(ByVal sender As Object, ByVal e As TextChangedEventArgs)
        Dim rtb As RichTextBox = TryCast(sender, RichTextBox)
        If rtb IsNot Nothing Then
            SetDocumentXaml(sender, rtb.Document)
        End If
    End Sub

End Class

Moving Average Pandas

The rolling mean returns a Series you only have to add it as a new column of your DataFrame (MA) as described below.

For information, the rolling_mean function has been deprecated in pandas newer versions. I have used the new method in my example, see below a quote from the pandas documentation.

Warning Prior to version 0.18.0, pd.rolling_*, pd.expanding_*, and pd.ewm* were module level functions and are now deprecated. These are replaced by using the Rolling, Expanding and EWM. objects and a corresponding method call.

df['MA'] = df.rolling(window=5).mean()

print(df)
#             Value    MA
# Date                   
# 1989-01-02   6.11   NaN
# 1989-01-03   6.08   NaN
# 1989-01-04   6.11   NaN
# 1989-01-05   6.15   NaN
# 1989-01-09   6.25  6.14
# 1989-01-10   6.24  6.17
# 1989-01-11   6.26  6.20
# 1989-01-12   6.23  6.23
# 1989-01-13   6.28  6.25
# 1989-01-16   6.31  6.27

Add and remove multiple classes in jQuery

easiest way to append class name using javascript. It can be useful when .siblings() are misbehaving.

document.getElementById('myId').className += ' active';

How to install an APK file on an Android phone?

If you dont have SDK or you are setting up 3rd party app here is another way:

  1. Copy the .APK file to your device.
  2. Use file manager to locate the file.
  3. Then click on it.
  4. Android App installer should be one of the options in pop-up.
  5. Select it and it installs.

Excel VBA For Each Worksheet Loop

You need to put the worksheet identifier in your range statements as shown below ...

 Option Explicit
 Dim ws As Worksheet, a As Range

Sub forEachWs()

For Each ws In ActiveWorkbook.Worksheets
Call resizingColumns
Next

End Sub

Sub resizingColumns()
ws.Range("A:A").ColumnWidth = 20.14
ws.Range("B:B").ColumnWidth = 9.71
ws.Range("C:C").ColumnWidth = 35.86
ws.Range("D:D").ColumnWidth = 30.57
ws.Range("E:E").ColumnWidth = 23.57
ws.Range("F:F").ColumnWidth = 21.43
ws.Range("G:G").ColumnWidth = 18.43
ws.Range("H:H").ColumnWidth = 23.86
ws.Range("i:I").ColumnWidth = 27.43
ws.Range("J:J").ColumnWidth = 36.71
ws.Range("K:K").ColumnWidth = 30.29
ws.Range("L:L").ColumnWidth = 31.14
ws.Range("M:M").ColumnWidth = 31
ws.Range("N:N").ColumnWidth = 41.14
ws.Range("O:O").ColumnWidth = 33.86
End Sub

Android: disabling highlight on listView click

Add this to your xml:

android:listSelector="@android:color/transparent"

And for the problem this may work (I'm not sure and I don't know if there are better solutions):

You could apply a ColorStateList to your TextView.

get user timezone

On server-side it will be not as accurate as with JavaScript. Meanwhile, sometimes it is required to solve such task. Just to share the possible solution in this case I write this answer.

If you need to determine user's time zone it could be done via Geo-IP services. Some of them providing timezone. For example, this one (http://smart-ip.net/geoip-api) could help:

<?php
$ip     = $_SERVER['REMOTE_ADDR']; // means we got user's IP address 
$json   = file_get_contents( 'http://smart-ip.net/geoip-json/' . $ip); // this one service we gonna use to obtain timezone by IP
// maybe it's good to add some checks (if/else you've got an answer and if json could be decoded, etc.)
$ipData = json_decode( $json, true);

if ($ipData['timezone']) {
    $tz = new DateTimeZone( $ipData['timezone']);
    $now = new DateTime( 'now', $tz); // DateTime object corellated to user's timezone
} else {
   // we can't determine a timezone - do something else...
}

Failed to load ApplicationContext (with annotation)

Your test requires a ServletContext: add @WebIntegrationTest

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
@WebIntegrationTest
public class UserServiceImplIT

...or look here for other options: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html

UPDATE In Spring Boot 1.4.x and above @WebIntegrationTest is no longer preferred. @SpringBootTest or @WebMvcTest

Difference between Apache CXF and Axis

One more thing is the activity of the community. Compare the mailing list traffic for axis and cxf (2013).

So if this is any indicator of usage then axis is by far less used than cxf.

Compare CXF and Axis statistics at ohloh. CXF has very high activity while Axis has low activity overall.

This is the chart for the number of commits over time for CXF (red) and Axis1 (green) Axis2 (blue). enter image description here

What does it mean to "program to an interface"?

To add to the existing posts, sometimes coding to interfaces helps on large projects when developers work on separate components simultaneously. All you need is to define interfaces upfront and write code to them while other developers write code to the interface you are implementing.

Chrome Fullscreen API

In Google's closure library project , there is a module which has do the job , below is the API and source code.

Closure library fullscreen.js API

Closure libray fullscreen.js Code

How can I add shadow to the widget in flutter?

class ShadowContainer extends StatelessWidget {
  ShadowContainer({
    Key key,
    this.margin = const EdgeInsets.fromLTRB(0, 10, 0, 8),
    this.padding = const EdgeInsets.symmetric(horizontal: 8),
    this.circular = 4,
    this.shadowColor = const Color.fromARGB(
        128, 158, 158, 158), //Colors.grey.withOpacity(0.5),
    this.backgroundColor = Colors.white,
    this.spreadRadius = 1,
    this.blurRadius = 3,
    this.offset = const Offset(0, 1),
    @required this.child,
  }) : super(key: key);

  final Widget child;
  final EdgeInsetsGeometry margin;
  final EdgeInsetsGeometry padding;
  final double circular;
  final Color shadowColor;
  final double spreadRadius;
  final double blurRadius;
  final Offset offset;
  final Color backgroundColor;

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: margin,
      padding: padding,
      decoration: BoxDecoration(
        color: backgroundColor,
        borderRadius: BorderRadius.circular(circular),
        boxShadow: [
          BoxShadow(
            color: shadowColor,
            spreadRadius: spreadRadius,
            blurRadius: blurRadius,
            offset: offset,
          ),
        ],
      ),
      child: child,
    );
  }
}

Bootstrap Dropdown menu is not working

I had a bootstrap + rails project, and dropdown worked fine. They stopped to works after an update...

This is the solution that fixed the problem, add the following to .js file:

$(document).ready(function() {
    $(".dropdown-toggle").dropdown();
});

How can I create an object and add attributes to it?

Coming to this late in the day but here is my pennyworth with an object that just happens to hold some useful paths in an app but you can adapt it for anything where you want a sorta dict of information that you can access with getattr and dot notation (which is what I think this question is really about):

import os

def x_path(path_name):
    return getattr(x_path, path_name)

x_path.root = '/home/x'
for name in ['repository', 'caches', 'projects']:
    setattr(x_path, name, os.path.join(x_path.root, name))

This is cool because now:

In [1]: x_path.projects
Out[1]: '/home/x/projects'

In [2]: x_path('caches')
Out[2]: '/home/x/caches'

So this uses the function object like the above answers but uses the function to get the values (you can still use (getattr, x_path, 'repository') rather than x_path('repository') if you prefer).

How to kill zombie process

Sometimes the parent ppid cannot be killed, hence kill the zombie pid

kill -9 $(ps -A -ostat,pid | awk '/[zZ]/{ print $2 }')

Delete from a table based on date

delete from YOUR_TABLE where your_date_column < '2009-01-01';

This will delete rows from YOUR_TABLE where the date in your_date_column is older than January 1st, 2009. i.e. a date with 2008-12-31 would be deleted.

How to create a sticky navigation bar that becomes fixed to the top after scrolling

Note (2015): Both question and the answer below apply to the old, deprecated version 2.x of Twitter Bootstrap.

This feature of making and element "sticky" is built into the Twitter's Bootstrap and it is called Affix. All you have to do is to add:

<div data-spy="affix" data-offset-top="121">
  ... your navbar ...
</div>

around your tag and do not forget to load the Bootstrap's JS files as described in the manual. Data attribute offset-top tells how many pixels the page is scrolled (from the top) to fix you menu component. Usually it is just the space to the top of the page.

Note: You will have to take care of the missing space when the menu will be fixed. Fixing means cutting it off out of your page layer and pasting in different layer that does not scroll. I am doing the following:

<div style="height: 77px;">
  <div data-spy="affix" data-offset-top="121">
    <div style="position: relative; height: 0; width: 100%;">
      <div style="position: absolute; top: 0; left: 0;">
        ... my menu ...
      </div>
    </div>
  </div>
</div>

where 77px is the height of my affixed component.

jquery datatables hide column

You can hide columns by this command:

fnSetColumnVis( 1, false );

Where first parameter is index of column and second parameter is visibility.

Via: http://www.datatables.net/api - function fnSetColumnVis

bodyParser is deprecated express 4

I found that while adding

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));

helps, sometimes it's a matter of your querying that determines how express handles it.

For instance, it could be that your parameters are passed in the URL rather than in the body

In such a case, you need to capture both the body and url parameters and use whichever is available (with preference for the body parameters in the case below)

app.route('/echo')
    .all((req,res)=>{
        let pars = (Object.keys(req.body).length > 0)?req.body:req.query;
        res.send(pars);
    });

Python Pandas replicate rows in dataframe

df = df_try
for i in range(4):
   df = df.append(df_try)

# Here, we have df_try times 5

df = df.append(df)

# Here, we have df_try times 10

Check if table exists in SQL Server

Also note that if for any reason you need to check for a temporary table you can do this:

if OBJECT_ID('tempdb..#test') is not null
 --- temp table exists

Retrieving the COM class factory for component failed

This did the trick for me: (solution from the msdn forum)

goto Controlpanel --> Administrative tools-->Component Services -->computers --> myComputer -->DCOM Config --> Microsoft Excel Application.

right click to get properties dialog. Goto Security tab and customize permissions accordingly.

In Launch and Application Permissions, select Customize, Edit. Add the user / group that calls the application.

Getting json body in aws Lambda via API gateway

I am using lambda with Zappa; I am sending data with POST in json format:

My code for basic_lambda_pure.py is:

import time
import requests
import json
def my_handler(event, context):
    print("Received event: " + json.dumps(event, indent=2))
    print("Log stream name:", context.log_stream_name)
    print("Log group name:",  context.log_group_name)
    print("Request ID:", context.aws_request_id)
    print("Mem. limits(MB):", context.memory_limit_in_mb)
    # Code will execute quickly, so we add a 1 second intentional delay so you can see that in time remaining value.
    print("Time remaining (MS):", context.get_remaining_time_in_millis())

    if event["httpMethod"] == "GET":
        hub_mode = event["queryStringParameters"]["hub.mode"]
        hub_challenge = event["queryStringParameters"]["hub.challenge"]
        hub_verify_token = event["queryStringParameters"]["hub.verify_token"]
        return {'statusCode': '200', 'body': hub_challenge, 'headers': 'Content-Type': 'application/json'}}

    if event["httpMethod"] == "post":
        token = "xxxx"
    params = {
        "access_token": token
    }
    headers = {
        "Content-Type": "application/json"
    }
        _data = {"recipient": {"id": 1459299024159359}}
        _data.update({"message": {"text": "text"}})
        data = json.dumps(_data)
        r = requests.post("https://graph.facebook.com/v2.9/me/messages",params=params, headers=headers, data=data, timeout=2)
        return {'statusCode': '200', 'body': "ok", 'headers': {'Content-Type': 'application/json'}}

I got the next json response:

{
"resource": "/",
"path": "/",
"httpMethod": "POST",
"headers": {
"Accept": "*/*",
"Accept-Encoding": "deflate, gzip",
"CloudFront-Forwarded-Proto": "https",
"CloudFront-Is-Desktop-Viewer": "true",
"CloudFront-Is-Mobile-Viewer": "false",
"CloudFront-Is-SmartTV-Viewer": "false",
"CloudFront-Is-Tablet-Viewer": "false",
"CloudFront-Viewer-Country": "US",
"Content-Type": "application/json",
"Host": "ox53v9d8ug.execute-api.us-east-1.amazonaws.com",
"Via": "1.1 f1836a6a7245cc3f6e190d259a0d9273.cloudfront.net (CloudFront)",
"X-Amz-Cf-Id": "LVcBZU-YqklHty7Ii3NRFOqVXJJEr7xXQdxAtFP46tMewFpJsQlD2Q==",
"X-Amzn-Trace-Id": "Root=1-59ec25c6-1018575e4483a16666d6f5c5",
"X-Forwarded-For": "69.171.225.87, 52.46.17.84",
"X-Forwarded-Port": "443",
"X-Forwarded-Proto": "https",
"X-Hub-Signature": "sha1=10504e2878e56ea6776dfbeae807de263772e9f2"
},
"queryStringParameters": null,
"pathParameters": null,
"stageVariables": null,
"requestContext": {
"path": "/dev",
"accountId": "001513791584",
"resourceId": "i6d2tyihx7",
"stage": "dev",
"requestId": "d58c5804-b6e5-11e7-8761-a9efcf8a8121",
"identity": {
"cognitoIdentityPoolId": null,
"accountId": null,
"cognitoIdentityId": null,
"caller": null,
"apiKey": "",
"sourceIp": "69.171.225.87",
"accessKey": null,
"cognitoAuthenticationType": null,
"cognitoAuthenticationProvider": null,
"userArn": null,
"userAgent": null,
"user": null
},
"resourcePath": "/",
"httpMethod": "POST",
"apiId": "ox53v9d8ug"
},
"body": "eyJvYmplY3QiOiJwYWdlIiwiZW50cnkiOlt7ImlkIjoiMTA3OTk2NDk2NTUxMDM1IiwidGltZSI6MTUwODY0ODM5MDE5NCwibWVzc2FnaW5nIjpbeyJzZW5kZXIiOnsiaWQiOiIxNDAzMDY4MDI5ODExODY1In0sInJlY2lwaWVudCI6eyJpZCI6IjEwNzk5NjQ5NjU1MTAzNSJ9LCJ0aW1lc3RhbXAiOjE1MDg2NDgzODk1NTUsIm1lc3NhZ2UiOnsibWlkIjoibWlkLiRjQUFBNHo5RmFDckJsYzdqVHMxZlFuT1daNXFaQyIsInNlcSI6MTY0MDAsInRleHQiOiJob2xhIn19XX1dfQ==",
"isBase64Encoded": true
}

my data was on body key, but is code64 encoded, How can I know this? I saw the key isBase64Encoded

I copy the value for body key and decode with This tool and "eureka", I get the values.

I hope this help you. :)

Is it ok to use `any?` to check if an array is not empty?

Prefixing the statement with an exclamation mark will let you know whether the array is not empty. So in your case -

a = [1,2,3]
!a.empty?
=> true

Call to undefined function curl_init().?

The CURL extension ext/curl is not installed or enabled in your PHP installation. Check the manual for information on how to install or enable CURL on your system.

Validation of file extension before uploading file

I like this example:

<asp:FileUpload ID="fpImages" runat="server" title="maximum file size 1 MB or less" onChange="return validateFileExtension(this)" />

<script language="javascript" type="text/javascript">
    function ValidateFileUpload(Source, args) {
        var fuData = document.getElementById('<%= fpImages.ClientID %>');
        var FileUploadPath = fuData.value;

        if (FileUploadPath == '') {
            // There is no file selected 
            args.IsValid = false;
        }
        else {
            var Extension = FileUploadPath.substring(FileUploadPath.lastIndexOf('.') + 1).toLowerCase();
            if (Extension == "gif" || Extension == "png" || Extension == "bmp" || Extension == "jpeg") {
                args.IsValid = true; // Valid file type
                FileUploadPath == '';
            }
            else {
                args.IsValid = false; // Not valid file type
            }
        }
    }
</script>

How do I check if a string contains another string in Swift?

You can just do what you have mentioned:

import Foundation
...
string.contains("Swift");

From the docs:

Swift’s String type is bridged seamlessly to Foundation’s NSString class. If you are working with the Foundation framework in Cocoa or Cocoa Touch, the entire NSString API is available to call on any String value you create, in addition to the String features described in this chapter. You can also use a String value with any API that requires an NSString instance.

You need to import Foundation to bridge the NSString methods and make them available to Swift's String class.

Getting query parameters from react-router hash fragment

You may get the following error while creating an optimized production build when using query-string module.

Failed to minify the code from this file: ./node_modules/query-string/index.js:8

To overcome this, kindly use the alternative module called stringquery which does the same process well without any issues while running the build.

import querySearch from "stringquery";

var query = querySearch(this.props.location.search);

Multiple Cursors in Sublime Text 2 Windows

It's usually just easier to skip the mouse altogether--or it would be if Sublime didn't mess up multiselect when word wrapping. Here's the official documentation on using the keyboard and mouse for multiple selection. Since it's a bit spread out, I'll summarize it:

Where shortcuts are different in Sublime Text 3, I've made a note. For v3, I always test using the latest dev build; if you're using the beta build, your experience may be different.

If you lose your selection when switching tabs or windows (particularly on Linux), try using Ctrl + U to restore it.

Mouse

Windows/Linux

Building blocks:

  • Positive/negative:
    • Add to selection: Ctrl
    • Subtract from selection: Alt In early builds of v3, this didn't work for linear selection.
  • Selection type:
    • Linear selection: Left Click
    • Block selection: Middle Click or Shift + Right Click On Linux, middle click pastes instead by default.

Combine as you see fit. For example:

  • Add to selection: Ctrl + Left Click (and optionally drag)
  • Subtract from selection: Alt + Left Click This didn't work in early builds of v3.
  • Add block selection: Ctrl + Shift + Right Click (and drag)
  • Subtract block selection: Alt + Shift + Right Click (and drag)

Mac OS X

Building blocks:

  • Positive/negative:
    • Add to selection: ?
    • Subtract from selection: ?? (only works with block selection in v3; presumably bug)
  • Selection type:
    • Linear selection: Left Click
    • Block selection: Middle Click or ? + Left Click

Combine as you see fit. For example:

  • Add to selection: ? + Left Click (and optionally drag)
  • Subtract from selection: ?? + Left Click (and drag--this combination doesn't work in Sublime Text 3, but supposedly it works in 2)
  • Add block selection: ?? + Left Click (and drag)
  • Subtract block selection: ??? + Left Click (and drag)

Keyboard

Windows

  • Return to single selection mode: Esc
  • Extend selection upward/downward at all carets: Ctrl + Alt + Up/Down
  • Extend selection leftward/rightward at all carets: Shift + Left/Right
  • Move all carets up/down/left/right, and clear selection: Up/Down/Left/Right
  • Undo the last selection motion: Ctrl + U
  • Add next occurrence of selected text to selection: Ctrl + D
  • Add all occurrences of the selected text to the selection: Alt + F3
  • Rotate between occurrences of selected text (single selection): Ctrl + F3 (reverse: Ctrl + Shift + F3)
  • Turn a single linear selection into a block selection, with a caret at the end of the selected text in each line: Ctrl + Shift + L

Linux

  • Return to single selection mode: Esc
  • Extend selection upward/downward at all carets: Alt + Up/Down Note that you may be able to hold Ctrl as well to get the same shortcuts as Windows, but Linux tends to use Ctrl + Alt combinations for global shortcuts.
  • Extend selection leftward/rightward at all carets: Shift + Left/Right
  • Move all carets up/down/left/right, and clear selection: Up/Down/Left/Right
  • Undo the last selection motion: Ctrl + U
  • Add next occurrence of selected text to selection: Ctrl + D
  • Add all occurrences of the selected text to the selection: Alt + F3
  • Rotate between occurrences of selected text (single selection): Ctrl + F3 (reverse: Ctrl + Shift + F3)
  • Turn a single linear selection into a block selection, with a caret at the end of the selected text in each line: Ctrl + Shift + L

Mac OS X

  • Return to single selection mode: ? (that's the Mac symbol for Escape)
  • Extend selection upward/downward at all carets: ^??, ^?? (See note)
  • Extend selection leftward/rightward at all carets: ??/??
  • Move all carets up/down/left/right and clear selection: ?, ?, ?, ?
  • Undo the last selection motion: ?U
  • Add next occurrence of selected text to selection: ?D
  • Add all occurrences of the selected text to the selection: ^?G
  • Rotate between occurrences of selected text (single selection): ??G (reverse: ???G)
  • Turn a single linear selection into a block selection, with a caret at the end of the selected text in each line: ??L

Notes for Mac users

On Yosemite and El Capitan, ^?? and ^?? are system keyboard shortcuts by default. If you want them to work in Sublime Text, you will need to change them:

  1. Open System Preferences.
  2. Select the Shortcuts tab.
  3. Select Mission Control in the left listbox.
  4. Change the keyboard shortcuts for Mission Control and Application windows (or disable them). I use ^?? and ^??. They defaults are ^? and ^?; adding ^ to those shortcuts triggers the same actions, but slows the animations.

In case you're not familiar with Mac's keyboard symbols:

  • ? is the escape key
  • ^ is the control key
  • ? is the option key
  • ? is the shift key
  • ? is the command key
  • ? et al are the arrow keys, as depicted

Determine the line of code that causes a segmentation fault?

You could also use a core dump and then examine it with gdb. To get useful information you also need to compile with the -g flag.

Whenever you get the message:

 Segmentation fault (core dumped)

a core file is written into your current directory. And you can examine it with the command

 gdb your_program core_file

The file contains the state of the memory when the program crashed. A core dump can be useful during the deployment of your software.

Make sure your system doesn't set the core dump file size to zero. You can set it to unlimited with:

ulimit -c unlimited

Careful though! that core dumps can become huge.

Replace all particular values in a data frame

Like this:

> df[df==""]<-NA
> df
     A    B
1 <NA>   12
2  xyz <NA>
3  jkl  100

What causes a Python segmentation fault?

Looks like you are out of stack memory. You may want to increase it as Davide stated. To do it in python code, you would need to run your "main()" using threading:

def main():
    pass # write your code here

sys.setrecursionlimit(2097152)    # adjust numbers
threading.stack_size(134217728)   # for your needs

main_thread = threading.Thread(target=main)
main_thread.start()
main_thread.join()

Source: c1729's post on codeforces. Runing it with PyPy is a bit trickier.

Android App Not Install. An existing package by the same name with a conflicting signature is already installed

Same package error:

  1. Create a new Package in your app with different name.
  2. Copy and paste all file in your old package to new Package.
  3. Save Code.
  4. Delete old Package And Clean and rebuild project.

How to use getJSON, sending data with post method?

I had code that was doing getJSON. I simply replaced it with post. To my surprise, it worked

   $.post("@Url.Action("Command")", { id: id, xml: xml })
      .done(function (response) {
           // stuff
        })
        .fail(function (jqxhr, textStatus, error) {
           // stuff
        });



    [HttpPost]
    public JsonResult Command(int id, string xml)
    {
          // stuff
    } 

How to use numpy.genfromtxt when first column is string and the remaining columns are numbers?

By default, np.genfromtxt uses dtype=float: that's why you string columns are converted to NaNs because, after all, they're Not A Number...

You can ask np.genfromtxt to try to guess the actual type of your columns by using dtype=None:

>>> from StringIO import StringIO
>>> test = "a,1,2\nb,3,4"
>>> a = np.genfromtxt(StringIO(test), delimiter=",", dtype=None)
>>> print a
array([('a',1,2),('b',3,4)], dtype=[('f0', '|S1'),('f1', '<i8'),('f2', '<i8')])

You can access the columns by using their name, like a['f0']...

Using dtype=None is a good trick if you don't know what your columns should be. If you already know what type they should have, you can give an explicit dtype. For example, in our test, we know that the first column is a string, the second an int, and we want the third to be a float. We would then use

>>> np.genfromtxt(StringIO(test), delimiter=",", dtype=("|S10", int, float))
array([('a', 1, 2.0), ('b', 3, 4.0)], 
      dtype=[('f0', '|S10'), ('f1', '<i8'), ('f2', '<f8')])

Using an explicit dtype is much more efficient than using dtype=None and is the recommended way.

In both cases (dtype=None or explicit, non-homogeneous dtype), you end up with a structured array.

[Note: With dtype=None, the input is parsed a second time and the type of each column is updated to match the larger type possible: first we try a bool, then an int, then a float, then a complex, then we keep a string if all else fails. The implementation is rather clunky, actually. There had been some attempts to make the type guessing more efficient (using regexp), but nothing that stuck so far]

Bitbucket fails to authenticate on git pull

First, edit your .git/config and remove your username from 'url'.

I had this:

url = https://[email protected]/pathto/myrepo.git

And after modification:

url = https://bitbucket.org/pathto/myrepo.git

Then try to pull (or push) and use your email and password credentials to login.

Hosting a Maven repository on github

You can use JitPack (free for public Git repositories) to expose your GitHub repository as a Maven artifact. Its very easy. Your users would need to add this to their pom.xml:

  1. Add repository:
<repository>
    <id>jitpack.io</id>
    <url>https://jitpack.io</url>
</repository>
  1. Add dependency:
<dependency>
    <groupId>com.github.User</groupId>
    <artifactId>Repo name</artifactId>
    <version>Release tag</version>
</dependency>

As answered elsewhere the idea is that JitPack will build your GitHub repo and will serve the jars. The requirement is that you have a build file and a GitHub release.

The nice thing is that you don't have to handle deployment and uploads. Since you didn't want to maintain your own artifact repository its a good match for your needs.

Why Visual Studio 2015 can't run exe file (ucrtbased.dll)?

I would like to suggest additional solution to fix this issue. So, I recommend to reinstall/install the latest Windows SDK. In my case it has helped me to fix the issue when using Qt with MSVC compiler to debug a program.

Convert tabs to spaces in Notepad++

Obsolete: This answer is correct only for an older version of Notepad++. Converting between tabs/spaces is now built into Notepad++ and the TextFX plugin is no longer available in the Plugin Manager dialog.

  • First set the "replace by spaces" setting in Preferences -> Language Menu/Tab Settings.
  • Next, open the document you wish to replace tabs with.
  • Highlight all the text (CTRL+A).
  • Then select TextFX -> TextFX Edit -> Leading spaces to tabs or tabs to spaces.

Note: Make sure TextFX Characters plugin is installed (Plugins -> Plugin manager -> Show plugin manager, Installed tab). Otherwise, there will be no TextFX menu.

JavaScript code for getting the selected value from a combo box

I use this

var e = document.getElementById('ticket_category_clone').value;

Notice that you don't need the '#' character in javascript.

    function check () {

    var str = document.getElementById('ticket_category_clone').value;

      if (str==="Hardware")
      {
        SPICEWORKS.utils.addStyle('#ticket_c_hardware_clone{display: none !important;}');
      }

    }

SPICEWORKS.app.helpdesk.ready(check);?

Tab space instead of multiple non-breaking spaces ("nbsp")?

If you needed only one tab, the following worked for me.

<style>
  .tab {
    position: absolute;
    left: 10em;
   }
</style>

with the HTML something like:

<p><b>asdf</b> <span class="tab">99967</span></p>
<p><b>hjkl</b> <span class="tab">88868</span></p> 

You can add more "tabs" by adding additional "tab" styles and changing the HTML such as:

<style>
  .tab {
    position: absolute;
    left: 10em;
   }
  .tab1 {
    position: absolute;
    left: 20em;
   }
</style>

with the HTML something like:

<p><b>asdf</b> <span class="tab">99967</span><span class="tab1">hear</span></p>
<p><b>hjkl</b> <span class="tab">88868</span><span class="tab1">here</span></p>

If isset $_POST

You can try this:

if (isset($_POST["mail"]) !== false) {
    echo "Yes, mail is set";    
}else{  
    echo "N0, mail is not set";
}

How to add local .jar file dependency to build.gradle file?

The accepted answer is good, however, I would have needed various library configurations within my multi-project Gradle build to use the same 3rd-party Java library.

Adding '$rootProject.projectDir' to the 'dir' path element within my 'allprojects' closure meant each sub-project referenced the same 'libs' directory, and not a version local to that sub-project:

//gradle.build snippet
allprojects {
    ...

    repositories {
        //All sub-projects will now refer to the same 'libs' directory
        flatDir {
            dirs "$rootProject.projectDir/libs"
        }
        mavenCentral()
    }

    ...
}

EDIT by Quizzie: changed "${rootProject.projectDir}" to "$rootProject.projectDir" (works in the newest Gradle version).

What is the meaning of the term "thread-safe"?

Don't confuse thread safety with determinism. Thread-safe code can also be non-deterministic. Given the difficulty of debugging problems with threaded code, this is probably the normal case. :-)

Thread safety simply ensures that when a thread is modifying or reading shared data, no other thread can access it in a way that changes the data. If your code depends on a certain order for execution for correctness, then you need other synchronization mechanisms beyond those required for thread safety to ensure this.

Pointer to a string in C?

The same notation is used for pointing at a single character or the first character of a null-terminated string:

char c = 'Z';
char a[] = "Hello world";

char *ptr1 = &c;
char *ptr2 = a;      // Points to the 'H' of "Hello world"
char *ptr3 = &a[0];  // Also points to the 'H' of "Hello world"
char *ptr4 = &a[6];  // Points to the 'w' of "world"
char *ptr5 = a + 6;  // Also points to the 'w' of "world"

The values in ptr2 and ptr3 are the same; so are the values in ptr4 and ptr5. If you're going to treat some data as a string, it is important to make sure it is null terminated, and that you know how much space there is for you to use. Many problems are caused by not understanding what space is available and not knowing whether the string was properly null terminated.

Note that all the pointers above can be dereferenced as if they were an array:

 *ptr1    == 'Z'
  ptr1[0] == 'Z'

 *ptr2    == 'H'
  ptr2[0] == 'H'
  ptr2[4] == 'o'

 *ptr4    == 'w'
  ptr4[0] == 'w'
  ptr4[4] == 'd'

  ptr5[0] ==   ptr3[6]
*(ptr5+0) == *(ptr3+6)

Late addition to question

What does char (*ptr)[N]; represent?

This is a more complex beastie altogether. It is a pointer to an array of N characters. The type is quite different; the way it is used is quite different; the size of the object pointed to is quite different.

char (*ptr)[12] = &a;

(*ptr)[0] == 'H'
(*ptr)[6] == 'w'

*(*ptr + 6) == 'w'

Note that ptr + 1 points to undefined territory, but points 'one array of 12 bytes' beyond the start of a. Given a slightly different scenario:

char b[3][12] = { "Hello world", "Farewell", "Au revoir" };

char (*pb)[12] = &b[0];

Now:

(*(pb+0))[0] == 'H'
(*(pb+1))[0] == 'F'
(*(pb+2))[5] == 'v'

You probably won't come across pointers to arrays except by accident for quite some time; I've used them a few times in the last 25 years, but so few that I can count the occasions on the fingers of one hand (and several of those have been answering questions on Stack Overflow). Beyond knowing that they exist, that they are the result of taking the address of an array, and that you probably didn't want it, you don't really need to know more about pointers to arrays.

How to use youtube-dl from a python program?

For simple code, may be i think

import os
os.system('youtube-dl [OPTIONS] URL [URL...]')

Above is just running command line inside python.

Other is mentioned in the documentation Using youtube-dl on python Here is the way

from __future__ import unicode_literals
import youtube_dl

ydl_opts = {}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
    ydl.download(['https://www.youtube.com/watch?v=BaW_jenozKc'])

Insert if not exists Oracle

If you do NOT want to merge in from an other table, but rather insert new data... I came up with this. Is there perhaps a better way to do this?

MERGE INTO TABLE1 a
    USING DUAL
    ON (a.C1_pk= 6)
WHEN NOT MATCHED THEN
    INSERT(C1_pk, C2,C3,C4)
    VALUES (6, 1,0,1);

JavaScript URL Decode function

Here is a complete function (taken from PHPJS):

function urldecode(str) {
   return decodeURIComponent((str+'').replace(/\+/g, '%20'));
}

Ignoring new fields on JSON objects using Jackson

If using a pojo class based on JSON response. If chances are there that json changes frequently declare at pojo class level:

@JsonIgnoreProperties(ignoreUnknown = true)

and at the objectMapper add this if you are converting:

objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);

So that code will not break.

Getting first value from map in C++

A map will not keep insertion order. Use *(myMap.begin()) to get the value of the first pair (the one with the smallest key when ordered).

You could also do myMap.begin()->first to get the key and myMap.begin()->second to get the value.

Error - SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM

In my case this error was raised because table date column is not null-able

As below:

Create Table #TempTable(
 ...
 ApprovalDate datatime not null.
 ...)

To avoid this error just make it null-able

 Create Table #TempTable(
 ...
 ApprovalDate datatime null.
 ...)

CSS horizontal centering of a fixed div?

Edit September 2016: Although it's nice to still get an occasional up-vote for this, because the world has moved on, I'd now go with the answer that uses transform (and which has a ton of upvotes). I wouldn't do it this way any more.

Another way not to have to calculate a margin or need a sub-container:

#menu {
    position: fixed;   /* Take it out of the flow of the document */
    left: 0;           /* Left edge at left for now */
    right: 0;          /* Right edge at right for now, so full width */ 
    top: 30px;         /* Move it down from top of window */
    width: 500px;      /* Give it the desired width */ 
    margin: auto;      /* Center it */
    max-width: 100%;   /* Make it fit window if under 500px */ 
    z-index: 10000;    /* Whatever needed to force to front (1 might do) */
}

How to add multiple files to Git at the same time

step1.

git init

step2.

a) for all files

git add -a

b) only specific folder

git add <folder1> <folder2> <etc.>

step3.

git commit -m "Your message about the commit"

step4.

enter image description here

git remote add origin https://github.com/yourUsername/yourRepository.git

step5.

git push -u origin master
git push origin master

if you are face this error than

 ! [rejected]        master -> master (fetch first)
error: failed to push some refs to 'https://github.com/harishkumawat2610/Qt5-with-C-plus-plus.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

Use this command

git push --force origin master

Get most recent file in a directory on Linux

I use:

ls -ABrt1 --group-directories-first | tail -n1

It gives me just the file name, excluding folders.

Using Laravel Homestead: 'no input file specified'

This is easy to fix, because you have changed the folder name to: exampleproject

So SSH to your vagrant:

ssh [email protected] -p 2222

Then change your nginx config:

sudo vi /etc/nginx/sites-enabled/homestead.app

Edit the correct URI to the root on line 3 to this with the new folder name:

root "/Users/MYUSERNAME/Code/exampleproject/public";

Restart Nginx

sudo service nginx reload

Reload the web browser, it should work now

Get ID of element that called a function

Pass a reference to the element into the function when it is called:

<area id="nose" onmouseover="zoom(this);" />

<script>
  function zoom(ele) {
    var id = ele.id;

    console.log('area element id = ' + id);
  }
</script>

Solve error javax.mail.AuthenticationFailedException

Most of AuthenticationFieldException Error occur when sign-in attempted prevented, login your gmail first and go to https://www.google.com/settings/security/lesssecureapps and check turn on. I solved this kind of problem like this way.

Selecting a row of pandas series/dataframe by integer index

you can loop through the data frame like this .

for ad in range(1,dataframe_c.size):
    print(dataframe_c.values[ad])

Setting the classpath in java using Eclipse IDE

Just had the same issue, for those having the same one it may be that you put the library on the modulepath rather than the classpath while adding it to your project

How do you configure HttpOnly cookies in tomcat / java webapps?

In Tomcat6, You can conditionally enable from your HTTP Listener Class:

public void contextInitialized(ServletContextEvent event) {                 
   if (Boolean.getBoolean("HTTP_ONLY_SESSION")) HttpOnlyConfig.enable(event);
}

Using this class

import java.lang.reflect.Field;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import org.apache.catalina.core.StandardContext;
public class HttpOnlyConfig
{
    public static void enable(ServletContextEvent event)
    {
        ServletContext servletContext = event.getServletContext();
        Field f;
        try
        { // WARNING TOMCAT6 SPECIFIC!!
            f = servletContext.getClass().getDeclaredField("context");
            f.setAccessible(true);
            org.apache.catalina.core.ApplicationContext ac = (org.apache.catalina.core.ApplicationContext) f.get(servletContext);
            f = ac.getClass().getDeclaredField("context");
            f.setAccessible(true);
            org.apache.catalina.core.StandardContext sc = (StandardContext) f.get(ac);
            sc.setUseHttpOnly(true);
        }
        catch (Exception e)
        {
            System.err.print("HttpOnlyConfig cant enable");
            e.printStackTrace();
        }
    }
}

How can you determine a point is between two other points on a line segment?

Check if the cross product of b-a and c-a is0: that means all the points are collinear. If they are, check if c's coordinates are between a's and b's. Use either the x or the y coordinates, as long as a and b are separate on that axis (or they're the same on both).

def is_on(a, b, c):
    "Return true iff point c intersects the line segment from a to b."
    # (or the degenerate case that all 3 points are coincident)
    return (collinear(a, b, c)
            and (within(a.x, c.x, b.x) if a.x != b.x else 
                 within(a.y, c.y, b.y)))

def collinear(a, b, c):
    "Return true iff a, b, and c all lie on the same line."
    return (b.x - a.x) * (c.y - a.y) == (c.x - a.x) * (b.y - a.y)

def within(p, q, r):
    "Return true iff q is between p and r (inclusive)."
    return p <= q <= r or r <= q <= p

This answer used to be a mess of three updates. The worthwhile info from them: Brian Hayes's chapter in Beautiful Code covers the design space for a collinearity-test function -- useful background. Vincent's answer helped to improve this one. And it was Hayes who suggested testing only one of the x or the y coordinates; originally the code had and in place of if a.x != b.x else.

Difference between break and continue in PHP?

break used to get out from the loop statement, but continue just stop script on specific condition and then continue looping statement until reach the end..

for($i=0; $i<10; $i++){
    if($i == 5){
        echo "It reach five<br>";
        continue;
    }
    echo $i . "<br>";
}

echo "<hr>";

for($i=0; $i<10; $i++){
    if($i == 5){
         echo "It reach end<br>";
         break;
    }
    echo $i . "<br>";
}

Hope it can help u;

No assembly found containing an OwinStartupAttribute Error

just paste this code <add key="owin:AutomaticAppStartup" value="false" /> in Web.config Not In web.config there is two webconfig so be sure that it will been paste in Web.Config

How to convert char to int?

int val = '1' - 48;

IP to Location using Javascript

A free open source community run geolocation ip service that runs on the MaxMind database is available here: https://ipstack.com/

Example

https://api.ipstack.com/160.39.144.19

Limitation

10,000 queries per month

Unmarshaling nested JSON objects

Is there a way to unmarshal the nested bar property and assign it directly to a struct property without creating a nested struct?

No, encoding/json cannot do the trick with ">some>deep>childnode" like encoding/xml can do. Nested structs is the way to go.

What's the difference between returning value or Promise.resolve from then()

The only difference is that you're creating an unnecessary promise when you do return Promise.resolve("bbb"). Returning a promise from an onFulfilled() handler kicks off promise resolution. That's how promise chaining works.

How to write a link like <a href="#id"> which link to the same page in PHP?

try this

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html>
    <body>
        <a href="#name">click me</a>
<br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br>
        <div name="name" id="name">here</div>
    </body>
    </html>

No suitable driver found for 'jdbc:mysql://localhost:3306/mysql

In this particular case (assuming that the Class#forName() didn't throw an exception; your code is namely continuing with running instead of throwing the exception), this SQLException means that Driver#acceptsURL() has returned false for any of the loaded drivers.

And indeed, your JDBC URL is wrong:

String url = "'jdbc:mysql://localhost:3306/mysql";

Remove the singlequote:

String url = "jdbc:mysql://localhost:3306/mysql";

See also:

java.io.FileNotFoundException: (Access is denied)

Here's a gotcha that I just discovered - perhaps it might help someone else. If using windows the classes folder must not have encryption enabled! Tomcat doesn't seem to like that. Right click on the classes folder, select "Properties" and then click the "Advanced..." button. Make sure the "Encrypt contents to secure data" checkbox is cleared. Restart Tomcat.

It worked for me so here's hoping it helps someone else, too.

python pandas: Remove duplicates by columns A, keeping the row with the highest value in column B

I think in your case you don't really need a groupby. I would sort by descending order your B column, then drop duplicates at column A and if you want you can also have a new nice and clean index like that:

df.sort_values('B', ascending=False).drop_duplicates('A').sort_index().reset_index(drop=True)

Cannot resolve symbol AppCompatActivity - Support v7 libraries aren't recognized?

1.Delete the .idea folder
2.Close and reopen the project
3.File - > Sync Project With Gradle Files

This worked for me

Using LIMIT within GROUP BY to get N results per group?

This requires a series of subqueries to rank the values, limit them, then perform the sum while grouping

@Rnk:=0;
@N:=2;
select
  c.id,
  sum(c.val)
from (
select
  b.id,
  b.bal
from (
select   
  if(@last_id=id,@Rnk+1,1) as Rnk,
  a.id,
  a.val,
  @last_id=id,
from (   
select 
  id,
  val 
from list
order by id,val desc) as a) as b
where b.rnk < @N) as c
group by c.id;

What is Express.js?

Express.js is a framework used for Node and it is most commonly used as a web application for node js.

Here is a link to a video on how to quickly set up a node app with express https://www.youtube.com/watch?v=QEcuSSnqvck

"commence before first target. Stop." error

if you have added a new line, Make sure you have added next line syntax in previous line. typically if "\" is missing in your previous line of changes, you will get this error.

How to create a drop shadow only on one side of an element?

If your background is solid (or you can reproduce it using CSS), you can use linear gradient that way:

_x000D_
_x000D_
div {_x000D_
  background-image: linear-gradient(to top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.3) 5px, #fff 5px, #fff 100%)_x000D_
}
_x000D_
<div>_x000D_
<p>Foobar</p>_x000D_
<p>test</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

This will generate a 5px gradient at the bottom of the element, from black at 30% opacity to completely transparent. The rest of the element has white background. Of course, changing the last 2 color stops of the linear gradient, you could make the background completely transparent.

C++: Converting Hexadecimal to Decimal

Well, the C way might be something like ...

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

int main()
{
        int n;
        scanf("%d", &n);
        printf("%X", n);

        exit(0);
}

YouTube API to fetch all videos on a channel

First, you need to get the ID of the playlist that represents the uploads from the user/channel:

https://developers.google.com/youtube/v3/docs/channels/list#try-it

You can specify the username with the forUsername={username} param, or specify mine=true to get your own (you need to authenticate first). Include part=contentDetails to see the playlists.

GET https://www.googleapis.com/youtube/v3/channels?part=contentDetails&forUsername=jambrose42&key={YOUR_API_KEY}

In the result "relatedPlaylists" will include "likes" and "uploads" playlists. Grab that "upload" playlist ID. Also note the "id" is your channelID for future reference.

Next, get a list of videos in that playlist:

https://developers.google.com/youtube/v3/docs/playlistItems/list#try-it

Just drop in the playlistId!

GET https://www.googleapis.com/youtube/v3/playlistItems?part=snippet%2CcontentDetails&maxResults=50&playlistId=UUpRmvjdu3ixew5ahydZ67uA&key={YOUR_API_KEY}

How to install Android SDK on Ubuntu?

sudo add-apt-repository -y ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java7-installer oracle-java7-set-default
wget https://dl.google.com/dl/android/studio/ide-zips/2.2.0.12/android-studio-ide-145.3276617-linux.zip
unzip android-studio-ide-145.3276617-linux.zip
cd android-studio/bin
./studio.sh

How to execute AngularJS controller function on page load?

You can use angular's $window object:

$window.onload = function(e) {
  //your magic here
}

bootstrap multiselect get selected values

Shorter version:

$('#multiselect1').multiselect({
    ...
    onChange: function() {
        console.log($('#multiselect1').val());
    }
}); 

count of entries in data frame in R

A one-line solution with data.table could be

library(data.table)
setDT(x)[,.N,by=Believe]
   Believe N
1:   FALSE 1
2:    TRUE 3

XAMPP installation on Win 8.1 with UAC Warning

To disable UAC (as an administrator), from Control Panel:

Type UAC in the search button in your windows the upper right corner. Click the (Change User Account Control settings) in the search results. Drag the slider down and select Never notify and click OK.it will work.

Sending HTTP POST Request In Java

The first answer was great, but I had to add try/catch to avoid Java compiler errors.
Also, I had troubles to figure how to read the HttpResponse with Java libraries.

Here is the more complete code :

/*
 * Create the POST request
 */
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://example.com/");
// Request parameters and other properties.
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user", "Bob"));
try {
    httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
} catch (UnsupportedEncodingException e) {
    // writing error to Log
    e.printStackTrace();
}
/*
 * Execute the HTTP Request
 */
try {
    HttpResponse response = httpClient.execute(httpPost);
    HttpEntity respEntity = response.getEntity();

    if (respEntity != null) {
        // EntityUtils to get the response content
        String content =  EntityUtils.toString(respEntity);
    }
} catch (ClientProtocolException e) {
    // writing exception to log
    e.printStackTrace();
} catch (IOException e) {
    // writing exception to log
    e.printStackTrace();
}

Dilemma: when to use Fragments vs Activities:

Why I prefer Fragment over Activity in ALL CASES.

  • Activity is expensive. In Fragment, views and property states are separated - whenever a fragment is in backstack, its views will be destroyed. So you can stack much more Fragments than Activity.

  • Backstack manipulation. With FragmentManager, it's easy to clear all the Fragments, insert more than on Fragments and etcs. But for Activity, it will be a nightmare to manipulate those stuff.

  • A much predictable lifecycle. As long as the host Activity is not recycled. the Fragments in the backstack will not be recycled. So it's possible to use FragmentManager::getFragments() to find specific Fragment (not encouraged).

No serializer found for class org.hibernate.proxy.pojo.javassist.Javassist?

I've the same problem right now. check if you fix fetch in lazy with a @jsonIQgnore

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="teachers")
@JsonIgnoreProperties("course")
Teacher teach;

Just delete the "(fetch=...)" or the annotation "@jsonIgnore" and it will work

@ManyToOne
@JoinColumn(name="teachers")
@JsonIgnoreProperties("course")
Teacher teach;

Adding an image to a project in Visual Studio

  • You just need to have an existing file, open the context menu on your folder , and then choose Add => Existing item...

    enter image description here

  • If you have the file already placed within your project structure, but it is not yet included, you can do so by making them visible in the solution explorer

    enter image description here

and then include them via the file context menu enter image description here

append new row to old csv file python

If the file exists and contains data, then it is possible to generate the fieldname parameter for csv.DictWriter automatically:

# read header automatically
with open(myFile, "r") as f:
    reader = csv.reader(f)
    for header in reader:
        break

# add row to CSV file
with open(myFile, "a", newline='') as f:
    writer = csv.DictWriter(f, fieldnames=header)
    writer.writerow(myDict)

Creating an instance using the class name and calling constructor

If anyone is looking for a way to create an instance of a class despite the class following the Singleton Pattern, here is a way to do it.

// Get Class instance
Class<?> clazz = Class.forName("myPackage.MyClass");

// Get the private constructor.
Constructor<?> cons = clazz.getDeclaredConstructor();

// Since it is private, make it accessible.
cons.setAccessible(true);

// Create new object. 
Object obj = cons.newInstance();

This only works for classes that implement singleton pattern using a private constructor.

Using Node.js require vs. ES6 import/export

Are there any performance benefits to using one over the other?

The current answer is no, because none of the current browser engines implements import/export from the ES6 standard.

Some comparison charts http://kangax.github.io/compat-table/es6/ don't take this into account, so when you see almost all greens for Chrome, just be careful. import keyword from ES6 hasn't been taken into account.

In other words, current browser engines including V8 cannot import new JavaScript file from the main JavaScript file via any JavaScript directive.

( We may be still just a few bugs away or years away until V8 implements that according to the ES6 specification. )

This document is what we need, and this document is what we must obey.

And the ES6 standard said that the module dependencies should be there before we read the module like in the programming language C, where we had (headers) .h files.

This is a good and well-tested structure, and I am sure the experts that created the ES6 standard had that in mind.

This is what enables Webpack or other package bundlers to optimize the bundle in some special cases, and reduce some dependencies from the bundle that are not needed. But in cases we have perfect dependencies this will never happen.

It will need some time until import/export native support goes live, and the require keyword will not go anywhere for a long time.

What is require?

This is node.js way to load modules. ( https://github.com/nodejs/node )

Node uses system-level methods to read files. You basically rely on that when using require. require will end in some system call like uv_fs_open (depends on the end system, Linux, Mac, Windows) to load JavaScript file/module.

To check that this is true, try to use Babel.js, and you will see that the import keyword will be converted into require.

enter image description here

Angular File Upload

Complete example of File upload using Angular and nodejs(express)

HTML Code

            <div class="form-group">
                <label for="file">Choose File</label><br/>
                <input type="file" id="file" (change)="uploadFile($event.target.files)" multiple>
            </div>

TS Component Code

uploadFile(files) {
    console.log('files', files)
        var formData = new FormData();

    for(let i =0; i < files.length; i++){
      formData.append("files", files[i], files[i]['name']);
        }

    this.httpService.httpPost('/fileUpload', formData)
      .subscribe((response) => {
        console.log('response', response)
      },
        (error) => {
      console.log('error in fileupload', error)
       })
  }

Node Js code

fileUpload API controller

function start(req, res) {
fileUploadService.fileUpload(req, res)
    .then(fileUploadServiceResponse => {
        res.status(200).send(fileUploadServiceResponse)
    })
    .catch(error => {
        res.status(400).send(error)
    })
}

module.exports.start = start

Upload service using multer

const multer = require('multer') // import library
const moment = require('moment')
const q = require('q')
const _ = require('underscore')
const fs = require('fs')
const dir = './public'

/** Store file on local folder */
let storage = multer.diskStorage({
destination: function (req, file, cb) {
    cb(null, 'public')
},
filename: function (req, file, cb) {
    let date = moment(moment.now()).format('YYYYMMDDHHMMSS')
    cb(null, date + '_' + file.originalname.replace(/-/g, '_').replace(/ /g,     '_'))
}
})

/** Upload files  */
let upload = multer({ storage: storage }).array('files')

/** Exports fileUpload function */
module.exports = {
fileUpload: function (req, res) {
    let deferred = q.defer()

    /** Create dir if not exist */
    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir)
        console.log(`\n\n ${dir} dose not exist, hence created \n\n`)
    }

    upload(req, res, function (err) {
        if (req && (_.isEmpty(req.files))) {
            deferred.resolve({ status: 200, message: 'File not attached', data: [] })
        } else {
            if (err) {
                deferred.reject({ status: 400, message: 'error', data: err })
            } else {
                deferred.resolve({
                    status: 200,
                    message: 'File attached',
                    filename: _.pluck(req.files,
                        'filename'),
                    data: req.files
                })
            }
        }
    })
    return deferred.promise
}
}