Programs & Examples On #Greatest n per group

Query the row with the greatest/least value per group.

Get most recent row for given ID

I had a similar problem. I needed to get the last version of page content translation, in other words - to get that specific record which has highest number in version column. So I select all records ordered by version and then take the first row from result (by using LIMIT clause).

SELECT *
FROM `page_contents_translations`
ORDER BY version DESC
LIMIT 1

Fetch the row which has the Max value for a column

Just had to write a "live" example at work :)

This one supports multiple values for UserId on the same date.

Columns: UserId, Value, Date

SELECT
   DISTINCT UserId,
   MAX(Date) OVER (PARTITION BY UserId ORDER BY Date DESC),
   MAX(Values) OVER (PARTITION BY UserId ORDER BY Date DESC)
FROM
(
   SELECT UserId, Date, SUM(Value) As Values
   FROM <<table_name>>
   GROUP BY UserId, Date
)

You can use FIRST_VALUE instead of MAX and look it up in the explain plan. I didn't have the time to play with it.

Of course, if searching through huge tables, it's probably better if you use FULL hints in your query.

Select info from table where row has max date

SELECT group, date, checks
  FROM table 
  WHERE checks > 0
  GROUP BY group HAVING date = max(date) 

should work.

Get top 1 row of each group

SELECT * FROM
DocumentStatusLogs JOIN (
  SELECT DocumentID, MAX(DateCreated) DateCreated
  FROM DocumentStatusLogs
  GROUP BY DocumentID
  ) max_date USING (DocumentID, DateCreated)

What database server? This code doesn't work on all of them.

Regarding the second half of your question, it seems reasonable to me to include the status as a column. You can leave DocumentStatusLogs as a log, but still store the latest info in the main table.

BTW, if you already have the DateCreated column in the Documents table you can just join DocumentStatusLogs using that (as long as DateCreated is unique in DocumentStatusLogs).

Edit: MsSQL does not support USING, so change it to:

ON DocumentStatusLogs.DocumentID = max_date.DocumentID AND DocumentStatusLogs.DateCreated = max_date.DateCreated

Select row with most recent date per user

I have done same thing like below

SELECT t1.* FROM lms_attendance t1 WHERE t1.id in (SELECT max(t2.id) as id FROM lms_attendance t2 group BY t2.user)

This will also reduce memory utilization.

Thanks.

SQL query to select distinct row with minimum value

Try:

select id, game, min(point) from t
group by id 

GROUP BY having MAX date

Fast and easy with HAVING:

SELECT * FROM tblpm n 
FROM tblpm GROUP BY control_number 
HAVING date_updated=MAX(date_updated);

In the context of HAVING, MAX finds the max of each group. Only the latest entry in each group will satisfy date_updated=max(date_updated). If there's a tie for latest within a group, both will pass the HAVING filter, but GROUP BY means that only one will appear in the returned table.

GROUP BY with MAX(DATE)

SELECT train, dest, time FROM ( 
  SELECT train, dest, time, 
    RANK() OVER (PARTITION BY train ORDER BY time DESC) dest_rank
    FROM traintable
  ) where dest_rank = 1

how to sort order of LEFT JOIN in SQL query?

Try using MAX with a GROUP BY.

SELECT u.userName, MAX(c.carPrice)
FROM users u
    LEFT JOIN cars c ON u.id = c.belongsToUser
WHERE u.id = 4;
GROUP BY u.userName;

Further information on GROUP BY

The group by clause is used to split the selected records into groups based on unique combinations of the group by columns. This then allows us to use aggregate functions (eg. MAX, MIN, SUM, AVG, ...) that will be applied to each group of records in turn. The database will return a single result record for each grouping.

For example, if we have a set of records representing temperatures over time and location in a table like this:

Location   Time    Temperature
--------   ----    -----------
London     12:00          10.0
Bristol    12:00          12.0
Glasgow    12:00           5.0
London     13:00          14.0
Bristol    13:00          13.0
Glasgow    13:00           7.0
...

Then if we want to find the maximum temperature by location, then we need to split the temperature records into groupings, where each record in a particular group has the same location. We then want to find the maximum temperature of each group. The query to do this would be as follows:

SELECT Location, MAX(Temperature)
FROM Temperatures
GROUP BY Location;

How to select data where a field has a min value in MySQL?

Use HAVING MIN(...)

Something like:

SELECT MIN(price) AS price, pricegroup
FROM articles_prices
WHERE articleID=10
GROUP BY pricegroup
HAVING MIN(price) > 0;

SQL select only rows with max value on a column

If you have many fields in select statement and you want latest value for all of those fields through optimized code:

select * from
(select * from table_name
order by id,rev desc) temp
group by id 

How to get the latest record in each group using GROUP BY?

You need to order them.

SELECT * FROM messages GROUP BY from_id ORDER BY timestamp DESC LIMIT 1

Get the latest date from grouped MySQL data

And why not to use this ?

SELECT model, date FROM doc ORDER BY date DESC LIMIT 1

How to select the rows with maximum values in each group with dplyr?

You can use top_n

df %>% group_by(A, B) %>% top_n(n=1)

This will rank by the last column (value) and return the top n=1 rows.

Currently, you can't change the this default without causing an error (See https://github.com/hadley/dplyr/issues/426)

Retrieving the last record in each group - MySQL

You can group by counting and also get the last item of group like:

SELECT 
    user,
    COUNT(user) AS count,
    MAX(id) as last
FROM request 
GROUP BY user

Select first row in each GROUP BY group?

This way it work for me:

SELECT article, dealer, price
FROM   shop s1
WHERE  price=(SELECT MAX(s2.price)
              FROM shop s2
              WHERE s1.article = s2.article
              GROUP BY s2.article)
ORDER BY article;

Select highest price on each article

Mysql select distinct

Are you looking for "SELECT * FROM temp_tickets GROUP BY ticket_id ORDER BY ticket_id ?

UPDATE

SELECT t.* 
FROM 
(SELECT ticket_id, MAX(id) as id FROM temp_tickets GROUP BY ticket_id) a  
INNER JOIN temp_tickets t ON (t.id = a.id)

Select top 10 records for each category

I do it this way:

SELECT a.* FROM articles AS a
  LEFT JOIN articles AS a2 
    ON a.section = a2.section AND a.article_date <= a2.article_date
GROUP BY a.article_id
HAVING COUNT(*) <= 10;

update: This example of GROUP BY works in MySQL and SQLite only, because those databases are more permissive than standard SQL regarding GROUP BY. Most SQL implementations require that all columns in the select-list that aren't part of an aggregate expression are also in the GROUP BY.

Get top n records for each group of grouped results

I wanted to share this because I spent a long time searching for an easy way to implement this in a java program I'm working on. This doesn't quite give the output you're looking for but its close. The function in mysql called GROUP_CONCAT() worked really well for specifying how many results to return in each group. Using LIMIT or any of the other fancy ways of trying to do this with COUNT didn't work for me. So if you're willing to accept a modified output, its a great solution. Lets say I have a table called 'student' with student ids, their gender, and gpa. Lets say I want to top 5 gpas for each gender. Then I can write the query like this

SELECT sex, SUBSTRING_INDEX(GROUP_CONCAT(cast(gpa AS char ) ORDER BY gpa desc), ',',5) 
AS subcategories FROM student GROUP BY sex;

Note that the parameter '5' tells it how many entries to concatenate into each row

And the output would look something like

+--------+----------------+
| Male   | 4,4,4,4,3.9    |
| Female | 4,4,3.9,3.9,3.8|
+--------+----------------+

You can also change the ORDER BY variable and order them a different way. So if I had the student's age I could replace the 'gpa desc' with 'age desc' and it will work! You can also add variables to the group by statement to get more columns in the output. So this is just a way I found that is pretty flexible and works good if you are ok with just listing results.

Using LIMIT within GROUP BY to get N results per group?

Took some working, but I thougth my solution would be something to share as it is seems elegant as well as quite fast.

SELECT h.year, h.id, h.rate 
  FROM (
    SELECT id, 
      SUBSTRING_INDEX(GROUP_CONCAT(CONCAT(id, '-', year) ORDER BY rate DESC), ',' , 5) AS l
      FROM h
      WHERE year BETWEEN 2000 AND 2009
      GROUP BY id
      ORDER BY id
  ) AS h_temp
    LEFT JOIN h ON h.id = h_temp.id 
      AND SUBSTRING_INDEX(h_temp.l, CONCAT(h.id, '-', h.year), 1) != h_temp.l

Note that this example is specified for the purpose of the question and can be modified quite easily for other similar purposes.

MAX function in where clause mysql

You are using word 'max' as an alias for your column. Try to:

MAX(id) as mymax ... WHERE ID - mymax

Aggregate a dataframe on a given column and display another column

I don't have a high enough reputation to comment on Gavin Simpson's answer, but I wanted to warn that there seems to be a difference in the default treatment of missing values between the standard syntax and the formula syntax for aggregate.

#Create some data with missing values 
a<-data.frame(day=rep(1,5),hour=c(1,2,3,3,4),val=c(1,NA,3,NA,5))
  day hour val
1   1    1   1
2   1    2  NA
3   1    3   3
4   1    3  NA
5   1    4   5

#Standard syntax
aggregate(a$val,by=list(day=a$day,hour=a$hour),mean,na.rm=T)
  day hour   x
1   1    1   1
2   1    2 NaN
3   1    3   3
4   1    4   5

#Formula syntax.  Note the index for hour 2 has been silently dropped.
aggregate(val ~ hour + day,data=a,mean,na.rm=T)
  hour day val
1    1   1   1
2    3   1   3
3    4   1   5

How to select id with max date group by category in PostgreSQL?

Try this one:

SELECT t1.* FROM Table1 t1
JOIN 
(
   SELECT category, MAX(date) AS MAXDATE
   FROM Table1
   GROUP BY category
) t2
ON T1.category = t2.category
AND t1.date = t2.MAXDATE

See this SQLFiddle

SQL Left Join first match only

Try this

 SELECT *
 FROM people P 
 where P.IDNo in (SELECT DISTINCT IDNo
              FROM people)

how do I query sql for a latest record date for each user

select t.username, t.date, t.value
from MyTable t
inner join (
    select username, max(date) as MaxDate
    from MyTable
    group by username
) tm on t.username = tm.username and t.date = tm.MaxDate

Pandas get topmost n records within each group

Did you try df.groupby('id').head(2)

Ouput generated:

>>> df.groupby('id').head(2)
       id  value
id             
1  0   1      1
   1   1      2 
2  3   2      1
   4   2      2
3  7   3      1
4  8   4      1

(Keep in mind that you might need to order/sort before, depending on your data)

EDIT: As mentioned by the questioner, use df.groupby('id').head(2).reset_index(drop=True) to remove the multindex and flatten the results.

>>> df.groupby('id').head(2).reset_index(drop=True)
    id  value
0   1      1
1   1      2
2   2      1
3   2      2
4   3      1
5   4      1

How can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL?

This will work even if you have two or more rows for each home with equal DATETIME's:

SELECT id, home, datetime, player, resource
FROM   (
       SELECT (
              SELECT  id
              FROM    topten ti
              WHERE   ti.home = t1.home
              ORDER BY
                      ti.datetime DESC
              LIMIT 1
              ) lid
       FROM   (
              SELECT  DISTINCT home
              FROM    topten
              ) t1
       ) ro, topten t2
WHERE  t2.id = ro.lid

SQL join: selecting the last records in a one-to-many relationship

Tested on SQLite:

SELECT c.*, p.*, max(p.date)
FROM customer c
LEFT OUTER JOIN purchase p
ON c.id = p.customer_id
GROUP BY c.id

The max() aggregate function will make sure that the latest purchase is selected from each group (but assumes that the date column is in a format whereby max() gives the latest - which is normally the case). If you want to handle purchases with the same date then you can use max(p.date, p.id).

In terms of indexes, I would use an index on purchase with (customer_id, date, [any other purchase columns you want to return in your select]).

The LEFT OUTER JOIN (as opposed to INNER JOIN) will make sure that customers that have never made a purchase are also included.

FORCE INDEX in MySQL - where do I put it?

The syntax for index hints is documented here:
http://dev.mysql.com/doc/refman/5.6/en/index-hints.html

FORCE INDEX goes right after the table reference:

SELECT * FROM (
    SELECT owner_id,
           product_id,
           start_time,
           price,
           currency,
           name,
           closed,
           active,
           approved,
           deleted,
           creation_in_progress
    FROM db_products FORCE INDEX (products_start_time)
    ORDER BY start_time DESC
) as resultstable
WHERE resultstable.closed = 0
      AND resultstable.active = 1
      AND resultstable.approved = 1
      AND resultstable.deleted = 0
      AND resultstable.creation_in_progress = 0
GROUP BY resultstable.owner_id
ORDER BY start_time DESC

WARNING:

If you're using ORDER BY before GROUP BY to get the latest entry per owner_id, you're using a nonstandard and undocumented behavior of MySQL to do that.

There's no guarantee that it'll continue to work in future versions of MySQL, and the query is likely to be an error in any other RDBMS.

Search the tag for many explanations of better solutions for this type of query.

How can I select rows with most recent timestamp for each key value?

You can join the table with itself (on sensor id), and add left.timestamp < right.timestamp as join condition. Then you pick the rows, where right.id is null. Voila, you got the latest entry per sensor.

http://sqlfiddle.com/#!9/45147/37

SELECT L.* FROM sensorTable L
LEFT JOIN sensorTable R ON
L.sensorID = R.sensorID AND
L.timestamp < R.timestamp
WHERE isnull (R.sensorID)

But please note, that this will be very resource intensive if you have a little amount of ids and many values! So, I wouldn't recommend this for some sort of Measuring-Stuff, where each Sensor collects a value every minute. However in a Use-Case, where you need to track "Revisions" of something that changes just "sometimes", it's easy going.

Select a Column in SQL not in Group By

The columns in the result set of a select query with group by clause must be:

  • an expression used as one of the group by criteria , or ...
  • an aggregate function , or ...
  • a literal value

So, you can't do what you want to do in a single, simple query. The first thing to do is state your problem statement in a clear way, something like:

I want to find the individual claim row bearing the most recent creation date within each group in my claims table

Given

create table dbo.some_claims_table
(
  claim_id     int      not null ,
  group_id     int      not null ,
  date_created datetime not null ,

  constraint some_table_PK primary key ( claim_id                ) ,
  constraint some_table_AK01 unique    ( group_id , claim_id     ) ,
  constraint some_Table_AK02 unique    ( group_id , date_created ) ,

)

The first thing to do is identify the most recent creation date for each group:

select group_id ,
       date_created = max( date_created )
from dbo.claims_table
group by group_id

That gives you the selection criteria you need (1 row per group, with 2 columns: group_id and the highwater created date) to fullfill the 1st part of the requirement (selecting the individual row from each group. That needs to be a virtual table in your final select query:

select *
from dbo.claims_table t
join ( select group_id ,
       date_created = max( date_created )
       from dbo.claims_table
       group by group_id
      ) x on x.group_id     = t.group_id
         and x.date_created = t.date_created

If the table is not unique by date_created within group_id (AK02), you you can get duplicate rows for a given group.

How do I do top 1 in Oracle?

I had the same issue, and I can fix this with this solution:

select a.*, rownum 
from (select Fname from MyTbl order by Fname DESC) a
where
rownum = 1

You can order your result before to have the first value on top.

Good luck

Get records with max value for each group of grouped SQL results

You can join against a subquery that pulls the MAX(Group) and Age. This method is portable across most RDBMS.

SELECT t1.*
FROM yourTable t1
INNER JOIN
(
    SELECT `Group`, MAX(Age) AS max_age
    FROM yourTable
    GROUP BY `Group`
) t2
    ON t1.`Group` = t2.`Group` AND t1.Age = t2.max_age;

ROW_NUMBER() in MySQL

This is not the most robust solution - but if you're just looking to create a partitioned rank on a field with only a few different values, it may not be unwieldily to use some case when logic with as many variables as you require.

Something like this has worked for me in the past:

SELECT t.*, 
   CASE WHEN <partition_field> = @rownum1 := @rownum1 + 1 
     WHEN <partition_field> = @rownum2 := @rownum2 + 1 
     ...
     END AS rank
FROM YOUR_TABLE t, 
   (SELECT @rownum1 := 0) r1, (SELECT @rownum2 := 0) r2
ORDER BY <rank_order_by_field>
;

Hope that makes sense / helps!

SQL query to get most recent row for each instance of a given key

Something like this:

select * 
from User U1
where time_stamp = (
  select max(time_stamp) 
  from User 
  where username = U1.username)

should do it.

Using ORDER BY and GROUP BY together

One way to do this that correctly uses group by:

select l.* 
from table l
inner join (
  select 
    m_id, max(timestamp) as latest 
  from table 
  group by m_id
) r
  on l.timestamp = r.latest and l.m_id = r.m_id
order by timestamp desc

How this works:

  • selects the latest timestamp for each distinct m_id in the subquery
  • only selects rows from table that match a row from the subquery (this operation -- where a join is performed, but no columns are selected from the second table, it's just used as a filter -- is known as a "semijoin" in case you were curious)
  • orders the rows

Duplicate ID, tag null, or parent id with another fragment for com.google.android.gms.maps.MapFragment

Anyone coming here now that's getting this type of error when opening a Dialog or other Fragment with the Google Places AutocompleteSupportFragment, try this one-liner (I don't know how safe this is but it works for me):

autocompleteFragment.getFragmentManager().beginTransaction().remove(autocompleteFragment).commit();

before you dismiss/destroy your fragment.

how to concat two columns into one with the existing column name in mysql?

You can try this simple way for combining columns:

select some_other_column,first_name || ' ' || last_name AS First_name from customer;

Unresolved reference issue in PyCharm

If anyone is still looking at this, the accepted answer still works for PyCharm 2016.3 when I tried it. The UI might have changed, but the options are still the same.

ie. Right click on your root folder --> 'Mark Directory As' --> Source Root

XMLHttpRequest module not defined/found

Since the last update of the xmlhttprequest module was around 2 years ago, in some cases it does not work as expected.

So instead, you can use the xhr2 module. In other words:

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();

becomes:

var XMLHttpRequest = require('xhr2');
var xhr = new XMLHttpRequest();

But ... of course, there are more popular modules like Axios, because -for example- uses promises:

// Make a request for a user with a given ID
axios.get('/user?ID=12345').then(function (response) {
    console.log(response);
}).catch(function (error) {
    console.log(error);
});

How to enable assembly bind failure logging (Fusion) in .NET

If you already have logging enabled and you still get this error on Windows 7 64 bit, try this in IIS 7.5:

  1. Create a new application pool

  2. Go to the Advanced Settings of this application pool

  3. Set the Enable 32-Bit Application to True

  4. Point your web application to use this new pool

Why should hash functions use a prime number modulus?

For a hash function it's not only important to minimize colisions generally but to make it impossible to stay with the same hash while chaning a few bytes.

Say you have an equation: (x + y*z) % key = x with 0<x<key and 0<z<key. If key is a primenumber n*y=key is true for every n in N and false for every other number.

An example where key isn't a prime example: x=1, z=2 and key=8 Because key/z=4 is still a natural number, 4 becomes a solution for our equation and in this case (n/2)*y = key is true for every n in N. The amount of solutions for the equation have practially doubled because 8 isn't a prime.

If our attacker already knows that 8 is possible solution for the equation he can change the file from producing 8 to 4 and still gets the same hash.

How to get all options of a select using jQuery?

If you're looking for all options with some selected text then the below code will work.

$('#test').find("select option:contains('B')").filter(":selected");

Excel VBA - How to Redim a 2D array?

A small update to what @control freak and @skatun wrote previously (sorry I don't have enough reputation to just make a comment). I used skatun's code and it worked well for me except that it was creating a larger array than what I needed. Therefore, I changed:

ReDim aPreservedArray(nNewFirstUBound, nNewLastUBound)

to:

ReDim aPreservedArray(LBound(aArrayToPreserve, 1) To nNewFirstUBound, LBound(aArrayToPreserve, 2) To nNewLastUBound)

This will maintain whatever the original array's lower bounds were (either 0, 1, or whatever; the original code assumes 0) for both dimensions.

How do disable paging by swiping with finger in ViewPager but still be able to swipe programmatically?

Try overriding and returning true from either onInterceptTouchEvent() and/or onTouchEvent(), which will consume touch events on the pager.

Showing all errors and warnings

You can see a detailed description here.

ini_set('display_errors', 1);

// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);

// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);

// Report all PHP errors (see changelog)
error_reporting(E_ALL);

// Report all PHP errors
error_reporting(-1);

// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);

Changelog

  • 5.4.0 E_STRICT became part of E_ALL

  • 5.3.0 E_DEPRECATED and E_USER_DEPRECATED introduced.

  • 5.2.0 E_RECOVERABLE_ERROR introduced.

  • 5.0.0 E_STRICT introduced (not part of E_ALL).

Cross-reference (named anchor) in markdown

Take me to [pookie](#pookie)

should be the correct markdown syntax to jump to the anchor point named pookie.

To insert an anchor point of that name use HTML:

<a name="pookie"></a>

Markdown doesn't seem to mind where you put the anchor point. A useful place to put it is in a header. For example:

### <a name="tith"></a>This is the Heading

works very well. (I'd demonstrate here but SO's renderer strips out the anchor.)

Note on self-closing tags and id= versus name=

An earlier version of this post suggested using <a id='tith' />, using the self-closing syntax for XHTML, and using the id attribute instead of name.

XHTML allows for any tag to be 'empty' and 'self-closed'. That is, <tag /> is short-hand for <tag></tag>, a matched pair of tags with an empty body. Most browsers will accept XHTML, but some do not. To avoid cross-browser problems, close the tag explicitly using <tag></tag>, as recommended above.

Finally, the attribute name= was deprecated in XHTML, so I originally used id=, which everyone recognises. However, HTML5 now creates a global variable in JavaScript when using id=, and this may not necessarily be what you want. So, using name= is now likely to be more friendly.

(Thanks to Slipp Douglas for explaining XHTML to me, and nailer for pointing out the HTML5 side-effect — see the comments and nailer's answer for more detail. name= appears to work everywhere, though it is deprecated in XHTML.)

How do I decrease the size of my sql server log file?

  • Perform a full backup of your database. Don't skip this. Really.
  • Change the backup method of your database to "Simple"
  • Open a query window and enter "checkpoint" and execute
  • Perform another backup of the database
  • Change the backup method of your database back to "Full" (or whatever it was, if it wasn't already Simple)
  • Perform a final full backup of the database.
  • Run below queries one by one
    1. USE Database_Name
    2. select name,recovery_model_desc from sys.databases
    3. ALTER DATABASE Database_Name SET RECOVERY simple
    4. DBCC SHRINKFILE (Database_Name_log , 1)

What does the "On Error Resume Next" statement do?

It basically tells the program when you encounter an error just continue at the next line.

How can I remove file extension from a website address?

You have different choices. One on them is creating a folder named "profile" and rename your "profile.php" to "default.php" and put it into "profile" folder. and you can give orders to this page in this way:

Old page: http://something.com/profile.php?id=a&abc=1

New page: http://something.com/profile/?id=a&abc=1

If you are not satisfied leave a comment for complicated methods.

javax.naming.NameNotFoundException: Name is not bound in this Context. Unable to find

Ok found out the Tomcat file server.xml must be configured as well for the data source to work. So just add:

<Resource 
auth="Container" 
driverClassName="org.apache.derby.jdbc.EmbeddedDriver" 
maxActive="20" 
maxIdle="10" 
maxWait="-1" 
name="ds/flexeraDS" 
type="javax.sql.DataSource" 
url="jdbc:derby:flexeraDB;create=true" 
  />

Python, print all floats to 2 decimal places in output

Format String Syntax.

https://docs.python.org/3/library/string.html#formatstrings

from math import pi
var1, var2, var3, var4 = pi, pi*2, pi*3, pi*4
'{:0.2f}, kg={:0.2f}, lb={:0.2f}, gal={:0.2f}'.format(var1, var2, var3, var4)

The output would be:

'3.14, kg=6.28, lb=9.42, gal=12.57'

GET parameters in the URL with CodeIgniter

You can Try this

$this->uri->segment('');

Getting last month's date in php

Incorrect answers are:

$lastMonth = date('M Y', strtotime("-1 month"));
$lastDate = date('Y-m', strtotime('last month'));

The reason is if current month is 30+ days but previous month is 29 and less $lastMonth will be the same as current month.

e.g.

If $currentMonth = '30/03/2016';
echo $lastMonth = date('m-Y', strtotime("-1 month")); => 03-2016
echo $lastDate = date('Y-m', strtotime('last month')); => 2016-03

The correct answer will be:

echo date("m-Y", strtotime("first day of previous month")); => 02-2016
echo sprintf("%02d",date("m")-1) . date("-Y"); => 02-2016
echo date("m-Y",mktime(0,0,0,date("m")-1,1,date("Y"))); => 02-2016

There was no endpoint listening at (url) that could accept the message

go to webconfig page of your site, look for the tag endpoint, and check the port in the address attribute, maybe there was a change in the port number

Removing u in list

You don't "remove the character 'u' from a list", you encode Unicode strings. In fact the strings you have are perfectly fine for most uses; you will just need to encode them appropriately before outputting them.

Order a List (C#) by many fields?

Your object should implement the IComparable interface.

With it your class becomes a new function called CompareTo(T other). Within this function you can make any comparison between the current and the other object and return an integer value about if the first is greater, smaller or equal to the second one.

Copy folder recursively in Node.js

The easiest approach for this problem is to use only the 'fs' and 'Path' module and some logic...

All files in the root folder copy with the new name if you want to just set the version number, i.e., " var v = 'Your Directory Name'"

In the file name prefix with content added with the file name.

var fs = require('fs-extra');
var path = require('path');

var c = 0;
var i = 0;
var v = "1.0.2";
var copyCounter = 0;
var directoryCounter = 0;
var directoryMakerCounter = 0;
var recursionCounter = -1;
var Flag = false;
var directoryPath = [];
var directoryName = [];
var directoryFileName = [];
var fileName;
var directoryNameStorer;
var dc = 0;
var route;

if (!fs.existsSync(v)) {
    fs.mkdirSync(v);
}

var basePath = path.join(__dirname, v);


function walk(dir) {

    fs.readdir(dir, function(err, items) {

        items.forEach(function(file) {

            file = path.resolve(dir, file);

            fs.stat(file, function(err, stat) {

                if(stat && stat.isDirectory()) {
                    directoryNameStorer = path.basename(file);
                    route = file;
                    route = route.replace("gd", v);

                    directoryFileName[directoryCounter] = route;
                    directoryPath[directoryCounter] = file;
                    directoryName[directoryCounter] = directoryNameStorer;

                    directoryCounter++;
                    dc++;

                    if (!fs.existsSync(basePath + "/" + directoryName[directoryMakerCounter])) {
                        fs.mkdirSync(directoryFileName[directoryMakerCounter]);
                        directoryMakerCounter++;
                    }
                }
                else {
                    fileName = path.basename(file);
                    if(recursionCounter >= 0) {
                        fs.copyFileSync(file, directoryFileName[recursionCounter] + "/" + v + "_" + fileName, err => {
                            if(err) return console.error(err);
                        });
                        copyCounter++;
                    }
                    else {
                        fs.copyFileSync(file, v + "/" + v + "_" + fileName, err => {
                            if(err) return console.error(err);
                        });
                        copyCounter++;
                    }
                }
                if(copyCounter + dc == items.length && directoryCounter > 0 && recursionCounter < directoryMakerCounter-1) {
                    console.log("COPY COUNTER:             " + copyCounter);
                    console.log("DC COUNTER:               " + dc);
                    recursionCounter++;
                    dc = 0;
                    copyCounter = 0;
                    console.log("ITEM DOT LENGTH:          " + items.length);
                    console.log("RECURSION COUNTER:        " + recursionCounter);
                    console.log("DIRECOTRY MAKER COUNTER:  " + directoryMakerCounter);
                    console.log(": START RECURSION:        " + directoryPath[recursionCounter]);
                    walk(directoryPath[recursionCounter]); //recursive call to copy sub-folder
                }
            })
        })
    });
}

walk('./gd', function(err, data) { // Just pass the root directory which you want to copy
    if(err)
        throw err;
    console.log("done");
})

Saving plots (AxesSubPlot) generated from python pandas with matplotlib's savefig

this may be a simpler approach:

(DesiredFigure).get_figure().savefig('figure_name.png')

i.e.

dfcorr.hist(bins=50).get_figure().savefig('correlation_histogram.png')

Remove elements from collection while iterating

why not this?

for( int i = 0; i < Foo.size(); i++ )
{
   if( Foo.get(i).equals( some test ) )
   {
      Foo.remove(i);
   }
}

And if it's a map, not a list, you can use keyset()

Can table columns with a Foreign Key be NULL?

The above works but this does not. Note the ON DELETE CASCADE

CREATE DATABASE t;
USE t;

CREATE TABLE parent (id INT NOT NULL,
                 PRIMARY KEY (id)
) ENGINE=INNODB;

CREATE TABLE child (id INT NULL, 
                parent_id INT NULL,
                FOREIGN KEY (parent_id) REFERENCES parent(id) ON DELETE CASCADE

) ENGINE=INNODB;


INSERT INTO child (id, parent_id) VALUES (1, NULL);
-- Query OK, 1 row affected (0.01 sec)

Adding asterisk to required fields in Bootstrap 3

Assuming this is what the HTML looks like

<div class="form-group required">
   <label class="col-md-2 control-label">E-mail</label>
   <div class="col-md-4"><input class="form-control" id="id_email" name="email" placeholder="E-mail" required="required" title="" type="email" /></div>
</div>

To display an asterisk on the right of the label:

.form-group.required .control-label:after { 
    color: #d00;
    content: "*";
    position: absolute;
    margin-left: 8px;
    top:7px;
}

Or to the left of the label:

.form-group.required .control-label:before{
   color: red;
   content: "*";
   position: absolute;
   margin-left: -15px;
}

To make a nice big red asterisks you can add these lines:

font-family: 'Glyphicons Halflings';
font-weight: normal;
font-size: 14px;

Or if you are using Font Awesome add these lines (and change the content line):

font-family: 'FontAwesome';
font-weight: normal;
font-size: 14px;
content: "\f069";

Displaying a Table in Django from Database

$ pip install django-tables2

settings.py

INSTALLED_APPS , 'django_tables2'
TEMPLATES.OPTIONS.context-processors , 'django.template.context_processors.request'

models.py

class hotel(models.Model):
     name = models.CharField(max_length=20)

views.py

from django.shortcuts import render

def people(request):
    istekler = hotel.objects.all()
    return render(request, 'list.html', locals())

list.html

{# yonetim/templates/list.html #}
{% load render_table from django_tables2 %}
{% load static %}
<!doctype html>
<html>
    <head>
        <link rel="stylesheet" href="{% static 
'ticket/static/css/screen.css' %}" />
    </head>
    <body>
        {% render_table istekler %}
    </body>
</html>

Spark - SELECT WHERE or filtering?

As Yaron mentioned, there isn't any difference between where and filter.

filter is an overloaded method that takes a column or string argument. The performance is the same, regardless of the syntax you use.

filter overloaded method

We can use explain() to see that all the different filtering syntaxes generate the same Physical Plan. Suppose you have a dataset with person_name and person_country columns. All of the following code snippets will return the same Physical Plan below:

df.where("person_country = 'Cuba'").explain()
df.where($"person_country" === "Cuba").explain()
df.where('person_country === "Cuba").explain()
df.filter("person_country = 'Cuba'").explain()

These all return this Physical Plan:

== Physical Plan ==
*(1) Project [person_name#152, person_country#153]
+- *(1) Filter (isnotnull(person_country#153) && (person_country#153 = Cuba))
   +- *(1) FileScan csv [person_name#152,person_country#153] Batched: false, Format: CSV, Location: InMemoryFileIndex[file:/Users/matthewpowers/Documents/code/my_apps/mungingdata/spark2/src/test/re..., PartitionFilters: [], PushedFilters: [IsNotNull(person_country), EqualTo(person_country,Cuba)], ReadSchema: struct<person_name:string,person_country:string>

The syntax doesn't change how filters are executed under the hood, but the file format / database that a query is executed on does. Spark will execute the same query differently on Postgres (predicate pushdown filtering is supported), Parquet (column pruning), and CSV files. See here for more details.

Associative arrays in Shell scripts

You can use dynamic variable names and let the variables names work like the keys of a hashmap.

For example, if you have an input file with two columns, name, credit, as the example bellow, and you want to sum the income of each user:

Mary 100
John 200
Mary 50
John 300
Paul 100
Paul 400
David 100

The command bellow will sum everything, using dynamic variables as keys, in the form of map_${person}:

while read -r person money; ((map_$person+=$money)); done < <(cat INCOME_REPORT.log)

To read the results:

set | grep map

The output will be:

map_David=100
map_John=500
map_Mary=150
map_Paul=500

Elaborating on these techniques, I'm developing on GitHub a function that works just like a HashMap Object, shell_map.

In order to create "HashMap instances" the shell_map function is able create copies of itself under different names. Each new function copy will have a different $FUNCNAME variable. $FUNCNAME then is used to create a namespace for each Map instance.

The map keys are global variables, in the form $FUNCNAME_DATA_$KEY, where $KEY is the key added to the Map. These variables are dynamic variables.

Bellow I'll put a simplified version of it so you can use as example.

#!/bin/bash

shell_map () {
    local METHOD="$1"

    case $METHOD in
    new)
        local NEW_MAP="$2"

        # loads shell_map function declaration
        test -n "$(declare -f shell_map)" || return

        # declares in the Global Scope a copy of shell_map, under a new name.
        eval "${_/shell_map/$2}"
    ;;
    put)
        local KEY="$2"  
        local VALUE="$3"

        # declares a variable in the global scope
        eval ${FUNCNAME}_DATA_${KEY}='$VALUE'
    ;;
    get)
        local KEY="$2"
        local VALUE="${FUNCNAME}_DATA_${KEY}"
        echo "${!VALUE}"
    ;;
    keys)
        declare | grep -Po "(?<=${FUNCNAME}_DATA_)\w+((?=\=))"
    ;;
    name)
        echo $FUNCNAME
    ;;
    contains_key)
        local KEY="$2"
        compgen -v ${FUNCNAME}_DATA_${KEY} > /dev/null && return 0 || return 1
    ;;
    clear_all)
        while read var; do  
            unset $var
        done < <(compgen -v ${FUNCNAME}_DATA_)
    ;;
    remove)
        local KEY="$2"
        unset ${FUNCNAME}_DATA_${KEY}
    ;;
    size)
        compgen -v ${FUNCNAME}_DATA_${KEY} | wc -l
    ;;
    *)
        echo "unsupported operation '$1'."
        return 1
    ;;
    esac
}

Usage:

shell_map new credit
credit put Mary 100
credit put John 200
for customer in `credit keys`; do 
    value=`credit get $customer`       
    echo "customer $customer has $value"
done
credit contains_key "Mary" && echo "Mary has credit!"

FCM getting MismatchSenderId

I spent hours on this and finally figured it out. This problem happens if service account your sender application is using differs from the service account your receiver is using.

You can find out your receiver service account via Firebase -> Project Overview -> Project Settings -> Service Accounts and generate a new key and use that key when you are initializing your FirebaseApp in the sender:

FileInputStream serviceAccount = new FileInputStream("YOUR_PATH_TO_GENERATED_KEY.json");
GoogleCredentials googleCredentials = GoogleCredentials.fromStream(serviceAccount);
FirebaseOptions options = new FirebaseOptions.Builder().setCredentials(googleCredentials).build();
firebaseApp =  FirebaseApp.initializeApp(options);

This initialization need to be done once before you send push notifications.

In my case, I had done everything correctly and I still had this problem. I had made some changes in the "google-services.json" used in the receiver app and I noticed AndroidStudio was not using my new file. The solution was so simple:

AndroidStudio -> Build -> Clean Project and Build -> Rebuild Project

How to increase the max upload file size in ASP.NET?

You can write that block of code in your application web.config file.

<httpRuntime maxRequestLength="2048576000" />
<sessionState timeout="3600"  />

By writing that code you can upload a larger file than now

What is the best way to generate a unique and short file name in Java

How about generate based on time stamp rounded to the nearest millisecond, or whatever accuracy you need... then use a lock to synchronize access to the function.

If you store the last generated file name, you can append sequential letters or further digits to it as needed to make it unique.

Or if you'd rather do it without locks, use a time step plus a thread ID, and make sure that the function takes longer than a millisecond, or waits so that it does.

Save base64 string as PDF at client side with JavaScript

You will do not need any library for this. JavaScript support this already. Here is my end-to-end solution.

const xhr = new XMLHttpRequest();
xhr.open('GET', 'your-end-point', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
xhr.responseType = 'blob';
xhr.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
       if (window.navigator.msSaveOrOpenBlob) {
           window.navigator.msSaveBlob(this.response, "fileName.pdf");
        } else {
           const downloadLink = window.document.createElement('a');
           const contentTypeHeader = xhr.getResponseHeader("Content-Type");
           downloadLink.href = window.URL.createObjectURL(new Blob([this.response], { type: contentTypeHeader }));
           downloadLink.download = "fileName.pdf";
           document.body.appendChild(downloadLink);
           downloadLink.click();
           document.body.removeChild(downloadLink);
        }
    }
};
xhr.send(null);

This also work for .xls or .zip file. You just need to change file name to fileName.xls or fileName.zip. This depends on your case.

GROUP BY and COUNT in PostgreSQL

I think you just need COUNT(DISTINCT post_id) FROM votes.

See "4.2.7. Aggregate Expressions" section in http://www.postgresql.org/docs/current/static/sql-expressions.html.

EDIT: Corrected my careless mistake per Erwin's comment.

Eclipse+Maven src/main/java not visible in src folder in Package Explorer

I was not able to see the build path option in the properties as well. Also the

src/main/java

was not visible in Project Explorer. below solution worked for me

  1. Go to Project root
  2. Select "Project facets" from Properties
  3. Check "Java"

This fixes the issue

Can't open and lock privilege tables: Table 'mysql.user' doesn't exist

As suggested above, i had similar issue with mysql-5.7.18,
i did this in this way

1. Executed this command from "MYSQL_HOME\bin\mysqld.exe --initialize-insecure"
2. then started "MYSQL_HOME\bin\mysqld.exe"
3. Connect workbench to this localhost:3306 with username 'root'
4. then executed this query "SET PASSWORD FOR 'root'@'localhost' = 'root';"

password was also updated successfully.

How can I count occurrences with groupBy?

Here is example for list of Objects

Map<String, Long> requirementCountMap = requirements.stream().collect(Collectors.groupingBy(Requirement::getRequirementType, Collectors.counting()));

How to get input text value from inside td

var values = {};
$('td input').each(function(){
  values[$(this).attr('name')] = $(this).val();
}

Haven't tested, but that should do it...

Get page title with Selenium WebDriver using Java

You can do it easily by using JUnit or TestNG framework. Do the assertion as below:

String actualTitle = driver.getTitle();
String expectedTitle = "Title of Page";
assertEquals(expectedTitle,actualTitle);

OR,

assertTrue(driver.getTitle().contains("Title of Page"));

how to re-format datetime string in php?

https://en.functions-online.com/date.html?command={"format":"l jS \\of F Y h:i:s A"}

How to Compare two Arrays are Equal using Javascript?

You could try this simple approach

_x000D_
_x000D_
var array1 = [4,8,9,10];_x000D_
var array2 = [4,8,9,10];_x000D_
_x000D_
console.log(array1.join('|'));_x000D_
console.log(array2.join('|'));_x000D_
_x000D_
if (array1.join('|') === array2.join('|')) {_x000D_
 console.log('The arrays are equal.');_x000D_
} else {_x000D_
 console.log('The arrays are NOT equal.');_x000D_
}_x000D_
_x000D_
array1 = [[1,2],[3,4],[5,6],[7,8]];_x000D_
array2 = [[1,2],[3,4],[5,6],[7,8]];_x000D_
_x000D_
console.log(array1.join('|'));_x000D_
console.log(array2.join('|'));_x000D_
_x000D_
if (array1.join('|') === array2.join('|')) {_x000D_
 console.log('The arrays are equal.');_x000D_
} else {_x000D_
 console.log('The arrays are NOT equal.');_x000D_
}
_x000D_
_x000D_
_x000D_

If the position of the values are not important you could sort the arrays first.

if (array1.sort().join('|') === array2.sort().join('|')) {
    console.log('The arrays are equal.');
} else {
    console.log('The arrays are NOT equal.');
}

How can I catch all the exceptions that will be thrown through reading and writing a file?

Catch the base exception 'Exception'

   try { 
         //some code
   } catch (Exception e) {
        //catches exception and all subclasses 
   }

Indexing vectors and arrays with +:

Description and examples can be found in IEEE Std 1800-2017 § 11.5.1 "Vector bit-select and part-select addressing". First IEEE appearance is IEEE 1364-2001 (Verilog) § 4.2.1 "Vector bit-select and part-select addressing". Here is an direct example from the LRM:

logic [31: 0] a_vect;
logic [0 :31] b_vect;
logic [63: 0] dword;
integer sel;
a_vect[ 0 +: 8] // == a_vect[ 7 : 0]
a_vect[15 -: 8] // == a_vect[15 : 8]
b_vect[ 0 +: 8] // == b_vect[0 : 7]
b_vect[15 -: 8] // == b_vect[8 :15]
dword[8*sel +: 8] // variable part-select with fixed width

If sel is 0 then dword[8*(0) +: 8] == dword[7:0]
If sel is 7 then dword[8*(7) +: 8] == dword[63:56]

The value to the left always the starting index. The number to the right is the width and must be a positive constant. the + and - indicates to select the bits of a higher or lower index value then the starting index.

Assuming address is in little endian ([msb:lsb]) format, then if(address[2*pointer+:2]) is the equivalent of if({address[2*pointer+1],address[2*pointer]})

Reading from a text file and storing in a String

How can we read data from a text file and store in a String Variable?

Err, read data from the file and store it in a String variable. It's just code. Not a real question so far.

Is it possible to pass the filename in a method and it would return the String which is the text from the file.

Yes it's possible. It's also a very bad idea. You should deal with the file a part at a time, for example a line at a time. Reading the entire file into memory before you process any of it adds latency; wastes memory; and assumes that the entire file will fit into memory. One day it won't. You don't want to do it this way.

"continue" in cursor.forEach()

Each iteration of the forEach() will call the function that you have supplied. To stop further processing within any given iteration (and continue with the next item) you just have to return from the function at the appropriate point:

elementsCollection.forEach(function(element){
  if (!element.shouldBeProcessed)
    return; // stop processing this iteration

  // This part will be avoided if not neccessary
  doSomeLengthyOperation();
});

Importing the private-key/public-certificate pair in the Java KeyStore

With your private key and public certificate, you need to create a PKCS12 keystore first, then convert it into a JKS.

# Create PKCS12 keystore from private key and public certificate.
openssl pkcs12 -export -name myservercert -in selfsigned.crt -inkey server.key -out keystore.p12

# Convert PKCS12 keystore into a JKS keystore
keytool -importkeystore -destkeystore mykeystore.jks -srckeystore keystore.p12 -srcstoretype pkcs12 -alias myservercert

To verify the contents of the JKS, you can use this command:

keytool -list -v -keystore mykeystore.jks

If this was not a self-signed certificate, you would probably want to follow this step with importing the certificate chain leading up to the trusted CA cert.

how to find host name from IP with out login to the host

You can do a reverse DNS lookup with host, too. Just give it the IP address as an argument:

$ host 192.168.0.10
server10 has address 192.168.0.10

SQLite - getting number of rows in a database

If you want to use the MAX(id) instead of the count, after reading the comments from Pax then the following SQL will give you what you want

SELECT COALESCE(MAX(id)+1, 0) FROM words

install / uninstall APKs programmatically (PackageManager vs Intents)

API level 14 introduced two new actions: ACTION_INSTALL_PACKAGE and ACTION_UNINSTALL_PACKAGE. Those actions allow you to pass EXTRA_RETURN_RESULT boolean extra to get an (un)installation result notification.

Example code for invoking the uninstall dialog:

String app_pkg_name = "com.example.app";
int UNINSTALL_REQUEST_CODE = 1;

Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);  
intent.setData(Uri.parse("package:" + app_pkg_name));  
intent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
startActivityForResult(intent, UNINSTALL_REQUEST_CODE);

And receive the notification in your Activity#onActivityResult method:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == UNINSTALL_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            Log.d("TAG", "onActivityResult: user accepted the (un)install");
        } else if (resultCode == RESULT_CANCELED) {
            Log.d("TAG", "onActivityResult: user canceled the (un)install");
        } else if (resultCode == RESULT_FIRST_USER) {
            Log.d("TAG", "onActivityResult: failed to (un)install");
        }
    }
}

node.js: read a text file into an array. (Each line an item in the array.)

I had the same problem, and I have solved it with the module line-by-line

https://www.npmjs.com/package/line-by-line

At least for me works like a charm, both in synchronous and asynchronous mode.

Also, the problem with lines terminating not terminating \n can be solved with the option:

{ encoding: 'utf8', skipEmptyLines: false }

Synchronous processing of lines:

var LineByLineReader = require('line-by-line'),
    lr = new LineByLineReader('big_file.txt');

lr.on('error', function (err) {
    // 'err' contains error object
});

lr.on('line', function (line) {
    // 'line' contains the current line without the trailing newline character.
});

lr.on('end', function () {
    // All lines are read, file is closed now.
}); 

Including a css file in a blade template?

You should try this :

{{ Html::style('css/styles.css') }}

OR

<link href="{{ asset('css/styles.css') }}" rel="stylesheet">

Hope this help for you !!!

How to Read from a Text File, Character by Character in C++

Here is a c++ stylish function your can use to read files char by char.

void readCharFile(string &filePath) {
    ifstream in(filePath);
    char c;

    if(in.is_open()) {
        while(in.good()) {
            in.get(c);
            // Play with the data
        }
    }

    if(!in.eof() && in.fail())
        cout << "error reading " << filePath << endl;

    in.close();
}

How can I determine whether a specific file is open in Windows?

If you right-click on your "Computer" (or "My Computer") icon and select "Manage" from the pop-up menu, that'll take you to the Computer Management console.

In there, under System Tools\Shared Folders, you'll find "Open Files". This is probably close to what you want, but if the file is on a network share then you'd need to do the same thing on the server on which the file lives.

Removing black dots from li and ul

CSS :

ul{
list-style-type:none;
}

You can take a look at W3School

You need to install postgresql-server-dev-X.Y for building a server-side extension or libpq-dev for building a client-side application

They changed the packaging for psycopg2. Installing the binary version fixed this issue for me. The above answers still hold up if you want to compile the binary yourself.

See http://initd.org/psycopg/docs/news.html#what-s-new-in-psycopg-2-8.

Binary packages no longer installed by default. The ‘psycopg2-binary’ package must be used explicitly.

And http://initd.org/psycopg/docs/install.html#binary-install-from-pypi

So if you don't need to compile your own binary, use:

pip install psycopg2-binary

Redirect on select option in select box

I'd strongly suggest moving away from inline JavaScript, to something like the following:

function redirect(goto){
    var conf = confirm("Are you sure you want to go elswhere?");
    if (conf && goto != '') {
        window.location = goto;
    }
}

var selectEl = document.getElementById('redirectSelect');

selectEl.onchange = function(){
    var goto = this.value;
    redirect(goto);

};

JS Fiddle demo (404 linkrot victim).
JS Fiddle demo via Wayback Machine.
Forked JS Fiddle for current users.

In the mark-up in the JS Fiddle the first option has no value assigned, so clicking it shouldn't trigger the function to do anything, and since it's the default value clicking the select and then selecting that first default option won't trigger the change event anyway.

Update:
The latest example's (2017-08-09) redirect URLs required swapping out due to errors regarding mixed content between JS Fiddle and both domains, as well as both domains requiring 'sameorigin' for framed content. - Albert

Query to get the names of all tables in SQL Server 2008 Database

To get the fields info too, you can use the following:

SELECT TABLE_SCHEMA, TABLE_NAME, 
       COLUMN_NAME, substring(DATA_TYPE, 1,1) AS DATA_TYPE
FROM information_schema.COLUMNS 
WHERE TABLE_SCHEMA NOT IN("information_schema", "mysql", "performance_schema") 
ORDER BY TABLE_SCHEMA, TABLE_NAME, ORDINAL_POSITION

Splitting a string into chunks of a certain size

You can use morelinq by Jon Skeet. Use Batch like:

string str = "1111222233334444";
int chunkSize = 4;
var chunks = str.Batch(chunkSize).Select(r => new String(r.ToArray()));

This will return 4 chunks for the string "1111222233334444". If the string length is less than or equal to the chunk size Batch will return the string as the only element of IEnumerable<string>

For output:

foreach (var chunk in chunks)
{
    Console.WriteLine(chunk);
}

and it will give:

1111
2222
3333
4444

How to get Locale from its String representation in Java?

This answer may be a little late, but it turns out that parsing out the string is not as ugly as the OP assumed. I found it quite simple and concise:

public static Locale fromString(String locale) {
    String parts[] = locale.split("_", -1);
    if (parts.length == 1) return new Locale(parts[0]);
    else if (parts.length == 2
            || (parts.length == 3 && parts[2].startsWith("#")))
        return new Locale(parts[0], parts[1]);
    else return new Locale(parts[0], parts[1], parts[2]);
}

I tested this (on Java 7) with all the examples given in the Locale.toString() documentation: "en", "de_DE", "_GB", "en_US_WIN", "de__POSIX", "zh_CN_#Hans", "zh_TW_#Hant-x-java", and "th_TH_TH_#u-nu-thai".

IMPORTANT UPDATE: This is not recommended for use in Java 7+ according to the documentation:

In particular, clients who parse the output of toString into language, country, and variant fields can continue to do so (although this is strongly discouraged), although the variant field will have additional information in it if script or extensions are present.

Use Locale.forLanguageTag and Locale.toLanguageTag instead, or if you must, Locale.Builder.

Picasso v/s Imageloader v/s Fresco vs Glide

These answers are totally my opinion

Answers

  1. Picasso is an easy to use image loader, same goes for Imageloader. Fresco uses a different approach to image loading, i haven't used it yet but it looks too me more like a solution for getting image from network and caching them then showing the images. then the other way around like Picasso/Imageloader/Glide which to me are more Showing image on screen that also does getting images from network and caching them.

  2. Glide tries to be somewhat interchangeable with Picasso.I think when they were created Picasso's mind set was follow HTTP spec's and let the server decide the caching policies and cache full sized and resize on demand. Glide is the same with following the HTTP spec but tries to have a smaller memory footprint by making some different assumptions like cache the resized images instead of the fullsized images, and show images with RGB_565 instead of RGB_8888. Both libraries offer full customization of the default settings.

  3. As to which library is the best to use is really hard to say. Picasso, Glide and Imageloader are well respected and well tested libraries which all are easy to use with the default settings. Both Picasso and Glide require only 1 line of code to load an image and have a placeholder and error image. Customizing the behaviour also doesn't require that much work. Same goes for Imageloader which is also an older library then Picasso and Glide, however I haven't used it so can't say much about performance/memory usage/customizations but looking at the readme on github gives me the impression that it is also relatively easy to use and setup. So in choosing any of these 3 libraries you can't make the wrong decision, its more a matter of personal taste. For fresco my opinion is that its another facebook library so we have to see how that is going to work out for them, so far there track record isn't that good. Like the facebook SDK is still isn't officially released on mavenCentral I have not used to facebook sdk since sept 2014 and it seems they have put the first version online on mavenCentral in oct 2014. So it will take some time before we can get any good opinion about it.

  4. between the 3 big name libraries I think there are no significant differences. The only one that stand out is fresco but that is because it has a different approach and is new and not battle tested.

Batch file FOR /f tokens

for /f "tokens=* delims= " %%f in (myfile) do

This reads a file line-by-line, removing leading spaces (thanks, jeb).

set line=%%f

sets then the line variable to the line just read and

call :procesToken

calls a subroutine that does something with the line

:processToken

is the start of the subroutine mentioned above.

for /f "tokens=1* delims=/" %%a in ("%line%") do

will then split the line at /, but stopping tokenization after the first token.

echo Got one token: %%a

will output that first token and

set line=%%b

will set the line variable to the rest of the line.

if not "%line%" == "" goto :processToken

And if line isn't yet empty (i.e. all tokens processed), it returns to the start, continuing with the rest of the line.

PHP how to get local IP of system

I fiddled with this question for a server-side php (running from Linux terminal)

I exploded 'ifconfig' and trimmed it down to the IP address.

Here it is:

$interface_to_detect = 'wlan0';
echo explode(' ',explode(':',explode('inet addr',explode($interface_to_detect,trim(`ifconfig`))[1])[1])[1])[0];

And of course change 'wlan0' to your desired network device.

My output is:

192.168.1.5

How to retrieve current workspace using Jenkins Pipeline Groovy script?

This is where you can find the answer in the job-dsl-plugin code.

Basically you can do something like this:

readFileFromWorkspace('src/main/groovy/com/groovy/jenkins/scripts/enable_safehtml.groovy')

Using a Loop to add objects to a list(python)

The problem appears to be that you are reinitializing the list to an empty list in each iteration:

while choice != 0:
    ...
    a = []
    a.append(s)

Try moving the initialization above the loop so that it is executed only once.

a = []
while choice != 0:
    ...
    a.append(s)

Checking if a key exists in a JavaScript object?

ES6 solution

using Array#some and Object.keys. It will return true if given key exists in the object or false if it doesn't.

_x000D_
_x000D_
var obj = {foo: 'one', bar: 'two'};_x000D_
    _x000D_
function isKeyInObject(obj, key) {_x000D_
    var res = Object.keys(obj).some(v => v == key);_x000D_
    console.log(res);_x000D_
}_x000D_
_x000D_
isKeyInObject(obj, 'foo');_x000D_
isKeyInObject(obj, 'something');
_x000D_
_x000D_
_x000D_

One-line example.

_x000D_
_x000D_
console.log(Object.keys({foo: 'one', bar: 'two'}).some(v => v == 'foo'));
_x000D_
_x000D_
_x000D_

Case insensitive string compare in LINQ-to-SQL

To perform case sensitive Linq to Sql queries declare ‘string’ fields to be case sensitive by specifying the server data type by using one of the following;

varchar(4000) COLLATE SQL_Latin1_General_CP1_CS_AS 

or

nvarchar(Max) COLLATE SQL_Latin1_General_CP1_CS_AS

Note: The ‘CS’ in the above collation types means ‘Case Sensitive’.

This can be entered in the “Server Data Type” field when viewing a property using Visual Studio DBML Designer.

For more details see http://yourdotnetdesignteam.blogspot.com/2010/06/case-sensitive-linq-to-sql-queries.html

Resize background image in div using css

With the background-size property in those browsers which support this very new feature of CSS.

jQuery Mobile: document ready vs. page events

jQuery Mobile 1.4 Update:

My original article was intended for old way of page handling, basically everything before jQuery Mobile 1.4. Old way of handling is now deprecated and it will stay active until (including) jQuery Mobile 1.5, so you can still use everything mentioned below, at least until next year and jQuery Mobile 1.6.

Old events, including pageinit don't exist any more, they are replaced with pagecontainer widget. Pageinit is erased completely and you can use pagecreate instead, that event stayed the same and its not going to be changed.

If you are interested in new way of page event handling take a look here, in any other case feel free to continue with this article. You should read this answer even if you are using jQuery Mobile 1.4 +, it goes beyond page events so you will probably find a lot of useful information.

Older content:

This article can also be found as a part of my blog HERE.

$(document).on('pageinit') vs $(document).ready()

The first thing you learn in jQuery is to call code inside the $(document).ready() function so everything will execute as soon as the DOM is loaded. However, in jQuery Mobile, Ajax is used to load the contents of each page into the DOM as you navigate. Because of this $(document).ready() will trigger before your first page is loaded and every code intended for page manipulation will be executed after a page refresh. This can be a very subtle bug. On some systems it may appear that it works fine, but on others it may cause erratic, difficult to repeat weirdness to occur.

Classic jQuery syntax:

$(document).ready(function() {

});

To solve this problem (and trust me this is a problem) jQuery Mobile developers created page events. In a nutshell page events are events triggered in a particular point of page execution. One of those page events is a pageinit event and we can use it like this:

$(document).on('pageinit', function() {

});

We can go even further and use a page id instead of document selector. Let's say we have jQuery Mobile page with an id index:

<div data-role="page" id="index">
    <div data-theme="a" data-role="header">
        <h3>
            First Page
        </h3>
        <a href="#second" class="ui-btn-right">Next</a>
    </div>

    <div data-role="content">
        <a href="#" data-role="button" id="test-button">Test button</a>
    </div>

    <div data-theme="a" data-role="footer" data-position="fixed">

    </div>
</div>

To execute code that will only available to the index page we could use this syntax:

$('#index').on('pageinit', function() {

});

Pageinit event will be executed every time page is about be be loaded and shown for the first time. It will not trigger again unless page is manually refreshed or Ajax page loading is turned off. In case you want code to execute every time you visit a page it is better to use pagebeforeshow event.

Here's a working example: http://jsfiddle.net/Gajotres/Q3Usv/ to demonstrate this problem.

Few more notes on this question. No matter if you are using 1 html multiple pages or multiple HTML files paradigm it is advised to separate all of your custom JavaScript page handling into a single separate JavaScript file. This will note make your code any better but you will have much better code overview, especially while creating a jQuery Mobile application.

There's also another special jQuery Mobile event and it is called mobileinit. When jQuery Mobile starts, it triggers a mobileinit event on the document object. To override default settings, bind them to mobileinit. One of a good examples of mobileinit usage is turning off Ajax page loading, or changing default Ajax loader behavior.

$(document).on("mobileinit", function(){
  //apply overrides here
});

Page events transition order

First all events can be found here: http://api.jquerymobile.com/category/events/

Lets say we have a page A and a page B, this is a unload/load order:

  1. page B - event pagebeforecreate

  2. page B - event pagecreate

  3. page B - event pageinit

  4. page A - event pagebeforehide

  5. page A - event pageremove

  6. page A - event pagehide

  7. page B - event pagebeforeshow

  8. page B - event pageshow

For better page events understanding read this:

  • pagebeforeload, pageload and pageloadfailed are fired when an external page is loaded
  • pagebeforechange, pagechange and pagechangefailed are page change events. These events are fired when a user is navigating between pages in the applications.
  • pagebeforeshow, pagebeforehide, pageshow and pagehide are page transition events. These events are fired before, during and after a transition and are named.
  • pagebeforecreate, pagecreate and pageinit are for page initialization.
  • pageremove can be fired and then handled when a page is removed from the DOM

Page loading jsFiddle example: http://jsfiddle.net/Gajotres/QGnft/

If AJAX is not enabled, some events may not fire.

Prevent page transition

If for some reason page transition needs to be prevented on some condition it can be done with this code:

$(document).on('pagebeforechange', function(e, data){
    var to = data.toPage,
        from = data.options.fromPage;

    if (typeof to  === 'string') {
        var u = $.mobile.path.parseUrl(to);
        to = u.hash || '#' + u.pathname.substring(1);
        if (from) from = '#' + from.attr('id');

        if (from === '#index' && to === '#second') {
            alert('Can not transition from #index to #second!');
            e.preventDefault();
            e.stopPropagation();

            // remove active status on a button, if transition was triggered with a button
            $.mobile.activePage.find('.ui-btn-active').removeClass('ui-btn-active ui-focus ui-btn');;
        }
    }
});

This example will work in any case because it will trigger at a begging of every page transition and what is most important it will prevent page change before page transition can occur.

Here's a working example:

Prevent multiple event binding/triggering

jQuery Mobile works in a different way than classic web applications. Depending on how you managed to bind your events each time you visit some page it will bind events over and over. This is not an error, it is simply how jQuery Mobile handles its pages. For example, take a look at this code snippet:

$(document).on('pagebeforeshow','#index' ,function(e,data){
    $(document).on('click', '#test-button',function(e) {
        alert('Button click');
    });
});

Working jsFiddle example: http://jsfiddle.net/Gajotres/CCfL4/

Each time you visit page #index click event will is going to be bound to button #test-button. Test it by moving from page 1 to page 2 and back several times. There are few ways to prevent this problem:

Solution 1

Best solution would be to use pageinit to bind events. If you take a look at an official documentation you will find out that pageinit will trigger ONLY once, just like document ready, so there's no way events will be bound again. This is best solution because you don't have processing overhead like when removing events with off method.

Working jsFiddle example: http://jsfiddle.net/Gajotres/AAFH8/

This working solution is made on a basis of a previous problematic example.

Solution 2

Remove event before you bind it:

$(document).on('pagebeforeshow', '#index', function(){
    $(document).off('click', '#test-button').on('click', '#test-button',function(e) {
        alert('Button click');
    });
});

Working jsFiddle example: http://jsfiddle.net/Gajotres/K8YmG/

Solution 3

Use a jQuery Filter selector, like this:

$('#carousel div:Event(!click)').each(function(){
    //If click is not bind to #carousel div do something
});

Because event filter is not a part of official jQuery framework it can be found here: http://www.codenothing.com/archives/2009/event-filter/

In a nutshell, if speed is your main concern then Solution 2 is much better than Solution 1.

Solution 4

A new one, probably an easiest of them all.

$(document).on('pagebeforeshow', '#index', function(){
    $(document).on('click', '#test-button',function(e) {
        if(e.handled !== true) // This will prevent event triggering more than once
        {
            alert('Clicked');
            e.handled = true;
        }
    });
});

Working jsFiddle example: http://jsfiddle.net/Gajotres/Yerv9/

Tnx to the sholsinger for this solution: http://sholsinger.com/archive/2011/08/prevent-jquery-live-handlers-from-firing-multiple-times/

pageChange event quirks - triggering twice

Sometimes pagechange event can trigger twice and it does not have anything to do with the problem mentioned before.

The reason the pagebeforechange event occurs twice is due to the recursive call in changePage when toPage is not a jQuery enhanced DOM object. This recursion is dangerous, as the developer is allowed to change the toPage within the event. If the developer consistently sets toPage to a string, within the pagebeforechange event handler, regardless of whether or not it was an object an infinite recursive loop will result. The pageload event passes the new page as the page property of the data object (This should be added to the documentation, it's not listed currently). The pageload event could therefore be used to access the loaded page.

In few words this is happening because you are sending additional parameters through pageChange.

Example:

<a data-role="button" data-icon="arrow-r" data-iconpos="right" href="#care-plan-view?id=9e273f31-2672-47fd-9baa-6c35f093a800&amp;name=Sat"><h3>Sat</h3></a>

To fix this problem use any page event listed in Page events transition order.

Page Change Times

As mentioned, when you change from one jQuery Mobile page to another, typically either through clicking on a link to another jQuery Mobile page that already exists in the DOM, or by manually calling $.mobile.changePage, several events and subsequent actions occur. At a high level the following actions occur:

  • A page change process is begun
  • A new page is loaded
  • The content for that page is “enhanced” (styled)
  • A transition (slide/pop/etc) from the existing page to the new page occurs

This is a average page transition benchmark:

Page load and processing: 3 ms

Page enhance: 45 ms

Transition: 604 ms

Total time: 670 ms

*These values are in milliseconds.

So as you can see a transition event is eating almost 90% of execution time.

Data/Parameters manipulation between page transitions

It is possible to send a parameter/s from one page to another during page transition. It can be done in few ways.

Reference: https://stackoverflow.com/a/13932240/1848600

Solution 1:

You can pass values with changePage:

$.mobile.changePage('page2.html', { dataUrl : "page2.html?paremeter=123", data : { 'paremeter' : '123' }, reloadPage : true, changeHash : true });

And read them like this:

$(document).on('pagebeforeshow', "#index", function (event, data) {
    var parameters = $(this).data("url").split("?")[1];;
    parameter = parameters.replace("parameter=","");
    alert(parameter);
});

Example:

index.html

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
  <html>_x000D_
    <head>_x000D_
    <meta charset="utf-8" />_x000D_
    <meta name="viewport" content="widdiv=device-widdiv, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />_x000D_
    <meta name="apple-mobile-web-app-capable" content="yes" />_x000D_
    <meta name="apple-mobile-web-app-status-bar-style" content="black" />_x000D_
    <title>_x000D_
    </title>_x000D_
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />_x000D_
    <script src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js">_x000D_
    </script>_x000D_
    <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>_x000D_
    <script>_x000D_
        $(document).on('pagebeforeshow', "#index",function () {_x000D_
            $(document).on('click', "#changePage",function () {_x000D_
                $.mobile.changePage('second.html', { dataUrl : "second.html?paremeter=123", data : { 'paremeter' : '123' }, reloadPage : false, changeHash : true });_x000D_
            });_x000D_
        });_x000D_
_x000D_
        $(document).on('pagebeforeshow', "#second",function () {_x000D_
            var parameters = $(this).data("url").split("?")[1];;_x000D_
            parameter = parameters.replace("parameter=","");_x000D_
            alert(parameter);_x000D_
        });_x000D_
    </script>_x000D_
   </head>_x000D_
   <body>_x000D_
    <!-- Home -->_x000D_
    <div data-role="page" id="index">_x000D_
        <div data-role="header">_x000D_
            <h3>_x000D_
                First Page_x000D_
            </h3>_x000D_
        </div>_x000D_
        <div data-role="content">_x000D_
          <a data-role="button" id="changePage">Test</a>_x000D_
        </div> <!--content-->_x000D_
    </div><!--page-->_x000D_
_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

second.html

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
  <html>_x000D_
    <head>_x000D_
    <meta charset="utf-8" />_x000D_
    <meta name="viewport" content="widdiv=device-widdiv, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />_x000D_
    <meta name="apple-mobile-web-app-capable" content="yes" />_x000D_
    <meta name="apple-mobile-web-app-status-bar-style" content="black" />_x000D_
    <title>_x000D_
    </title>_x000D_
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />_x000D_
    <script src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js">_x000D_
    </script>_x000D_
    <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>_x000D_
   </head>_x000D_
   <body>_x000D_
    <!-- Home -->_x000D_
    <div data-role="page" id="second">_x000D_
        <div data-role="header">_x000D_
            <h3>_x000D_
                Second Page_x000D_
            </h3>_x000D_
        </div>_x000D_
        <div data-role="content">_x000D_
_x000D_
        </div> <!--content-->_x000D_
    </div><!--page-->_x000D_
_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Solution 2:

Or you can create a persistent JavaScript object for a storage purpose. As long Ajax is used for page loading (and page is not reloaded in any way) that object will stay active.

var storeObject = {
    firstname : '',
    lastname : ''
}

Example: http://jsfiddle.net/Gajotres/9KKbx/

Solution 3:

You can also access data from the previous page like this:

$(document).on('pagebeforeshow', '#index',function (e, data) {
    alert(data.prevPage.attr('id'));
});

prevPage object holds a complete previous page.

Solution 4:

As a last solution we have a nifty HTML implementation of localStorage. It only works with HTML5 browsers (including Android and iOS browsers) but all stored data is persistent through page refresh.

if(typeof(Storage)!=="undefined") {
    localStorage.firstname="Dragan";
    localStorage.lastname="Gaic";
}

Example: http://jsfiddle.net/Gajotres/J9NTr/

Probably best solution but it will fail in some versions of iOS 5.X. It is a well know error.

Don’t Use .live() / .bind() / .delegate()

I forgot to mention (and tnx andleer for reminding me) use on/off for event binding/unbinding, live/die and bind/unbind are deprecated.

The .live() method of jQuery was seen as a godsend when it was introduced to the API in version 1.3. In a typical jQuery app there can be a lot of DOM manipulation and it can become very tedious to hook and unhook as elements come and go. The .live() method made it possible to hook an event for the life of the app based on its selector. Great right? Wrong, the .live() method is extremely slow. The .live() method actually hooks its events to the document object, which means that the event must bubble up from the element that generated the event until it reaches the document. This can be amazingly time consuming.

It is now deprecated. The folks on the jQuery team no longer recommend its use and neither do I. Even though it can be tedious to hook and unhook events, your code will be much faster without the .live() method than with it.

Instead of .live() you should use .on(). .on() is about 2-3x faster than .live(). Take a look at this event binding benchmark: http://jsperf.com/jquery-live-vs-delegate-vs-on/34, everything will be clear from there.

Benchmarking:

There's an excellent script made for jQuery Mobile page events benchmarking. It can be found here: https://github.com/jquery/jquery-mobile/blob/master/tools/page-change-time.js. But before you do anything with it I advise you to remove its alert notification system (each “change page” is going to show you this data by halting the app) and change it to console.log function.

Basically this script will log all your page events and if you read this article carefully (page events descriptions) you will know how much time jQm spent of page enhancements, page transitions ....

Final notes

Always, and I mean always read official jQuery Mobile documentation. It will usually provide you with needed information, and unlike some other documentation this one is rather good, with enough explanations and code examples.

Changes:

  • 30.01.2013 - Added a new method of multiple event triggering prevention
  • 31.01.2013 - Added a better clarification for chapter Data/Parameters manipulation between page transitions
  • 03.02.2013 - Added new content/examples to the chapter Data/Parameters manipulation between page transitions
  • 22.05.2013 - Added a solution for page transition/change prevention and added links to the official page events API documentation
  • 18.05.2013 - Added another solution against multiple event binding

Redirect form to different URL based on select option element

Just use a onchnage Event for select box.

<select id="selectbox" name="" onchange="javascript:location.href = this.value;">
    <option value="https://www.yahoo.com/" selected>Option1</option>
    <option value="https://www.google.co.in/">Option2</option>
    <option value="https://www.gmail.com/">Option3</option>

</select>

And if selected option to be loaded at the page load then add some javascript code

<script type="text/javascript">
    window.onload = function(){
        location.href=document.getElementById("selectbox").value;
    }       
</script>

for jQuery: Remove the onchange event from <select> tag

jQuery(function () {
    // remove the below comment in case you need chnage on document ready
    // location.href=jQuery("#selectbox").val(); 
    jQuery("#selectbox").change(function () {
        location.href = jQuery(this).val();
    })
})

How to Detect cause of 503 Service Temporarily Unavailable error and handle it?

There is of course some apache log files. Search in your apache configuration files for 'Log' keyword, you'll certainly find plenty of them. Depending on your OS and installation places may vary (in a Typical Linux server it would be /var/log/apache2/[access|error].log).

Having a 503 error in Apache usually means the proxied page/service is not available. I assume you're using tomcat and that means tomcat is either not responding to apache (timeout?) or not even available (down? crashed?). So chances are that it's a configuration error in the way to connect apache and tomcat or an application inside tomcat that is not even sending a response for apache.

Sometimes, in production servers, it can as well be that you get too much traffic for the tomcat server, apache handle more request than the proxyied service (tomcat) can accept so the backend became unavailable.

pandas resample documentation

B         business day frequency
C         custom business day frequency (experimental)
D         calendar day frequency
W         weekly frequency
M         month end frequency
SM        semi-month end frequency (15th and end of month)
BM        business month end frequency
CBM       custom business month end frequency
MS        month start frequency
SMS       semi-month start frequency (1st and 15th)
BMS       business month start frequency
CBMS      custom business month start frequency
Q         quarter end frequency
BQ        business quarter endfrequency
QS        quarter start frequency
BQS       business quarter start frequency
A         year end frequency
BA, BY    business year end frequency
AS, YS    year start frequency
BAS, BYS  business year start frequency
BH        business hour frequency
H         hourly frequency
T, min    minutely frequency
S         secondly frequency
L, ms     milliseconds
U, us     microseconds
N         nanoseconds

See the timeseries documentation. It includes a list of offsets (and 'anchored' offsets), and a section about resampling.

Note that there isn't a list of all the different how options, because it can be any NumPy array function and any function that is available via groupby dispatching can be passed to how by name.

Install php-zip on php 5.6 on Ubuntu

Try either

  • sudo apt-get install php-zip or
  • sudo apt-get install php5.6-zip

Then, you might have to restart your web server.

  • sudo service apache2 restart or
  • sudo service nginx restart

If you are installing on centos or fedora OS then use yum in place of apt-get. example:-

sudo yum install php-zip or sudo yum install php5.6-zip and sudo service httpd restart

Change "on" color of a Switch

Solution for Android Studio 3.6:

yourSwitch.setTextColor(getResources().getColor(R.color.yourColor));

Changes the text color of a in the color XML file defined value (yourColor).

What is a mixin, and why are they useful?

I think there have been some good explanations here but I wanted to provide another perspective.

In Scala, you can do mixins as has been described here but what is very interesting is that the mixins are actually 'fused' together to create a new kind of class to inherit from. In essence, you do not inherit from multiple classes/mixins, but rather, generate a new kind of class with all the properties of the mixin to inherit from. This makes sense since Scala is based on the JVM where multiple-inheritance is not currently supported (as of Java 8). This mixin class type, by the way, is a special type called a Trait in Scala.

It's hinted at in the way a class is defined: class NewClass extends FirstMixin with SecondMixin with ThirdMixin ...

I'm not sure if the CPython interpreter does the same (mixin class-composition) but I wouldn't be surprised. Also, coming from a C++ background, I would not call an ABC or 'interface' equivalent to a mixin -- it's a similar concept but divergent in use and implementation.

Proper way to wait for one function to finish before continuing?

The only issue with promises is that IE doesn't support them. Edge does, but there's plenty of IE 10 and 11 out there: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise (compatibility at the bottom)

So, JavaScript is single-threaded. If you're not making an asynchronous call, it will behave predictably. The main JavaScript thread will execute one function completely before executing the next one, in the order they appear in the code. Guaranteeing order for synchronous functions is trivial - each function will execute completely in the order it was called.

Think of the synchronous function as an atomic unit of work. The main JavaScript thread will execute it fully, in the order the statements appear in the code.

But, throw in the asynchronous call, as in the following situation:

showLoadingDiv(); // function 1

makeAjaxCall(); // function 2 - contains async ajax call

hideLoadingDiv(); // function 3

This doesn't do what you want. It instantaneously executes function 1, function 2, and function 3. Loading div flashes and it's gone, while the ajax call is not nearly complete, even though makeAjaxCall() has returned. THE COMPLICATION is that makeAjaxCall() has broken its work up into chunks which are advanced little by little by each spin of the main JavaScript thread - it's behaving asychronously. But that same main thread, during one spin/run, executed the synchronous portions quickly and predictably.

So, the way I handled it: Like I said the function is the atomic unit of work. I combined the code of function 1 and 2 - I put the code of function 1 in function 2, before the asynch call. I got rid of function 1. Everything up to and including the asynchronous call executes predictably, in order.

THEN, when the asynchronous call completes, after several spins of the main JavaScript thread, have it call function 3. This guarantees the order. For example, with ajax, the onreadystatechange event handler is called multiple times. When it reports it's completed, then call the final function you want.

I agree it's messier. I like having code be symmetric, I like having functions do one thing (or close to it), and I don't like having the ajax call in any way be responsible for the display (creating a dependency on the caller). BUT, with an asynchronous call embedded in a synchronous function, compromises have to be made in order to guarantee order of execution. And I have to code for IE 10 so no promises.

Summary: For synchronous calls, guaranteeing order is trivial. Each function executes fully in the order it was called. For a function with an asynchronous call, the only way to guarantee order is to monitor when the async call completes, and call the third function when that state is detected.

For a discussion of JavaScript threads, see: https://medium.com/@francesco_rizzi/javascript-main-thread-dissected-43c85fce7e23 and https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop

Also, another similar, highly rated question on this subject: How should I call 3 functions in order to execute them one after the other?

Table with table-layout: fixed; and how to make one column wider

What you could do is something like this (pseudocode):

<container table>
  <tr>
    <td>
      <"300px" table>
    <td>
      <fixed layout table>

Basically, split up the table into two tables and have it contained by another table.

Import SQL dump into PostgreSQL database

I use:

cat /home/path/to/dump/file | psql -h localhost -U <user_name> -d <db_name>

Hope this will help someone.

How to remove button shadow (android)

the @Alt-Cat answer work for me!

R.attr.borderlessButtonStyle doesn't contain shadow.

and the document of button is great.

Also, you can set this style on your custom button, in second constructor.

    public CustomButton(Context context, AttributeSet attrs) {
        this(context, attrs, R.attr.borderlessButtonStyle);
    }

How do I fire an event when a iframe has finished loading in jQuery?

If you can expect the browser's open/save interface to pop up for the user once the download is complete, then you can run this when you start the download:

$( document ).blur( function () {
    // Your code here...
});

When the dialogue pops up on top of the page, the blur event will trigger.

How to split a python string on new line characters

a.txt

this is line 1
this is line 2

code:

Python 3.4.0 (default, Mar 20 2014, 22:43:40) 
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> file = open('a.txt').read()
>>> file
>>> file.split('\n')
['this is line 1', 'this is line 2', '']

I'm on Linux, but I guess you just use \r\n on Windows and it would also work

How to read values from properties file?

I wanted an utility class which is not managed by spring, so no spring annotations like @Component, @Configuration etc. But I wanted the class to read from application.properties

I managed to get it working by getting the class to be aware of the Spring Context, hence is aware of Environment, and hence environment.getProperty() works as expected.

To be explicit, I have:

application.properties

mypath=somestring

Utils.java

import org.springframework.core.env.Environment;

// No spring annotations here
public class Utils {
    public String execute(String cmd) {
        // Making the class Spring context aware
        ApplicationContextProvider appContext = new ApplicationContextProvider();
        Environment env = appContext.getApplicationContext().getEnvironment();

        // env.getProperty() works!!!
        System.out.println(env.getProperty("mypath")) 
    }
}

ApplicationContextProvider.java (see Spring get current ApplicationContext)

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class ApplicationContextProvider implements ApplicationContextAware {
    private static ApplicationContext CONTEXT;

    public ApplicationContext getApplicationContext() {
        return CONTEXT;
    }

    public void setApplicationContext(ApplicationContext context) throws BeansException {
        CONTEXT = context;
    }

    public static Object getBean(String beanName) {
        return CONTEXT.getBean(beanName);
    }
}

Android SDK manager won't open

I installed Android Studio for Mac. I was not able to access the SDK manager through the IDE. It turns out I just had to have my JAVA_HOME environment variable set. Once I got this set I was able to launch the SDK manager.

Best way to convert list to comma separated string in java

You could count the total length of the string first, and pass it to the StringBuilder constructor. And you do not need to convert the Set first.

Set<String> abc = new HashSet<String>();
abc.add("A");
abc.add("B");
abc.add("C");

String separator = ", ";
int total = abc.size() * separator.length();
for (String s : abc) {
    total += s.length();
}

StringBuilder sb = new StringBuilder(total);
for (String s : abc) {
    sb.append(separator).append(s);
}

String result = sb.substring(separator.length()); // remove leading separator

getting the X/Y coordinates of a mouse click on an image with jQuery

You can use pageX and pageY to get the position of the mouse in the window. You can also use jQuery's offset to get the position of an element.

So, it should be pageX - offset.left for how far from the left of the image and pageY - offset.top for how far from the top of the image.

Here is an example:

$(document).ready(function() {
  $('img').click(function(e) {
    var offset = $(this).offset();
    alert(e.pageX - offset.left);
    alert(e.pageY - offset.top);
  });
});

I've made a live example here and here is the source.

To calculate how far from the bottom or right, you would have to use jQuery's width and height methods.

How to set tbody height with overflow scroll

Webkit seems to use internally display: table-row-group for the tbody tag. There is currently a bug with setting height to it: https://github.com/w3c/csswg-drafts/issues/476

Let's hope it will be solved soon.

MySQL - Trigger for updating same table after insert

Had the same problem but had to update a column with the id that was about to enter, so you can make an update should be done BEFORE and AFTER not BEFORE had no id so I did this trick

DELIMITER $$
DROP TRIGGER IF EXISTS `codigo_video`$$
CREATE TRIGGER `codigo_video` BEFORE INSERT ON `videos` 
FOR EACH ROW BEGIN
    DECLARE ultimo_id, proximo_id INT(11);
    SELECT id INTO ultimo_id FROM videos ORDER BY id DESC LIMIT 1;
    SET proximo_id = ultimo_id+1;
    SET NEW.cassette = CONCAT(NEW.cassette, LPAD(proximo_id, 5, '0'));
END$$
DELIMITER ;

Disable elastic scrolling in Safari

None of the 'overflow' solutions worked for me. I'm coding a parallax effect with JavaScript using jQuery. In Chrome and Safari on OSX the elastic/rubber-band effect was messing up my scroll numbers, since it actually scrolls past the document's height and updates the window variables with out-of-boundary numbers. What I had to do was check if the scrolled amount was larger than the actual document's height, like so:

$(window).scroll(
    function() {
        if ($(window).scrollTop() + $(window).height() > $(document).height()) return;
        updateScroll(); // my own function to do my parallaxing stuff
    }
);

How to subtract X day from a Date object in Java?

Simply use this to get date before 300 days, replace 300 with your days:

Date date = new Date(); // Or where ever you get it from
Date daysAgo = new DateTime(date).minusDays(300).toDate();

Here,

DateTime is org.joda.time.DateTime;

Date is java.util.Date

Which to use <div class="name"> or <div id="name">?

ID's must be unique (only be given to one element in the DOM at a time), whereas classes don't have to be. You've already discovered the CSS . class and # ID prefixes, so that's pretty much it.

How do I autoindent in Netbeans?

If you want auto-indent just like Emacs does it on TAB, i.e. indent the current line and move the cursor to the first non-whitespace character, do this:

  1. Go to Tools -> Options -> Editor -> Macros
  2. Create a new macro and call it something like "tabindent"
  3. Insert the following macro code:

    reindent-line caret-line-first-column caret-begin-line

  4. Click "Set Shortcut" and press TAB

Error #2032: Stream Error

Just to clarify my comment (it's illegible in a single line)

I think the best answer is the comment by Mike Chambers in this link (http://www.judahfrangipane.com/blog/2007/02/15/error-2032-stream-error/) by Hunter McMillen.

A note from Mike Chambers:

If you run into this using URLLoader, listen for the:

flash.events.HTTPStatusEvent.HTTP_STATUS

and in AIR :

flash.events.HTTPStatusEvent.HTTP_RESPONSE_STATUS

It should give you some more information (such as the status code being returned from the server).

Angular: How to download a file from HttpClient?

It took me a while to implement the other responses, as I'm using Angular 8 (tested up to 10). I ended up with the following code (heavily inspired by Hasan).

Note that for the name to be set, the header Access-Control-Expose-Headers MUST include Content-Disposition. To set this in django RF:

http_response = HttpResponse(package, content_type='application/javascript')
http_response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
http_response['Access-Control-Expose-Headers'] = "Content-Disposition"

In angular:

  // component.ts
  // getFileName not necessary, you can just set this as a string if you wish
  getFileName(response: HttpResponse<Blob>) {
    let filename: string;
    try {
      const contentDisposition: string = response.headers.get('content-disposition');
      const r = /(?:filename=")(.+)(?:")/
      filename = r.exec(contentDisposition)[1];
    }
    catch (e) {
      filename = 'myfile.txt'
    }
    return filename
  }

  
  downloadFile() {
    this._fileService.downloadFile(this.file.uuid)
      .subscribe(
        (response: HttpResponse<Blob>) => {
          let filename: string = this.getFileName(response)
          let binaryData = [];
          binaryData.push(response.body);
          let downloadLink = document.createElement('a');
          downloadLink.href = window.URL.createObjectURL(new Blob(binaryData, { type: 'blob' }));
          downloadLink.setAttribute('download', filename);
          document.body.appendChild(downloadLink);
          downloadLink.click();
        }
      )
  }

  // service.ts
  downloadFile(uuid: string) {
    return this._http.get<Blob>(`${environment.apiUrl}/api/v1/file/${uuid}/package/`, { observe: 'response', responseType: 'blob' as 'json' })
  }

Android - Activity vs FragmentActivity?

ianhanniballake is right. You can get all the functionality of Activity from FragmentActivity. In fact, FragmentActivity has more functionality.

Using FragmentActivity you can easily build tab and swap format. For each tab you can use different Fragment (Fragments are reusable). So for any FragmentActivity you can reuse the same Fragment.

Still you can use Activity for single pages like list down something and edit element of the list in next page.

Also remember to use Activity if you are using android.app.Fragment; use FragmentActivity if you are using android.support.v4.app.Fragment. Never attach a android.support.v4.app.Fragment to an android.app.Activity, as this will cause an exception to be thrown.

Iterating through a golang map

You could just write it out in multiline like this,

$ cat dict.go
package main

import "fmt"

func main() {
        items := map[string]interface{}{
                "foo": map[string]int{
                        "strength": 10,
                        "age": 2000,
                },
                "bar": map[string]int{
                        "strength": 20,
                        "age": 1000,
                },
        }
        for key, value := range items {
                fmt.Println("[", key, "] has items:")
                for k,v := range value.(map[string]int) {
                        fmt.Println("\t-->", k, ":", v)
                }

        }
}

And the output:

$ go run dict.go
[ foo ] has items:
        --> strength : 10
        --> age : 2000
[ bar ] has items:
        --> strength : 20
        --> age : 1000

Base64 Decoding in iOS 7+

In case you want to write fallback code, decoding from base64 has been present in iOS since the very beginning by caveat of NSURL:

NSURL *URL = [NSURL URLWithString:
      [NSString stringWithFormat:@"data:application/octet-stream;base64,%@",
           base64String]];

return [NSData dataWithContentsOfURL:URL];

How to redirect to a 404 in Rails?

The selected answer doesn't work in Rails 3.1+ as the error handler was moved to a middleware (see github issue).

Here's the solution I found which I'm pretty happy with.

In ApplicationController:

  unless Rails.application.config.consider_all_requests_local
    rescue_from Exception, with: :handle_exception
  end

  def not_found
    raise ActionController::RoutingError.new('Not Found')
  end

  def handle_exception(exception=nil)
    if exception
      logger = Logger.new(STDOUT)
      logger.debug "Exception Message: #{exception.message} \n"
      logger.debug "Exception Class: #{exception.class} \n"
      logger.debug "Exception Backtrace: \n"
      logger.debug exception.backtrace.join("\n")
      if [ActionController::RoutingError, ActionController::UnknownController, ActionController::UnknownAction].include?(exception.class)
        return render_404
      else
        return render_500
      end
    end
  end

  def render_404
    respond_to do |format|
      format.html { render template: 'errors/not_found', layout: 'layouts/application', status: 404 }
      format.all { render nothing: true, status: 404 }
    end
  end

  def render_500
    respond_to do |format|
      format.html { render template: 'errors/internal_server_error', layout: 'layouts/application', status: 500 }
      format.all { render nothing: true, status: 500}
    end
  end

and in application.rb:

config.after_initialize do |app|
  app.routes.append{ match '*a', :to => 'application#not_found' } unless config.consider_all_requests_local
end

And in my resources (show, edit, update, delete):

@resource = Resource.find(params[:id]) or not_found

This could certainly be improved, but at least, I have different views for not_found and internal_error without overriding core Rails functions.

how to access downloads folder in android?

If you're using a shell, the filepath to the Download (no "s") folder is

/storage/emulated/0/Download

How to convert int[] to Integer[] in Java?

Simply use:

public static int[] intArrayToIntegerArray(int[] a) {
    Integer[] b = new Integer[a.length];
    for(int i = 0; i < array.length; i++){
        b[i] = a[i];
    }
    return g;
}

Change the encoding of a file in Visual Studio Code

The existing answers show a possible solution for single files or file types. However, you can define the charset standard in VS Code by following this path:

File > Preferences > Settings > Encoding > Choose your option

This will define a character set as default. Besides that, you can always change the encoding in the lower right corner of the editor (blue symbol line) for the current project.

How to set the allowed url length for a nginx request (error code: 414, uri too large)

From: http://nginx.org/r/large_client_header_buffers

Syntax: large_client_header_buffers number size ;
Default: large_client_header_buffers 4 8k;
Context: http, server

Sets the maximum number and size of buffers used for reading large client request header. A request line cannot exceed the size of one buffer, or the 414 (Request-URI Too Large) error is returned to the client. A request header field cannot exceed the size of one buffer as well, or the 400 (Bad Request) error is returned to the client. Buffers are allocated only on demand. By default, the buffer size is equal to 8K bytes. If after the end of request processing a connection is transitioned into the keep-alive state, these buffers are released.

so you need to change the size parameter at the end of that line to something bigger for your needs.

'sprintf': double precision in C

The problem is with sprintf

sprintf(aa,"%lf",a);

%lf says to interpet "a" as a "long double" (16 bytes) but it is actually a "double" (8 bytes). Use this instead:

sprintf(aa, "%f", a);

More details here on cplusplus.com

R define dimensions of empty data frame

If only the column names are available like :

cnms <- c("Nam1","Nam2","Nam3")

To create an empty data frame with the above variable names, first create a data.frame object:

emptydf <- data.frame()

Now call zeroth element of every column, thus creating an empty data frame with the given variable names:

for( i in 1:length(cnms)){
     emptydf[0,eval(cnms[i])]
 }

Html5 Full screen video

You can do it with jQuery.

I have my video and controls in their own <div> like this:

<div id="videoPlayer" style="width:520px; -webkit-border-radius:10px; height:420px; background-color:white; position:relative; float:left; left:25px; top:55px;" align="center">

    <video controls width="500" height="400" style="background-color:black; margin-top:10px; -webkit-border-radius:10px;">
         <source src="videos/gin.mp4" type="video/mp4" />
    </video>

    <script>  
        video.removeAttribute('controls');  
    </script> 

    <div id="vidControls" style="position:relative; width:100%; height:50px; background-color:white; -webkit-border-bottom-left-radius:10px; -webkit-border-bottom-right-radius:10px; padding-top:10px; padding-bottom:10px;">

         <table width="100%" height="100%" border="0">

             <tr>
                 <td width="100%" align="center" valign="middle" colspan="4"><input class="vidPos" type="range" value="0" step="0.1" style="width:500px;" /></td>
             </tr>

             <tr>
                 <td width="100%" align="center" valign="middle"><a href="javascript:;" class="playVid">Play</a></td>
                 <td width="100%" align="center" valign="middle"><a href="javascript:;" class="vol">Vol</a></td>
                 <td width="100%" align="left" valign="middle"><p class="timer"><strong>0:00</strong> / 0:00</p></td>
                 <td width="100%" align="center" valign="middle"><a href="javascript:;" class="fullScreen">Full</a></td>
              </tr>

            </table>

         </div>

      </div>

And then my jQuery for the .fullscreen class is:

var fullscreen = 0;

$(".fullscreen").click(function(){
  if(fullscreen == 0){
    fullscreen = 1;
    $("video").appendTo('body');
    $("#vidControls").appendTo('body');
    $("video").css('position', 'absolute').css('width', '100%').css('height', '90%').css('margin', 0).css('margin-top', '5%').css('top', '0').css('left', '0').css('float', 'left').css('z-index', 600);
    $("#vidControls").css('position', 'absolute').css('bottom', '5%').css('width', '90%').css('backgroundColor', 'rgba(150, 150, 150, 0.5)').css('float', 'none').css('left', '5%').css('z-index', 700).css('-webkit-border-radius', '10px');

}
else
    {

        fullscreen = 0;

        $("video").appendTo('#videoPlayer');
        $("#vidControls").appendTo('#videoPlayer');

        //change <video> css back to normal

        //change "#vidControls" css back to normal

    }

});

It needs a little cleaning up as I'm still working on it but that should work for most browsers as far as I can see.

Hope it helps!

How to use SQL Order By statement to sort results case insensitive?

You can just convert everything to lowercase for the purposes of sorting:

SELECT * FROM NOTES ORDER BY LOWER(title);

If you want to make sure that the uppercase ones still end up ahead of the lowercase ones, just add that as a secondary sort:

SELECT * FROM NOTES ORDER BY LOWER(title), title;

Add Whatsapp function to website, like sms, tel

Rahul's answer gives me an error: You seem to be trying to send a WhatsApp message to a phone number that is not registered with WhatsApp..., even though I'm sending it to a registered WhatsApp number.

This, however works:

<li><a href="intent:0123456789#Intent;scheme=smsto;package=com.whatsapp;action=android.intent.action.SENDTO;end"><i class="fa fa-whatsapp"></i>+237 655 421 621</li>

Convert varchar to uniqueidentifier in SQL Server

It would make for a handy function. Also, note I'm using STUFF instead of SUBSTRING.

create function str2uniq(@s varchar(50)) returns uniqueidentifier as begin
    -- just in case it came in with 0x prefix or dashes...
    set @s = replace(replace(@s,'0x',''),'-','')
    -- inject dashes in the right places
    set @s = stuff(stuff(stuff(stuff(@s,21,0,'-'),17,0,'-'),13,0,'-'),9,0,'-')
    return cast(@s as uniqueidentifier)
end

Clang vs GCC - which produces faster binaries?

There is very little overall difference between GCC 4.8 and clang 3.3 in terms of speed of the resulting binary. In most cases code generated by both compilers performs similarly. Neither of these two compilers dominates the other one.

Benchmarks telling that there is a significant performance gap between GCC and clang are coincidental.

Program performance is affected by the choice of the compiler. If a developer or a group of developers is exclusively using GCC then the program can be expected to run slightly faster with GCC than with clang, and vice versa.

From developer viewpoint, a notable difference between GCC 4.8+ and clang 3.3 is that GCC has the -Og command line option. This option enables optimizations that do not interfere with debugging, so for example it is always possible to get accurate stack traces. The absence of this option in clang makes clang harder to use as an optimizing compiler for some developers.

Java - get index of key in HashMap?

The HashMap has no defined ordering of keys.

How do I concatenate a boolean to a string in Python?

answer = True

myvar = 'the answer is ' + str(answer) #since answer variable is in boolean format, therefore, we have to convert boolean into string format which can be easily done using this

print(myvar)

How to make Unicode charset in cmd.exe by default?

Save the following into a file with ".reg" suffix:

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Console\%SystemRoot%_system32_cmd.exe]
"CodePage"=dword:0000fde9

Double click this file, and regedit will import it.

It basically sets the key HKEY_CURRENT_USER\Console\%SystemRoot%_system32_cmd.exe\CodePage to 0xfde9 (65001 in decimal system).

Rotating a view in Android

Joininig @Rudi's and @Pete's answers. I have created an RotateAnimation that keeps buttons functionality also after rotation.

setRotation() method preserves buttons functionality.

Code Sample:

Animation an = new RotateAnimation(0.0f, 180.0f, mainLayout.getWidth()/2, mainLayout.getHeight()/2);

    an.setDuration(1000);              
    an.setRepeatCount(0);                     
    an.setFillAfter(false);              // DO NOT keep rotation after animation
    an.setFillEnabled(true);             // Make smooth ending of Animation
    an.setAnimationListener(new AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {}

        @Override
        public void onAnimationRepeat(Animation animation) {}

        @Override
        public void onAnimationEnd(Animation animation) {
                mainLayout.setRotation(180.0f);      // Make instant rotation when Animation is finished
            }
            }); 

mainLayout.startAnimation(an);

mainLayout is a (LinearLayout) field

How to check compiler log in sql developer?

control-shift-L should open the log(s) for you. this will by default be the messages log, but if you create the item that is creating the error the Compiler Log will show up (for me the box shows up in the bottom middle left).

if the messages log is the only log that shows up, simply re-execute the item that was causing the failure and the compiler log will show up

for instance, hit Control-shift-L then execute this

CREATE OR REPLACE FUNCTION TEST123() IS
BEGIN
VAR := 2;
end TEST123;

and you will see the message "Error(1,18): PLS-00103: Encountered the symbol ")" when expecting one of the following: current delete exists prior "

(You can also see this in "View--Log")

One more thing, if you are having a problem with a (function || package || procedure) if you do the coding via the SQL Developer interface (by finding the object in question on the connections tab and editing it the error will be immediately displayed (and even underlined at times)

How do I use NSTimer?

The answers are missing a specific time of day timer here is on the next hour:

NSCalendarUnit allUnits = NSCalendarUnitYear   | NSCalendarUnitMonth |
                          NSCalendarUnitDay    | NSCalendarUnitHour  |
                          NSCalendarUnitMinute | NSCalendarUnitSecond;

NSCalendar *calendar = [[ NSCalendar alloc]  
                          initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponents *weekdayComponents = [calendar components: allUnits 
                                                  fromDate: [ NSDate date ] ];

[ weekdayComponents setHour: weekdayComponents.hour + 1 ];
[ weekdayComponents setMinute: 0 ];
[ weekdayComponents setSecond: 0 ];

NSDate *nextTime = [ calendar dateFromComponents: weekdayComponents ];

refreshTimer = [[ NSTimer alloc ] initWithFireDate: nextTime
                                          interval: 0.0
                                            target: self
                                          selector: @selector( doRefresh )
                                          userInfo: nil repeats: NO ];

[[NSRunLoop currentRunLoop] addTimer: refreshTimer forMode: NSDefaultRunLoopMode];

Of course, substitute "doRefresh" with your class's desired method

try to create the calendar object once and make the allUnits a static for efficiency.

adding one to hour component works just fine, no need for a midnight test (link)

How do I set an absolute include path in PHP?

Not directly answering your question but something to remember:

When using includes with allow_url_include on in your ini beware that, when accessing sessions from included files, if from a script you include one file using an absolute file reference and then include a second file from on your local server using a url file reference that they have different variable scope and the same session will not be seen from both included files. The original session won't be seen from the url included file.

from: http://us2.php.net/manual/en/function.include.php#84052

How can I sort one set of data to match another set of data in Excel?

You could also simply link both cells, and have an =Cell formula in each column like, =Sheet2!A2 in Sheet 1 A2 and =Sheet2!B2 in Sheet 1 B2, and drag it down, and then sort those two columns the way you want.

  • If they don't sort the way you want, put the order you want to sort them in another column and sort all three columns by that.
  • If you drag it down further and get zeros you can edit the =Cell formula to show "" IF there is nothing. =(if(cell="","",cell)
  • Cutting, pasting, deleting, and inserting rows is something to be weary of. #REF! errors could occur.

This would be better if your unique items change also, then all you would do is sort and be done.

Two divs side by side - Fluid display

This is easy with a flexbox:

_x000D_
_x000D_
#wrapper {_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
#left {_x000D_
  flex: 0 0 65%;_x000D_
}_x000D_
_x000D_
#right {_x000D_
  flex: 1;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
  <div id="left">Left side div</div>_x000D_
  <div id="right">Right side div</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is the difference between Promises and Observables?

Promises

  1. Definition: Helps you run functions asynchronously, and use their return values (or exceptions) but only once when executed.
  2. Not Lazy
  3. Not cancellable( There are Promise libraries out there that support cancellation, but ES6 Promise doesn't so far). The two possible decisions are
    • Reject
    • Resolve
  4. Cannot be retried(Promises should have access to the original function that returned the promise to have a retry capability, which is a bad practice)

Observables

  1. Definition: Helps you run functions asynchronously, and use their return values in a continuous sequence(multiple times) when executed.
  2. By default, it is Lazy as it emits values when time progresses.
  3. Has a lot of operators which simplifies the coding effort.
  4. One operator retry can be used to retry whenever needed, also if we need to retry the observable based on some conditions retryWhen can be used.

    Note: A list of operators along with their interactive diagrams is available here at RxMarbles.com

How many significant digits do floats and doubles have in java?

A 32-bit float has about 7 digits of precision and a 64-bit double has about 16 digits of precision

Long answer:

Floating-point numbers have three components:

  1. A sign bit, to determine if the number is positive or negative.
  2. An exponent, to determine the magnitude of the number.
  3. A fraction, which determines how far between two exponent values the number is. This is sometimes called “the significand, mantissa, or coefficient”

Essentially, this works out to sign * 2^exponent * (1 + fraction). The “size” of the number, it’s exponent, is irrelevant to us, because it only scales the value of the fraction portion. Knowing that log10(n) gives the number of digits of n,† we can determine the precision of a floating point number with log10(largest_possible_fraction). Because each bit in a float stores 2 possibilities, a binary number of n bits can store a number up to 2n - 1 (a total of 2n values where one of the values is zero). This gets a bit hairier, because it turns out that floating point numbers are stored with one less bit of fraction than they can use, because zeroes are represented specially and all non-zero numbers have at least one non-zero binary bit.‡

Combining this, the digits of precision for a floating point number is log10(2n), where n is the number of bits of the floating point number’s fraction. A 32-bit float has 24 bits of fraction for ˜7.22 decimal digits of precision, and a 64-bit double has 53 bits of fraction for ˜15.95 decimal digits of precision.

For more on floating point accuracy, you might want to read about the concept of a machine epsilon.


† For n = 1 at least — for other numbers your formula will look more like ?log10(|n|)? + 1.

‡ “This rule is variously called the leading bit convention, the implicit bit convention, or the hidden bit convention.” (Wikipedia)

What is a raw type and why shouldn't we use it?

What are raw types in Java, and why do I often hear that they shouldn't be used in new code?

Raw-types are ancient history of the Java language. In the beginning there were Collections and they held Objects nothing more and nothing less. Every operation on Collections required casts from Object to the desired type.

List aList = new ArrayList();
String s = "Hello World!";
aList.add(s);
String c = (String)aList.get(0);

While this worked most of the time, errors did happen

List aNumberList = new ArrayList();
String one = "1";//Number one
aNumberList.add(one);
Integer iOne = (Integer)aNumberList.get(0);//Insert ClassCastException here

The old typeless collections could not enforce type-safety so the programmer had to remember what he stored within a collection.
Generics where invented to get around this limitation, the developer would declare the stored type once and the compiler would do it instead.

List<String> aNumberList = new ArrayList<String>();
aNumberList.add("one");
Integer iOne = aNumberList.get(0);//Compile time error
String sOne = aNumberList.get(0);//works fine

For Comparison:

// Old style collections now known as raw types
List aList = new ArrayList(); //Could contain anything
// New style collections with Generics
List<String> aList = new ArrayList<String>(); //Contains only Strings

More complex the Compareable interface:

//raw, not type save can compare with Other classes
class MyCompareAble implements CompareAble
{
   int id;
   public int compareTo(Object other)
   {return this.id - ((MyCompareAble)other).id;}
}
//Generic
class MyCompareAble implements CompareAble<MyCompareAble>
{
   int id;
   public int compareTo(MyCompareAble other)
   {return this.id - other.id;}
}

Note that it is impossible to implement the CompareAble interface with compareTo(MyCompareAble) with raw types. Why you should not use them:

  • Any Object stored in a Collection has to be cast before it can be used
  • Using generics enables compile time checks
  • Using raw types is the same as storing each value as Object

What the compiler does: Generics are backward compatible, they use the same java classes as the raw types do. The magic happens mostly at compile time.

List<String> someStrings = new ArrayList<String>();
someStrings.add("one");
String one = someStrings.get(0);

Will be compiled as:

List someStrings = new ArrayList();
someStrings.add("one"); 
String one = (String)someStrings.get(0);

This is the same code you would write if you used the raw types directly. Thought I'm not sure what happens with the CompareAble interface, I guess that it creates two compareTo functions, one taking a MyCompareAble and the other taking an Object and passing it to the first after casting it.

What are the alternatives to raw types: Use generics

Why ModelState.IsValid always return false in mvc

Please post your Model Class.

To check the errors in your ModelState use the following code:

var errors = ModelState
    .Where(x => x.Value.Errors.Count > 0)
    .Select(x => new { x.Key, x.Value.Errors })
    .ToArray();

OR: You can also use

var errors = ModelState.Values.SelectMany(v => v.Errors);

Place a break point at the above line and see what are the errors in your ModelState.

copy-item With Alternate Credentials

Here is a post where someone got it to work. It looks like it requires a registry change.

Actual meaning of 'shell=True' in subprocess

let's assume you are using shell=False and providing the command as a list. And some malicious user tried injecting an 'rm' command. You will see, that 'rm' will be interpreted as an argument and effectively 'ls' will try to find a file called 'rm'

>>> subprocess.run(['ls','-ld','/home','rm','/etc/passwd'])
ls: rm: No such file or directory
-rw-r--r--    1 root     root          1172 May 28  2020 /etc/passwd
drwxr-xr-x    2 root     root          4096 May 29  2020 /home
CompletedProcess(args=['ls', '-ld', '/home', 'rm', '/etc/passwd'], returncode=1)

shell=False is not a secure by default, if you don't control the input properly. You can still execute dangerous commands.

>>> subprocess.run(['rm','-rf','/home'])
CompletedProcess(args=['rm', '-rf', '/home'], returncode=0)
>>> subprocess.run(['ls','-ld','/home'])
ls: /home: No such file or directory
CompletedProcess(args=['ls', '-ld', '/home'], returncode=1)
>>>

I am writing most of my applications in container environments, I know which shell is being invoked and i am not taking any user input.

So in my use case, I see no security risk. And it is much easier creating long string of commands. Hope I am not wrong.

Adding +1 to a variable inside a function

You could also pass points to the function: Small example:

def test(points):
    addpoint = raw_input ("type ""add"" to add a point")
    if addpoint == "add":
        points = points + 1
    else:
        print "asd"
    return points;
if __name__ == '__main__':
    points = 0
    for i in range(10):
        points = test(points)
        print points

How to select lines between two marker patterns which may occur multiple times with awk/sed

perl -lne 'print if((/abc/../mno/) && !(/abc/||/mno/))' your_file

jQuery's .click - pass parameters to user function

For thoroughness, I came across another solution which was part of the functionality introduced in version 1.4.3 of the jQuery click event handler.

It allows you to pass a data map to the event object that automatically gets fed back to the event handler function by jQuery as the first parameter. The data map would be handed to the .click() function as the first parameter, followed by the event handler function.

Here's some code to illustrate what I mean:

// say your selector and click handler looks something like this...
$("some selector").click({param1: "Hello", param2: "World"}, cool_function);

// in your function, just grab the event object and go crazy...
function cool_function(event){
    alert(event.data.param1);
    alert(event.data.param2);
}

I know it's late in the game for this question, but the previous answers led me to this solution, so I hope it helps someone sometime!

How to select the first row for each group in MySQL?

Select the first row for each group (as ordered by a column) in Mysql .

We have:

a table: mytable
a column we are ordering by: the_column_to_order_by
a column that we wish to group by: the_group_by_column

Here's my solution. The inner query gets you a unique set of rows, selected as a dual key. The outer query joins the same table by joining on both of those keys (with AND).

SELECT * FROM 
    ( 
        SELECT the_group_by_column, MAX(the_column_to_order_by) the_column_to_order_by 
        FROM mytable 
        GROUP BY the_group_by_column 
        ORDER BY MAX(the_column_to_order_by) DESC 
    ) as mytable1 
JOIN mytable mytable2 ON mytable2.the_group_by_column = 
mytablealiamytable2.the_group_by_column 
  AND mytable2.the_column_to_order_by = mytable1.the_column_to_order_by;

FYI: I haven't thought about efficiency at all for this and can't speak to that one way or the other.

Location Services not working in iOS 8

The problem for me was that the class that was the CLLocationManagerDelegate was private, which prevented all the delegate methods from being called. Guess it's not a very common situation but thought I'd mention it in case t helps anyone.

Build Step Progress Bar (css and jquery)

This is how I have achieved it using purely CSS and HTML (no JavaScript/images etc.).

http://jsfiddle.net/tuPrn/

It gracefully degrades in most browsers (I do need to add in a fix for lack of last-of-type in < IE9).

How do I use 'git reset --hard HEAD' to revert to a previous commit?

WARNING: git clean -f will remove untracked files, meaning they're gone for good since they aren't stored in the repository. Make sure you really want to remove all untracked files before doing this.


Try this and see git clean -f.

git reset --hard will not remove untracked files, where as git-clean will remove any files from the tracked root directory that are not under Git tracking.

Alternatively, as @Paul Betts said, you can do this (beware though - that removes all ignored files too)

  • git clean -df
  • git clean -xdf CAUTION! This will also delete ignored files

How to set selected index JComboBox by value

The right way to set an item selected when the combobox is populated by some class' constructor (as @milosz posted):

combobox.getModel().setSelectedItem(new ClassName(parameter1, parameter2));

In your case the code would be:

test.getModel().setSelectedItem(new ComboItem(3, "banana"));

Propagate all arguments in a bash shell script

Use "$@" instead of plain $@ if you actually wish your parameters to be passed the same.

Observe:

$ cat no_quotes.sh
#!/bin/bash
echo_args.sh $@

$ cat quotes.sh
#!/bin/bash
echo_args.sh "$@"

$ cat echo_args.sh
#!/bin/bash
echo Received: $1
echo Received: $2
echo Received: $3
echo Received: $4

$ ./no_quotes.sh first second
Received: first
Received: second
Received:
Received:

$ ./no_quotes.sh "one quoted arg"
Received: one
Received: quoted
Received: arg
Received:

$ ./quotes.sh first second
Received: first
Received: second
Received:
Received:

$ ./quotes.sh "one quoted arg"
Received: one quoted arg
Received:
Received:
Received:

How to set full calendar to a specific start date when it's initialized for the 1st time?

You have it backwards. Display the calendar first, and then call gotoDate.

$('#calendar').fullCalendar({
  // Options
});

$('#calendar').fullCalendar('gotoDate', currentDate);

What is the inclusive range of float and double in Java?

Java's Double class has members containing the Min and Max value for the type.

2^-1074 <= x <= (2-2^-52)·2^1023 // where x is the double.

Check out the Min_VALUE and MAX_VALUE static final members of Double.

(some)People will suggest against using floating point types for things where accuracy and precision are critical because rounding errors can throw off calculations by measurable (small) amounts.

Associating enums with strings in C#

Following the answer of @Even Mien I have tried to go a bit further and make it Generic, I seem to be almost there but one case still resist and I probably can simplify my code a bit.
I post it here if anyone see how I could improve and especially make it works as I can't assign it from a string

So Far I have the following results:

        Console.WriteLine(TestEnum.Test1);//displays "TEST1"

        bool test = "TEST1" == TestEnum.Test1; //true

        var test2 = TestEnum.Test1; //is TestEnum and has value

        string test3 = TestEnum.Test1; //test3 = "TEST1"

        var test4 = TestEnum.Test1 == TestEnum.Test2; //false
         EnumType<TestEnum> test5 = "TEST1"; //works fine

        //TestEnum test5 = "string"; DOESN'T compile .... :(:(

Where the magics happens :

public abstract  class EnumType<T>  where T : EnumType<T>   
{

    public  string Value { get; set; }

    protected EnumType(string value)
    {
        Value = value;
    }


    public static implicit operator EnumType<T>(string s)
    {
        if (All.Any(dt => dt.Value == s))
        {
            Type t = typeof(T);

            ConstructorInfo ci = t.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic,null, new Type[] { typeof(string) }, null);

            return (T)ci.Invoke(new object[] {s});
        }
        else
        {
            return null;
        }
    }

    public static implicit operator string(EnumType<T> dt)
    {
        return dt?.Value;
    }


    public static bool operator ==(EnumType<T> ct1, EnumType<T> ct2)
    {
        return (string)ct1 == (string)ct2;
    }

    public static bool operator !=(EnumType<T> ct1, EnumType<T> ct2)
    {
        return !(ct1 == ct2);
    }


    public override bool Equals(object obj)
    {
        try
        {
            return (string)obj == Value;
        }
        catch
        {
            return false;
        }
    }

    public override int GetHashCode()
    {
        return Value.GetHashCode();
    }

    public static IEnumerable<T> All
     => typeof(T).GetProperties()
       .Where(p => p.PropertyType == typeof(T))
       .Select(x => (T)x.GetValue(null, null));



}

I only then have to declare this for my enums:

public class TestEnum : EnumType<TestEnum> 
{

    private TestEnum(string value) : base(value)
    {}

    public static TestEnum Test1 { get { return new TestEnum("TEST1"); } }
    public static TestEnum Test2 { get { return new TestEnum("TEST2"); } }
}

What is the PostgreSQL equivalent for ISNULL()

How do I emulate the ISNULL() functionality ?

SELECT (Field IS NULL) FROM ...

How to pass dictionary items as function arguments in python?

*data interprets arguments as tuples, instead you have to pass **data which interprets the arguments as dictionary.

data = {'school':'DAV', 'class': '7', 'name': 'abc', 'city': 'pune'}


def my_function(**data):
    schoolname  = data['school']
    cityname = data['city']
    standard = data['class']
    studentname = data['name']

You can call the function like this:

my_function(**data)

How to delete zero components in a vector in Matlab?

Data

a=[0  3   0   0   7   10   3   0   1   0   7   7   1   7   4]

Do

aa=nonzeros(a)'

Result

aa=[3   7   10   3   1   7   7   1   7   4]

How do I create an .exe for a Java program?

I used exe4j to package all java jars into one final .exe file, which user can use it as normal windows application.

How do you Change a Package's Log Level using Log4j?

I encountered the exact same problem today, Ryan.

In my src (or your root) directory, my log4j.properties file now has the following addition

# https://issues.apache.org/jira/browse/AXIS2-4363
log4j.category.org.apache.axiom=WARN

Thanks for the heads up as to how to do this, Benjamin.

Mutex example / tutorial?

I stumbled upon this post recently and think that it needs an updated solution for the standard library's c++11 mutex (namely std::mutex).

I've pasted some code below (my first steps with a mutex - I learned concurrency on win32 with HANDLE, SetEvent, WaitForMultipleObjects etc).

Since it's my first attempt with std::mutex and friends, I'd love to see comments, suggestions and improvements!

#include <condition_variable>
#include <mutex>
#include <algorithm>
#include <thread>
#include <queue>
#include <chrono>
#include <iostream>


int _tmain(int argc, _TCHAR* argv[])
{   
    // these vars are shared among the following threads
    std::queue<unsigned int>    nNumbers;

    std::mutex                  mtxQueue;
    std::condition_variable     cvQueue;
    bool                        m_bQueueLocked = false;

    std::mutex                  mtxQuit;
    std::condition_variable     cvQuit;
    bool                        m_bQuit = false;


    std::thread thrQuit(
        [&]()
        {
            using namespace std;            

            this_thread::sleep_for(chrono::seconds(5));

            // set event by setting the bool variable to true
            // then notifying via the condition variable
            m_bQuit = true;
            cvQuit.notify_all();
        }
    );


    std::thread thrProducer(
        [&]()
        {
            using namespace std;

            int nNum = 13;
            unique_lock<mutex> lock( mtxQuit );

            while ( ! m_bQuit )
            {
                while( cvQuit.wait_for( lock, chrono::milliseconds(75) ) == cv_status::timeout )
                {
                    nNum = nNum + 13 / 2;

                    unique_lock<mutex> qLock(mtxQueue);
                    cout << "Produced: " << nNum << "\n";
                    nNumbers.push( nNum );
                }
            }
        }   
    );

    std::thread thrConsumer(
        [&]()
        {
            using namespace std;
            unique_lock<mutex> lock(mtxQuit);

            while( cvQuit.wait_for(lock, chrono::milliseconds(150)) == cv_status::timeout )
            {
                unique_lock<mutex> qLock(mtxQueue);
                if( nNumbers.size() > 0 )
                {
                    cout << "Consumed: " << nNumbers.front() << "\n";
                    nNumbers.pop();
                }               
            }
        }
    );

    thrQuit.join();
    thrProducer.join();
    thrConsumer.join();

    return 0;
}

How to convert a factor to integer\numeric without loss of information?

late to the game, accidently, I found trimws() can convert factor(3:5) to c("3","4","5"). Then you can call as.numeric(). That is:

as.numeric(trimws(x_factor_var))

Regular expression to match balanced parentheses

This do not fully address the OP question but I though it may be useful to some coming here to search for nested structure regexp:

Parse parmeters from function string (with nested structures) in javascript

Match structures like:
Parse parmeters from function string

  • matches brackets, square brackets, parentheses, single and double quotes

Here you can see generated regexp in action

/**
 * get param content of function string.
 * only params string should be provided without parentheses
 * WORK even if some/all params are not set
 * @return [param1, param2, param3]
 */
exports.getParamsSAFE = (str, nbParams = 3) => {
    const nextParamReg = /^\s*((?:(?:['"([{](?:[^'"()[\]{}]*?|['"([{](?:[^'"()[\]{}]*?|['"([{][^'"()[\]{}]*?['")}\]])*?['")}\]])*?['")}\]])|[^,])*?)\s*(?:,|$)/;
    const params = [];
    while (str.length) { // this is to avoid a BIG performance issue in javascript regexp engine
        str = str.replace(nextParamReg, (full, p1) => {
            params.push(p1);
            return '';
        });
    }
    return params;
};

How do I work with a git repository within another repository?

I had issues with subtrees and submodules that the other answers suggest... mainly because I am using SourceTree and it seems fairly buggy.

Instead, I ended up using SymLinks and that seems to work well so I am posting it here as a possible alternative.

There is a complete guide here: http://www.howtogeek.com/howto/16226/complete-guide-to-symbolic-links-symlinks-on-windows-or-linux/

But basically you just need to mklink the two paths in an elevated command prompt. Make sure you use the /J hard link prefix. Something along these lines: mklink /J C:\projects\MainProject\plugins C:\projects\SomePlugin

You can also use relative folder paths and put it in a bat to be executed by each person when they first check out your project.

Example: mklink /J .\Assets\TaqtileTools ..\TaqtileHoloTools

Once the folder has been linked you may need to ignore the folder within your main repository that is referencing it. Otherwise you are good to go.

Note I've deleted my duplicate answer from another post as that post was marked as a duplicate question to this one.

JSON.stringify doesn't work with normal Javascript array

Nice explanation and example above. I found this (JSON.stringify() array bizarreness with Prototype.js) to complete the answer. Some sites implements its own toJSON with JSONFilters, so delete it.

if(window.Prototype) {
    delete Object.prototype.toJSON;
    delete Array.prototype.toJSON;
    delete Hash.prototype.toJSON;
    delete String.prototype.toJSON;
}

it works fine and the output of the test:

console.log(json);

Result:

"{"a":"test","b":["item","item2","item3"]}"

How can you undo the last git add?

You can use git reset. This will 'unstage' all the files you've added after your last commit.

If you want to unstage only some files, use git reset -- <file 1> <file 2> <file n>.

Also it's possible to unstage some of the changes in files by using git reset -p.

Read a file line by line with VB.NET

Like this... I used it to read Chinese characters...

Dim reader as StreamReader = My.Computer.FileSystem.OpenTextFileReader(filetoimport.Text)
Dim a as String

Do
   a = reader.ReadLine
   '
   ' Code here
   '
Loop Until a Is Nothing

reader.Close()

How to pull remote branch from somebody else's repo

If antak's answer:

git fetch [email protected]:<THEIR USERNAME>/<REPO>.git <THEIR BRANCH>:<OUR NAME FOR BRANCH> 

gives you:

Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

Then (following Przemek D's advice) use

git fetch https://github.com/<THEIR USERNAME>/<REPO>.git <THEIR BRANCH>:<OUR NAME FOR BRANCH>

AngularJS : How do I switch views from a controller function?

I've got an example working.

Here's how my doc looks:

<html>
<head>
    <link rel="stylesheet" href="css/main.css">
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular-resource.min.js"></script>
    <script src="js/app.js"></script>
    <script src="controllers/ctrls.js"></script>
</head>
<body ng-app="app">
    <div id="contnr">
        <ng-view></ng-view>
    </div>
</body>
</html>

Here's what my partial looks like:

<div id="welcome" ng-controller="Index">
    <b>Welcome! Please Login!</b>
    <form ng-submit="auth()">
        <input class="input login username" type="text" placeholder="username" /><br>
        <input class="input login password" type="password" placeholder="password" /><br>
        <input class="input login submit" type="submit" placeholder="login!" />
    </form>
</div>

Here's what my Ctrl looks like:

app.controller('Index', function($scope, $routeParams, $location){
    $scope.auth = function(){
        $location.url('/map');
    };
});

app is my module:

var app = angular.module('app', ['ngResource']).config(function($routeProvider)...

Hope this is helpful!

What is the difference between ports 465 and 587?

587 vs. 465

These port assignments are specified by the Internet Assigned Numbers Authority (IANA):

  • Port 587: [SMTP] Message submission (SMTP-MSA), a service that accepts submission of email from email clients (MUAs). Described in RFC 6409.
  • Port 465: URL Rendezvous Directory for SSM (entirely unrelated to email)

Historically, port 465 was initially planned for the SMTPS encryption and authentication “wrapper” over SMTP, but it was quickly deprecated (within months, and over 15 years ago) in favor of STARTTLS over SMTP (RFC 3207). Despite that fact, there are probably many servers that support the deprecated protocol wrapper, primarily to support older clients that implemented SMTPS. Unless you need to support such older clients, SMTPS and its use on port 465 should remain nothing more than an historical footnote.

The hopelessly confusing and imprecise term, SSL, has often been used to indicate the SMTPS wrapper and TLS to indicate the STARTTLS protocol extension.

For completeness: Port 25

  • Port 25: Simple Mail Transfer (SMTP-MTA), a service that accepts submission of email from other servers (MTAs or MSAs). Described in RFC 5321.

Sources:

Print PHP Call Stack

Backtrace dumps a whole lot of garbage that you don't need. It takes is very long, difficult to read. All you usuall ever want is "what called what from where?" Here is a simple static function solution. I usually put it in a class called 'debug', which contains all of my debugging utility functions.

class debugUtils {
    public static function callStack($stacktrace) {
        print str_repeat("=", 50) ."\n";
        $i = 1;
        foreach($stacktrace as $node) {
            print "$i. ".basename($node['file']) .":" .$node['function'] ."(" .$node['line'].")\n";
            $i++;
        }
    } 
}

You call it like this:

debugUtils::callStack(debug_backtrace());

And it produces output like this:

==================================================
 1. DatabaseDriver.php::getSequenceTable(169)
 2. ClassMetadataFactory.php::loadMetadataForClass(284)
 3. ClassMetadataFactory.php::loadMetadata(177)
 4. ClassMetadataFactory.php::getMetadataFor(124)
 5. Import.php::getAllMetadata(188)
 6. Command.php::execute(187)
 7. Application.php::run(194)
 8. Application.php::doRun(118)
 9. doctrine.php::run(99)
 10. doctrine::include(4)
==================================================

What is the difference between map and flatMap and a good use case for each?

map: It returns a new RDD by applying a function to each element of the RDD. Function in .map can return only one item.

flatMap: Similar to map, it returns a new RDD by applying a function to each element of the RDD, but the output is flattened.

Also, function in flatMap can return a list of elements (0 or more)

For Example:

sc.parallelize([3,4,5]).map(lambda x: range(1,x)).collect()

Output: [[1, 2], [1, 2, 3], [1, 2, 3, 4]]

sc.parallelize([3,4,5]).flatMap(lambda x: range(1,x)).collect()

Output: notice o/p is flattened out in a single list [1, 2, 1, 2, 3, 1, 2, 3, 4]

Source:https://www.linkedin.com/pulse/difference-between-map-flatmap-transformations-spark-pyspark-pandey/

How to update column with null value

In the above answers, many ways and repetitions have been suggested for the same. I kept looking for an answer as mentioned is the question but couldn't find here.

Another way to put the above question "update a column with a null value" could be "UPDATE ALL THE ROWS IN THE COLUMN TO NULL"

In such a situation following works

update table_name
set field_name = NULL
where field_name is not NULL;

is as well is not works in mysql

TypeError: ObjectId('') is not JSON serializable

For those who need to return the data thru Jsonify with Flask:

cursor = db.collection.find()
data = []
for doc in cursor:
    doc['_id'] = str(doc['_id']) # This does the trick!
    data.append(doc)
return jsonify(data)

Set min-width either by content or 200px (whichever is greater) together with max-width

The problem is that flex: 1 sets flex-basis: 0. Instead, you need

.container .box {
  min-width: 200px;
  max-width: 400px;
  flex-basis: auto; /* default value */
  flex-grow: 1;
}

_x000D_
_x000D_
.container {_x000D_
  display: -webkit-flex;_x000D_
  display: flex;_x000D_
  -webkit-flex-wrap: wrap;_x000D_
  flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
.container .box {_x000D_
  -webkit-flex-grow: 1;_x000D_
  flex-grow: 1;_x000D_
  min-width: 100px;_x000D_
  max-width: 400px;_x000D_
  height: 200px;_x000D_
  background-color: #fafa00;_x000D_
  overflow: hidden;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Send file via cURL from form POST in PHP

cURL file object in procedural method:

$file = curl_file_create('full path/filename','extension','filename');

cURL file object in Oop method:

$file = new CURLFile('full path/filename','extension','filename');

$post= array('file' => $file);

$curl = curl_init();  
//curl_setopt ... 
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($curl);
curl_close($curl);

How to implement if-else statement in XSLT?

If I may offer some suggestions (two years later but hopefully helpful to future readers):

  • Factor out the common h2 element.
  • Factor out the common ooooooooooooo text.
  • Be aware of new XPath 2.0 if/then/else construct if using XSLT 2.0.

XSLT 1.0 Solution (also works with XSLT 2.0)

<h2>
  <xsl:choose>
    <xsl:when test="$CreatedDate > $IDAppendedDate">m</xsl:when>
    <xsl:otherwise>d</xsl:otherwise>
  </xsl:choose>
  ooooooooooooo
</h2>

XSLT 2.0 Solution

<h2>
   <xsl:value-of select="if ($CreatedDate > $IDAppendedDate) then 'm' else 'd'"/>
   ooooooooooooo
</h2>

How do I center floated elements?

text-align: center;
float: none;

Find the differences between 2 Excel worksheets?

I think your best option is a freeware app called Compare IT! .... absolutely brilliant utility and dead easy to use. http://www.grigsoft.com/wincmp3.htm

How to create a Calendar table for 100 years in Sql

This will create you the result in lightning fast.

select top 100000  identity (int ,1,1) as Sequence into Tally from sysobjects , sys.all_columns


select dateadd(dd,sequence,-1) Dates into CalenderTable from tally


delete from CalenderTable where dates < -- mention the mindate you need
delete from CalenderTable where dates >  -- mention the max date you need

Step 1 : Create a sequence table

Step 2 : Use the sequence table to generate the desired dates

Step 3 : Delete unwanted dates

How to move Docker containers between different hosts?

From Docker documentation:

docker export does not export the contents of volumes associated with the container. If a volume is mounted on top of an existing directory in the container, docker export will export the contents of the underlying directory, not the contents of the volume. Refer to Backup, restore, or migrate data volumes in the user guide for examples on exporting data in a volume.

what do these symbolic strings mean: %02d %01d?

http://www.cplusplus.com/reference/clibrary/cstdio/printf/

the same rules should apply to Java.

in your case it means output of integer values in 2 or more digits, the first being zero if number less than or equal to 9

Store output of sed into a variable

Use command substitution like this:

line=$(sed -n '2p' myfile)
echo "$line"

Also note that there is no space around the = sign.

How can I get the content of CKEditor using JQuery?

version 4.6

CKEDITOR.instances.editor.getData()

Assert that a WebElement is not present using Selenium WebDriver with java

It's easier to do this:

driver.findElements(By.linkText("myLinkText")).size() < 1

Interesting 'takes exactly 1 argument (2 given)' Python error

try using:

def extractAll(self,tag):

attention to self

AngularJS format JSON string output

If you are looking to render JSON as HTML and it can be collapsed/opened, you can use this directive that I just made to render it nicely:

https://github.com/mohsen1/json-formatter/

enter image description here

Carriage return and Line feed... Are both required in C#?

It depends on where you're displaying the text. On the console or a textbox for example, \n will suffice. On a RichTextBox I think you need both.

Excel - find cell with same value in another worksheet and enter the value to the left of it

Assuming employee numbers are in the first column and their names are in the second:

=VLOOKUP(A1, Sheet2!A:B, 2,false)

How to remove package using Angular CLI?

It's an open issue #900 on GitHub, unfortunately at this point of time it looks that in Angular CLI there's nothing like ng remove/rm/..., only using npm uninstall DEPENDENCY is the current workaround.

How do I update pip itself from inside my virtual environment?

I tried all of these solutions mentioned above under Debian Jessie. They don't work, because it just takes the latest version compile by the debian package manager which is 1.5.6 which equates to version 6.0.x. Some packages that use pip as prerequisites will not work as a results, such as spaCy (which needs the option --no-cache-dir to function correctly).

So the actual best way to solve these problems is to run get-pip.py downloaded using wget, from the website or using curl as follows:

 wget https://bootstrap.pypa.io/get-pip.py -O ./get-pip.py
 python ./get-pip.py
 python3 ./get-pip.py

This will install the current version which at the time of writing this solution is 9.0.1 which is way beyond what Debian provides.

 $ pip --version
 pip 9.0.1 from /home/myhomedir/myvirtualenvdir/lib/python2.7/dist-packages (python 2.7)
 $ pip3 --version
 pip 9.0.1 from /home/myhomedir/myvirtualenvdir/lib/python3.4/site-packages (python 3.4)

WCF service maxReceivedMessageSize basicHttpBinding issue

When using HTTPS instead of ON the binding, put it IN the binding with the httpsTransport tag:

    <binding name="MyServiceBinding">
      <security defaultAlgorithmSuite="Basic256Rsa15" 
                authenticationMode="MutualCertificate" requireDerivedKeys="true" 
                securityHeaderLayout="Lax" includeTimestamp="true" 
                messageProtectionOrder="SignBeforeEncrypt" 
                messageSecurityVersion="WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10"
                requireSignatureConfirmation="false">
        <localClientSettings detectReplays="true" />
        <localServiceSettings detectReplays="true" />
        <secureConversationBootstrap keyEntropyMode="CombinedEntropy" />
      </security>
      <textMessageEncoding messageVersion="Soap11WSAddressing10">
        <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" 
                      maxArrayLength="2147483647" maxBytesPerRead="4096" 
                      maxNameTableCharCount="16384"/>
      </textMessageEncoding>
      <httpsTransport maxReceivedMessageSize="2147483647" 
                      maxBufferSize="2147483647" maxBufferPoolSize="2147483647" 
                      requireClientCertificate="false" />
    </binding>

How to detect if a string contains at least a number?

  1. You could use CLR based UDFs or do a CONTAINS query using all the digits on the search column.

Dataset - Vehicle make/model/year (free)

Apparently there is not much out there. And a lot of doubt that someone would be willing to provide such a repository. So I solved the problem myself, and am sharing my dataset with anyone else who finds themselves facing the same problem.

https://github.com/n8barr/automotive-model-year-data

How do I access an access array item by index in handlebars?

Please try this, if you want to fetch first/last.

{{#each list}}

    {{#if @first}}
        <div class="active">
    {{else}}
        <div>
    {{/if}}

{{/each}}


{{#each list}}

    {{#if @last}}
        <div class="last-element">
    {{else}}
        <div>
    {{/if}}

{{/each}}

Find the index of a dict within a list, by matching the dict's value

def search(itemID,list):
     return[i for i in list if i.itemID==itemID]

Enable 'xp_cmdshell' SQL Server

As listed in other answers, the trick (in SQL 2005 or later) is to change the global configuration settings for show advanced options and xp_cmdshell to 1, in that order.

Adding to this, if you want to preserve the previous values, you can read them from sys.configurations first, then apply them in reverse order at the end. We can also avoid unnecessary reconfigure calls:

declare @prevAdvancedOptions int
declare @prevXpCmdshell int

select @prevAdvancedOptions = cast(value_in_use as int) from sys.configurations where name = 'show advanced options'
select @prevXpCmdshell = cast(value_in_use as int) from sys.configurations where name = 'xp_cmdshell'

if (@prevAdvancedOptions = 0)
begin
    exec sp_configure 'show advanced options', 1
    reconfigure
end

if (@prevXpCmdshell = 0)
begin
    exec sp_configure 'xp_cmdshell', 1
    reconfigure
end

/* do work */

if (@prevXpCmdshell = 0)
begin
    exec sp_configure 'xp_cmdshell', 0
    reconfigure
end

if (@prevAdvancedOptions = 0)
begin
    exec sp_configure 'show advanced options', 0
    reconfigure
end

Note that this relies on SQL Server version 2005 or later (original question was for 2008).

How do I get the AM/PM value from a DateTime?

If you want to add time to LongDateString Date, you can format it this way:

    DateTime date = DateTime.Now;
    string formattedDate = date.ToLongDateString(); 
    string formattedTime = date.ToShortTimeString();
    Label1.Text = "New Formatted Date: " + formattedDate + " " + formattedTime;

Output:

New Formatted Date: Monday, January 1, 1900 8:53 PM 

Add bottom line to view in SwiftUI / Swift / Objective-C / Xamarin

In SwiftUI, The simplest implementation would be,

struct MyTextField: View {
  var myPlaceHolder: String
  @Binding var text: String

  var underColor: Color
  var height: CGFloat

  var body: some View {
    VStack {
        TextField(self.myPlaceHolder, text: $text)
        .padding(.horizontal, 24)
        .font(.title)

        Rectangle().frame(height: self.height)
            .padding(.horizontal, 24).foregroundColor(self.underColor)
    }
  }
}

Usage:

MyTextField(myPlaceHolder: "PlaceHolder", text: self.$text, underColor: .red, height: 3)

Example Implementation

How to set null to a GUID property

I think this is the correct way:

Guid filed = Guid.Empty;

Where is the Microsoft.IdentityModel dll

Check namespace mapping changed after 3.5 see below URL for details. http://msdn.microsoft.com/en-us/library/jj157091.aspx

How can I get the day of a specific date with PHP

$date = '2009-10-22';
$sepparator = '-';
$parts = explode($sepparator, $date);
$dayForDate = date("l", mktime(0, 0, 0, $parts[1], $parts[2], $parts[0]));

How to get 0-padded binary representation of an integer in java?

You can use Apache Commons StringUtils. It offers methods for padding strings:

StringUtils.leftPad(Integer.toBinaryString(1), 16, '0');

Mysql service is missing

I also face the same problem. do the simple steps

  1. Go to bin directory copy the path and set it as a environment variable.
  2. Run the command prompt as admin and cd to bin directory:
  3. Run command : mysqld –install
  4. Now the services are successfully installed
  5. Start the service in service windows of os
  6. Type mysql and go

how to pass parameter from @Url.Action to controller function

public ActionResult CreatePerson (string id)

window.location.href = '@Url.Action("CreatePerson", "Person" , new {id = "ID"})'.replace("ID",id);

public ActionResult CreatePerson (int id)

window.location.href = '@Url.Action("CreatePerson", "Person" , new {id = "ID"})'.replace("ID", parseInt(id));

Tomcat: How to find out running tomcat version

Another option is view release notes from tomcat,applicable to linux/window

{Tomcat_home}/webapps/ROOT/RELEASE-NOTES.txt

Inserting created_at data with Laravel

You can manually set this using Laravel, just remember to add 'created_at' to your $fillable array:

protected $fillable = ['name', 'created_at']; 

How do you pull first 100 characters of a string in PHP

$small = substr($big, 0, 100);

For String Manipulation here is a page with a lot of function that might help you in your future work.

JQuery, Spring MVC @RequestBody and JSON - making it work together

I'm pretty sure you only have to register MappingJacksonHttpMessageConverter

(the easiest way to do that is through <mvc:annotation-driven /> in XML or @EnableWebMvc in Java)

See:


Here's a working example:

Maven POM

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion><groupId>test</groupId><artifactId>json</artifactId><packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version><name>json test</name>
    <dependencies>
        <dependency><!-- spring mvc -->
            <groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>3.0.5.RELEASE</version>
        </dependency>
        <dependency><!-- jackson -->
            <groupId>org.codehaus.jackson</groupId><artifactId>jackson-mapper-asl</artifactId><version>1.4.2</version>
        </dependency>
    </dependencies>
    <build><plugins>
            <!-- javac --><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version><configuration><source>1.6</source><target>1.6</target></configuration></plugin>
            <!-- jetty --><plugin><groupId>org.mortbay.jetty</groupId><artifactId>jetty-maven-plugin</artifactId>
            <version>7.4.0.v20110414</version></plugin>
    </plugins></build>
</project>

in folder src/main/webapp/WEB-INF

web.xml

<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4">
    <servlet><servlet-name>json</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>json</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
</web-app>

json-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <import resource="classpath:mvc-context.xml" />

</beans>

in folder src/main/resources:

mvc-context.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <mvc:annotation-driven />
    <context:component-scan base-package="test.json" />
</beans>

In folder src/main/java/test/json

TestController.java

@Controller
@RequestMapping("/test")
public class TestController {

    @RequestMapping(method = RequestMethod.POST, value = "math")
    @ResponseBody
    public Result math(@RequestBody final Request request) {
        final Result result = new Result();
        result.setAddition(request.getLeft() + request.getRight());
        result.setSubtraction(request.getLeft() - request.getRight());
        result.setMultiplication(request.getLeft() * request.getRight());
        return result;
    }

}

Request.java

public class Request implements Serializable {
    private static final long serialVersionUID = 1513207428686438208L;
    private int left;
    private int right;
    public int getLeft() {return left;}
    public void setLeft(int left) {this.left = left;}
    public int getRight() {return right;}
    public void setRight(int right) {this.right = right;}
}

Result.java

public class Result implements Serializable {
    private static final long serialVersionUID = -5054749880960511861L;
    private int addition;
    private int subtraction;
    private int multiplication;

    public int getAddition() { return addition; }
    public void setAddition(int addition) { this.addition = addition; }
    public int getSubtraction() { return subtraction; }
    public void setSubtraction(int subtraction) { this.subtraction = subtraction; }
    public int getMultiplication() { return multiplication; }
    public void setMultiplication(int multiplication) { this.multiplication = multiplication; }
}

You can test this setup by executing mvn jetty:run on the command line, and then sending a POST request:

URL:        http://localhost:8080/test/math
mime type:  application/json
post body:  { "left": 13 , "right" : 7 }

I used the Poster Firefox plugin to do this.

Here's what the response looks like:

{"addition":20,"subtraction":6,"multiplication":91}

How to input a string from user into environment variable from batch file

A rather roundabout way, just for completeness:

 for /f "delims=" %i in ('type CON') do set inp=%i

Of course that requires ^Z as a terminator, and so the Johannes answer is better in all practical ways.

Converting file into Base64String and back again

private String encodeFileToBase64Binary(File file){    
String encodedfile = null;  
try {  
    FileInputStream fileInputStreamReader = new FileInputStream(file);  
    byte[] bytes = new byte[(int)file.length()];
    fileInputStreamReader.read(bytes);  
    encodedfile = Base64.encodeBase64(bytes).toString();  
} catch (FileNotFoundException e) {  
    // TODO Auto-generated catch block  
    e.printStackTrace();  
} catch (IOException e) {  
    // TODO Auto-generated catch block  
    e.printStackTrace();  
}  
    return encodedfile;  
}

Why is this error, 'Sequence contains no elements', happening?

In the following line.

temp.Response = db.Responses.Where(y => y.ResponseId.Equals(item.ResponseId)).First();

You are calling First but the collection returned from db.Responses.Where is empty.

How to loop through an associative array and get the key?

Use $key => $val to get the keys:

<?php

$arr = array(
    1 => "Value1",
    2 => "Value2",
    10 => "Value10",
);

foreach ($arr as $key => $val) {
   print "$key\n";
}

?>

How to remove first and last character of a string?

This will gives you basic idea

    String str="";
    String str1="";
    Scanner S=new Scanner(System.in);
    System.out.println("Enter the string");
    str=S.nextLine();
    int length=str.length();
    for(int i=0;i<length;i++)
    {
        str1=str.substring(1, length-1);
    }
    System.out.println(str1);

Getter and Setter declaration in .NET

Just to clarify, in your 3rd example _myProperty isn't actually a property. It's a field with get and set methods (and as has already been mentioned the get and set methods should specify return types).

In C# the 3rd method should be avoided in most situations. You'd only really use it if the type you wanted to return was an array, or if the get method did a lot of work rather than just returning a value. The latter isn't really necessary but for the purpose of clarity a property's get method that does a lot of work is misleading.