Programs & Examples On #Aggregate functions

Aggregate functions are a subset of SQL functions that compute a single value from multiple input rows, mostly used in `SELECT` queries with a `GROUP BY` clause. Practically all modern RDBMS feature aggregate functions. Typical examples include `COUNT()`, `SUM()`, `MIN()`, `MAX()`, and `AVG()`.

Optimal way to concatenate/aggregate strings

For those of us who found this and are not using Azure SQL Database:

STRING_AGG() in PostgreSQL, SQL Server 2017 and Azure SQL
https://www.postgresql.org/docs/current/static/functions-aggregate.html
https://docs.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql

GROUP_CONCAT() in MySQL
http://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_group-concat

(Thanks to @Brianjorden and @milanio for Azure update)

Example Code:

select Id
, STRING_AGG(Name, ', ') Names 
from Demo
group by Id

SQL Fiddle: http://sqlfiddle.com/#!18/89251/1

How to SUM and SUBTRACT using SQL?

Simple copy & paste example with subqueries, Note, that both queries should return 1 row:

select
(select sum(items_1) from items_table_1 where ...)
-
(select count(items_2) from items_table_1 where ...) 

as difference

LISTAGG in Oracle to return distinct values

select col1, listaggr(col2,',') within group(Order by col2) from table group by col1 meaning aggregate the strings (col2) into list keeping the order n then afterwards deal with the duplicates as group by col1 meaning merge col1 duplicates in 1 group. perhaps this looks clean and simple as it should be and if in case you want col3 as well just you need to add one more listagg() that is select col1, listaggr(col2,',') within group(Order by col2),listaggr(col3,',') within group(order by col3) from table group by col1

mysql count group by having

What about:

SELECT COUNT(*) FROM (SELECT ID FROM Movies GROUP BY ID HAVING COUNT(Genre)=4) a

How to sum data.frame column values?

to order after the colsum :

order(colSums(people),decreasing=TRUE)

if more than 20+ columns

order(colSums(people[,c(5:25)],decreasing=TRUE) ##in case of keeping the first 4 columns remaining.

Concatenate multiple result rows of one column into one, group by another column

You can use array_agg function for that:

SELECT "Movie",
array_to_string(array_agg(distinct "Actor"),',') AS Actor
FROM Table1
GROUP BY "Movie";

Result:

MOVIE ACTOR
A 1,2,3
B 4

See this SQLFiddle

For more See 9.18. Aggregate Functions

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

This is how I would do it (assuming I understand the question)

SELECT * FROM pieces ORDER BY price ASC LIMIT 1

If you are trying to select multiple rows where each of them may have the same price (which is the minimum) then @JohnWoo's answer should suffice.

Basically here we are just ordering the results by the price in ASCending order (increasing) and taking the first row of the result.

MySQL "Group By" and "Order By"

Here's one approach:

SELECT cur.textID, cur.fromEmail, cur.subject, 
     cur.timestamp, cur.read
FROM incomingEmails cur
LEFT JOIN incomingEmails next
    on cur.fromEmail = next.fromEmail
    and cur.timestamp < next.timestamp
WHERE next.timestamp is null
and cur.toUserID = '$userID' 
ORDER BY LOWER(cur.fromEmail)

Basically, you join the table on itself, searching for later rows. In the where clause you state that there cannot be later rows. This gives you only the latest row.

If there can be multiple emails with the same timestamp, this query would need refining. If there's an incremental ID column in the email table, change the JOIN like:

LEFT JOIN incomingEmails next
    on cur.fromEmail = next.fromEmail
    and cur.id < next.id

GROUP BY + CASE statement

Try adding the other two non COUNT columns to the GROUP BY:

select CURRENT_DATE-1 AS day, 
model.name, 
attempt.type, 
CASE WHEN attempt.result = 0 THEN 0 ELSE 1 END, 
count(*) 
from attempt attempt, prod_hw_id prod_hw_id, model model
where time >= '2013-11-06 00:00:00'  
AND time < '2013-11-07 00:00:00'
AND attempt.hard_id = prod_hw_id.hard_id
AND prod_hw_id.model_id = model.model_id
group by 1,2,3,4
order by model.name, attempt.type, attempt.result;

How to include "zero" / "0" results in COUNT aggregate?

USE join to get 0 count in the result using GROUP BY.

simply 'join' does Inner join in MS SQL so , Go for left or right join.

If the table which contains the primary key is mentioned first in the QUERY then use LEFT join else RIGHT join.

EG:

select WARDNO,count(WARDCODE) from MAIPADH 
right join  MSWARDH on MSWARDH.WARDNO= MAIPADH.WARDCODE
group by WARDNO

.

select WARDNO,count(WARDCODE) from MSWARDH
left join  MAIPADH on MSWARDH.WARDNO= MAIPADH.WARDCODE group by WARDNO

Take group by from the table which has Primary key and count from the another table which has actual entries/details.

The SQL OVER() clause - when and why is it useful?

Let me explain with an example and you would be able to see how it works.

Assuming you have the following table DIM_EQUIPMENT:

VIN         MAKE    MODEL   YEAR    COLOR
-----------------------------------------
1234ASDF    Ford    Taurus  2008    White
1234JKLM    Chevy   Truck   2005    Green
5678ASDF    Ford    Mustang 2008    Yellow

Run below SQL

SELECT VIN,
  MAKE,
  MODEL,
  YEAR,
  COLOR ,
  COUNT(*) OVER (PARTITION BY YEAR) AS COUNT2
FROM DIM_EQUIPMENT

The result would be as below

VIN         MAKE    MODEL   YEAR    COLOR     COUNT2
 ----------------------------------------------  
1234JKLM    Chevy   Truck   2005    Green     1
5678ASDF    Ford    Mustang 2008    Yellow    2
1234ASDF    Ford    Taurus  2008    White     2

See what happened.

You are able to count without Group By on YEAR and Match with ROW.

Another Interesting WAY to get same result if as below using WITH Clause, WITH works as in-line VIEW and can simplify the query especially complex ones, which is not the case here though since I am just trying to show usage

 WITH EQ AS
  ( SELECT YEAR AS YEAR2, COUNT(*) AS COUNT2 FROM DIM_EQUIPMENT GROUP BY YEAR
  )
SELECT VIN,
  MAKE,
  MODEL,
  YEAR,
  COLOR,
  COUNT2
FROM DIM_EQUIPMENT,
  EQ
WHERE EQ.YEAR2=DIM_EQUIPMENT.YEAR;

SQL select only rows with max value on a column

NOT mySQL, but for other people finding this question and using SQL, another way to resolve the problem is using Cross Apply in MS SQL

WITH DocIds AS (SELECT DISTINCT id FROM docs)

SELECT d2.id, d2.rev, d2.content
FROM DocIds d1
CROSS APPLY (
  SELECT Top 1 * FROM docs d
  WHERE d.id = d1.id
  ORDER BY rev DESC
) d2

Here's an example in SqlFiddle

MySQL Update Column +1?

update table_name set field1 = field1 + 1;

SQL Server: Difference between PARTITION BY and GROUP BY

We can take a simple example.

Consider a table named TableA with the following values:

id  firstname                   lastname                    Mark
-------------------------------------------------------------------
1   arun                        prasanth                    40
2   ann                         antony                      45
3   sruthy                      abc                         41
6   new                         abc                         47
1   arun                        prasanth                    45
1   arun                        prasanth                    49
2   ann                         antony                      49

GROUP BY

The SQL GROUP BY clause can be used in a SELECT statement to collect data across multiple records and group the results by one or more columns.

In more simple words GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns.

Syntax:

SELECT expression1, expression2, ... expression_n, 
       aggregate_function (aggregate_expression)
FROM tables
WHERE conditions
GROUP BY expression1, expression2, ... expression_n;

We can apply GROUP BY in our table:

select SUM(Mark)marksum,firstname from TableA
group by id,firstName

Results:

marksum  firstname
----------------
94      ann                      
134     arun                     
47      new                      
41      sruthy   

In our real table we have 7 rows and when we apply GROUP BY id, the server group the results based on id:

In simple words:

here GROUP BY normally reduces the number of rows returned by rolling them up and calculating Sum() for each row.

PARTITION BY

Before going to PARTITION BY, let us look at the OVER clause:

According to the MSDN definition:

OVER clause defines a window or user-specified set of rows within a query result set. A window function then computes a value for each row in the window. You can use the OVER clause with functions to compute aggregated values such as moving averages, cumulative aggregates, running totals, or a top N per group results.

PARTITION BY will not reduce the number of rows returned.

We can apply PARTITION BY in our example table:

SELECT SUM(Mark) OVER (PARTITION BY id) AS marksum, firstname FROM TableA

Result:

marksum firstname 
-------------------
134     arun                     
134     arun                     
134     arun                     
94      ann                      
94      ann                      
41      sruthy                   
47      new  

Look at the results - it will partition the rows and returns all rows, unlike GROUP BY.

Function to Calculate Median in SQL Server

For your question, Jeff Atwood had already given the simple and effective solution. But, if you are looking for some alternative approach to calculate the median, below SQL code will help you.

_x000D_
_x000D_
create table employees(salary int);_x000D_
_x000D_
insert into employees values(8); insert into employees values(23); insert into employees values(45); insert into employees values(123); insert into employees values(93); insert into employees values(2342); insert into employees values(2238);_x000D_
_x000D_
select * from employees;_x000D_
_x000D_
declare @odd_even int; declare @cnt int; declare @middle_no int;_x000D_
_x000D_
_x000D_
set @cnt=(select count(*) from employees); set @middle_no=(@cnt/2)+1; select @odd_even=case when (@cnt%2=0) THEN -1 ELse 0 END ;_x000D_
_x000D_
_x000D_
 select AVG(tbl.salary) from  (select  salary,ROW_NUMBER() over (order by salary) as rno from employees group by salary) tbl  where tbl.rno=@middle_no or tbl.rno=@middle_no+@odd_even;
_x000D_
_x000D_
_x000D_

If you are looking to calculate median in MySQL, this github link will be useful.

How to use Oracle's LISTAGG function with a unique filter?

below is undocumented and not recomended by oracle. and can not apply in function, show error

select wm_concat(distinct name) as names from demotable group by group_id

regards zia

Spark SQL: apply aggregate functions to a list of columns

Current answers are perfectly correct on how to create the aggregations, but none actually address the column alias/renaming that is also requested in the question.

Typically, this is how I handle this case:

val dimensionFields = List("col1")
val metrics = List("col2", "col3", "col4")
val columnOfInterests = dimensions ++ metrics

val df = spark.read.table("some_table"). 
    .select(columnOfInterests.map(c => col(c)):_*)
    .groupBy(dimensions.map(d => col(d)): _*)
    .agg(metrics.map( m => m -> "sum").toMap)
    .toDF(columnOfInterests:_*)    // that's the interesting part

The last line essentially renames every columns of the aggregated dataframe to the original fields, essentially changing sum(col2) and sum(col3) to simply col2 and col3.

Count number of times value appears in particular column in MySQL

select email, count(*) as c FROM orders GROUP BY email

MAX() and MAX() OVER PARTITION BY produces error 3504 in Teradata Query

I know this is a very old question, but I've been asked by someone else something similar.

I don't have TeraData, but can't you do the following?

SELECT employee_number,
       course_code,
       MAX(course_completion_date)                                     AS max_course_date,
       MAX(course_completion_date) OVER (PARTITION BY employee_number) AS max_date
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code

The GROUP BY now ensures one row per course per employee. This means that you just need a straight MAX() to get the max_course_date.

Before your GROUP BY was just giving one row per employee, and the MAX() OVER() was trying to give multiple results for that one row (one per course).

Instead, you now need the OVER() clause to get the MAX() for the employee as a whole. This is now legitimate because each individual row gets just one answer (as it is derived from a super-set, not a sub-set). Also, for the same reason, the OVER() clause now refers to a valid scalar value, as defined by the GROUP BY clause; employee_number.


Perhaps a short way of saying this would be that an aggregate with an OVER() clause must be a super-set of the GROUP BY, not a sub-set.

Create your query with a GROUP BY at the level that represents the rows you want, then specify OVER() clauses if you want to aggregate at a higher level.

SELECTING with multiple WHERE conditions on same column

Use this: For example:

select * from ACCOUNTS_DETAILS
where ACCOUNT_ID=1001
union
select * from ACCOUNTS_DETAILS
where ACCOUNT_ID=1002

Selecting a Record With MAX Value

Say, for an user, there is revision for each date. The following will pick up record for the max revision of each date for each employee.

select job, adate, rev, usr, typ 
from tbl
where exists (  select 1 from ( select usr, adate, max(rev) as max_rev 
                                from tbl
                                group by usr, adate 
                              ) as cond
                where tbl.usr=cond.usr 
                and tbl.adate =cond.adate 
                and tbl.rev =cond.max_rev
             )
order by adate, job, usr

must appear in the GROUP BY clause or be used in an aggregate function

In Postgres, you can also use the special DISTINCT ON (expression) syntax:

SELECT DISTINCT ON (cname) 
    cname, wmname, avg
FROM 
    makerar 
ORDER BY 
    cname, avg DESC ;

GROUP BY without aggregate function

As an addition

basically the number of columns have to be equal to the number of columns in the GROUP BY clause

is not a correct statement.

  • Any attribute which is not a part of GROUP BY clause can not be used for selection
  • Any attribute which is a part of GROUP BY clause can be used for selection but not mandatory.

Naming returned columns in Pandas aggregate function?

For pandas >= 0.25

The functionality to name returned aggregate columns has been reintroduced in the master branch and is targeted for pandas 0.25. The new syntax is .agg(new_col_name=('col_name', 'agg_func'). Detailed example from the PR linked above:

In [2]: df = pd.DataFrame({'kind': ['cat', 'dog', 'cat', 'dog'],
   ...:                    'height': [9.1, 6.0, 9.5, 34.0],
   ...:                    'weight': [7.9, 7.5, 9.9, 198.0]})
   ...:

In [3]: df
Out[3]:
  kind  height  weight
0  cat     9.1     7.9
1  dog     6.0     7.5
2  cat     9.5     9.9
3  dog    34.0   198.0

In [4]: df.groupby('kind').agg(min_height=('height', 'min'), 
                               max_weight=('weight', 'max'))
Out[4]:
      min_height  max_weight
kind
cat          9.1         9.9
dog          6.0       198.0

It will also be possible to use multiple lambda expressions with this syntax and the two-step rename syntax I suggested earlier (below) as per this PR. Again, copying from the example in the PR:

In [2]: df = pd.DataFrame({"A": ['a', 'a'], 'B': [1, 2], 'C': [3, 4]})

In [3]: df.groupby("A").agg({'B': [lambda x: 0, lambda x: 1]})
Out[3]:
         B
  <lambda> <lambda 1>
A
a        0          1

and then .rename(), or in one go:

In [4]: df.groupby("A").agg(b=('B', lambda x: 0), c=('B', lambda x: 1))
Out[4]:
   b  c
A
a  0  0

For pandas < 0.25

The currently accepted answer by unutbu describes are great way of doing this in pandas versions <= 0.20. However, as of pandas 0.20, using this method raises a warning indicating that the syntax will not be available in future versions of pandas.

Series:

FutureWarning: using a dict on a Series for aggregation is deprecated and will be removed in a future version

DataFrames:

FutureWarning: using a dict with renaming is deprecated and will be removed in a future version

According to the pandas 0.20 changelog, the recommended way of renaming columns while aggregating is as follows.

# Create a sample data frame
df = pd.DataFrame({'A': [1, 1, 1, 2, 2],
                   'B': range(5),
                   'C': range(5)})

# ==== SINGLE COLUMN (SERIES) ====
# Syntax soon to be deprecated
df.groupby('A').B.agg({'foo': 'count'})
# Recommended replacement syntax
df.groupby('A').B.agg(['count']).rename(columns={'count': 'foo'})

# ==== MULTI COLUMN ====
# Syntax soon to be deprecated
df.groupby('A').agg({'B': {'foo': 'sum'}, 'C': {'bar': 'min'}})
# Recommended replacement syntax
df.groupby('A').agg({'B': 'sum', 'C': 'min'}).rename(columns={'B': 'foo', 'C': 'bar'})
# As the recommended syntax is more verbose, parentheses can
# be used to introduce line breaks and increase readability
(df.groupby('A')
    .agg({'B': 'sum', 'C': 'min'})
    .rename(columns={'B': 'foo', 'C': 'bar'})
)

Please see the 0.20 changelog for additional details.

Update 2017-01-03 in response to @JunkMechanic's comment.

With the old style dictionary syntax, it was possible to pass multiple lambda functions to .agg, since these would be renamed with the key in the passed dictionary:

>>> df.groupby('A').agg({'B': {'min': lambda x: x.min(), 'max': lambda x: x.max()}})

    B    
  max min
A        
1   2   0
2   4   3

Multiple functions can also be passed to a single column as a list:

>>> df.groupby('A').agg({'B': [np.min, np.max]})

     B     
  amin amax
A          
1    0    2
2    3    4

However, this does not work with lambda functions, since they are anonymous and all return <lambda>, which causes a name collision:

>>> df.groupby('A').agg({'B': [lambda x: x.min(), lambda x: x.max]})
SpecificationError: Function names must be unique, found multiple named <lambda>

To avoid the SpecificationError, named functions can be defined a priori instead of using lambda. Suitable function names also avoid calling .rename on the data frame afterwards. These functions can be passed with the same list syntax as above:

>>> def my_min(x):
>>>     return x.min()

>>> def my_max(x):
>>>     return x.max()

>>> df.groupby('A').agg({'B': [my_min, my_max]})

       B       
  my_min my_max
A              
1      0      2
2      3      4

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.

Apply multiple functions to multiple groupby columns

This is a twist on 'exans' answer that uses Named Aggregations. It's the same but with argument unpacking which allows you to still pass in a dictionary to the agg function.

The named aggs are a nice feature, but at first glance might seem hard to write programmatically since they use keywords, but it's actually simple with argument/keyword unpacking.

animals = pd.DataFrame({'kind': ['cat', 'dog', 'cat', 'dog'],
                         'height': [9.1, 6.0, 9.5, 34.0],
                         'weight': [7.9, 7.5, 9.9, 198.0]})
 
agg_dict = {
    "min_height": pd.NamedAgg(column='height', aggfunc='min'),
    "max_height": pd.NamedAgg(column='height', aggfunc='max'),
    "average_weight": pd.NamedAgg(column='weight', aggfunc=np.mean)
}

animals.groupby("kind").agg(**agg_dict)

The Result

      min_height  max_height  average_weight
kind                                        
cat          9.1         9.5            8.90
dog          6.0        34.0          102.75

use mysql SUM() in a WHERE clause

When using aggregate functions to filter, you must use a HAVING statement.

SELECT *
FROM tblMoney
HAVING Sum(CASH) > 500

Reason for Column is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause

Basically, what this error is saying is that if you are going to use the GROUP BY clause, then your result is going to be a relation/table with a row for each group, so in your SELECT statement you can only "select" the column that you are grouping by and use aggregate functions on that column because the other columns will not appear in the resulting table.

Android ADT error, dx.jar was not loaded from the SDK folder

sometimes you need just to restart Eclipse after the update, it worked for me to fix that error

How to iterate over a JavaScript object?

If you have a simple object you can iterate through it using the following code:

_x000D_
_x000D_
let myObj = {
  abc: '...',
  bca: '...',
  zzz: '...',
  xxx: '...',
  ccc: '...',
  // ...
};

let objKeys = Object.keys(myObj);

//Now we can use objKeys to iterate over myObj

for (item of objKeys) {
  //this will print out the keys
  console.log('key:', item);
  
  //this will print out the values 
  console.log('value:', myObj[item]);
}
_x000D_
_x000D_
_x000D_

If you have a nested object you can iterate through it using the following code:

_x000D_
_x000D_
let b = {
  one: {
    a: 1,
    b: 2,
    c: 3
  },
  two: {
    a: 4,
    b: 5,
    c: 6
  },
  three: {
    a: 7,
    b: 8,
    c: 9
  }
};

let myKeys = Object.keys(b);

for (item of myKeys) {
  //print the key
  console.log('Key', item)
  
  //print the value (which will be another object)
  console.log('Value', b[item])
  
  //print the nested value
  console.log('Nested value', b[item]['a'])
}
_x000D_
_x000D_
_x000D_

If you have array of objects you can iterate through it using the following code:

_x000D_
_x000D_
let c = [
{
  a: 1,
  b: 2
},
{
  a: 3,
  b: 4
}
];

for(item of c){
//print the whole object individually 
console.log('object', item);

//print the value inside the object
console.log('value', item['a']);
}
_x000D_
_x000D_
_x000D_

HTML Mobile -forcing the soft keyboard to hide

For further readers/searchers:

As Rene Pot points out on this topic,

By adding the attribute readonly (or readonly="readonly") to the input field you should prevent anyone typing anything in it, but still be able to launch a click event on it.

With this method, you can avoid popping up the "soft" Keyboard and still launch click events / fill the input by any on-screen keyboard.

This solution also works fine with date-time-pickers which generally already implement controls.

How to make a Div appear on top of everything else on the screen?

Are you using position: relative?

Try to set position: relative and then z-index because you want this div has a z-index in relation with other div.

By the way, your browser is important to check if it working or not. Neither IE or Firefox is a good one.

What is the ultimate postal code and zip regex?

This is a very simple RegEx for validating US Zipcode (not ZipCode Plus Four):

(?!([089])\1{4})\d{5}

Seems all five digit numeric are valid zipcodes except 00000, 88888 & 99999.

I have tested this RegEx with http://regexpal.com/

SP

datatable jquery - table header width not aligned with body width

I fixed, Work for me.

var table = $('#example').DataTable();
$('#container').css( 'display', 'block' );
table.columns.adjust().draw();

Or

var table = $('#example').DataTable();
table.columns.adjust().draw();

Reference: https://datatables.net/reference/api/columns.adjust()

Git - What is the difference between push.default "matching" and "simple"

Git v2.0 Release Notes

Backward compatibility notes

When git push [$there] does not say what to push, we have used the traditional "matching" semantics so far (all your branches were sent to the remote as long as there already are branches of the same name over there). In Git 2.0, the default is now the "simple" semantics, which pushes:

  • only the current branch to the branch with the same name, and only when the current branch is set to integrate with that remote branch, if you are pushing to the same remote as you fetch from; or

  • only the current branch to the branch with the same name, if you are pushing to a remote that is not where you usually fetch from.

You can use the configuration variable "push.default" to change this. If you are an old-timer who wants to keep using the "matching" semantics, you can set the variable to "matching", for example. Read the documentation for other possibilities.

When git add -u and git add -A are run inside a subdirectory without specifying which paths to add on the command line, they operate on the entire tree for consistency with git commit -a and other commands (these commands used to operate only on the current subdirectory). Say git add -u . or git add -A . if you want to limit the operation to the current directory.

git add <path> is the same as git add -A <path> now, so that git add dir/ will notice paths you removed from the directory and record the removal. In older versions of Git, git add <path> used to ignore removals. You can say git add --ignore-removal <path> to add only added or modified paths in <path>, if you really want to.

How to comment out particular lines in a shell script

Yes (although it's a nasty hack). You can use a heredoc thus:

#!/bin/sh

# do valuable stuff here
touch /tmp/a

# now comment out all the stuff below up to the EOF
echo <<EOF
...
...
...
EOF

What's this doing ? A heredoc feeds all the following input up to the terminator (in this case, EOF) into the nominated command. So you can surround the code you wish to comment out with

echo <<EOF
...
EOF

and it'll take all the code contained between the two EOFs and feed them to echo (echo doesn't read from stdin so it all gets thrown away).

Note that with the above you can put anything in the heredoc. It doesn't have to be valid shell code (i.e. it doesn't have to parse properly).

This is very nasty, and I offer it only as a point of interest. You can't do the equivalent of C's /* ... */

Excel Macro - Select all cells with data and format as table

Try this one for current selection:

Sub A_SelectAllMakeTable2()
    Dim tbl As ListObject
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

or equivalent of your macro (for Ctrl+Shift+End range selection):

Sub A_SelectAllMakeTable()
    Dim tbl As ListObject
    Dim rng As Range

    Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

Correct way to pass multiple values for same parameter name in GET request

Indeed, there is no defined standard. To support that information, have a look at wikipedia, in the Query String chapter. There is the following comment:

While there is no definitive standard, most web frameworks allow multiple values to be associated with a single field.[3][4]

Furthermore, when you take a look at the RFC 3986, in section 3.4 Query, there is no definition for parameters with multiple values.

Most applications use the first option you have shown: http://server/action?id=a&id=b. To support that information, take a look at this Stackoverflow link, and this MSDN link regarding ASP.NET applications, which use the same standard for parameters with multiple values.

However, since you are developing the APIs, I suggest you to do what is the easiest for you, since the caller of the API will not have much trouble creating the query string.

Check if cookies are enabled

A transparent, clean and simple approach, checking cookies availability with PHP and taking advantage of AJAX transparent redirection, hence not triggering a page reload. It doesn't require sessions either.

Client-side code (JavaScript)

function showCookiesMessage(cookiesEnabled) {
    if (cookiesEnabled == 'true')
        alert('Cookies enabled');
    else
        alert('Cookies disabled');
}

$(document).ready(function() {
    var jqxhr = $.get('/cookiesEnabled.php');
    jqxhr.done(showCookiesMessage);
});

(JQuery AJAX call can be replaced with pure JavaScript AJAX call)

Server-side code (PHP)

if (isset($_COOKIE['cookieCheck'])) {
    echo 'true';
} else {
    if (isset($_GET['reload'])) {
        echo 'false';
    } else {
        setcookie('cookieCheck', '1', time() + 60);
        header('Location: ' . $_SERVER['PHP_SELF'] . '?reload');
        exit();
    }
}

First time the script is called, the cookie is set and the script tells the browser to redirect to itself. The browser does it transparently. No page reload takes place because it's done within an AJAX call scope.

The second time, when called by redirection, if the cookie is received, the script responds an HTTP 200 (with string "true"), hence the showCookiesMessage function is called.

If the script is called for the second time (identified by the "reload" parameter) and the cookie is not received, it responds an HTTP 200 with string "false" -and the showCookiesMessage function gets called.

Add a column in a table in HIVE QL

You cannot add a column with a default value in Hive. You have the right syntax for adding the column ALTER TABLE test1 ADD COLUMNS (access_count1 int);, you just need to get rid of default sum(max_count). No changes to that files backing your table will happen as a result of adding the column. Hive handles the "missing" data by interpreting NULL as the value for every cell in that column.

So now your have the problem of needing to populate the column. Unfortunately in Hive you essentially need to rewrite the whole table, this time with the column populated. It may be easier to rerun your original query with the new column. Or you could add the column to the table you have now, then select all of its columns plus value for the new column.

You also have the option to always COALESCE the column to your desired default and leave it NULL for now. This option fails when you want NULL to have a meaning distinct from your desired default. It also requires you to depend on always remembering to COALESCE.

If you are very confident in your abilities to deal with the files backing Hive, you could also directly alter them to add your default. In general I would recommend against this because most of the time it will be slower and more dangerous. There might be some case where it makes sense though, so I've included this option for completeness.

Is Java "pass-by-reference" or "pass-by-value"?

Java passes everything by value!!

//create an object by passing in a name and age:

PersonClass variable1 = new PersonClass("Mary", 32);

PersonClass variable2;

//Both variable2 and variable1 now reference the same object

variable2 = variable1; 


PersonClass variable3 = new PersonClass("Andre", 45);

// variable1 now points to variable3

variable1 = variable3;

//WHAT IS OUTPUT BY THIS?

System.out.println(variable2);
System.out.println(variable1);

Mary 32
Andre 45

if you could understand this example we r done. otherwise, please visit this webPage for detailed explanation:

webPage

IF...THEN...ELSE using XML

I think that the thing you must keep in mind is that your XML is being processed by a machine, not a human, so it only needs to be readable for the machine.

In other words, I think you should use whatever XML schema you need to make parsing/processing the rules as efficient as possible at run time.

As far as your current schema goes, I think that the id attribute should be unique per element, so perhaps you should use a different attribute to capture the relationship among your IF, THEN, and ELSE elements.

How to find largest objects in a SQL Server database?

If you are using Sql Server Management Studio 2008 there are certain data fields you can view in the object explorer details window. Simply browse to and select the tables folder. In the details view you are able to right-click the column titles and add fields to the "report". Your mileage may vary if you are on SSMS 2008 express.

"This operation requires IIS integrated pipeline mode."

GitHub solution solved the problem for me by adding

  • Global.asax.cs: Set AntiForgeryConfig.SuppressXFrameOptionsHeader = true; in Application_Start:
  • Manually add the X-Frame-Options header in Application_BeginRequest

DataGridView AutoFit and Fill

This is my favorite approach...

_dataGrid.DataBindingComplete += (o, _) =>
    {
        var dataGridView = o as DataGridView;
        if (dataGridView != null)
        {
           dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
           dataGridView.Columns[dataGridView.ColumnCount-1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
        }
    };

Change url query string value using jQuery

If you only need to modify the page num you can replace it:

var newUrl = location.href.replace("page="+currentPageNum, "page="+newPageNum);

How to Validate a DateTime in C#?

Don't use exceptions for flow control. Use DateTime.TryParse and DateTime.TryParseExact. Personally I prefer TryParseExact with a specific format, but I guess there are times when TryParse is better. Example use based on your original code:

DateTime value;
if (!DateTime.TryParse(startDateTextBox.Text, out value))
{
    startDateTextox.Text = DateTime.Today.ToShortDateString();
}

Reasons for preferring this approach:

  • Clearer code (it says what it wants to do)
  • Better performance than catching and swallowing exceptions
  • This doesn't catch exceptions inappropriately - e.g. OutOfMemoryException, ThreadInterruptedException. (Your current code could be fixed to avoid this by just catching the relevant exception, but using TryParse would still be better.)

Bootstrap 3 unable to display glyphicon properly

I ended up switching to Font-Awesome Icons. They are just as good if not better, and all you need to do is link in the font, happy days.

Creating a new DOM element from an HTML string using built-in DOM methods or Prototype

Note: most current browsers support HTML <template> elements, which provide a more reliable way of turning creating elements from strings. See Mark Amery's answer below for details.

For older browsers, and node/jsdom: (which doesn't yet support <template> elements at the time of writing), use the following method. It's the same thing the libraries use to do to get DOM elements from an HTML string (with some extra work for IE to work around bugs with its implementation of innerHTML):

function createElementFromHTML(htmlString) {
  var div = document.createElement('div');
  div.innerHTML = htmlString.trim();

  // Change this to div.childNodes to support multiple top-level nodes
  return div.firstChild; 
}

Note that unlike HTML templates this won't work for some elements that cannot legally be children of a <div>, such as <td>s.

If you're already using a library, I would recommend you stick to the library-approved method of creating elements from HTML strings:

How do I use regex in a SQLite query?

UPDATE TableName
 SET YourField = ''
WHERE YourField REGEXP 'YOUR REGEX'

And :

SELECT * from TableName
 WHERE YourField REGEXP 'YOUR REGEX'

adb not finding my device / phone (MacOS X)

When I plugged the Android 10 device to the Mac OS a popup showed on the phone saying:

The Mac OS cannot access data on this device, you will have to download filetransfer or smart-switch.

  1. Download file transfer https://www.android.com/filetransfer/ for android
  2. Download smart-switch https://www.samsung.com/us/smart-switch/ for Samsung I guess

Though not sure why there are two options here!

I downloaded file transfer and it worked perfectly even though the device was Samsung Note.

Note: I forgot to mention that first you have to enable Developer mode then USB Debugging.

Find and replace string values in list

You can use, for example:

words = [word.replace('[br]','<br />') for word in words]

How to uninstall Anaconda completely from macOS

Adding export PATH="/Users/<username>/anaconda/bin:$PATH" (or export PATH="/Users/<username>/anaconda3/bin:$PATH" if you have anaconda 3) to my ~/.bash_profile file, fixed this issue for me.

Play local (hard-drive) video file with HTML5 video tag?

That will be possible only if the HTML file is also loaded with the file protocol from the local user's harddisk.

If the HTML page is served by HTTP from a server, you can't access any local files by specifying them in a src attribute with the file:// protocol as that would mean you could access any file on the users computer without the user knowing which would be a huge security risk.

As Dimitar Bonev said, you can access a file if the user selects it using a file selector on their own. Without that step, it's forbidden by all browsers for good reasons. Thus, while his answer might prove useful for many people, it loosens the requirement from the code in the original question.

CORS Access-Control-Allow-Headers wildcard being ignored?

Those CORS headers do not support * as value, the only way is to replace * with this:

Accept, Accept-CH, Accept-Charset, Accept-Datetime, Accept-Encoding, Accept-Ext, Accept-Features, Accept-Language, Accept-Params, Accept-Ranges, Access-Control-Allow-Credentials, Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin, Access-Control-Expose-Headers, Access-Control-Max-Age, Access-Control-Request-Headers, Access-Control-Request-Method, Age, Allow, Alternates, Authentication-Info, Authorization, C-Ext, C-Man, C-Opt, C-PEP, C-PEP-Info, CONNECT, Cache-Control, Compliance, Connection, Content-Base, Content-Disposition, Content-Encoding, Content-ID, Content-Language, Content-Length, Content-Location, Content-MD5, Content-Range, Content-Script-Type, Content-Security-Policy, Content-Style-Type, Content-Transfer-Encoding, Content-Type, Content-Version, Cookie, Cost, DAV, DELETE, DNT, DPR, Date, Default-Style, Delta-Base, Depth, Derived-From, Destination, Differential-ID, Digest, ETag, Expect, Expires, Ext, From, GET, GetProfile, HEAD, HTTP-date, Host, IM, If, If-Match, If-Modified-Since, If-None-Match, If-Range, If-Unmodified-Since, Keep-Alive, Label, Last-Event-ID, Last-Modified, Link, Location, Lock-Token, MIME-Version, Man, Max-Forwards, Media-Range, Message-ID, Meter, Negotiate, Non-Compliance, OPTION, OPTIONS, OWS, Opt, Optional, Ordering-Type, Origin, Overwrite, P3P, PEP, PICS-Label, POST, PUT, Pep-Info, Permanent, Position, Pragma, ProfileObject, Protocol, Protocol-Query, Protocol-Request, Proxy-Authenticate, Proxy-Authentication-Info, Proxy-Authorization, Proxy-Features, Proxy-Instruction, Public, RWS, Range, Referer, Refresh, Resolution-Hint, Resolver-Location, Retry-After, Safe, Sec-Websocket-Extensions, Sec-Websocket-Key, Sec-Websocket-Origin, Sec-Websocket-Protocol, Sec-Websocket-Version, Security-Scheme, Server, Set-Cookie, Set-Cookie2, SetProfile, SoapAction, Status, Status-URI, Strict-Transport-Security, SubOK, Subst, Surrogate-Capability, Surrogate-Control, TCN, TE, TRACE, Timeout, Title, Trailer, Transfer-Encoding, UA-Color, UA-Media, UA-Pixels, UA-Resolution, UA-Windowpixels, URI, Upgrade, User-Agent, Variant-Vary, Vary, Version, Via, Viewport-Width, WWW-Authenticate, Want-Digest, Warning, Width, X-Content-Duration, X-Content-Security-Policy, X-Content-Type-Options, X-CustomHeader, X-DNSPrefetch-Control, X-Forwarded-For, X-Forwarded-Port, X-Forwarded-Proto, X-Frame-Options, X-Modified, X-OTHER, X-PING, X-PINGOTHER, X-Powered-By, X-Requested-With


.htaccess Example (CORS Included):

<IfModule mod_headers.c>
  Header unset Connection
  Header unset Time-Zone
  Header unset Keep-Alive
  Header unset Access-Control-Allow-Origin
  Header unset Access-Control-Allow-Headers
  Header unset Access-Control-Expose-Headers
  Header unset Access-Control-Allow-Methods
  Header unset Access-Control-Allow-Credentials

  Header set   Connection                         keep-alive
  Header set   Time-Zone                          "Asia/Jerusalem"
  Header set   Keep-Alive                         timeout=100,max=500
  Header set   Access-Control-Allow-Origin        "*"
  Header set   Access-Control-Allow-Headers       "Accept, Accept-CH, Accept-Charset, Accept-Datetime, Accept-Encoding, Accept-Ext, Accept-Features, Accept-Language, Accept-Params, Accept-Ranges, Access-Control-Allow-Credentials, Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin, Access-Control-Expose-Headers, Access-Control-Max-Age, Access-Control-Request-Headers, Access-Control-Request-Method, Age, Allow, Alternates, Authentication-Info, Authorization, C-Ext, C-Man, C-Opt, C-PEP, C-PEP-Info, CONNECT, Cache-Control, Compliance, Connection, Content-Base, Content-Disposition, Content-Encoding, Content-ID, Content-Language, Content-Length, Content-Location, Content-MD5, Content-Range, Content-Script-Type, Content-Security-Policy, Content-Style-Type, Content-Transfer-Encoding, Content-Type, Content-Version, Cookie, Cost, DAV, DELETE, DNT, DPR, Date, Default-Style, Delta-Base, Depth, Derived-From, Destination, Differential-ID, Digest, ETag, Expect, Expires, Ext, From, GET, GetProfile, HEAD, HTTP-date, Host, IM, If, If-Match, If-Modified-Since, If-None-Match, If-Range, If-Unmodified-Since, Keep-Alive, Label, Last-Event-ID, Last-Modified, Link, Location, Lock-Token, MIME-Version, Man, Max-Forwards, Media-Range, Message-ID, Meter, Negotiate, Non-Compliance, OPTION, OPTIONS, OWS, Opt, Optional, Ordering-Type, Origin, Overwrite, P3P, PEP, PICS-Label, POST, PUT, Pep-Info, Permanent, Position, Pragma, ProfileObject, Protocol, Protocol-Query, Protocol-Request, Proxy-Authenticate, Proxy-Authentication-Info, Proxy-Authorization, Proxy-Features, Proxy-Instruction, Public, RWS, Range, Referer, Refresh, Resolution-Hint, Resolver-Location, Retry-After, Safe, Sec-Websocket-Extensions, Sec-Websocket-Key, Sec-Websocket-Origin, Sec-Websocket-Protocol, Sec-Websocket-Version, Security-Scheme, Server, Set-Cookie, Set-Cookie2, SetProfile, SoapAction, Status, Status-URI, Strict-Transport-Security, SubOK, Subst, Surrogate-Capability, Surrogate-Control, TCN, TE, TRACE, Timeout, Title, Trailer, Transfer-Encoding, UA-Color, UA-Media, UA-Pixels, UA-Resolution, UA-Windowpixels, URI, Upgrade, User-Agent, Variant-Vary, Vary, Version, Via, Viewport-Width, WWW-Authenticate, Want-Digest, Warning, Width, X-Content-Duration, X-Content-Security-Policy, X-Content-Type-Options, X-CustomHeader, X-DNSPrefetch-Control, X-Forwarded-For, X-Forwarded-Port, X-Forwarded-Proto, X-Frame-Options, X-Modified, X-OTHER, X-PING, X-PINGOTHER, X-Powered-By, X-Requested-With"
  Header set   Access-Control-Expose-Headers      "Accept, Accept-CH, Accept-Charset, Accept-Datetime, Accept-Encoding, Accept-Ext, Accept-Features, Accept-Language, Accept-Params, Accept-Ranges, Access-Control-Allow-Credentials, Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin, Access-Control-Expose-Headers, Access-Control-Max-Age, Access-Control-Request-Headers, Access-Control-Request-Method, Age, Allow, Alternates, Authentication-Info, Authorization, C-Ext, C-Man, C-Opt, C-PEP, C-PEP-Info, CONNECT, Cache-Control, Compliance, Connection, Content-Base, Content-Disposition, Content-Encoding, Content-ID, Content-Language, Content-Length, Content-Location, Content-MD5, Content-Range, Content-Script-Type, Content-Security-Policy, Content-Style-Type, Content-Transfer-Encoding, Content-Type, Content-Version, Cookie, Cost, DAV, DELETE, DNT, DPR, Date, Default-Style, Delta-Base, Depth, Derived-From, Destination, Differential-ID, Digest, ETag, Expect, Expires, Ext, From, GET, GetProfile, HEAD, HTTP-date, Host, IM, If, If-Match, If-Modified-Since, If-None-Match, If-Range, If-Unmodified-Since, Keep-Alive, Label, Last-Event-ID, Last-Modified, Link, Location, Lock-Token, MIME-Version, Man, Max-Forwards, Media-Range, Message-ID, Meter, Negotiate, Non-Compliance, OPTION, OPTIONS, OWS, Opt, Optional, Ordering-Type, Origin, Overwrite, P3P, PEP, PICS-Label, POST, PUT, Pep-Info, Permanent, Position, Pragma, ProfileObject, Protocol, Protocol-Query, Protocol-Request, Proxy-Authenticate, Proxy-Authentication-Info, Proxy-Authorization, Proxy-Features, Proxy-Instruction, Public, RWS, Range, Referer, Refresh, Resolution-Hint, Resolver-Location, Retry-After, Safe, Sec-Websocket-Extensions, Sec-Websocket-Key, Sec-Websocket-Origin, Sec-Websocket-Protocol, Sec-Websocket-Version, Security-Scheme, Server, Set-Cookie, Set-Cookie2, SetProfile, SoapAction, Status, Status-URI, Strict-Transport-Security, SubOK, Subst, Surrogate-Capability, Surrogate-Control, TCN, TE, TRACE, Timeout, Title, Trailer, Transfer-Encoding, UA-Color, UA-Media, UA-Pixels, UA-Resolution, UA-Windowpixels, URI, Upgrade, User-Agent, Variant-Vary, Vary, Version, Via, Viewport-Width, WWW-Authenticate, Want-Digest, Warning, Width, X-Content-Duration, X-Content-Security-Policy, X-Content-Type-Options, X-CustomHeader, X-DNSPrefetch-Control, X-Forwarded-For, X-Forwarded-Port, X-Forwarded-Proto, X-Frame-Options, X-Modified, X-OTHER, X-PING, X-PINGOTHER, X-Powered-By, X-Requested-With"
  Header set   Access-Control-Allow-Methods       "CONNECT, DEBUG, DELETE, DONE, GET, HEAD, HTTP, HTTP/0.9, HTTP/1.0, HTTP/1.1, HTTP/2, OPTIONS, ORIGIN, ORIGINS, PATCH, POST, PUT, QUIC, REST, SESSION, SHOULD, SPDY, TRACE, TRACK"
  Header set   Access-Control-Allow-Credentials   "true"

  Header set DNT "0"
  Header set Accept-Ranges "bytes"
  Header set Vary "Accept-Encoding"
  Header set X-UA-Compatible "IE=edge,chrome=1"
  Header set X-Frame-Options "SAMEORIGIN"
  Header set X-Content-Type-Options "nosniff"
  Header set X-Xss-Protection "1; mode=block"
</IfModule>

F.A.Q:

  • Why Access-Control-Allow-Headers, Access-Control-Expose-Headers, Access-Control-Allow-Methods values are super long?

    Those do not support the * syntax, so I've collected the most common (and exotic) headers from around the web, in various formats #1 #2 #3 (and I will update the list from time to time)

  • Why do you use Header unset ______ syntax?

    GoDaddy servers (which my website is hosted on..) have a weird bug where if the headers are already set, the previous value will join the existing one.. (instead of replacing it) this way I "pre-clean" existing values (really just a a quick && dirty solution)

  • Is it safe for me to use 'as-is'?

    Well.. mostly the answer would be YES since the .htaccess is limiting the headers to the scripts (PHP, HTML, ...) and resources (.JPG, .JS, .CSS) served from the following "folder"-location. You optionally might want to remove the Access-Control-Allow-Methods lines. Also Connection, Time-Zone, Keep-Alive and DNT, Accept-Ranges, Vary, X-UA-Compatible, X-Frame-Options, X-Content-Type-Options and X-Xss-Protection are just a suggestion I'm using for my online-service.. feel free to remove those too...

taken from my comment above

How can I import a large (14 GB) MySQL dump file into a new MySQL database?

I've searched around, and only this solution helped me:

mysql -u root -p

set global net_buffer_length=1000000; --Set network buffer length to a large byte number

set global max_allowed_packet=1000000000; --Set maximum allowed packet size to a large byte number

SET foreign_key_checks = 0; --Disable foreign key checking to avoid delays,errors and unwanted behaviour

source file.sql --Import your sql dump file

SET foreign_key_checks = 1; --Remember to enable foreign key checks when procedure is complete!

The answer is found here.

What are the rules for JavaScript's automatic semicolon insertion (ASI)?

Regarding semicolon insertion and the var statement, beware forgetting the comma when using var but spanning multiple lines. Somebody found this in my code yesterday:

    var srcRecords = src.records
        srcIds = [];

It ran but the effect was that the srcIds declaration/assignment was global because the local declaration with var on the previous line no longer applied as that statement was considered finished due to automatic semi-colon insertion.

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

I had the same problem with a stripes taglib uri showing as not found. I was using Indigo and Maven and when I checked Properties->Java Build Path->Order & Export Tab I found (on a fresh project checkout) that the "Maven Dependencies" checkbox was unchecked for some reason. Simply checking that box and doing a Maven clean install cleared all the errors.

I wonder why Eclipse doesn't assume I want my Maven dependencies in the build path...

how to assign a block of html code to a javascript variable

Please use symbol backtick '`' in your front and end of html string, this is so called template literals, now you able to write pure html in multiple lines and assign to variable.

Example >>

var htmlString =

`

<span>Your</span>
<p>HTML</p>

`

CSS3 transform not working

In webkit-based browsers(Safari and Chrome), -webkit-transform is ignored on inline elements.. Set display: inline-block; to make it work. For demonstration/testing purposes, you may also want to use a negative angle or a transformation-origin lest the text is rotated out of the visible area.

How do I "decompile" Java class files?

I use JAD Decompiler.

There is an Eclipse plugin for it, jadeclipse. It is pretty nice.

C#: HttpClient with POST parameters

A cleaner alternative would be to use a Dictionary to handle parameters. They are key-value pairs after all.

private static readonly HttpClient httpclient;

static MyClassName()
{
    // HttpClient is intended to be instantiated once and re-used throughout the life of an application. 
    // Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads. 
    // This will result in SocketException errors.
    // https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.7.1
    httpclient = new HttpClient();    
} 

var url = "http://myserver/method";
var parameters = new Dictionary<string, string> { { "param1", "1" }, { "param2", "2" } };
var encodedContent = new FormUrlEncodedContent (parameters);

var response = await httpclient.PostAsync (url, encodedContent).ConfigureAwait (false);
if (response.StatusCode == HttpStatusCode.OK) {
    // Do something with response. Example get content:
    // var responseContent = await response.Content.ReadAsStringAsync ().ConfigureAwait (false);
}

Also dont forget to Dispose() httpclient, if you dont use the keyword using

As stated in the Remarks section of the HttpClient class in the Microsoft docs, HttpClient should be instantiated once and re-used.

Edit:

You may want to look into response.EnsureSuccessStatusCode(); instead of if (response.StatusCode == HttpStatusCode.OK).

You may want to keep your httpclient and dont Dispose() it. See: Do HttpClient and HttpClientHandler have to be disposed?

Edit:

Do not worry about using .ConfigureAwait(false) in .NET Core. For more details look at https://blog.stephencleary.com/2017/03/aspnetcore-synchronization-context.html

How to find rows that have a value that contains a lowercase letter

I have to add BINARY to the ColumnX, to get result as case sensitive

SELECT * FROM MyTable WHERE BINARY(ColumnX) REGEXP '^[a-z]';

Define a fixed-size list in Java

The public java.util.List subclasses of the JDK don't provide a fixed size feature that doesn't make part of the List specification.
You could find it only in Queue subclasses (for example ArrayBlockingQueue, a bounded blocking queue backed by an array for example) that handle very specific requirements.

In Java, with a List type, you could implement it according to two scenarios :

1) The fixed list size is always both the actual and the maximum size.

It sounds as an array definition. So Arrays.asList() that returns a fixed-size list backed by the specified array is what you are looking for. And as with an array you can neither increase nor decrease its size but only changing its content. So adding and removing operation are not supported.

For example :

Foo[] foosInput= ...;
List<Foo> foos = Arrays.asList(foosInput);
foos.add(new Foo()); // throws an Exception
foos.remove(new Foo()); // throws an Exception

It works also with a collection as input while first we convert it into an array :

Collection<Foo> foosInput= ...;
List<Foo> foos = Arrays.asList(foosInput.toArray(Foo[]::new)); // Java 11 way
// Or
List<Foo> foos = Arrays.asList(foosInput.stream().toArray(Foo[]::new)); // Java 8 way

2) The list content is not known as soon as its creation. So you mean by fixed size list its maximum size.

You could use inheritance (extends ArrayList) but you should favor composition over that since it allows you to not couple your class with the implementation details of this implementation and provides also flexibility about the implementation of the decorated/composed.

With Guava Forwarding classes you could do :

import com.google.common.collect.ForwardingList;

public class FixedSizeList<T> extends ForwardingList<T> {

  private final List<T> delegate;
  private final int maxSize;

  public FixedSizeList(List<T> delegate, int maxSize) {
    this.delegate = delegate;
    this.maxSize = maxSize;
  }

  @Override protected List<T> delegate() {
    return delegate;
  }

  @Override public boolean add(T element) {
    assertMaxSizeNotReached(1);
    return super.add(element);
  }

  @Override public void add(int index, T element) {
    assertMaxSizeNotReached(1);
    super.add(index, element);
  }

  @Override public boolean addAll(Collection<? extends T> collection) {
    assertMaxSizeNotReached(collection.size());
    return super.addAll(collection);
  }

  @Override public boolean addAll(int index, Collection<? extends T> elements) {
    assertMaxSizeNotReached(elements.size());
    return super.addAll(index, elements);
  }    

  private void assertMaxSizeNotReached(int size) {
    if (delegate.size() + size >= maxSize) {
      throw new RuntimeException("size max reached");
    }
  }

}

And use it :

List<String> fixedSizeList = new FixedSizeList<>(new ArrayList<>(), 3); 
fixedSizeList.addAll(Arrays.asList("1", "2", "3"));
fixedSizeList.add("4");  // throws an Exception

Note that with composition, you could use it with any List implementation :

List<String> fixedSizeList = new FixedSizeList<>(new LinkedList<>(), 3); 
//...

Which is not possible with inheritance.

How can I have Github on my own server?

Also you can install Trac. It's more than a Git server, it has other feature like tickets management and project management. Also it has the possiblity to extend it through plugins.

Is there a way to make npm install (the command) to work behind proxy?

Have you tried command-line options instead of the .npmrc file?

I think something like npm --proxy http://proxy-server:8080/ install {package-name} worked for me.

I've also seen the following: npm config set proxy http://proxy-server:8080/

HTML form with two submit buttons and two "target" attributes

I do this on the server-side. That is, the form always submits to the same target, but I've got a server-side script who is responsible for redirecting to the appropriate location depending on what button was pressed.

If you have multiple buttons, such as

<form action="mypage" method="get">

  <input type="submit" name="retry" value="Retry" />
  <input type="submit" name="abort" value="Abort" />

</form>

Note : I used GET, but it works for POST too

Then you can easily determine which button was pressed - if the variable retry exists and has a value then retry was pressed, and if the variable abort exists and has a value then abort was pressed. This knowledge can then be used to redirect to the appropriate place.

This method needs no Javascript.

Note : that some browsers are capable of submitting a form without pressing any buttons (by pressing enter). Non-standard as this is, you have to account for it, by having a clear default action and activating that whenever no buttons were pressed. In other words, make sure your form does something sensible (whether that's displaying a helpful error message or assuming a default) when someone hits enter in a different form element instead of clicking a submit button, rather than just breaking.

How do I update Ruby Gems from behind a Proxy (ISA-NTLM)

I've been using cntlm (http://cntlm.sourceforge.net/) at work. Configuration is very similar to ntlmaps.

Works great, and also allows me to connect my Ubuntu box to the ISA proxy.

Check out http://cntlm.wiki.sourceforge.net/ for more information

Count the number of commits on a Git branch

It might require a relatively recent version of Git, but this works well for me:

git rev-list --count develop..HEAD

This gives me an exact count of commits in the current branch having its base on master.

The command in Peter's answer, git rev-list --count HEAD ^develop includes many more commits, 678 vs 97 on my current project.

My commit history is linear on this branch, so YMMV, but it gives me the exact answer I wanted, which is "How many commits have I added so far on this feature branch?".

How do I test a private function or a class that has private methods, fields or inner classes?

Android has @VisibleForTesting annotation from android.support.annotation package.

The @VisibleForTesting annotation indicates that an annotated method is more visible than normally necessary to make the method testable. This annotation has an optional otherwise argument that lets you designate what the visibility of the method should have been if not for the need to make it visible for testing. Lint uses the otherwise argument to enforce the intended visibility.

On the practice it means that you should make a method open for testing and the @VisibleForTesting annotation will show a warning.

For example

package com.mypackage;

public class ClassA {

    @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
    static void myMethod() {

    }
}

And when you call ClassA.myMethod() within the same package(com.mypackage) you will see the warning.

enter image description here

Returning IEnumerable<T> vs. IQueryable<T>

Yes, both will give you deferred execution.

The difference is that IQueryable<T> is the interface that allows LINQ-to-SQL (LINQ.-to-anything really) to work. So if you further refine your query on an IQueryable<T>, that query will be executed in the database, if possible.

For the IEnumerable<T> case, it will be LINQ-to-object, meaning that all objects matching the original query will have to be loaded into memory from the database.

In code:

IQueryable<Customer> custs = ...;
// Later on...
var goldCustomers = custs.Where(c => c.IsGold);

That code will execute SQL to only select gold customers. The following code, on the other hand, will execute the original query in the database, then filtering out the non-gold customers in the memory:

IEnumerable<Customer> custs = ...;
// Later on...
var goldCustomers = custs.Where(c => c.IsGold);

This is quite an important difference, and working on IQueryable<T> can in many cases save you from returning too many rows from the database. Another prime example is doing paging: If you use Take and Skip on IQueryable, you will only get the number of rows requested; doing that on an IEnumerable<T> will cause all of your rows to be loaded in memory.

Detect if string contains any spaces

function hasSpaces(str) {
  if (str.indexOf(' ') !== -1) {
    return true
  } else {
    return false
  }
}

Update Angular model after setting input value with jQuery

I've written this little plugin for jQuery which will make all calls to .val(value) update the angular element if present:

(function($, ng) {
  'use strict';

  var $val = $.fn.val; // save original jQuery function

  // override jQuery function
  $.fn.val = function (value) {
    // if getter, just return original
    if (!arguments.length) {
      return $val.call(this);
    }

    // get result of original function
    var result = $val.call(this, value);

    // trigger angular input (this[0] is the DOM object)
    ng.element(this[0]).triggerHandler('input');

    // return the original result
    return result; 
  }
})(window.jQuery, window.angular);

Just pop this script in after jQuery and angular.js and val(value) updates should now play nice.


Minified version:

!function(n,t){"use strict";var r=n.fn.val;n.fn.val=function(n){if(!arguments.length)return r.call(this);var e=r.call(this,n);return t.element(this[0]).triggerHandler("input"),e}}(window.jQuery,window.angular);

Example:

_x000D_
_x000D_
// the function_x000D_
(function($, ng) {_x000D_
  'use strict';_x000D_
  _x000D_
  var $val = $.fn.val;_x000D_
  _x000D_
  $.fn.val = function (value) {_x000D_
    if (!arguments.length) {_x000D_
      return $val.call(this);_x000D_
    }_x000D_
    _x000D_
    var result = $val.call(this, value);_x000D_
    _x000D_
    ng.element(this[0]).triggerHandler('input');_x000D_
    _x000D_
    return result;_x000D_
    _x000D_
  }_x000D_
})(window.jQuery, window.angular);_x000D_
_x000D_
(function(ng){ _x000D_
  ng.module('example', [])_x000D_
    .controller('ExampleController', function($scope) {_x000D_
      $scope.output = "output";_x000D_
      _x000D_
      $scope.change = function() {_x000D_
        $scope.output = "" + $scope.input;_x000D_
      }_x000D_
    });_x000D_
})(window.angular);_x000D_
_x000D_
(function($){  _x000D_
  $(function() {_x000D_
    var button = $('#button');_x000D_
  _x000D_
    if (button.length)_x000D_
      console.log('hello, button');_x000D_
    _x000D_
    button.click(function() {_x000D_
      var input = $('#input');_x000D_
      _x000D_
      var value = parseInt(input.val());_x000D_
      value = isNaN(value) ? 0 : value;_x000D_
      _x000D_
      input.val(value + 1);_x000D_
    });_x000D_
  });_x000D_
})(window.jQuery);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div ng-app="example" ng-controller="ExampleController">_x000D_
  <input type="number" id="input" ng-model="input" ng-change="change()" />_x000D_
  <span>{{output}}</span>_x000D_
  <button id="button">+</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Should ol/ul be inside <p> or outside?

actually you should only put in-line elements inside the p, so in your case ol is better outside

multiple prints on the same line in Python

Use sys.stdout.write('Installing XXX... ') and sys.stdout.write('Done'). In this way, you have to add the new line by hand with "\n" if you want to recreate the print functionality. I think that it might be unnecessary to use curses just for this.

How to redirect 404 errors to a page in ExpressJS?

The 404 page should be set up just before the call to app.listen.Express has support for * in route paths. This is a special character which matches anything. This can be used to create a route handler that matches all requests.

app.get('*', (req, res) => {
  res.render('404', {
    title: '404',
    name: 'test',
    errorMessage: 'Page not found.'
  })
})

What's the best practice using a settings file in Python?

The sample config you provided is actually valid YAML. In fact, YAML meets all of your demands, is implemented in a large number of languages, and is extremely human friendly. I would highly recommend you use it. The PyYAML project provides a nice python module, that implements YAML.

To use the yaml module is extremely simple:

import yaml
config = yaml.safe_load(open("path/to/config.yml"))

Move the most recent commit(s) to a new branch with Git

How can I go from this

A - B - C - D - E 
                |
                master

to this?

A - B - C - D - E 
    |           |
    master      newbranch

With two commands

  • git branch -m master newbranch

giving

A - B - C - D - E 
                |
                newbranch

and

  • git branch master B

giving

A - B - C - D - E
    |           |
    master      newbranch

Response Content type as CSV

Over the years I've been honing a perfect set of headers for this that work brilliantly in all browsers that I know of

// these headers avoid IE problems when using https:
// see http://support.microsoft.com/kb/812935
header("Cache-Control: must-revalidate");
header("Pragma: must-revalidate");

header("Content-type: application/vnd.ms-excel");
header("Content-disposition: attachment; filename=$filename.csv");

Can I avoid the native fullscreen video player with HTML5 on iPhone or android?

There's a property that enables/disables in line media playback in the iOS web browser (if you were writing a native app, it would be the allowsInlineMediaPlayback property of a UIWebView). By default on iPhone this is set to NO, but on iPad it's set to YES.

Fortunately for you, you can also adjust this behaviour in HTML as follows:

<video id="myVideo" width="280" height="140" webkit-playsinline>

...that should hopefully sort it out for you. I don't know if it will work on your Android devices. It's a webkit property, so it might. Worth a go, anyway.

No 'Access-Control-Allow-Origin' header is present on the requested resource - Resteasy

Seems your resource POSTmethod won't get hit as @peeskillet mention. Most probably your ~POST~ request won't work, because it may not be a simple request. The only simple requests are GET, HEAD or POST and request headers are simple(The only simple headers are Accept, Accept-Language, Content-Language, Content-Type= application/x-www-form-urlencoded, multipart/form-data, text/plain).

Since in you already add Access-Control-Allow-Origin headers to your Response, you can add new OPTIONS method to your resource class.

    @OPTIONS
@Path("{path : .*}")
public Response options() {
    return Response.ok("")
            .header("Access-Control-Allow-Origin", "*")
            .header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization")
            .header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD")
            .header("Access-Control-Max-Age", "2000")
            .build();
}

Appending output of a Batch file To log file

Instead of using ">" to redirect like this:

java Foo > log

use ">>" to append normal "stdout" output to a new or existing file:

java Foo >> log

However, if you also want to capture "stderr" errors (such as why the Java program couldn't be started), you should also use the "2>&1" tag which redirects "stderr" (the "2") to "stdout" (the "1"). For example:

java Foo >> log 2>&1 

LINQ to read XML

XDocument xdoc = XDocument.Load("data.xml");
var lv1s = xdoc.Root.Descendants("level1"); 
var lvs = lv1s.SelectMany(l=>
     new string[]{ l.Attribute("name").Value }
     .Union(
         l.Descendants("level2")
         .Select(l2=>"   " + l2.Attribute("name").Value)
      )
    );
foreach (var lv in lvs)
{
   result.AppendLine(lv);
}

Ps. You have to use .Root on any of these versions.

get url content PHP

Try using cURL instead. cURL implements a cookie jar, while file_get_contents doesn't.

What is Java String interning?

Update for Java 8 or plus. In Java 8, PermGen (Permanent Generation) space is removed and replaced by Meta Space. The String pool memory is moved to the heap of JVM.

Compared with Java 7, the String pool size is increased in the heap. Therefore, you have more space for internalized Strings, but you have less memory for the whole application.

One more thing, you have already known that when comparing 2 (referrences of) objects in Java, '==' is used for comparing the reference of object, 'equals' is used for comparing the contents of object.

Let's check this code:

String value1 = "70";
String value2 = "70";
String value3 = new Integer(70).toString();

Result:

value1 == value2 ---> true

value1 == value3 ---> false

value1.equals(value3) ---> true

value1 == value3.intern() ---> true

That's why you should use 'equals' to compare 2 String objects. And that's is how intern() is useful.

How to quietly remove a directory with content in PowerShell

rm -Force -Recurse -Confirm:$false $directory2Delete didn't work in the PowerShell ISE, but it worked through the regular PowerShell CLI.

I hope this helps. It was driving me bannanas.

How do I fix 'ImportError: cannot import name IncompleteRead'?

My version of pip on ubuntu suggests:

  pip install --upgrade pip

Securing a password in a properties file

What about providing a custom N-Factor authentication mechanism?

Before combining available methods, let's assume we can perform the following:

1) Hard-code inside the Java program

2) Store in a .properties file

3) Ask user to type password from command line

4) Ask user to type password from a form

5) Ask user to load a password-file from command line or a form

6) Provide the password through network

7) many alternatives (eg Draw A Secret, Fingerprint, IP-specific, bla bla bla)

1st option: We could make things more complicated for an attacker by using obfuscation, but this is not considered a good countermeasure. A good coder can easily understand how it works if he/she can access the file. We could even export a per-user binary (or just the obfuscation part or key-part), so an attacker must have access to this user-specific file, not another distro. Again, we should find a way to change passwords, eg by recompiling or using reflection to on-the-fly change class behavior.

2nd option: We can store the password in the .properties file in an encrypted format, so it's not directly visible from an attacker (just like jasypt does). If we need a password manager we'll need a master password too which again should be stored somewhere - inside a .class file, the keystore, kernel, another file or even in memory - all have their pros and cons.
But, now users will just edit the .properties file for password change.

3rd option: type the password when running from command line e.g. java -jar /myprogram.jar -p sdflhjkiweHIUHIU8976hyd.

This doesn't require the password to be stored and will stay in memory. However, history commands and OS logs, may be your worst enemy here. To change passwords on-the-fly, you will need to implement some methods (eg listen for console inputs, RMI, sockets, REST bla bla bla), but the password will always stay in memory.

One can even temporarily decrypt it only when required -> then delete the decrypted, but always keep the encrypted password in memory. Unfortunately, the aforementioned method does not increase security against unauthorized in-memory access, because the person who achieves that, will probably have access to the algorithm, salt and any other secrets being used.

4th option: provide the password from a custom form, rather than the command line. This will circumvent the problem of logging exposure.

5th option: provide a file as a password stored previously on a another medium -> then hard delete file. This will again circumvent the problem of logging exposure, plus no typing is required that could be shoulder-surfing stolen. When a change is required, provide another file, then delete again.

6th option: again to avoid shoulder-surfing, one can implement an RMI method call, to provide the password (through an encrypted channel) from another device, eg via a mobile phone. However, you now need to protect your network channel and access to the other device.

I would choose a combination of the above methods to achieve maximum security so one would have to access the .class files, the property file, logs, network channel, shoulder surfing, man in the middle, other files bla bla bla. This can be easily implemented using a XOR operation between all sub_passwords to produce the actual password.

We can't be protected from unauthorized in-memory access though, this can only be achieved by using some access-restricted hardware (eg smartcards, HSMs, SGX), where everything is computed into them, without anyone, even the legitimate owner being able to access decryption keys or algorithms. Again, one can steal this hardware too, there are reported side-channel attacks that may help attackers in key extraction and in some cases you need to trust another party (eg with SGX you trust Intel). Of course, situation may worsen when secure-enclave cloning (de-assembling) will be possible, but I guess this will take some years to be practical.

Also, one may consider a key sharing solution where the full key is split between different servers. However, upon reconstruction, the full key can be stolen. The only way to mitigate the aforementioned issue is by secure multiparty computation.

We should always keep in mind that whatever the input method, we need to ensure we are not vulnerable from network sniffing (MITM attacks) and/or key-loggers.

Download text/csv content as files from server in Angular

Most of the references on the web about this issue point out to the fact that you cannot download files via ajax call 'out of the box'. I have seen (hackish) solutions that involve iframes and also solutions like @dcodesmith's that work and are perfectly viable.

Here's another solution I found that works in Angular and is very straighforward.

In the view, wrap the csv download button with <a> tag the following way :

<a target="_self" ng-href="{{csv_link}}">
  <button>download csv</button>
</a>

(Notice the target="_self there, it's crucial to disable Angular's routing inside the ng-app more about it here)

Inside youre controller you can define csv_link the following way :

$scope.csv_link = '/orders' + $window.location.search;

(the $window.location.search is optional and onlt if you want to pass additionaly search query to your server)

Now everytime you click the button, it should start downloading.

How do I calculate tables size in Oracle

I modified the query to get the schema size per tablespace ..

SELECT owner,
     tablespace_name,
     TRUNC (SUM (bytes) / 1024 / 1024)   Meg,
     ROUND (ratio_to_report (SUM (bytes)) OVER () * 100) Percent
FROM (SELECT tablespace_name, owner, bytes
        FROM dba_segments
       WHERE segment_type IN
                 ('TABLE', 'TABLE PARTITION', 'TABLE SUBPARTITION')
      UNION ALL
      SELECT i.tablespace_name, i.owner, s.bytes
        FROM dba_indexes i, dba_segments s
       WHERE     s.segment_name = i.index_name
             AND s.owner = i.owner
             AND s.segment_type IN
                     ('INDEX', 'INDEX PARTITION', 'INDEX SUBPARTITION')
      UNION ALL
      SELECT l.tablespace_name, l.owner, s.bytes
        FROM dba_lobs l, dba_segments s
       WHERE     s.segment_name = l.segment_name
             AND s.owner = l.owner
             AND s.segment_type IN ('LOBSEGMENT', 'LOB PARTITION')
      UNION ALL
      SELECT l.tablespace_name, l.owner, s.bytes
        FROM dba_lobs l, dba_segments s
       WHERE     s.segment_name = l.index_name
             AND s.owner = l.owner
             AND s.segment_type = 'LOBINDEX')
WHERE owner IN UPPER ('&owner')
GROUP BY owner, tablespace_name
--HAVING SUM(bytes)/1024/1024 > 10  /* Ignore really small tables */
ORDER BY tablespace_name -- desc
;

"Cannot open include file: 'config-win.h': No such file or directory" while installing mysql-python

Most probably the answer is to install MySQL Developer Build and selecting "C headers\libs" option during configuration. (as reported in this entry: Building MySQLdb for Python on Windows on rationalpie.wordpress.com)

Maybe even better solution is to install a precompiled build: http://www.technicalbard.com/files/MySQL-python-1.2.2.win32-py2.6.exe

Select entries between dates in doctrine 2


    EDIT: See the other answers for better solutions

The original newbie approaches that I offered were (opt1):

$qb->where("e.fecha > '" . $monday->format('Y-m-d') . "'");
$qb->andWhere("e.fecha < '" . $sunday->format('Y-m-d') . "'");

And (opt2):

$qb->add('where', "e.fecha between '2012-01-01' and '2012-10-10'");

That was quick and easy and got the original poster going immediately.

Hence the accepted answer.

As per comments, it is the wrong answer, but it's an easy mistake to make, so I'm leaving it here as a "what not to do!"

A select query selecting a select statement

Not sure if Access supports it, but in most engines (including SQL Server) this is called a correlated subquery and works fine:

SELECT  TypesAndBread.Type, TypesAndBread.TBName,
        (
        SELECT  Count(Sandwiches.[SandwichID]) As SandwichCount
        FROM    Sandwiches
        WHERE   (Type = 'Sandwich Type' AND Sandwiches.Type = TypesAndBread.TBName)
                OR (Type = 'Bread' AND Sandwiches.Bread = TypesAndBread.TBName)
        ) As SandwichCount
FROM    TypesAndBread

This can be made more efficient by indexing Type and Bread and distributing the subqueries over the UNION:

SELECT  [Sandwiches Types].[Sandwich Type] As TBName, "Sandwich Type" As Type,
        (
        SELECT  COUNT(*) As SandwichCount
        FROM    Sandwiches
        WHERE   Sandwiches.Type = [Sandwiches Types].[Sandwich Type]
        )
FROM    [Sandwiches Types]
UNION ALL
SELECT  [Breads].[Bread] As TBName, "Bread" As Type,
        (
        SELECT  COUNT(*) As SandwichCount
        FROM    Sandwiches
        WHERE   Sandwiches.Bread = [Breads].[Bread]
        )
FROM    [Breads]

Save string to the NSUserDefaults?

Here Swift updated:

let userID = "BOB"  

Declare userDefaults:

let defaults = UserDefaults.standard
defaults.setValue(userID, forKey: "userID")

And get it:

let userID = defaults.object(forKey: "userID")

Git: Remove committed file after push

If you want to remove the file from the remote repo, first remove it from your project with --cache option and then push it:

git rm --cache /path/to/file
git commit -am "Remove file"
git push

(This works even if the file was added to the remote repo some commits ago) Remember to add to .gitignore the file extensions that you don't want to push.

PHP: if !empty & empty

Here's a compact way to do something different in all four cases:

if(empty($youtube)) {
    if(empty($link)) {
        # both empty
    } else {
        # only $youtube not empty
    }
} else {
    if(empty($link)) {
        # only $link empty
    } else {
        # both not empty
    }
}

If you want to use an expression instead, you can use ?: instead:

echo empty($youtube) ? ( empty($link) ? 'both empty' : 'only $youtube not empty' )
                     : ( empty($link) ? 'only $link empty' : 'both not empty' );

Use and meaning of "in" in an if statement?

It depends on what next is.

If it's a string (as in your example), then in checks for substrings.

>>> "in" in "indigo"
True
>>> "in" in "violet"
False
>>> "0" in "10"
True
>>> "1" in "10"
True

If it's a different kind of iterable (list, tuple, set, dictionary...), then in checks for membership.

>>> "in" in ["in", "out"]
True
>>> "in" in ["indigo", "violet"]
False

In a dictionary, membership is seen as "being one of the keys":

>>> "in" in {"in": "out"}
True
>>> "in" in {"out": "in"}
False

Converting a POSTMAN request to Curl

Starting from Postman 8 you need to visit here

enter image description here

Bootstrap: wider input field

There are various classes for different size inputs

 :class=>"input-mini"

 :class=>"input-small"

 :class=>"input-medium"

 :class=>"input-large"

 :class=>"input-xlarge"

 :class=>"input-xxlarge"

How to set the environmental variable LD_LIBRARY_PATH in linux

The file .bash_profile is only executed by login shells. You may need to put it in ~/.bashrc, or simply logout and login again.

Dealing with "java.lang.OutOfMemoryError: PermGen space" error

resolved this for me as well; however, I noticed that the servlet restart times were much worse, so while it was better in production, it was kind of a drag in development.

Histogram Matplotlib

import matplotlib.pyplot as plt
import numpy as np

mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
hist, bins = np.histogram(x, bins=50)
width = 0.7 * (bins[1] - bins[0])
center = (bins[:-1] + bins[1:]) / 2
plt.bar(center, hist, align='center', width=width)
plt.show()

enter image description here

The object-oriented interface is also straightforward:

fig, ax = plt.subplots()
ax.bar(center, hist, align='center', width=width)
fig.savefig("1.png")

If you are using custom (non-constant) bins, you can pass compute the widths using np.diff, pass the widths to ax.bar and use ax.set_xticks to label the bin edges:

import matplotlib.pyplot as plt
import numpy as np

mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
bins = [0, 40, 60, 75, 90, 110, 125, 140, 160, 200]
hist, bins = np.histogram(x, bins=bins)
width = np.diff(bins)
center = (bins[:-1] + bins[1:]) / 2

fig, ax = plt.subplots(figsize=(8,3))
ax.bar(center, hist, align='center', width=width)
ax.set_xticks(bins)
fig.savefig("/tmp/out.png")

plt.show()

enter image description here

Pylint "unresolved import" error in Visual Studio Code

Changing Python:Language Server to 'Jedi' worked for me. It was 'Windows' initially.

how to extract only the year from the date in sql server 2008?

year(table_column)

Example:

select * from mytable where year(transaction_day)='2013' 

Joining Spark dataframes on the key

Alias Approach using scala (this is example given for older version of spark for spark 2.x see my other answer) :

You can use case class to prepare sample dataset ... which is optional for ex: you can get DataFrame from hiveContext.sql as well..

import org.apache.spark.sql.functions.col

case class Person(name: String, age: Int, personid : Int)

case class Profile(name: String, personid  : Int , profileDescription: String)

    val df1 = sqlContext.createDataFrame(
   Person("Bindu",20,  2) 
:: Person("Raphel",25, 5) 
:: Person("Ram",40, 9):: Nil)


val df2 = sqlContext.createDataFrame(
Profile("Spark",2,  "SparkSQLMaster") 
:: Profile("Spark",5, "SparkGuru") 
:: Profile("Spark",9, "DevHunter"):: Nil
)

// you can do alias to refer column name with aliases to  increase readablity

val df_asPerson = df1.as("dfperson")
val df_asProfile = df2.as("dfprofile")


val joined_df = df_asPerson.join(
    df_asProfile
, col("dfperson.personid") === col("dfprofile.personid")
, "inner")


joined_df.select(
  col("dfperson.name")
, col("dfperson.age")
, col("dfprofile.name")
, col("dfprofile.profileDescription"))
.show

sample Temp table approach which I don't like personally...

The reason to use the registerTempTable( tableName ) method for a DataFrame, is so that in addition to being able to use the Spark-provided methods of a DataFrame, you can also issue SQL queries via the sqlContext.sql( sqlQuery ) method, that use that DataFrame as an SQL table. The tableName parameter specifies the table name to use for that DataFrame in the SQL queries.

df_asPerson.registerTempTable("dfperson");
df_asProfile.registerTempTable("dfprofile")

sqlContext.sql("""SELECT dfperson.name, dfperson.age, dfprofile.profileDescription
                  FROM  dfperson JOIN  dfprofile
                  ON dfperson.personid == dfprofile.personid""")

If you want to know more about joins pls see this nice post : beyond-traditional-join-with-apache-spark

enter image description here

Note : 1) As mentioned by @RaphaelRoth ,

val resultDf = PersonDf.join(ProfileDf,Seq("personId")) is good approach since it doesnt have duplicate columns from both sides if you are using inner join with same table.
2) Spark 2.x example updated in another answer with full set of join operations supported by spark 2.x with examples + result

TIP :

Also, important thing in joins : broadcast function can help to give hint please see my answer

Select all child elements recursively in CSS

Use a white space to match all descendants of an element:

div.dropdown * {
    color: red;
}

x y matches every element y that is inside x, however deeply nested it may be - children, grandchildren and so on.

The asterisk * matches any element.

Official Specification: CSS 2.1: Chapter 5.5: Descendant Selectors

How do I install a JRE or JDK to run the Android Developer Tools on Windows 7?

Eclipse: failed to create the java virtual machine – message box

  1. Open folder with Eclipse.exe and find eclipse.ini file
  2. Replace -vmargs by your current real path of javaw.exe with

    -vm "c:\Program Files\Java\jdk1.7.0_07\bin\javaw.exe"
    

    or in case you've installed jre only:

    -vm "C:\Program Files\Java\jre7\bin\javaw.exe"
    

Creating a class object in c++

Example example;

This is a declaration of a variable named example of type Example. This will default-initialize the object which involves calling its default constructor. The object will have automatic storage duration which means that it will be destroyed when it goes out of scope.

Example* example;

This is a declaration of a variable named example which is a pointer to an Example. In this case, default-initialization leaves it uninitialized - the pointer is pointing nowhere in particular. There is no Example object here. The pointer object has automatic storage duration.

Example* example = new Example();

This is a declaration of a variable named example which is a pointer to an Example. This pointer object, as above, has automatic storage duration. It is then initialized with the result of new Example();. This new expression creates an Example object with dynamic storage duration and then returns a pointer to it. So the example pointer is now pointing to that dynamically allocated object. The Example object is value-initialized which will call a user-provided constructor if there is one or otherwise initialise all members to 0.

Example* example = new Example;

This is similar to the previous line. The difference is that the Example object is default-initialized, which will call the default constructor of Example (or leave it uninitialized if it is not of class type).

A dynamically allocated object must be deleted (probably with delete example;).

What is the current choice for doing RPC in Python?

XML-RPC is part of the Python standard library:

What is ToString("N0") format?

This is where the documentation is:

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

The numeric ("N") format specifier converts a number to a string of the form "-d,ddd,ddd.ddd…", where "-" indicates a negative number symbol if required, "d" indicates a digit (0-9) ...

And this is where they talk about the default (2):

http://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.numberdecimaldigits.aspx

      // Displays a negative value with the default number of decimal digits (2).
      Int64 myInt = -1234;
      Console.WriteLine( myInt.ToString( "N", nfi ) );

Field 'browser' doesn't contain a valid alias configuration

In my case, it is due to a case-sensitivity typo in import path. For example,

Should be:

import Dashboard from './Dashboard/dashboard';

Instead of:

import Dashboard from './Dashboard/Dashboard';

How to calculate the number of occurrence of a given character in each row of a column of strings?

Yet another base R option could be:

lengths(lapply(q.data$string, grepRaw, pattern = "a", all = TRUE, fixed = TRUE))

[1] 2 1 0

Is it a good idea to index datetime field in mysql?

MySQL recommends using indexes for a variety of reasons including elimination of rows between conditions: http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html

This makes your datetime column an excellent candidate for an index if you are going to be using it in conditions frequently in queries. If your only condition is BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 30 DAY) and you have no other index in the condition, MySQL will have to do a full table scan on every query. I'm not sure how many rows are generated in 30 days, but as long as it's less than about 1/3 of the total rows it will be more efficient to use an index on the column.

Your question about creating an efficient database is very broad. I'd say to just make sure that it's normalized and all appropriate columns are indexed (i.e. ones used in joins and where clauses).

com.google.android.gms:play-services-measurement-base is being requested by various other libraries

I updated

implementation 'com.google.android.gms:play-services-analytics:16.0.3'

and it works for me

Increasing the Command Timeout for SQL command

Since it takes 2 mins to respond, you can increase the timeout to 3 mins by adding the below code

scGetruntotals.CommandTimeout = 180;

Note : the parameter value is in seconds.

jQuery click event on radio button doesn't get fired

Personally, for me, the best solution for a similar issue was:

HTML

<input type="radio" name="selectAll" value="true" />
<input type="radio" name="selectAll" value="false" />

JQuery

var $selectAll = $( "input:radio[name=selectAll]" );
    $selectAll.on( "change", function() {
         console.log( "selectAll: " + $(this).val() );
         // or
         alert( "selectAll: " + $(this).val() );
    });

*The event "click" can work in place of "change" as well.

Hope this helps!

SelectedValue vs SelectedItem.Value of DropDownList

In droupDown list there are two item add property.

1) Text 2) value

If you want to get text property then u use selecteditem.text

and If you want to select value property then use selectedvalue property

In your case i thing both value and text property are the same so no matter if u use selectedvalue or selecteditem.text

If both are different then they give us different results

How to get element value in jQuery

  <div class="inter">
      <p>Liste des Produits</p>
      <ul>
          <li><a href="#1">P1</a></li>
          <li><a href="#2">P2</a></li>
          <li><a href="#3">P3</a></li>
      </ul>
  </div>

        $(document).ready(function(){
            $(".inter li").bind(
            "click", function(){
                alert($(this).children("a").text());
            });
        });

Android Intent Cannot resolve constructor

Use

Intent myIntent = new Intent(v.getContext(), MyClass.class);

or

 Intent myIntent = new Intent(MyFragment.this.getActivity(), MyClass.class);

to start a new Activity. This is because you will need to pass Application or component context as a first parameter to the Intent Constructor when you are creating an Intent for a specific component of your application.

Progress Bar with HTML and CSS

There is a tutorial for creating an HTML5 progress bar here. If you don't want to use HTML5 methods or you are looking for an all-browser solution, try this code:

_x000D_
_x000D_
<div style="width: 150px; height: 25px; background-color: #dbdbdb;">
  <div style="height: 25px; width:87%; background-color: gold">&nbsp;</div>
</div>
_x000D_
_x000D_
_x000D_

You can change the color GOLD to any progress bar color and #dbdbdb to the background-color of your progress bar.

How to convert a NumPy array to PIL image applying matplotlib colormap

  • input = numpy_image
  • np.unit8 -> converts to integers
  • convert('RGB') -> converts to RGB
  • Image.fromarray -> returns an image object

    from PIL import Image
    import numpy as np
    
    PIL_image = Image.fromarray(np.uint8(numpy_image)).convert('RGB')
    
    PIL_image = Image.fromarray(numpy_image.astype('uint8'), 'RGB')
    

What is a race condition?

A sort-of-canonical definition is "when two threads access the same location in memory at the same time, and at least one of the accesses is a write." In the situation the "reader" thread may get the old value or the new value, depending on which thread "wins the race." This is not always a bug—in fact, some really hairy low-level algorithms do this on purpose—but it should generally be avoided. @Steve Gury give's a good example of when it might be a problem.

What are the differences between struct and class in C++?

You might consider this for guidelines on when to go for struct or class, https://msdn.microsoft.com/en-us/library/ms229017%28v=vs.110%29.aspx .

v CONSIDER defining a struct instead of a class if instances of the type are small and commonly short-lived or are commonly embedded in other objects.

X AVOID defining a struct unless the type has all of the following characteristics:

It logically represents a single value, similar to primitive types (int, double, etc.).

It has an instance size under 16 bytes.

It is immutable.

It will not have to be boxed frequently.

SSRS expression to format two decimal places does not show zeros

Format(Fields!CUL1.Value, "0.00") would work better since @abe suggests they want to show 0.00 , and if the value was 0, "#0.##" would show "0".

C: socket connection timeout

This article might help:

Connect with timeout (or another use for select() )

Looks like you put the socket into non-blocking mode until you've connected, and then put it back into blocking mode once the connection's established.

void connect_w_to(void) { 
  int res; 
  struct sockaddr_in addr; 
  long arg; 
  fd_set myset; 
  struct timeval tv; 
  int valopt; 
  socklen_t lon; 

  // Create socket 
  soc = socket(AF_INET, SOCK_STREAM, 0); 
  if (soc < 0) { 
     fprintf(stderr, "Error creating socket (%d %s)\n", errno, strerror(errno)); 
     exit(0); 
  } 

  addr.sin_family = AF_INET; 
  addr.sin_port = htons(2000); 
  addr.sin_addr.s_addr = inet_addr("192.168.0.1"); 

  // Set non-blocking 
  if( (arg = fcntl(soc, F_GETFL, NULL)) < 0) { 
     fprintf(stderr, "Error fcntl(..., F_GETFL) (%s)\n", strerror(errno)); 
     exit(0); 
  } 
  arg |= O_NONBLOCK; 
  if( fcntl(soc, F_SETFL, arg) < 0) { 
     fprintf(stderr, "Error fcntl(..., F_SETFL) (%s)\n", strerror(errno)); 
     exit(0); 
  } 
  // Trying to connect with timeout 
  res = connect(soc, (struct sockaddr *)&addr, sizeof(addr)); 
  if (res < 0) { 
     if (errno == EINPROGRESS) { 
        fprintf(stderr, "EINPROGRESS in connect() - selecting\n"); 
        do { 
           tv.tv_sec = 15; 
           tv.tv_usec = 0; 
           FD_ZERO(&myset); 
           FD_SET(soc, &myset); 
           res = select(soc+1, NULL, &myset, NULL, &tv); 
           if (res < 0 && errno != EINTR) { 
              fprintf(stderr, "Error connecting %d - %s\n", errno, strerror(errno)); 
              exit(0); 
           } 
           else if (res > 0) { 
              // Socket selected for write 
              lon = sizeof(int); 
              if (getsockopt(soc, SOL_SOCKET, SO_ERROR, (void*)(&valopt), &lon) < 0) { 
                 fprintf(stderr, "Error in getsockopt() %d - %s\n", errno, strerror(errno)); 
                 exit(0); 
              } 
              // Check the value returned... 
              if (valopt) { 
                 fprintf(stderr, "Error in delayed connection() %d - %s\n", valopt, strerror(valopt) 
); 
                 exit(0); 
              } 
              break; 
           } 
           else { 
              fprintf(stderr, "Timeout in select() - Cancelling!\n"); 
              exit(0); 
           } 
        } while (1); 
     } 
     else { 
        fprintf(stderr, "Error connecting %d - %s\n", errno, strerror(errno)); 
        exit(0); 
     } 
  } 
  // Set to blocking mode again... 
  if( (arg = fcntl(soc, F_GETFL, NULL)) < 0) { 
     fprintf(stderr, "Error fcntl(..., F_GETFL) (%s)\n", strerror(errno)); 
     exit(0); 
  } 
  arg &= (~O_NONBLOCK); 
  if( fcntl(soc, F_SETFL, arg) < 0) { 
     fprintf(stderr, "Error fcntl(..., F_SETFL) (%s)\n", strerror(errno)); 
     exit(0); 
  } 
  // I hope that is all 
}

Service vs IntentService in the Android platform

Adding points to the accepted answer:

See the usage of IntentService within Android API. eg:

public class SimpleWakefulService extends IntentService {
    public SimpleWakefulService() {
        super("SimpleWakefulService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {  ...}

To create an IntentService component for your app, define a class that extends IntentService, and within it, define a method that overrides onHandleIntent().

Also, see the source code of the IntentService, it's constructor and life cycle methods like onStartCommand...

  @Override
    public int More ...onStartCommand(Intent intent, int flags, int startId) {
       onStart(intent, startId);
        return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
    }

Service together an AsyncTask is one of best approaches for many use cases where the payload is not huge. or just create a class extending IntentSerivce. From Android version 4.0 all network operations should be in background process otherwise the application compile/build fails. separate thread from the UI. The AsyncTask class provides one of the simplest ways to fire off a new task from the UI thread. For more discussion of this topic, see the blog post

from Android developers guide:

IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent, in turn, using a worker thread, and stops itself when it runs out of work.

Design pattern used in IntentService

: This "work queue processor" pattern is commonly used to offload tasks from an application's main thread. The IntentService class exists to simplify this pattern and take care of the mechanics. To use it, extend IntentService and implement onHandleIntent(Intent). IntentService will receive the Intents, launch a worker thread, and stop the service as appropriate.

All requests are handled on a single worker thread -- they may take as long as necessary (and will not block the application's main loop), but only one request will be processed at a time.

The IntentService class provides a straightforward structure for running an operation on a single background thread. This allows it to handle long-running operations without affecting your user interface's responsiveness. Also, an IntentService isn't affected by most user interface lifecycle events, so it continues to run in circumstances that would shut down an AsyncTask.

An IntentService has a few limitations:

It can't interact directly with your user interface. To put its results in the UI, you have to send them to an Activity. Work requests run sequentially. If an operation is running in an IntentService, and you send it another request, the request waits until the first operation is finished. An operation running on an IntentService can't be interrupted. However, in most cases

IntentService is the preferred way to simple background operations

**

Volley Library

There is the library called volley-library for developing android networking applications The source code is available for the public in GitHub.

The android official documentation for Best practices for Background jobs: helps better understand on intent service, thread, handler, service. and also Performing Network Operations

What does the percentage sign mean in Python

In python 2.6 the '%' operator performed a modulus. I don't think they changed it in 3.0.1

The modulo operator tells you the remainder of a division of two numbers.

Prevent flex items from stretching

You don't want to stretch the span in height?
You have the possiblity to affect one or more flex-items to don't stretch the full height of the container.

To affect all flex-items of the container, choose this:
You have to set align-items: flex-start; to div and all flex-items of this container get the height of their content.

_x000D_
_x000D_
div {_x000D_
  align-items: flex-start;_x000D_
  background: tan;_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
}_x000D_
span {_x000D_
  background: red;_x000D_
}
_x000D_
<div>_x000D_
  <span>This is some text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

To affect only a single flex-item, choose this:
If you want to unstretch a single flex-item on the container, you have to set align-self: flex-start; to this flex-item. All other flex-items of the container aren't affected.

_x000D_
_x000D_
div {_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
  background: tan;_x000D_
}_x000D_
span.only {_x000D_
  background: red;_x000D_
  align-self:flex-start;_x000D_
}_x000D_
span {_x000D_
    background:green;_x000D_
}
_x000D_
<div>_x000D_
  <span class="only">This is some text.</span>_x000D_
  <span>This is more text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Why is this happening to the span?
The default value of the property align-items is stretch. This is the reason why the span fill the height of the div.

Difference between baseline and flex-start?
If you have some text on the flex-items, with different font-sizes, you can use the baseline of the first line to place the flex-item vertically. A flex-item with a smaller font-size have some space between the container and itself at top. With flex-start the flex-item will be set to the top of the container (without space).

_x000D_
_x000D_
div {_x000D_
  align-items: baseline;_x000D_
  background: tan;_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
}_x000D_
span {_x000D_
  background: red;_x000D_
}_x000D_
span.fontsize {_x000D_
  font-size:2em;_x000D_
}
_x000D_
<div>_x000D_
  <span class="fontsize">This is some text.</span>_x000D_
  <span>This is more text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You can find more information about the difference between baseline and flex-start here:
What's the difference between flex-start and baseline?

Convert ascii char[] to hexadecimal char[] in C

replace this

printf("%c",word[i]);

by

printf("%02X",word[i]);

matplotlib colorbar for scatter

From the matplotlib docs on scatter 1:

cmap is only used if c is an array of floats

So colorlist needs to be a list of floats rather than a list of tuples as you have it now. plt.colorbar() wants a mappable object, like the CircleCollection that plt.scatter() returns. vmin and vmax can then control the limits of your colorbar. Things outside vmin/vmax get the colors of the endpoints.

How does this work for you?

import matplotlib.pyplot as plt
cm = plt.cm.get_cmap('RdYlBu')
xy = range(20)
z = xy
sc = plt.scatter(xy, xy, c=z, vmin=0, vmax=20, s=35, cmap=cm)
plt.colorbar(sc)
plt.show()

Image Example

Use of exit() function

Bad programming practice. Using a goto function is a complete no no in C programming.
Also include header file stdlib.h by writing #include <iostream.h>for using exit() function. Also remember that exit() function takes an integer argument . Use exit(0) if the program completed successfully and exit(-1) or exit function with any non zero value as the argument if the program has error.

Check if a string matches a regex in Bash script

You can use the test construct, [[ ]], along with the regular expression match operator, =~, to check if a string matches a regex pattern.

For your specific case, you can write:

[[ $date =~ ^[0-9]{8}$ ]] && echo "yes"

Or more a accurate test:

[[ $date =~ ^[0-9]{4}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])$ ]] && echo "yes"
#           |^^^^^^^^ ^^^^^^ ^^^^^^  ^^^^^^ ^^^^^^^^^^ ^^^^^^ |
#           |   |     ^^^^^^^^^^^^^  ^^^^^^^^^^^^^^^^^^^^^^^^ |
#           |   |          |                   |              |
#           |   |           \                  |              |
#           | --year--   --month--           --day--          |
#           |          either 01...09      either 01..09     end of line
# start of line            or 10,11,12         or 10..29
#                                              or 30, 31

That is, you can define a regex in Bash matching the format you want. This way you can do:

[[ $date =~ ^regex$ ]] && echo "matched" || echo "did not match"

where commands after && are executed if the test is successful, and commands after || are executed if the test is unsuccessful.

Note this is based on the solution by Aleks-Daniel Jakimenko in User input date format verification in bash.


In other shells you can use grep. If your shell is POSIX compliant, do

(echo "$date" | grep -Eq  ^regex$) && echo "matched" || echo "did not match"

In fish, which is not POSIX-compliant, you can do

echo "$date" | grep -Eq "^regex\$"; and echo "matched"; or echo "did not match"

What is the strict aliasing rule?

Type punning via pointer casts (as opposed to using a union) is a major example of breaking strict aliasing.

What's the difference between align-content and align-items?

I had the same confusion. After some tinkering based on many of the answers above, I can finally see the differences. In my humble opinion, the distinction is best demonstrated with a flex container that satisfies the following two conditions:

  1. The flex container itself has a height constraint (e.g., min-height: 60rem) and thus can become too tall for its content
  2. The child items enclosed in the container have uneven heights

Condition 1 helps me understand what content means relative to its parent container. When the content is flush with the container, we will not be able to see any positioning effects coming from align-content. It is only when we have extra space along the cross axis, we start to see its effect: It aligns the content relative to the boundaries of the parent container.

Condition 2 helps me visualize the effects of align-items: it aligns items relative to each other.


Here is a code example. Raw materials come from Wes Bos' CSS Grid tutorial (21. Flexbox vs. CSS Grid)

  • Example HTML:
  <div class="flex-container">
    <div class="item">Short</div>
    <div class="item">Longerrrrrrrrrrrrrr</div>
    <div class="item"></div>
    <div class="item" id="tall">This is Many Words</div>
    <div class="item">Lorem, ipsum.</div>
    <div class="item">10</div>
    <div class="item">Snickers</div>
    <div class="item">Wes Is Cool</div>
    <div class="item">Short</div>
  </div>
  • Example CSS:
.flex-container {
  display: flex;
  /*dictates a min-height*/
  min-height: 60rem;
  flex-flow: row wrap;
  border: 5px solid white;
  justify-content: center;
  align-items: center;
  align-content: flex-start;
 }

#tall {
  /*intentionally made tall*/
  min-height: 30rem;
}

.item {
  margin: 10px;
  max-height: 10rem;
}

Example 1: Let's narrow the viewport so that the content is flush with the container. This is when align-content: flex-start; has no effects since the entire content block is tightly fit inside the container (no extra room for repositioning!)

Also, note the 2nd row--see how the items are center aligned among themselves.

enter image description here

Example 2: As we widen the viewport, we no longer have enough content to fill the entire container. Now we start to see the effects of align-content: flex-start;--it aligns the content relative to the top edge of the container. enter image description here


These examples are based on flexbox, but the same principles are applicable to CSS grid. Hope this helps :)

How to make a ssh connection with python?

Twisted has SSH support : http://www.devshed.com/c/a/Python/SSH-with-Twisted/

The twisted.conch package adds SSH support to Twisted. This chapter shows how you can use the modules in twisted.conch to build SSH servers and clients.

Setting Up a Custom SSH Server

The command line is an incredibly efficient interface for certain tasks. System administrators love the ability to manage applications by typing commands without having to click through a graphical user interface. An SSH shell is even better, as it’s accessible from anywhere on the Internet.

You can use twisted.conch to create an SSH server that provides access to a custom shell with commands you define. This shell will even support some extra features like command history, so that you can scroll through the commands you’ve already typed.

How Do I Do That? Write a subclass of twisted.conch.recvline.HistoricRecvLine that implements your shell protocol. HistoricRecvLine is similar to twisted.protocols.basic.LineReceiver , but with higher-level features for controlling the terminal.

Write a subclass of twisted.conch.recvline.HistoricRecvLine that implements your shell protocol. HistoricRecvLine is similar to twisted.protocols.basic.LineReceiver, but with higher-level features for controlling the terminal.

To make your shell available through SSH, you need to implement a few different classes that twisted.conch needs to build an SSH server. First, you need the twisted.cred authentication classes: a portal, credentials checkers, and a realm that returns avatars. Use twisted.conch.avatar.ConchUser as the base class for your avatar. Your avatar class should also implement twisted.conch.interfaces.ISession , which includes an openShell method in which you create a Protocol to manage the user’s interactive session. Finally, create a twisted.conch.ssh.factory.SSHFactory object and set its portal attribute to an instance of your portal.

Example 10-1 demonstrates a custom SSH server that authenticates users by their username and password. It gives each user a shell that provides several commands.

Example 10-1. sshserver.py

from twisted.cred import portal, checkers, credentials
from twisted.conch import error, avatar, recvline, interfaces as conchinterfaces
from twisted.conch.ssh import factory, userauth, connection, keys, session, common from twisted.conch.insults import insults from twisted.application import service, internet
from zope.interface import implements
import os

class SSHDemoProtocol(recvline.HistoricRecvLine):
    def __init__(self, user):
        self.user = user

    def connectionMade(self) : 
     recvline.HistoricRecvLine.connectionMade(self)
        self.terminal.write("Welcome to my test SSH server.")
        self.terminal.nextLine() 
        self.do_help()
        self.showPrompt()

    def showPrompt(self): 
        self.terminal.write("$ ")

    def getCommandFunc(self, cmd):
        return getattr(self, ‘do_’ + cmd, None)

    def lineReceived(self, line):
        line = line.strip()
        if line: 
            cmdAndArgs = line.split()
            cmd = cmdAndArgs[0]
            args = cmdAndArgs[1:]
            func = self.getCommandFunc(cmd)
            if func: 
               try:
                   func(*args)
               except Exception, e: 
                   self.terminal.write("Error: %s" % e)
                   self.terminal.nextLine()
            else:
               self.terminal.write("No such command.")
               self.terminal.nextLine()
        self.showPrompt()

    def do_help(self, cmd=”):
        "Get help on a command. Usage: help command"
        if cmd: 
            func = self.getCommandFunc(cmd)
            if func:
                self.terminal.write(func.__doc__)
                self.terminal.nextLine()
                return

        publicMethods = filter(
            lambda funcname: funcname.startswith(‘do_’), dir(self)) 
        commands = [cmd.replace(‘do_’, ”, 1) for cmd in publicMethods] 
        self.terminal.write("Commands: " + " ".join(commands))
        self.terminal.nextLine()

    def do_echo(self, *args):
        "Echo a string. Usage: echo my line of text"
        self.terminal.write(" ".join(args)) 
        self.terminal.nextLine()

    def do_whoami(self):
        "Prints your user name. Usage: whoami"
        self.terminal.write(self.user.username)
        self.terminal.nextLine()

    def do_quit(self):
        "Ends your session. Usage: quit" 
        self.terminal.write("Thanks for playing!")
        self.terminal.nextLine() 
        self.terminal.loseConnection()

    def do_clear(self):
        "Clears the screen. Usage: clear" 
        self.terminal.reset()

class SSHDemoAvatar(avatar.ConchUser): 
    implements(conchinterfaces.ISession)

    def __init__(self, username): 
        avatar.ConchUser.__init__(self) 
        self.username = username 
        self.channelLookup.update({‘session’:session.SSHSession})

    def openShell(self, protocol): 
        serverProtocol = insults.ServerProtocol(SSHDemoProtocol, self)
        serverProtocol.makeConnection(protocol)
        protocol.makeConnection(session.wrapProtocol(serverProtocol))

    def getPty(self, terminal, windowSize, attrs):
        return None

    def execCommand(self, protocol, cmd): 
        raise NotImplementedError

    def closed(self):
        pass

class SSHDemoRealm:
    implements(portal.IRealm)

    def requestAvatar(self, avatarId, mind, *interfaces):
        if conchinterfaces.IConchUser in interfaces:
            return interfaces[0], SSHDemoAvatar(avatarId), lambda: None
        else:
            raise Exception, "No supported interfaces found."

def getRSAKeys():
    if not (os.path.exists(‘public.key’) and os.path.exists(‘private.key’)):
        # generate a RSA keypair
        print "Generating RSA keypair…" 
        from Crypto.PublicKey import RSA 
        KEY_LENGTH = 1024
        rsaKey = RSA.generate(KEY_LENGTH, common.entropy.get_bytes)
        publicKeyString = keys.makePublicKeyString(rsaKey) 
        privateKeyString = keys.makePrivateKeyString(rsaKey)
        # save keys for next time
        file(‘public.key’, ‘w+b’).write(publicKeyString)
        file(‘private.key’, ‘w+b’).write(privateKeyString)
        print "done."
    else:
        publicKeyString = file(‘public.key’).read()
        privateKeyString = file(‘private.key’).read() 
    return publicKeyString, privateKeyString

if __name__ == "__main__":
    sshFactory = factory.SSHFactory() 
    sshFactory.portal = portal.Portal(SSHDemoRealm())
    users = {‘admin’: ‘aaa’, ‘guest’: ‘bbb’}
    sshFactory.portal.registerChecker(
 checkers.InMemoryUsernamePasswordDatabaseDontUse(**users))

    pubKeyString, privKeyString =
getRSAKeys()
    sshFactory.publicKeys = {
        ‘ssh-rsa’: keys.getPublicKeyString(data=pubKeyString)}
    sshFactory.privateKeys = {
        ‘ssh-rsa’: keys.getPrivateKeyObject(data=privKeyString)}

    from twisted.internet import reactor 
    reactor.listenTCP(2222, sshFactory) 
    reactor.run()

{mospagebreak title=Setting Up a Custom SSH Server continued}

sshserver.py will run an SSH server on port 2222. Connect to this server with an SSH client using the username admin and password aaa, and try typing some commands:

$ ssh admin@localhost -p 2222 
admin@localhost’s password: aaa

>>> Welcome to my test SSH server.  
Commands: clear echo help quit whoami
$ whoami
admin
$ help echo
Echo a string. Usage: echo my line of text
$ echo hello SSH world!
hello SSH world!
$ quit

Connection to localhost closed.

Add and remove a class on click using jQuery?

var selector = '.classname';
$(selector).on('click', function(){
    $(selector).removeClass('classname');
    $(this).addClass('classname');
});

Format bytes to kilobytes, megabytes, gigabytes

Flexible solution:

function size($size, array $options=null) {

    $o = [
        'binary' => false,
        'decimalPlaces' => 2,
        'decimalSeparator' => '.',
        'thausandsSeparator' => '',
        'maxThreshold' => false, // or thresholds key
        'suffix' => [
            'thresholds' => ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'],
            'decimal' => ' {threshold}B',
            'binary' => ' {threshold}iB',
            'bytes' => ' B'
        ]
    ];

    if ($options !== null)
        $o = array_replace_recursive($o, $options);

    $base = $o['binary'] ? 1024 : 1000;
    $exp = $size ? floor(log($size) / log($base)) : 0;

    if (($o['maxThreshold'] !== false) &&
        ($o['maxThreshold'] < $exp)
    )
        $exp = $o['maxThreshold'];

    return !$exp
        ? (round($size) . $o['suffix']['bytes'])
        : (
            number_format(
                $size / pow($base, $exp),
                $o['decimalPlaces'],
                $o['decimalSeparator'],
                $o['thausandsSeparator']
            ) .
            str_replace(
                '{threshold}',
                $o['suffix']['thresholds'][$exp],
                $o['suffix'][$o['binary'] ? 'binary' : 'decimal']
            )
        );
}

var_dump(size(disk_free_space('/')));
// string(8) "14.63 GB"
var_dump(size(disk_free_space('/'), ['binary' => true]));
// string(9) "13.63 GiB"
var_dump(size(disk_free_space('/'), ['maxThreshold' => 2]));
// string(11) "14631.90 MB"
var_dump(size(disk_free_space('/'), ['binary' => true, 'maxThreshold' => 2]));
// string(12) "13954.07 MiB"

Cannot find either column "dbo" or the user-defined function or aggregate "dbo.Splitfn", or the name is ambiguous

You need to treat a table valued udf like a table, eg JOIN it

select Emp_Id 
from Employee E JOIN dbo.Splitfn(@Id,',') CSV ON E.Emp_Id = CSV.items 

sql how to cast a select query

If you're using SQL (which you didn't say):

select cast(column as varchar(200)) from table 

You can use it in any statement, for example:

select value where othervalue in( select cast(column as varchar(200)) from table)
from othertable

If you want to do a join query, the answer is here already in another post :)

Copy / Put text on the clipboard with FireFox, Safari and Chrome

For security reasons, Firefox doesn't allow you to place text on the clipboard. However, there is a work-around available using Flash.

function copyIntoClipboard(text) {

    var flashId = 'flashId-HKxmj5';

    /* Replace this with your clipboard.swf location */
    var clipboardSWF = 'http://appengine.bravo9.com/copy-into-clipboard/clipboard.swf';

    if(!document.getElementById(flashId)) {
        var div = document.createElement('div');
        div.id = flashId;
        document.body.appendChild(div);
    }
    document.getElementById(flashId).innerHTML = '';
    var content = '<embed src="' + 
        clipboardSWF +
        '" FlashVars="clipboard=' + encodeURIComponent(text) +
        '" width="0" height="0" type="application/x-shockwave-flash"></embed>';
    document.getElementById(flashId).innerHTML = content;
}

The only disadvantage is that this requires Flash to be enabled.

source is currently dead: http://bravo9.com/journal/copying-text-into-the-clipboard-with-javascript-in-firefox-safari-ie-opera-292559a2-cc6c-4ebf-9724-d23e8bc5ad8a/ (and so is it's Google cache)

If statement for strings in python?

Python is a case-sensitive language. All Python keywords are lowercase. Use if, not If.

Also, don't put a colon after the call to print(). Also, indent the print() and exit() calls, as Python uses indentation rather than brackets to represent code blocks.

And also, proceed = "y" or "Y" won't do what you want. Use proceed = "y" and if answer.lower() == proceed:, or something similar.

There's also the fact that your program will exit as long as the input value is not the single character "y" or "Y", which contradicts the prompting of "N" for the alternate case. Instead of your else clause there, use elif answer.lower() == info_incorrect:, with info_incorrect = "n" somewhere beforehand. Then just reprompt for the response or something if the input value was something else.


I'd recommend going through the tutorial in the Python documentation if you're having this much trouble the way you're learning now. http://docs.python.org/tutorial/index.html

CardView background color always white

Kotlin for XML

app:cardBackgroundColor="@android:color/red"

code

cardName.setCardBackgroundColor(ContextCompat.getColor(this, R.color.colorGray));

Disable Scrolling on Body

To accomplish this, add 2 CSS properties on the <body> element.

body {
   height: 100%;
   overflow-y: hidden;
}

These days there are many news websites which require users to create an account. Typically they will give full access to the page for about a second, and then they show a pop-up, and stop users from scrolling down.

The Telegraph

npm WARN ... requires a peer of ... but none is installed. You must install peer dependencies yourself

total edge case here: I had this issue installing an Arch AUR PKGBUILD file manually. In my case I needed to delete the 'pkg', 'src' and 'node_modules' folders, then it built fine without this npm error.

cannot find zip-align when publishing app

It becomes usable if you install

Android SDK Build-tools Rev.20

javascript function wait until another function to finish

Following answer can help in this and other similar situations like synchronous AJAX call -

Working example

waitForMe().then(function(intentsArr){
  console.log('Finally, I can execute!!!');
},
function(err){
  console.log('This is error message.');
})

function waitForMe(){
    // Returns promise
    console.log('Inside waitForMe');
    return new Promise(function(resolve, reject){
        if(true){ // Try changing to 'false'
            setTimeout(function(){
                console.log('waitForMe\'s function succeeded');
                resolve();
            }, 2500);
        }
        else{
            setTimeout(function(){
                console.log('waitForMe\'s else block failed');
                resolve();
            }, 2500);
        }
    });
}

Change the Bootstrap Modal effect


_x000D_
_x000D_
.custom-modal-header_x000D_
{_x000D_
    display: block;_x000D_
}_x000D_
.custom-modal .modal-content_x000D_
{_x000D_
    width:500px;_x000D_
    border: none;_x000D_
}_x000D_
.custom-modal_x000D_
{_x000D_
    display: block !important;_x000D_
}_x000D_
.custom-fade .modal-dialog {_x000D_
    transform: translateY(4%);_x000D_
    opacity: 0;_x000D_
    -webkit-transition: all .2s ease-out;_x000D_
    -o-transition: all .2s ease-out;_x000D_
    transition: all .2s ease-out;_x000D_
    will-change: transform;_x000D_
}_x000D_
.custom-fade.in .modal-dialog  {_x000D_
    opacity: 1;_x000D_
    transform: translateY(0%);_x000D_
}
_x000D_
<div class="modal custom-modal custom-fade" tabindex="-1" role="dialog"_x000D_
     aria-hidden="true">_x000D_
    <div class="modal-dialog modal-lg">_x000D_
        <div class="modal-content">_x000D_
            <div class="modal-header">_x000D_
                <h5 class="modal-title">Title</h5>_x000D_
            </div>_x000D_
            <div class="modal-body">_x000D_
                <p>My cat is dope.</p>_x000D_
            </div>_x000D_
            <div class="modal-footer">_x000D_
                <button type="button" class="btn btn-primary" data-dismiss="modal">Sure (Meow)</button>_x000D_
            </div>_x000D_
        </div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Removing items from a ListBox in VB.net

This worked for me.

Private Sub listbox_MouseDoubleClick(sender As Object, e As MouseEventArgs) 
        Handles listbox.MouseDoubleClick
        listbox.Items.RemoveAt(listbox.SelectedIndex.ToString())
    End Sub

Get last record of a table in Postgres

If you accept a tip, create an id in this table like serial. The default of this field will be:

nextval('table_name_field_seq'::regclass).

So, you use a query to call the last register. Using your example:

pg_query($connection, "SELECT currval('table_name_field_seq') AS id;

I hope this tip helps you.

How to compare two files in Notepad++ v6.6.8

There is the "Compare" plugin. You can install it via Plugins > Plugin Manager.

Alternatively you can install a specialized file compare software like WinMerge.

How can I remove time from date with Moment.js?

Use format('LL')

Depending on what you're trying to do with it, format('LL') could do the trick. It produces something like this:

Moment().format('LL'); // => April 29, 2016

Catch checked change event of a checkbox

Use the :checked selector to determine the checkbox's state:

$('input[type=checkbox]').click(function() {
    if($(this).is(':checked')) {
        ...
    } else {
        ...
    }
});

Parse usable Street Address, City, State, Zip from a string

I've done this in the past.

Either do it manually, (build a nice gui that helps the user do it quickly) or have it automated and check against a recent address database (you have to buy that) and manually handle errors.

Manual handling will take about 10 seconds each, meaning you can do 3600/10 = 360 per hour, so 4000 should take you approximately 11-12 hours. This will give you a high rate of accuracy.

For automation, you need a recent US address database, and tweak your rules against that. I suggest not going fancy on the regex (hard to maintain long-term, so many exceptions). Go for 90% match against the database, do the rest manually.

Do get a copy of Postal Addressing Standards (USPS) at http://pe.usps.gov/cpim/ftp/pubs/Pub28/pub28.pdf and notice it is 130+ pages long. Regexes to implement that would be nuts.

For international addresses, all bets are off. US-based workers would not be able to validate.

Alternatively, use a data service. I have, however, no recommendations.

Furthermore: when you do send out the stuff in the mail (that's what it's for, right?) make sure you put "address correction requested" on the envelope (in the right place) and update the database. (We made a simple gui for the front desk person to do that; the person who actually sorts through the mail)

Finally, when you have scrubbed data, look for duplicates.

Selecting an element in iFrame jQuery

Take a look at this post: http://praveenbattula.blogspot.com/2009/09/access-iframe-content-using-jquery.html

$("#iframeID").contents().find("[tokenid=" + token + "]").html();

Place your selector in the find method.

This may not be possible however if the iframe is not coming from your server. Other posts talk about permission denied errors.

jQuery/JavaScript: accessing contents of an iframe

How to specify credentials when connecting to boto3 S3?

You can get a client with new session directly like below.

 s3_client = boto3.client('s3', 
                      aws_access_key_id=settings.AWS_SERVER_PUBLIC_KEY, 
                      aws_secret_access_key=settings.AWS_SERVER_SECRET_KEY, 
                      region_name=REGION_NAME
                      )

Else clause on Python while statement

The else clause is only executed when your while condition becomes false. If you break out of the loop, or if an exception is raised, it won't be executed.

One way to think about it is as an if/else construct with respect to the condition:

if condition:
    handle_true()
else:
    handle_false()

is analogous to the looping construct:

while condition:
    handle_true()
else:
    # condition is false now, handle and go on with the rest of the program
    handle_false()

An example might be along the lines of:

while value < threshold:
    if not process_acceptable_value(value):
        # something went wrong, exit the loop; don't pass go, don't collect 200
        break
    value = update(value)
else:
    # value >= threshold; pass go, collect 200
    handle_threshold_reached()

Is the sizeof(some pointer) always equal to four?

The size of the pointer basically depends on the architecture of the system in which it is implemented. For example the size of a pointer in 32 bit is 4 bytes (32 bit ) and 8 bytes(64 bit ) in a 64 bit machines. The bit types in a machine are nothing but memory address, that it can have. 32 bit machines can have 2^32 address space and 64 bit machines can have upto 2^64 address spaces. So a pointer (variable which points to a memory location) should be able to point to any of the memory address (2^32 for 32 bit and 2^64 for 64 bit) that a machines holds.

Because of this reason we see the size of a pointer to be 4 bytes in 32 bit machine and 8 bytes in a 64 bit machine.

How can I check MySQL engine type for a specific table?

SHOW TABLE STATUS WHERE Name = 'xxx'

This will give you (among other things) an Engine column, which is what you want.

How do I list / export private keys from a keystore?

For android development, to convert keystore created in eclipse ADT into public key and private key used in SignApk.jar:

export private key:

keytool.exe -importkeystore -srcstoretype JKS -srckeystore my-release-key.keystore -deststoretype PKCS12 -destkeystore keys.pk12.der
openssl.exe pkcs12 -in keys.pk12.der -nodes -out private.rsa.pem

edit private.rsa.pem and leave "-----BEGIN PRIVATE KEY-----" to "-----END PRIVATE KEY-----" paragraph, then:

openssl.exe base64 -d -in private.rsa.pem -out private.rsa.der

export public key:

keytool.exe -exportcert -keystore my-release-key.keystore -storepass <KEYSTORE_PASSWORD> -alias alias_name -file public.x509.der

sign apk:

java -jar SignApk.jar public.x509.der private.rsa.der input.apk output.apk

Switch statement: must default be the last case?

One scenario where I would consider it appropriate to have a 'default' located somewhere other than the end of a case statement is in a state machine where an invalid state should reset the machine and proceed as though it were the initial state. For example:

switch(widget_state)
{
  default:  /* Fell off the rails--reset and continue */
    widget_state = WIDGET_START;
    /* Fall through */
  case WIDGET_START:
    ...
    break;
  case WIDGET_WHATEVER:
    ...
    break;
}

an alternative arrangement, if an invalid state should not reset the machine but should be readily identifiable as an invalid state:

switch(widget_state) { case WIDGET_IDLE: widget_ready = 0; widget_hardware_off(); break; case WIDGET_START: ... break; case WIDGET_WHATEVER: ... break; default: widget_state = WIDGET_INVALID_STATE; /* Fall through */ case WIDGET_INVALID_STATE: widget_ready = 0; widget_hardware_off(); ... do whatever else is necessary to establish a "safe" condition }

Code elsewhere may then check for (widget_state == WIDGET_INVALID_STATE) and provide whatever error-reporting or state-reset behavior seems appropriate. For example, the status-bar code could show an error icon, and the "start widget" menu option which is disabled in most non-idle states could be enabled for WIDGET_INVALID_STATE as well as WIDGET_IDLE.

How to close a window using jQuery

just window.close() is OK, why should write in jQuery?

How to display UTF-8 characters in phpMyAdmin?

I had the same problem,

Set all text/varchar collations in phpMyAdmin to utf-8 and in php files add this:

mysql_set_charset("utf8", $your_connection_name);

This solved it for me.

nginx- duplicate default server error

You likely have other files (such as the default configuration) located in /etc/nginx/sites-enabled that needs to be removed.

This issue is caused by a repeat of the default_server parameter supplied to one or more listen directives in your files. You'll likely find this conflicting directive reads something similar to:

listen 80 default_server;

As the nginx core module documentation for listen states:

The default_server parameter, if present, will cause the server to become the default server for the specified address:port pair. If none of the directives have the default_server parameter then the first server with the address:port pair will be the default server for this pair.

This means that there must be another file or server block defined in your configuration with default_server set for port 80. nginx is encountering that first before your mysite.com file so try removing or adjusting that other configuration.

If you are struggling to find where these directives and parameters are set, try a search like so:

grep -R default_server /etc/nginx

SVN upgrade working copy

You can upgrade to Subversion 1.7. In order to update to Subversion 1.7 you have to launch existing project in Xcode 5 or above. This will prompt an warning ‘The working copy ProjectName should be upgraded to Subversion 1.7’ (shown in below screenshot).

Screenshot for warning

You should select ‘Upgrade’ button to upgrade to Subversion 1.7. This will take a bit of time.

If you are using terminal then you can upgrade to Subversion 1.7 by running below command in your project directory: svn upgrade

Note that once you have upgraded to Subversion 1.7 you cannot go back to Subversion 1.6.

Refer Apple docs for more details.

set dropdown value by text using jquery

For GOOGLE, GOOGLEDOWN, GOOGLEUP i.e similar kind of value you can try below code

   $("#HowYouKnow option:contains('GOOGLE')").each(function () {

                        if($(this).html()=='GOOGLE'){
                            $(this).attr('selected', 'selected');
                        }
                    });

In this way,number of loop iteration can be reduced and will work in all situation.

Find provisioning profile in Xcode 5

xCode 6 allows you to right click on the provisioning profile under account -> detail (the screen shot you have there) & shows a popup "show in finder".

Hide Signs that Meteor.js was Used

The amount of hacks you would need to go through to completely hide the fact your site is built by Meteor.js is absolutely ridiculous. You would have to strip essentially all core functionality and just serve straight up html, completely defeating the purpose of using the framework anyway.

That being said, I suggest looking at buildwith.com

You enter a url, and it reveals a ton of information about a site. If you only need to "fool" engines like this, there may be simple solutions.

How to add to an NSDictionary

A mutable dictionary can be changed, i.e. you can add and remove objects. An immutable is fixed once it is created.

create and add:

NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
[dict setObject:[NSNumber numberWithInt:42] forKey:@"A cool number"];

and retrieve:

int myNumber = [[dict objectForKey:@"A cool number"] intValue];

Windows 8.1 gets Error 720 on connect VPN

Since I can't find a complete or clear answer on this issue, and since it's the second time that I use this post to fix my problems, I post my solution:

why 720? 720 is the error code for connection attempt fail, because your computer and the remote computer could not agree on PPP control protocol, I don't know exactly why it happens, but I think that is all about registry permission for installers and multiple miniport driver install made by vpn installers that are not properly programmed for win 8.1.

Solution:

  1. check write permissions on registers

    a. download a Process Monitor http://technet.microsoft.com/en-us//sysinternals/bb896645.aspx and run it

    b. Use registry as target and set the filters to check witch registers aren't writable for netsh: "Process Name is 'netsh.exe'" and "result is 'ACCESS DENIED'", then get a command prompt with admin permissions and type netsh int ipv4 reset reset.log

    c. for each registry key logged by the process monitor as not accessible, go to registers using regedit anche change these permissions to "complete access"

    d. run the following command netsh int ipv6 reset reset.log and repeat step c)

  2. unistall all not-working miniports

    a. go to device managers (windows+x -> device manager)

    b. for each not-working miniport (the ones with yellow mark): update driver -> show non-compatible driver -> select another driver (eg. generic broadband adapter)

    c. unistall these not working devices

    d. reboot your computer

    e. Repeat steps a) - d) until you will not see any yellow mark on miniports

  3. delete your vpn connection and create a new one.

that worked for me (2 times, one after my first vpn connection on win 8.1, then when I reinstalled a cisco client and tried to use windows vpn again)

references:

http://en.remontka.pro/error-720-windows-8-and-8-1-solved/

https://forums.lenovo.com/t5/Windows-8-and-8-1/SOLVED-WAN-Miniport-2-yellow-exclamation-mark-in-Device-Manager/td-p/1051981

Local package.json exists, but node_modules missing

This issue can also raise when you change your system password but not the same updated on your .npmrc file that exist on path C:\Users\user_name, so update your password there too.

please check on it and run npm install first and then npm start.

Put buttons at bottom of screen with LinearLayout?

Just add layout_weight="1" to in your linearLayout which having Buttons.

Edit :- let me make it simple

follow something like below, tags name may not be correct, it is just an Idea

<LL>// Top Parrent LinearLayout
   <LL1 height="fill_parent" weight="1" "other tags as requirement"> <TV /><Butons /></LL1> // this layout will fill your screen.
   <LL2 height="wrap_content" weight="1"  orientation="Horizontal" "other tags as requirement"> <BT1 /><BT2/ ></LL2> // this layout gonna take lower part of button height of your screen

<LL/> TOP PARENT CLOSED

Deleting all pending tasks in celery / rabbitmq

From the docs:

$ celery -A proj purge

or

from proj.celery import app
app.control.purge()

(EDIT: Updated with current method.)

Best way to specify whitespace in a String.Split operation

So don't copy and paste! Extract a function to do your splitting and reuse it.

public static string[] SplitWhitespace (string input)
{
    char[] whitespace = new char[] { ' ', '\t' };
    return input.Split(whitespace);
}

Code reuse is your friend.

change array size

In C#, Array.Resize is the simplest method to resize any array to new size, e.g.:

Array.Resize<LinkButton>(ref area, size);

Here, i want to resize the array size of LinkButton array:

<LinkButton> = specifies the array type
ref area = ref is a keyword and 'area' is the array name
size = new size array

Making an array of integers in iOS

You can use CFArray instead of NSArray. Here is an article explaining how.

CFMutableArrayRef ar = CFArrayCreateMutable(NULL, 0, NULL);
for (NSUInteger i = 0; i < 1000; i++)
{
  CFArrayAppendValue(ar, (void*)i);
}
CFRelease(ar); /* Releasing the array */

The same applies for the CoreFoundation version of the other containers too.

How can I exclude a directory from Visual Studio Code "Explore" tab?

tl;dr

  1. Press Ctrl + Shift + P or Command + Shift + P on mac
  2. Type "Workspace settings".
  3. Change exclude settings either via the GUI or in settings.json:

GUI way

  1. Type "exclude" to the search bar.
  2. Click the "Add Pattern" button. Add exclude pattern in VS Code settings

Code way

  1. Click on the little {} icon at the top right corner to open the settings.json: Click brackets icon to open settings.json
  2. Add excluded folders to files.exclude. Also check out search.exclude and files.watcherExclude as they might be useful too. This snippet contains their explanations and defaults:

    {
      // Configure glob patterns for excluding files and folders. 
      // For example, the files explorer decides which files and folders to show 
      // or hide based on this setting. 
      // Read more about glob patterns [here](https://code.visualstudio.com/docs/editor/codebasics#_advanced-search-options).
      "files.exclude": {
        "**/.git": true,
        "**/.svn": true,
        "**/.hg": true,
        "**/CVS": true,
        "**/.DS_Store": true
      },
      // Configure glob patterns for excluding files and folders in searches. 
      // Inherits all glob patterns from the `files.exclude` setting.   
      // Read more about glob patterns [here](https://code.visualstudio.com/docs/editor/codebasics#_advanced-search-options).
      "search.exclude": {
        "**/node_modules": true,
        "**/bower_components": true
      },
      // Configure glob patterns of file paths to exclude from file watching. 
      // Patterns must match on absolute paths 
      // (i.e. prefix with ** or the full path to match properly). 
      // Changing this setting requires a restart. 
      // When you experience Code consuming lots of cpu time on startup, 
      // you can exclude large folders to reduce the initial load.
      "files.watcherExclude": {
        "**/.git/objects/**": true,
        "**/.git/subtree-cache/**": true,
        "**/node_modules/*/**": true
      }
    }
    

For more details on the other settings, see the official settings.json reference.

Why would you use String.Equals over ==?

There is practical difference between string.Equals and ==

bool result = false;

object obj = "String";    
string str2 = "String";
string str3 = typeof(string).Name;
string str4 = "String";
object obj2 = str3;

// Comparision between object obj and string str2 -- Com 1
result = string.Equals(obj, str2);// true
result = String.ReferenceEquals(obj, str2); // true
result = (obj == str2);// true

// Comparision between object obj and string str3 -- Com 2
result = string.Equals(obj, str3);// true
result = String.ReferenceEquals(obj, str3); // false
result = (obj == str3);// false

// Comparision between object obj and string str4 -- Com 3
result = string.Equals(obj, str4);// true
result = String.ReferenceEquals(obj, str4); // true
result = (obj == str4);// true

// Comparision between string str2 and string str3 -- Com 4
result = string.Equals(str2, str3);// true
result = String.ReferenceEquals(str2, str3); // false
result = (str2 == str3);// true

// Comparision between string str2 and string str4 -- Com 5
result = string.Equals(str2, str4);// true
result = String.ReferenceEquals(str2, str4); // true
result = (str2 == str4);// true

// Comparision between string str3 and string str4 -- Com 6
result = string.Equals(str3, str4);// true
result = String.ReferenceEquals(str3, str4); // false
result = (str3 == str4);// true

// Comparision between object obj and object obj2 -- Com 7
result = String.Equals(obj, obj2);// true
result = String.ReferenceEquals(obj, obj2); // false
result = (obj == obj2);// false

Adding Watch

obj     "String" {1#}   object {string}
str2    "String" {1#}   string
str3    "String" {5#}   string
str4    "String" {1#}   string
obj2    "String" {5#}   object {string}

Now look at {1#} and {5#}

obj, str2, str4 and obj2 references are same.

obj and obj2 are object type and others are string type

Conclusion:

  1. com1: result = (obj == str2);// true
    • compares object and string so performs a reference equality check
    • obj and str2 point to the same reference so the result is true
  2. com2: result = (obj == str3);// false
    • compares object and string so performs a reference equality check
    • obj and str3 point to the different references so the result is false
  3. com3: result = (obj == str4);// true
    • compares object and string so performs a reference equality check
    • obj and str4 point to the same reference so the result is true
  4. com4: result = (str2 == str3);// true
    • compares string and string so performs a string value check
    • str2 and str3 are both "String" so the result is true
  5. com5: result = (str2 == str4);// true
    • compares string and string so performs a string value check
    • str2 and str4 are both "String" so the result is true
  6. com6: result = (str3 == str4);// true
    • compares string and string so performs a string value check
    • str3 and str4 are both "String" so the result is true
  7. com7: result = (obj == obj2);// false  - compares object and object so performs a reference equality check      - obj and obj2 point to the different references so the result is false

How to setup virtual environment for Python in VS Code?

I had the same problem and the solution was pretty easy:

"If you create a new conda environment while VS Code is running, use the Reload Window command to refresh the environment list shown with Python: Select Interpreter; otherwise you may not see the environment there. It might take a short time to appear; if you don't see it at first, wait 15 seconds then try using the command again."

That's written on Vscode site

Note: to Reload Window: ctrl+shift+p in Vscode, then write reload window

Weird PHP error: 'Can't use function return value in write context'

This also happens when using empty on a function return:

!empty(trim($someText)) and doSomething()

because empty is not a function but a language construct (not sure), and it only takes variables:

Right:

empty($someVar)

Wrong:

empty(someFunc())

Since PHP 5.5, it supports more than variables. But if you need it before 5.5, use trim($name) == false. From empty documentation.

Cannot set property 'innerHTML' of null

The JavaScript part needs to run once the page is loaded, therefore it is advised to place JavaScript script at the end of the body tag.

_x000D_
_x000D_
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Example</title>

</head>
<body>
<div id="hello"></div>
<script type ="text/javascript">
    what();
    function what(){
        document.getElementById('hello').innerHTML = 'hi';
    };
</script>  
</body>
</html>
_x000D_
_x000D_
_x000D_

What happened to Lodash _.pluck?

Or try pure ES6 nonlodash method like this

const reducer = (array, object) => {
  array.push(object.a)
  return array
}

var objects = [{ 'a': 1 }, { 'a': 2 }];
objects.reduce(reducer, [])

Should I test private methods or only public ones?

If you are developing test driven (TDD), you will test your private methods.

Windows XP or later Windows: How can I run a batch file in the background with no window displayed?

You can run your .bat file through a .vbs file
Copy the following code into your .vbs file :

Dim WshShell
Dim obj
Set WshShell = WScript.CreateObject("WScript.Shell") 
obj = WshShell.Run("C:\Users\file1.bat", 0) 
obj = WshShell.Run("C:\Users\file2.bat", 0)  and so on
set WshShell = Nothing 

JPA: how do I persist a String into a database field, type MYSQL Text

for mysql 'text':

@Column(columnDefinition = "TEXT")
private String description;

for mysql 'longtext':

@Lob
private String description;

How to convert float to int with Java

If you want to convert a float value into an integer value, you have several ways to do it that depends on how do you want to round the float value.

First way is floor rounding the float value:

float myFloat = 3.14f;
int myInteger = (int)myFloat;

The output of this code will be 3, even if the myFloat value is closer to 4.

The second way is ceil rounding the float value:

float myFloat = 3.14f;
int myInteger = Math.ceil(myFloat);

The output of this code will be 4, because the rounding mode is always looking for the highest value.

Node.js Web Application examples/tutorials

The closest thing is likely Dav Glass's experimental work using node.js, express and YUI3. Basically, he explains how YUI3 is used to render markup on the server side, then sent to the client where binding to event and data occurs. The beauty is YUI3 is used as-is on both the client and the server. Makes a lot of sense. The one big issue is there is not yet a production ready server-side DOM library.

screencast

MySQL OPTIMIZE all tables?

Following example php script can help you to optimize all tables in your database

<?php

dbConnect();

$alltables = mysql_query("SHOW TABLES");

while ($table = mysql_fetch_assoc($alltables))
{
   foreach ($table as $db => $tablename)
   {
       mysql_query("OPTIMIZE TABLE '".$tablename."'")
       or die(mysql_error());

   }
}

?>

How do I name the "row names" column in r

The tibble package now has a dedicated function that converts row names to an explicit variable.

library(tibble)
rownames_to_column(mtcars, var="das_Auto") %>% head

Gives:

           das_Auto  mpg cyl disp  hp drat    wt  qsec vs am gear carb
1         Mazda RX4 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
2     Mazda RX4 Wag 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
3        Datsun 710 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
4    Hornet 4 Drive 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
5 Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
6           Valiant 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

How do I download the Android SDK without downloading Android Studio?

Well the folks who are trying to download either on *ix or Ec2 machine would suggest to clean approach in below steps:

$ mkdir android-sdk
$ cd android-sdk
$ mkdir cmdline-tools
$ cd cmdline-tools
$ wget https://dl.google.com/android/repository/commandlinetools-linux-*.zip
$ unzip commandlinetools-linux-*.zip

The king - sdkmanager lives inside

cmdline-tools/tools/bin

, you'd better set in PATH environment variable.

but cmdline-tools should not be set as ANDROID_HOME. Because later, when updating Android SDK, or installing more packages, the other packages will be placed under ANDROID_HOME, but not under cmdline-tools.

The final, complete ANDROID_HOME directory structure should look like below, consist of quite a few sub-directories:

build-tools, cmdline-tools, emulator, licenses, patcher, platform-tools, platforms, tools. You can easily point out that build-tools and cmdline-tools are siblings, all resides inside the parent ANDROID_HOME.

Add SDK tools directory in PATH environment variable to make executable available globally. Add below line either in ~/.bashrc or ~/.profile file to make it permanent.

In order to edit the ~/.bashrc simply can be editable in vim mode

$ vim .bashrc

Now set your preferred ANDROID_HOME in .bashrc file :

export ANDROID_HOME=/home/<user>/android-sdk
export PATH=${PATH}:$ANDROID_HOME/cmdline-tools/tools/bin:$ANDROID_HOME/platform-tools

here strange thing that we haven't download the platform-tools directory as of now but mentoning it under path but let it be as it will help you avoid remodification on the same file later.

Now go inside the same directory:

$ cd android-sdk

NOTE: well in first attempt sdkmanager command didnt found for me so I close the terminal and again created the connection or you can also refresh the same if it works for you.

after that use the sdkmanager to list and install the packages needed:

$ sdkmanager "platform-tools" "platforms;android-27" "build-tools;27.0.3"

Hence Sdkmanager path is already set it will be accessible from anywhere:

$ sdkmanager --update


$ sdkmanager --list
Installed packages:=====================] 100% Computing updates...             
  Path                 | Version | Description                    | Location             
  -------              | ------- | -------                        | -------              
  build-tools;27.0.3   | 27.0.3  | Android SDK Build-Tools 27.0.3 | build-tools/27.0.3/  
  emulator             | 30.0.12 | Android Emulator               | emulator/            
  patcher;v4           | 1       | SDK Patch Applier v4           | patcher/v4/          
  platform-tools       | 30.0.1  | Android SDK Platform-Tools     | platform-tools/      
  platforms;android-27 | 3       | Android SDK Platform 27        | platforms/android-27/

How do you fade in/out a background color using jquery?

Depending on your browser support, you could use a css animation. Browser support is IE10 and up for CSS animation. This is nice so you don't have to add jquery UI dependency if its only a small easter egg. If it is integral to your site (aka needed for IE9 and below) go with the jquery UI solution.

.your-animation {
    background-color: #fff !important;
    -webkit-animation: your-animation-name 1s ease 0s 1 alternate !important;
}
//You have to add the vendor prefix versions for it to work in Firefox, Safari, and Opera.
@-webkit-keyframes your-animation-name {
    from { background-color: #5EB4FE;}
    to {background-color: #fff;}
}
-moz-animation: your-animation-name 1s ease 0s 1 alternate !important;
}
@-moz-keyframes your-animation-name {
    from { background-color: #5EB4FE;}
    to {background-color: #fff;}
}
-ms-animation: your-animation-name 1s ease 0s 1 alternate !important;
}
@-ms-keyframes your-animation-name {
    from { background-color: #5EB4FE;}
    to {background-color: #fff;}
}
-o-animation: your-animation-name 1s ease 0s 1 alternate !important;
}
@-o-keyframes your-animation-name {
    from { background-color: #5EB4FE;}
    to {background-color: #fff;}
}
animation: your-animation-name 1s ease 0s 1 alternate !important;
}
@keyframes your-animation-name {
    from { background-color: #5EB4FE;}
    to {background-color: #fff;}
}

Next create a jQuery click event that adds the your-animation class to the element you wish to animate, triggering the background fading from one color to another:

$(".some-button").click(function(e){
    $(".place-to-add-class").addClass("your-animation");
});

MySQL "Or" Condition

Your question is about the operator precedences in mysql and Alex has shown you how to "override" the precedence with parentheses.

But on a side note, if your column date is of the type Date you can use MySQL's date and time functions to fetch the records of the last seven days, like e.g.

SELECT
  *
FROM
  Drinks
WHERE
  email='$Email'
  AND date >= Now()-Interval 7 day

(or maybe Curdate() instead of Now())

SSL Error: unable to get local issuer certificate

If you are a linux user Update node to a later version by running

sudo apt update

 sudo apt install build-essential checkinstall libssl-dev

curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.35.1/install.sh | bash

nvm --version

nvm ls

nvm ls-remote

nvm install [version.number]

this should solve your problem

Using if elif fi in shell scripts

Change [ to [[, and ] to ]].

How do I log errors and warnings into a file?

See

  • error_log — Send an error message somewhere

Example

error_log("You messed up!", 3, "/var/tmp/my-errors.log");

You can customize error handling with your own error handlers to call this function for you whenever an error or warning or whatever you need to log occurs. For additional information, please refer to the Chapter Error Handling in the PHP Manual

How to overcome the CORS issue in ReactJS

The ideal way would be to add CORS support to your server.

You could also try using a separate jsonp module. As far as I know axios does not support jsonp. So I am not sure if the method you are using would qualify as a valid jsonp request.

There is another hackish work around for the CORS problem. You will have to deploy your code with an nginx server serving as a proxy for both your server and your client. The thing that will do the trick us the proxy_pass directive. Configure your nginx server in such a way that the location block handling your particular request will proxy_pass or redirect your request to your actual server. CORS problems usually occur because of change in the website domain. When you have a singly proxy serving as the face of you client and you server, the browser is fooled into thinking that the server and client reside in the same domain. Ergo no CORS.

Consider this example.

Your server is my-server.com and your client is my-client.com Configure nginx as follows:

// nginx.conf

upstream server {
    server my-server.com;
}

upstream client {
    server my-client.com;
}

server {
    listen 80;

    server_name my-website.com;
    access_log /path/to/access/log/access.log;
    error_log /path/to/error/log/error.log;

    location / {
        proxy_pass http://client;
    }

    location ~ /server/(?<section>.*) {
        rewrite ^/server/(.*)$ /$1 break;
        proxy_pass http://server;
    }
}

Here my-website.com will be the resultant name of the website where the code will be accessible (name of the proxy website). Once nginx is configured this way. You will need to modify the requests such that:

  • All API calls change from my-server.com/<API-path> to my-website.com/server/<API-path>

In case you are not familiar with nginx I would advise you to go through the documentation.

To explain what is happening in the configuration above in brief:

  • The upstreams define the actual servers to whom the requests will be redirected
  • The server block is used to define the actual behaviour of the nginx server.
  • In case there are multiple server blocks the server_name is used to identify the block which will be used to handle the current request.
  • The error_log and access_log directives are used to define the locations of the log files (used for debugging)
  • The location blocks define the handling of different types of requests:
    1. The first location block handles all requests starting with / all these requests are redirected to the client
    2. The second location block handles all requests starting with /server/<API-path>. We will be redirecting all such requests to the server.

Note: /server here is being used to distinguish the client side requests from the server side requests. Since the domain is the same there is no other way of distinguishing requests. Keep in mind there is no such convention that compels you to add /server in all such use cases. It can be changed to any other string eg. /my-server/<API-path>, /abc/<API-path>, etc.

Even though this technique should do the trick, I would highly advise you to add CORS support to the server as this is the ideal way situations like these should be handled.

If you wish to avoid doing all this while developing you could for this chrome extension. It should allow you to perform cross domain requests during development.

Invalid attempt to read when no data is present

I used the code below and it worked for me.

String email="";
    SqlDataReader reader=cmd.ExecuteReader();
    if(reader.Read()){
        email=reader["Email"].ToString();
    }

String To=email;

Converting Date and Time To Unix Timestamp

Using a date picker to get date and a time picker I get two variables, this is how I put them together in unixtime format and then pull them out...

let datetime = oDdate+' '+oDtime;
let unixtime = Date.parse(datetime)/1000;
console.log('unixtime:',unixtime);

to prove it:

let milliseconds = unixtime * 1000;
dateObject = new Date(milliseconds);
console.log('dateObject:',dateObject);

enjoy!

Get cursor position (in characters) within a text Input field

VERY EASY

Updated answer

Use selectionStart, it is compatible with all major browsers.

_x000D_
_x000D_
document.getElementById('foobar').addEventListener('keyup', e => {
  console.log('Caret at: ', e.target.selectionStart)
})
_x000D_
<input id="foobar" />
_x000D_
_x000D_
_x000D_

Update: This works only when no type is defined or type="text" or type="textarea" on the input.

How to create a trie in Python

from collections import defaultdict

Define Trie:

_trie = lambda: defaultdict(_trie)

Create Trie:

trie = _trie()
for s in ["cat", "bat", "rat", "cam"]:
    curr = trie
    for c in s:
        curr = curr[c]
    curr.setdefault("_end")

Lookup:

def word_exist(trie, word):
    curr = trie
    for w in word:
        if w not in curr:
            return False
        curr = curr[w]
    return '_end' in curr

Test:

print(word_exist(trie, 'cam'))

How do you follow an HTTP Redirect in Node.js?

If all you want to do is follow redirects but still want to use the built-in HTTP and HTTPS modules, I suggest you use https://github.com/follow-redirects/follow-redirects.

yarn add follow-redirects
npm install follow-redirects

All you need to do is replace:

var http = require('http');

with

var http = require('follow-redirects').http;

... and all your requests will automatically follow redirects.

With TypeScript you can also install the types

npm install @types/follow-redirects

and then use

import { http, https } from 'follow-redirects';

Disclosure: I wrote this module.

Find specific string in a text file with VBS script

Try to change like this ..

firstStr = "<?xml version" 'my file always starts like this

Do until objInputFile.AtEndOfStream  

    strToAdd = "<tr><td><a href=" & chr(34) & "../../Logs/DD/Beginning_of_DD_TC" & CStr(index) & ".html" & chr(34) & ">Beginning_of_DD_TC" & CStr(index) & "</a></td></tr>"  

   substrToFind = "<tr><td><a href=" & chr(34) & "../Test case " & trim(cstr((index)))

   tmpStr = objInputFile.ReadLine

   If InStr(tmpStr, substrToFind) <= 0 Then
       If Instr(tmpStr, firstStr) > 0 Then
          text = tmpStr 'to avoid the first empty line
       Else
          text = text & vbCrLf & tmpStr
       End If
   Else
      text = text & vbCrLf & strToAdd & vbCrLf & tmpStr

   End If
   index = index + 1
Loop

How to make a UILabel clickable?

Swift 5

Similar to @liorco, but need to replace @objc with @IBAction.

class DetailViewController: UIViewController {

    @IBOutlet weak var tripDetails: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        ...

        let tap = UITapGestureRecognizer(target: self, action: #selector(DetailViewController.tapFunction))
        tripDetails.isUserInteractionEnabled = true
        tripDetails.addGestureRecognizer(tap)
    }

    @IBAction func tapFunction(sender: UITapGestureRecognizer) {
        print("tap working")
    }
}

This is working on Xcode 10.2.

How to write MySQL query where A contains ( "a" or "b" )

I user for searching the size of motorcycle :

For example : Data = "Tire cycle size 70 / 90 - 16"

i can search with "70 90 16"

$searchTerms = preg_split("/[\s,-\/?!]+/", $itemName);

foreach ($searchTerms as $term) {
        $term = trim($term);
            if (!empty($term)) {
            $searchTermBits[] = "name LIKE '%$term%'";
            }
        }

$query = "SELECT * FROM item WHERE " .implode(' AND ', $searchTermBits);

JAVA_HOME directory in Linux

On Linux you can run $(dirname $(dirname $(readlink -f $(which javac))))

On Mac you can run $(dirname $(readlink $(which javac)))/java_home

I'm not sure about windows but I imagine where javac would get you pretty close

Fast way to concatenate strings in nodeJS/JavaScript

There is not really any other way in JavaScript to concatenate strings.
You could theoretically use .concat(), but that's way slower than just +

Libraries are more often than not slower than native JavaScript, especially on basic operations like string concatenation, or numerical operations.

Simply put: + is the fastest.

Reset select2 value and show placeholder

Well whenever I did

$('myselectdropdown').select2('val', '').trigger('change');

I started getting some kind of lag after some three to four triggers. I suppose there's a memory leak. Its not within my code because if I do remove the this line, my app is lag free.

Since I have allowClear options set to true, I went with

$('.select2-selection__clear').trigger('mousedown');

This can be followed by a $('myselectdropdown').select2('close'); event trigger on the select2 dom element in case you wanna close the open suggestion drop down.

How can I get the baseurl of site?

string baseUrl = Request.Url.GetLeftPart(UriPartial.Authority)

That's it ;)

Convert List(of object) to List(of string)

You mean something like this?

List<object> objects = new List<object>();
var strings = (from o in objects
              select o.ToString()).ToList();

Asp.net MVC ModelState.Clear

Well the ModelState basically holds the current State of the model in terms of validation, it holds

ModelErrorCollection: Represent the errors when the model try to bind the values. ex.

TryUpdateModel();
UpdateModel();

or like a parameter in the ActionResult

public ActionResult Create(Person person)

ValueProviderResult: Hold the details about the attempted bind to the model. ex. AttemptedValue, Culture, RawValue.

Clear() method must be use with caution because it can lead to unspected results. And you will lose some nice properties of the ModelState like AttemptedValue, this is used by MVC in the background to repopulate the form values in case of error.

ModelState["a"].Value.AttemptedValue

Efficient method to generate UUID String in JAVA (UUID.randomUUID().toString() without the dashes)

Well, since an UUID gets added the hyphens (dashes) on toString() we can steal the implementation from Java's own implementation, shorting the byte array to 32 and adjusting the offset.

        public static String special() {
            UUID uuid = UUID.randomUUID();
            return fastUUID(uuid.getLeastSignificantBits(), uuid.getMostSignificantBits());
        }

        private static String fastUUID(long lsb, long msb) {
            byte[] buf = new byte[32];
            formatUnsignedLong0(lsb,        4, buf, 20, 12);
            formatUnsignedLong0(lsb >>> 48, 4, buf, 16, 4);

            formatUnsignedLong0(msb,        4, buf, 12, 4);
            formatUnsignedLong0(msb >>> 16, 4, buf, 8,  4);
            formatUnsignedLong0(msb >>> 32, 4, buf, 0,  8);

            return new String(buf, 0);
        }

        private static final char[] digits = {
                '0' , '1' , '2' , '3' , '4' , '5' ,
                '6' , '7' , '8' , '9' , 'a' , 'b' ,
                'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
                'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
                'o' , 'p' , 'q' , 'r' , 's' , 't' ,
                'u' , 'v' , 'w' , 'x' , 'y' , 'z'
        };
        private static void formatUnsignedLong0(long val, int shift, byte[] buf, int offset, int len) {
            int charPos = offset + len;
            int radix = 1 << shift;
            int mask = radix - 1;
            do {
                buf[--charPos] = (byte)digits[((int) val) & mask];
                val >>>= shift;
            } while (charPos > offset);
        }

Running it:

        public static void main(String[] args) {
            IntStream.range(0, 100).forEach(i-> {
                System.out.println(special());
            });
        }

Generates:

23f57da8a2784bb5acca553030f82e61
a14427efd8d147fdae315c1cf20fc53c
ee972aa1cf85414ca364bef5c74a7e57
6877ef35eab94b9485c5dd7c8c5a8a56
578721476629422381c0f625e22564a8
dbf60f068b5443d7bc6e5280696fed9f
dd611e870700480d81d394dd2125316c
04d71b9379ef4db49c28e113485ea76d
fd4e8cf3f85a45ae8c1b9bfe3e489a4a
858c4e8297f849b784b65b6096dec4d4
b30a8ca318a349b486b5693814422555
351c2fab9bc1426fa3bb512484628f12
9ce59e01db38405aab82d46f2a236880
5ffb5acb547a4f15a4621b406391bc0d
541b5fba8ddb4f1ebbd59cdcd5f59f7c
77f9460c4baa43a7bbaaf7f2aff205bd
85fa5254305b4c72b1b7c0103aaee269
062d45aa86694b06aad841236b839341
7a265293560f4223ab8248fda502c89b
b748c13ac45747b99aead4b0a2d7d179
cbcbf623c75d407fa3c88cfc89a90ed4
da263eed8771496faebb6290527f77fa
22231088dec04cffa40fb79ff56c6453
594a66de4b874b3491649c5d033917f6
4f6802ebd0cc4a39b25a67191c3af09d
8878b7ab8aa445cdadbef0f7c70d3deb
2c3ed0154f0c4ddbad498b7ae928b9bc
cac1dcaa80e54e2db3248987d2dbda4a
f9a3567e6dd54bf5900444c8b1c03815
f0d25d7b615a4495b51c01ab15093a88
243e45926311437c8b26cede2dc7de25
e4738c50e4cd448fbac252571c0907df
261d3593cc054569bcd645885d22c2ee
64a4796356a04cc4a09506aeb6f5b8fd
9aeebcbdde074ed69738589ca9bde0f1
ec040c956861466b84ed7f7cec601be0
18bd233781e44e7cb152800db4c4edc7
1b7b251df1244e8db46a45c186aada2b
3e32f644c9074cb3bbb15c5be1d9b95e
625309e3ffd14a90bfbd6d48142ac60e
664f0cf347ce4767add576da584526e7
fe3893fd376849fe9fed00e328e61470
254ce1441bbf4a7eae1cdf8d288e61e8
90896c6b309a49f48cc3b7a1570e1846
5f47acd1319245648098c1aec9b95f23
f798033052614b9eae8da7eba4ba3475
3471c4320e4e431eb1fa9f5eb5cb21e0
855f473fed034b1fa17f4f65b850e03b
1245de826d0d4373bdd4cf2157792954
543a8b16efca4fa2b5263315e8b21660
2dc186d699274257922853d783c0ec13
a92e6b1783db4b49a4aaa424b9e1b03f
16773feb48054cf0942a2a27204b3572
1e58da2107ac4ee39e28a93b32e1df1d
67622c19498d4178a1bab6b19087f2c2
412b6b4474fc43ccbeb1e7707b6420ee
7d0fd632913c425eb5f087600ccea870
439687baddb44852a43048b04d38427c
8b2dcc4e50464429a18b11e4aacf51a2
2fccb1c832894fe6b0b61bbdf175cd39
6d224b3d6e8747319fcf01b0309d8a0f
b4982e3b4b594cb4b334c95c2c96355e
c47fbaf90d1d4e9caf211f93b742631f
9440271e8ba6447d9a008e89a93016a6
8d24274b6a3f436a88362438aa6a221d
60452bd3f71747ed8c3706abb2235bd5
6fa93f2ee30740b89496439dd7227a4f
cc17504cf80641f882c8665ae166ba44
743efe8eac6e47a789928da4fb5b6f70
4c4d2df3461448c4a3e934cf4a7ea74f
b231eb3fb46240d38157764e8906aa7b
a234ae65f7ed48f6b1887644eed36cc2
c9cd5ed3df3f4a27957b45498f0c48ef
3eb2fbbb0a714bb7986aef3ee34f0254
d15968e605f0440c9e740e3f4e498a9f
63a8d50e8db24b91a13d4ac2fb6f7d5b
5377df9296154c57926672ca8b3c9478
a4db4a3a9d5148648a23aa7f4f77f1e0
d0aee355a2ba42de89d659385514b0fa
e92e7702481a4575a66d59c061459c5b
1b6c542d8f994d85a1312ab2cf4545ce
88e347a515474ec59013673e5402b97f
2187d9b2dc2b4d96baceade5ae99db44
4d641e69ca5b4acf90f8afe238d8a940
9c0f4c101c434831b928114c5fc0c401
140e16f6cf134785a98ae9baee5b9e7b
4dac5910f4d047e1b213c058e2230bf3
fb50a7e6333f49e4b469234426d5002f
c96c5f2fa167458eaa6d01997d90a980
1e79721e587c4a92aa55cdf8195c8c55
0da27fc5d8384ce299197b4e06cda1d4
a5e32d9cf5834e86b3fe02bc0e3104d6
2dc1826647594b1fb728de67d3df363c
0276371815254198bd22cc76f901b332
bf9d77b7b4a64e7a97ade2a62af1f8e0
268cce3249f64895b6b47e86cf296e5b
d523201fc950435f803bf89d5f042c45
607a4306b90b467f8b19c2c943bc92ef
adfa9fb63a874ca1ad746ff573f03f28
fe88132c70d141e8839ce9e7f0308750

Should be just as efficient (more effecient) than Javas actually.

Eclipse: How to install a plugin manually?

You can try this

click Help>Install New Software on the menu bar

enter image description here

enter image description here

enter image description here

enter image description here

Select the first 10 rows - Laravel Eloquent

First you can use a Paginator. This is as simple as:

$allUsers = User::paginate(15);

$someUsers = User::where('votes', '>', 100)->paginate(15);

The variables will contain an instance of Paginator class. all of your data will be stored under data key.

Or you can do something like:

Old versions Laravel.

Model::all()->take(10)->get();

Newer version Laravel.

Model::all()->take(10);

For more reading consider these links:

How to install and run Typescript locally in npm?

You need to tell npm that "tsc" exists as a local project package (via the "scripts" property in your package.json) and then run it via npm run tsc. To do that (at least on Mac) I had to add the path for the actual compiler within the package, like this

{
  "name": "foo"
  "scripts": {
    "tsc": "./node_modules/typescript/bin/tsc"
  },
  "dependencies": {
    "typescript": "^2.3.3",
    "typings": "^2.1.1"
  }
}

After that you can run any TypeScript command like npm run tsc -- --init (the arguments come after the first --).

JQuery get data from JSON array

try this

$.getJSON(url, function(data){
    $.each(data.response.venue.tips.groups.items, function (index, value) {
        console.log(this.text);
    });
});

How to print strings with line breaks in java

You can try using StringBuilder: -

    final StringBuilder sb = new StringBuilder();

    sb.append("SHOP MA\n");
    sb.append("----------------------------\n");
    sb.append("Pannampitiya\n");
    sb.append("09-10-2012 harsha  no: 001\n");
    sb.append("No  Item  Qty  Price  Amount\n");
    sb.append("1 Bread 1 50.00  50.00\n");
    sb.append("____________________________\n");

    // To use StringBuilder as String.. Use `toString()` method..
    System.out.println(sb.toString());   

string.split - by multiple character delimiter

string tests = "abc][rfd][5][,][.";
string[] reslts = tests.Split(new char[] { ']', '[' }, StringSplitOptions.RemoveEmptyEntries);

MySQL Foreign Key Error 1005 errno 150 primary key as foreign key

For me, I was trying to match up a regular indexed field in a child table, to a primary key in the parent table, and by default some MySQL frontend GUIs like Sequel Pro set the primary key as unsigned, so you have to make sure that the child table field is unsigned too (unless these fields might contain negative ints, then make sure they're both signed).

How to Install pip for python 3.7 on Ubuntu 18?

pip3 not pip. You can create an alias like you did with python3 if you like.

How to check if an email address exists without sending an email?

Although this question is a bit old, this service tip might help users searching for a similar solution checking email addresses beyond syntax validation prior to sending.

I have been using this open sourced service for a more in depth validating of emails (checking for mx records on the e-mail address domain etc.) for a few projects with good results. It also checks for common typos witch is quite useful. Demo here.

git ignore exception

The solution depends on the relation between the git ignore rule and the exception rule:

  1. Files/Files at the same level: use the @Skilldrick solution.
  2. Folders/Subfolders: use the @Matiss Jurgelis solution.
  3. Files/Files in different levels or Files/Subfolders: you can do this:

    *.suo
    *.user
    *.userosscache
    *.sln.docstates
    
    # ...
    
    # Exceptions for entire subfolders
    !SetupFiles/elasticsearch-5.0.0/**/*
    !SetupFiles/filebeat-5.0.0-windows-x86_64/**/*
    
    # Exceptions for files in different levels
    !SetupFiles/kibana-5.0.0-windows-x86/**/*.suo
    !SetupFiles/logstash-5.0.0/**/*.suo
    

Converting Varchar Value to Integer/Decimal Value in SQL Server

You are getting arithmetic overflow. this means you are trying to make a conversion impossible to be made. This error is thrown when you try to make a conversion and the destiny data type is not enough to convert the origin data. For example:

If you try to convert 100.52 to decimal(4,2) you will get this error. The number 100.52 requires 5 positions and 2 of them are decimal.

Try to change the decimal precision to something like 16,2 or higher. Try with few records first then use it to all your select.

How to convert an array to object in PHP?

Using json_encode is problematic because of the way that it handles non UTF-8 data. It's worth noting that the json_encode/json_encode method also leaves non-associative arrays as arrays. This may or may not be what you want. I was recently in the position of needing to recreate the functionality of this solution but without using json_ functions. Here's what I came up with:

/**
 * Returns true if the array has only integer keys
 */
function isArrayAssociative(array $array) {
    return (bool)count(array_filter(array_keys($array), 'is_string'));
}

/**
 * Converts an array to an object, but leaves non-associative arrays as arrays. 
 * This is the same logic that `json_decode(json_encode($arr), false)` uses.
 */
function arrayToObject(array $array, $maxDepth = 10) {
    if($maxDepth == 0) {
        return $array;
    }

    if(isArrayAssociative($array)) {
        $newObject = new \stdClass;
        foreach ($array as $key => $value) {
            if(is_array($value)) {
                $newObject->{$key} = arrayToObject($value, $maxDepth - 1);
            } else {
                $newObject->{$key} = $value;
            }
        }
        return $newObject;
    } else {

        $newArray = array();
        foreach ($array as $value) {
            if(is_array($value)) {
                $newArray[] = arrayToObject($value, $maxDepth - 1);
            } else {
                $newArray[] = $value;
            }                
        }
        return $newArray;
    }
}

How do I display a MySQL error in PHP for a long query that depends on the user input?

One useful line of code for you would be:

$sql = "Your SQL statement here";
$result = mysqli_query($this->db_link, $sql) or trigger_error("Query Failed! SQL: $sql - Error: ".mysqli_error($this->db_link), E_USER_ERROR);

This method is better than die, because you can use it for development AND production. It's the permanent solution.

How to define a circle shape in an Android XML drawable file?

If you want a circle like this

enter image description here

Try using the code below:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:innerRadius="0dp"
    android:shape="ring"
    android:thicknessRatio="2"
    android:useLevel="false" >
    <solid android:color="@android:color/white" />
    <stroke
        android:width="1dp"
        android:color="@android:color/darker_gray" />
</shape>

Angular2 - Radio Button Binding

use [value]="1" instead of value="1"

<input name="options" ng-control="options" type="radio" [value]="1"  [(ngModel)]="model.options" ><br/>

<input name="options" ng-control="options" type="radio" [value]="2" [(ngModel)]="model.options" ><br/>

Edit:

As suggested by thllbrg "For angular 2.1+ use [(ngModel)] instead of [(ng-model)] "

How to get just numeric part of CSS property with jQuery?

The simplest way to get the element width without units is :

target.width()

Source : https://api.jquery.com/width/#width2