Programs & Examples On #Dynamic sql

Dynamic SQL is a technique using SQL (Structured Query Language) whose main difference from traditional SQL is that Dynamic SQL allows to build SQL statements dynamically at runtime, which eases the automatic generation and execution of program statements.

Declare Variable for a Query String

I will point out that in the article linked in the top rated answer The Curse and Blessings of Dynamic SQL the author states that the answer is not to use dynamic SQL. Scroll almost to the end to see this.

From the article: "The correct method is to unpack the list into a table with a user-defined function or a stored procedure."

Of course, once the list is in a table you can use a join. I could not comment directly on the top rated answer, so I just added this comment.

SQL update fields of one table from fields of another one

This is a great help. The code

UPDATE tbl_b b
SET   (  column1,   column2,   column3)
    = (a.column1, a.column2, a.column3)
FROM   tbl_a a
WHERE  b.id = 1
AND    a.id = b.id;

works perfectly.

noted that you need a bracket "" in

From "tbl_a" a

to make it work.

Why do I get "Procedure expects parameter '@statement' of type 'ntext/nchar/nvarchar'." when I try to use sp_executesql?

Sounds like you're calling sp_executesql with a VARCHAR statement, when it needs to be NVARCHAR.

e.g. This will give the error because @SQL needs to be NVARCHAR

DECLARE @SQL VARCHAR(100)
SET @SQL = 'SELECT TOP 1 * FROM sys.tables'
EXECUTE sp_executesql @SQL

So:

DECLARE @SQL NVARCHAR(100)
SET @SQL = 'SELECT TOP 1 * FROM sys.tables'
EXECUTE sp_executesql @SQL

Dynamic SQL results into temp table in SQL Stored procedure

CREATE PROCEDURE dbo.pdpd_DynamicCall 
AS
DECLARE @SQLString_2 NVARCHAR(4000)
SET NOCOUNT ON
Begin
    --- Create global temp table
    CREATE TABLE ##T1 ( column_1 varchar(10) , column_2 varchar(100) )

    SELECT @SQLString_2 = 'INSERT INTO ##T1( column_1, column_2) SELECT column_1 = "123", column_2 = "MUHAMMAD IMRON"'
    SELECT @SQLString_2 = REPLACE(@SQLString_2, '"', '''')

    EXEC SP_EXECUTESQL @SQLString_2

    --- Test Display records
    SELECT * FROM ##T1

    --- Drop global temp table 
    IF OBJECT_ID('tempdb..##T1','u') IS NOT NULL
    DROP TABLE ##T1
End

Drop all tables whose names begin with a certain string

In case of temporary tables, you might want to try

SELECT 'DROP TABLE "' + t.name + '"' 
FROM tempdb.sys.tables t
WHERE t.name LIKE '[prefix]%'

In SQL Server, how do I generate a CREATE TABLE statement for a given table?

Here's the script that I came up with. It handles Identity columns, default values, and primary keys. It does not handle foreign keys, indexes, triggers, or any other clever stuff. It works on SQLServer 2000, 2005 and 2008.

declare @schema varchar(100), @table varchar(100)
set @schema = 'dbo' -- set schema name here
set @table = 'MyTable' -- set table name here
declare @sql table(s varchar(1000), id int identity)

-- create statement
insert into  @sql(s) values ('create table [' + @table + '] (')

-- column list
insert into @sql(s)
select 
    '  ['+column_name+'] ' + 
    data_type + coalesce('('+cast(character_maximum_length as varchar)+')','') + ' ' +
    case when exists ( 
        select id from syscolumns
        where object_name(id)=@table
        and name=column_name
        and columnproperty(id,name,'IsIdentity') = 1 
    ) then
        'IDENTITY(' + 
        cast(ident_seed(@table) as varchar) + ',' + 
        cast(ident_incr(@table) as varchar) + ')'
    else ''
    end + ' ' +
    ( case when IS_NULLABLE = 'No' then 'NOT ' else '' end ) + 'NULL ' + 
    coalesce('DEFAULT '+COLUMN_DEFAULT,'') + ','

 from INFORMATION_SCHEMA.COLUMNS where table_name = @table AND table_schema = @schema
 order by ordinal_position

-- primary key
declare @pkname varchar(100)
select @pkname = constraint_name from INFORMATION_SCHEMA.TABLE_CONSTRAINTS
where table_name = @table and constraint_type='PRIMARY KEY'

if ( @pkname is not null ) begin
    insert into @sql(s) values('  PRIMARY KEY (')
    insert into @sql(s)
        select '   ['+COLUMN_NAME+'],' from INFORMATION_SCHEMA.KEY_COLUMN_USAGE
        where constraint_name = @pkname
        order by ordinal_position
    -- remove trailing comma
    update @sql set s=left(s,len(s)-1) where id=@@identity
    insert into @sql(s) values ('  )')
end
else begin
    -- remove trailing comma
    update @sql set s=left(s,len(s)-1) where id=@@identity
end

-- closing bracket
insert into @sql(s) values( ')' )

-- result!
select s from @sql order by id

sql use statement with variable

Just wanted to thank KM for his valuable solution. I implemented it myself to reduce the amount of lines in a shrinkdatabase request on SQLServer. Here is my SQL request if it can help anyone :

-- Declare the variable to be used
DECLARE @Query varchar (1000)
DECLARE @MyDBN varchar(11);
-- Initializing the @MyDBN variable (possible values : db1, db2, db3, ...)
SET @MyDBN = 'db1';
-- Creating the request to execute
SET @Query='use '+ @MyDBN +'; ALTER DATABASE '+ @MyDBN +' SET RECOVERY SIMPLE WITH NO_WAIT; DBCC SHRINKDATABASE ('+ @MyDBN +', 1, TRUNCATEONLY); ALTER DATABASE '+ @MyDBN +' SET RECOVERY FULL WITH NO_WAIT'
-- 
EXEC (@Query)

Using a cursor with dynamic SQL in a stored procedure

Working with a non-relational database (IDMS anyone?) over an ODBC connection qualifies as one of those times where cursors and dynamic SQL seems the only route.

select * from a where a=1 and b in (1,2)

takes 45 minutes to respond while re-written to use keysets without the in clause will run in under 1 second:

select * from a where (a=1 and b=1)
union all
select * from a where (a=1 and b=2)

If the in statement for column B contains 1145 rows, using a cursor to create indidivudal statements and execute them as dynamic SQL is far faster than using the in clause. Silly hey?

And yes, there's no time in a relational database that cursor's should be used. I just can't believe I've come across an instance where a cursor loop is several magnitudes quicker.

PostgreSQL - SQL state: 42601 syntax error

Your function would work like this:

CREATE OR REPLACE FUNCTION prc_tst_bulk(sql text)
RETURNS TABLE (name text, rowcount integer) AS 
$$
BEGIN

RETURN QUERY EXECUTE '
WITH v_tb_person AS (' || sql || $x$)
SELECT name, count(*)::int FROM v_tb_person WHERE nome LIKE '%a%' GROUP BY name
UNION
SELECT name, count(*)::int FROM v_tb_person WHERE gender = 1 GROUP BY name$x$;

END     
$$ LANGUAGE plpgsql;

Call:

SELECT * FROM prc_tst_bulk($$SELECT a AS name, b AS nome, c AS gender FROM tbl$$)
  • You cannot mix plain and dynamic SQL the way you tried to do it. The whole statement is either all dynamic or all plain SQL. So I am building one dynamic statement to make this work. You may be interested in the chapter about executing dynamic commands in the manual.

  • The aggregate function count() returns bigint, but you had rowcount defined as integer, so you need an explicit cast ::int to make this work

  • I use dollar quoting to avoid quoting hell.

However, is this supposed to be a honeypot for SQL injection attacks or are you seriously going to use it? For your very private and secure use, it might be ok-ish - though I wouldn't even trust myself with a function like that. If there is any possible access for untrusted users, such a function is a loaded footgun. It's impossible to make this secure.

Craig (a sworn enemy of SQL injection!) might get a light stroke, when he sees what you forged from his piece of code in the answer to your preceding question. :)

The query itself seems rather odd, btw. But that's beside the point here.

Create PostgreSQL ROLE (user) if it doesn't exist

Bash alternative (for Bash scripting):

psql -h localhost -U postgres -tc \
"SELECT 1 FROM pg_user WHERE usename = 'my_user'" \
| grep -q 1 \
|| psql -h localhost -U postgres \
-c "CREATE ROLE my_user LOGIN PASSWORD 'my_password';"

(isn't the answer for the question! it is only for those who may be useful)

How to get sp_executesql result into a variable?

If you want to return more than 1 value use this:

DECLARE @sqlstatement2      NVARCHAR(MAX);
DECLARE @retText            NVARCHAR(MAX);  
DECLARE @ParmDefinition     NVARCHAR(MAX);
DECLARE @retIndex           INT = 0;

SELECT @sqlstatement = 'SELECT @retIndexOUT=column1 @retTextOUT=column2 FROM XXX WHERE bla bla';

SET @ParmDefinition = N'@retIndexOUT INT OUTPUT, @retTextOUT NVARCHAR(MAX) OUTPUT';

exec sp_executesql @sqlstatement, @ParmDefinition, @retIndexOUT=@retIndex OUTPUT, @retTextOUT=@retText OUTPUT;

returned values are in @retIndex and @retText

nvarchar(max) still being truncated

I have encountered the same problem today and found that beyond that 4000 character limit, I had to split the dynamic query into two strings and concatenate them when executing the query.

DECLARE @Query NVARCHAR(max);
DECLARE @Query2 NVARCHAR(max);
SET @Query = 'SELECT...' -- some of the query gets set here
SET @Query2 = '...' -- more query gets added on, etc.

EXEC (@Query + @Query2)

Getting result of dynamic SQL into a variable for sql-server

 vMYQUERY := 'SELECT COUNT(*) FROM ALL_OBJECTS WHERE OWNER = UPPER(''MFI_IDBI2LIVE'') AND OBJECT_TYPE = ''TABLE'' 
    AND OBJECT_NAME  =''' || vTBL_CLIENT_MASTER || '''';
    PRINT_STRING(VMYQUERY);
    EXECUTE IMMEDIATE  vMYQUERY INTO VCOUNTTEMP ;

Truncating all tables in a Postgres database

Just execute the query bellow:

DO $$ DECLARE
    r RECORD;
BEGIN
    FOR r IN (SELECT tablename FROM pg_tables WHERE schemaname = current_schema()) LOOP
        EXECUTE 'TRUNCATE TABLE ' || quote_ident(r.tablename) || '';
    END LOOP;
END $$;

Why would someone use WHERE 1=1 AND <conditions> in a SQL clause?

This is useful in a case where you have to use dynamic query in which in where clause you have to append some filter options. Like if you include options 0 for status is inactive, 1 for active. Based from the options, there is only two available options(0 and 1) but if you want to display All records, it is handy to include in where close 1=1. See below sample:

Declare @SearchValue    varchar(8) 
Declare @SQLQuery varchar(max) = '
Select [FirstName]
    ,[LastName]
    ,[MiddleName]
    ,[BirthDate]
,Case
    when [Status] = 0 then ''Inactive''
    when [Status] = 1 then ''Active''
end as [Status]'

Declare @SearchOption nvarchar(100)
If (@SearchValue = 'Active')
Begin
    Set @SearchOption = ' Where a.[Status] = 1'
End

If (@SearchValue = 'Inactive')
Begin
    Set @SearchOption = ' Where a.[Status] = 0'
End

If (@SearchValue = 'All')
Begin
    Set @SearchOption = ' Where 1=1'
End

Set @SQLQuery = @SQLQuery + @SearchOption

Exec(@SQLQuery);

How to use table variable in a dynamic sql statement?

You can't do this because the table variables are out of scope.

You would have to declare the table variable inside the dynamic SQL statement or create temporary tables.

I would suggest you read this excellent article on dynamic SQL.

http://www.sommarskog.se/dynamic_sql.html

How do I make a fully statically linked .exe with Visual Studio Express 2005?

I've had this same dependency problem and I also know that you can include the VS 8.0 DLLs (release only! not debug!---and your program has to be release, too) in a folder of the appropriate name, in the parent folder with your .exe:

How to: Deploy using XCopy (MSDN)

Also note that things are guaranteed to go awry if you need to have C++ and C code in the same statically linked .exe because you will get linker conflicts that can only be resolved by ignoring the correct libXXX.lib and then linking dynamically (DLLs).

Lastly, with a different toolset (VC++ 6.0) things "just work", since Windows 2000 and above have the correct DLLs installed.

How to get the last char of a string in PHP?

From PHP 7.1 you can do this (Accepted rfc for negative string offsets):

<?php
$silly = 'Mary had a little lamb';
echo $silly[-20];
echo $silly{-6};
echo $silly[-3];
echo $silly[-15];
echo $silly[-13];
echo $silly[-1];
echo $silly[-4];
echo $silly{-10};
echo $silly[-4];
echo $silly[-8];
echo $silly{3}; // <-- this will be deprecated in PHP 7.4
die();

I'll let you guess the output.

Also, I added this to xenonite's performance code with these results:

substr() took 7.0334868431091seconds

array access took 2.3111131191254seconds

Direct string access (negative string offsets) took 1.7971360683441seconds

How does autowiring work in Spring?

The whole concept of inversion of control means you are free from a chore to instantiate objects manually and provide all necessary dependencies. When you annotate class with appropriate annotation (e.g. @Service) Spring will automatically instantiate object for you. If you are not familiar with annotations you can also use XML file instead. However, it's not a bad idea to instantiate classes manually (with the new keyword) in unit tests when you don't want to load the whole spring context.

Recover sa password

The best way is to simply reset the password by connecting with a domain/local admin (so you may need help from your system administrators), but this only works if SQL Server was set up to allow local admins (these are now left off the default admin group during setup).

If you can't use this or other existing methods to recover / reset the SA password, some of which are explained here:

Then you could always backup your important databases, uninstall SQL Server, and install a fresh instance.

You can also search for less scrupulous ways to do it (e.g. there are password crackers that I am not enthusiastic about sharing).

As an aside, the login properties for sa would never say Windows Authentication. This is by design as this is a SQL Authentication account. This does not mean that Windows Authentication is disabled at the instance level (in fact it is not possible to do so), it just doesn't apply for a SQL auth account.

I wrote a tip on using PSExec to connect to an instance using the NT AUTHORITY\SYSTEM account (which works < SQL Server 2012), and a follow-up that shows how to hack the SqlWriter service (which can work on more modern versions):

And some other resources:

#1130 - Host ‘localhost’ is not allowed to connect to this MySQL server

Find the file "config.inc.php" under your phpMyAdmin directory and edit the following lines:

$cfg['Servers'][$i]['auth_type'] = 'config'; // config, http, cookie

$cfg['Servers'][$i]['user'] = 'root'; // MySQL user

$cfg['Servers'][$i]['password'] = 'TYPE_YOUR_PASSWORD_HERE'; // MySQL password

Note that the password used in the 'password' field must be the same for the MySQL root password. Also, you should check if root login is allowed in this line:

$cfg['Servers'][$i]['AllowRoot']     = TRUE;        // true = allow root login

This way you have your root password set.

How to get current time with jQuery

_x000D_
_x000D_
.clock {_x000D_
width: 260px;_x000D_
margin: 0 auto;_x000D_
padding: 30px;_x000D_
color: #FFF;background:#333;_x000D_
}_x000D_
.clock ul {_x000D_
width: 250px;_x000D_
margin: 0 auto;_x000D_
padding: 0;_x000D_
list-style: none;_x000D_
text-align: center_x000D_
}_x000D_
_x000D_
.clock ul li {_x000D_
display: inline;_x000D_
font-size: 3em;_x000D_
text-align: center;_x000D_
font-family: "Arial", Helvetica, sans-serif;_x000D_
text-shadow: 0 2px 5px #55c6ff, 0 3px 6px #55c6ff, 0 4px 7px #55c6ff_x000D_
}_x000D_
#Date { _x000D_
font-family: 'Arial', Helvetica, sans-serif;_x000D_
font-size: 26px;_x000D_
text-align: center;_x000D_
text-shadow: 0 2px 5px #55c6ff, 0 3px 6px #55c6ff;_x000D_
padding-bottom: 40px;_x000D_
}_x000D_
_x000D_
#point {_x000D_
position: relative;_x000D_
-moz-animation: mymove 1s ease infinite;_x000D_
-webkit-animation: mymove 1s ease infinite;_x000D_
padding-left: 10px;_x000D_
padding-right: 10px_x000D_
}_x000D_
_x000D_
/* Animasi Detik Kedap - Kedip */_x000D_
@-webkit-keyframes mymove _x000D_
{_x000D_
0% {opacity:1.0; text-shadow:0 0 20px #00c6ff;}_x000D_
50% {opacity:0; text-shadow:none; }_x000D_
100% {opacity:1.0; text-shadow:0 0 20px #00c6ff; } _x000D_
}_x000D_
_x000D_
@-moz-keyframes mymove _x000D_
{_x000D_
0% {opacity:1.0; text-shadow:0 0 20px #00c6ff;}_x000D_
50% {opacity:0; text-shadow:none; }_x000D_
100% {opacity:1.0; text-shadow:0 0 20px #00c6ff; } _x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>_x000D_
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>_x000D_
<script type="text/javascript">_x000D_
$(document).ready(function() {_x000D_
// Making 2 variable month and day_x000D_
var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; _x000D_
var dayNames= ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]_x000D_
_x000D_
// make single object_x000D_
var newDate = new Date();_x000D_
// make current time_x000D_
newDate.setDate(newDate.getDate());_x000D_
// setting date and time_x000D_
$('#Date').html(dayNames[newDate.getDay()] + " " + newDate.getDate() + ' ' + monthNames[newDate.getMonth()] + ' ' + newDate.getFullYear());_x000D_
_x000D_
setInterval( function() {_x000D_
// Create a newDate() object and extract the seconds of the current time on the visitor's_x000D_
var seconds = new Date().getSeconds();_x000D_
// Add a leading zero to seconds value_x000D_
$("#sec").html(( seconds < 10 ? "0" : "" ) + seconds);_x000D_
},1000);_x000D_
_x000D_
setInterval( function() {_x000D_
// Create a newDate() object and extract the minutes of the current time on the visitor's_x000D_
var minutes = new Date().getMinutes();_x000D_
// Add a leading zero to the minutes value_x000D_
$("#min").html(( minutes < 10 ? "0" : "" ) + minutes);_x000D_
},1000);_x000D_
_x000D_
setInterval( function() {_x000D_
// Create a newDate() object and extract the hours of the current time on the visitor's_x000D_
var hours = new Date().getHours();_x000D_
// Add a leading zero to the hours value_x000D_
$("#hours").html(( hours < 10 ? "0" : "" ) + hours);_x000D_
}, 1000); _x000D_
});_x000D_
</script>_x000D_
<div class="clock">_x000D_
<div id="Date"></div>_x000D_
<ul>_x000D_
<li id="hours"></li>_x000D_
<li id="point">:</li>_x000D_
<li id="min"></li>_x000D_
<li id="point">:</li>_x000D_
<li id="sec"></li>_x000D_
</ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

COLLATION 'utf8_general_ci' is not valid for CHARACTER SET 'latin1'

In my case I created a database and gave the collation 'utf8_general_ci' but the required collation was 'latin1'. After changing my collation type to latin1_bin the error was gone.

Serving favicon.ico in ASP.NET MVC

1) You can put your favicon where you want and add this tag to your page head

<link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon" />

although some browsers will try to get the favicon from /favicon.ico by default, so you should use the IgnoreRoute.

2) If a browser makes a request for the favicon in another directory it will get a 404 error wich is fine and if you have the link tag in answer 1 in your master page the browser will get the favicon you want.

HTML/CSS: how to put text both right and left aligned in a paragraph

enter image description here

If the texts has different sizes and they must be underlined this is the solution:

<table>
  <tr>
    <td class='left'>January</td>
    <td class='right'>2014</td>
  </tr>
</table>

css:

table{
    width: 100%;
    border-bottom: 2px solid black;
    /*this is the size of the small text's baseline over part  (˜25px*3/4)*/
    line-height: 19.5px; 
}
table td{
    vertical-align: baseline;
}
.left{
    font-family: Arial;
    font-size: 40px;
    text-align: left;

}
.right{
    font-size: 25px;
    text-align: right;
}

demo here

How to enumerate an object's properties in Python?

See inspect.getmembers(object[, predicate]).

Return all the members of an object in a list of (name, value) pairs sorted by name. If the optional predicate argument is supplied, only members for which the predicate returns a true value are included.

>>> [name for name,thing in inspect.getmembers([])]
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', 
'__delslice__',    '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', 
'__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', 
'__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__','__reduce_ex__', 
'__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', 
'__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 
'insert', 'pop', 'remove', 'reverse', 'sort']
>>> 

AngularJS UI Router - change url without reloading state

Calling

$state.go($state.current, {myParam: newValue}, {notify: false});

will still reload the controller, meaning you will lose state data.

To avoid it, simply declare the parameter as dynamic:

$stateProvider.state({
    name: 'myState',
    url: '/my_state?myParam',
    params: {
        myParam: {
          dynamic: true,    // <----------
        }
    },
    ...
});

Then you don't even need the notify, just calling

$state.go($state.current, {myParam: newValue})

suffices. Neato!

From the documentation:

When dynamic is true, changes to the parameter value will not cause the state to be entered/exited. The resolves will not be re-fetched, nor will views be reloaded.

This can be useful to build UI where the component updates itself when the param values change.

What is "Signal 15 received"

This indicates the linux has delivered a SIGTERM to your process. This is usually at the request of some other process (via kill()) but could also be sent by your process to itself (using raise()). This signal requests an orderly shutdown of your process.

If you need a quick cheatsheet of signal numbers, open a bash shell and:

$ kill -l
 1) SIGHUP   2) SIGINT   3) SIGQUIT  4) SIGILL
 5) SIGTRAP  6) SIGABRT  7) SIGBUS   8) SIGFPE
 9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2
13) SIGPIPE 14) SIGALRM 15) SIGTERM 16) SIGSTKFLT
17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG  24) SIGXCPU
25) SIGXFSZ 26) SIGVTALRM   27) SIGPROF 28) SIGWINCH
29) SIGIO   30) SIGPWR  31) SIGSYS  34) SIGRTMIN
35) SIGRTMIN+1  36) SIGRTMIN+2  37) SIGRTMIN+3  38) SIGRTMIN+4
39) SIGRTMIN+5  40) SIGRTMIN+6  41) SIGRTMIN+7  42) SIGRTMIN+8
43) SIGRTMIN+9  44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12
47) SIGRTMIN+13 48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14
51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10
55) SIGRTMAX-9  56) SIGRTMAX-8  57) SIGRTMAX-7  58) SIGRTMAX-6
59) SIGRTMAX-5  60) SIGRTMAX-4  61) SIGRTMAX-3  62) SIGRTMAX-2
63) SIGRTMAX-1  64) SIGRTMAX    

You can determine the sender by using an appropriate signal handler like:

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

void sigterm_handler(int signal, siginfo_t *info, void *_unused)
{
  fprintf(stderr, "Received SIGTERM from process with pid = %u\n",
      info->si_pid);
  exit(0);
}

int main (void)
{
  struct sigaction action = {
    .sa_handler = NULL,
    .sa_sigaction = sigterm_handler,
    .sa_mask = 0,
    .sa_flags = SA_SIGINFO,
    .sa_restorer = NULL
  };

  sigaction(SIGTERM, &action, NULL);
  sleep(60);

  return 0;
}

Notice that the signal handler also includes a call to exit(). It's also possible for your program to continue to execute by ignoring the signal, but this isn't recommended in general (if it's a user doing it there's a good chance it will be followed by a SIGKILL if your process doesn't exit, and you lost your opportunity to do any cleanup then).

Change image in HTML page every few seconds

Change setTimeout("changeImage()", 30000); to setInterval("changeImage()", 30000); and remove var timerid = setInterval(changeImage, 30000);.

How to display image from URL on Android

Write the code using ASyncTask for http handling.

Bitmap b;
ImageView img;
......
try
    {
        URL url = new URL("http://10.119.120.10:80/img.jpg");
        InputStream is = new BufferedInputStream(url.openStream());
        b = BitmapFactory.decodeStream(is);
    } catch(Exception e){}
......
img.setImageBitmap(b);

Absolute Positioning & Text Alignment

Try this:

http://jsfiddle.net/HRz6X/2/

You need to add left: 0 and right: 0 (not supported by IE6). Or specify a width

List files recursively in Linux CLI with path relative to the current directory

That does the trick:

ls -R1 $PWD | while read l; do case $l in *:) d=${l%:};; "") d=;; *) echo "$d/$l";; esac; done | grep -i ".txt"

But it does that by "sinning" with the parsing of ls, though, which is considered bad form by the GNU and Ghostscript communities.

How can I detect if this dictionary key exists in C#?

I use a Dictionary and because of the repetetiveness and possible missing keys, I quickly patched together a small method:

 private static string GetKey(IReadOnlyDictionary<string, string> dictValues, string keyValue)
 {
     return dictValues.ContainsKey(keyValue) ? dictValues[keyValue] : "";
 }

Calling it:

var entry = GetKey(dictList,"KeyValue1");

Gets the job done.

URL Encode a string in jQuery for an AJAX request

try this one

var query = "{% url accounts.views.instasearch  %}?q=" + $('#tags').val().replace(/ /g, '+');

How to get substring from string in c#?

string newString = str.Substring(0,10)

will give you the first 10 characters (from position 0 to position 9).

See here.

CSS class for pointer cursor

Bootstrap 3 - Just adding the "btn" Class worked for me.

Without pointer cursor:

<span class="label label-success">text</span>

With pointer cursor:

<span class="label label-success btn">text</span>

How can I find the number of years between two dates?

I would recommend using the great Joda-Time library for everything date related in Java.

For your needs you can use the Years.yearsBetween() method.

row-level trigger vs statement-level trigger

You may want trigger action to execute once after the client executes a statement that modifies a million rows (statement-level trigger). Or, you may want to trigger the action once for every row that is modified (row-level trigger).

EXAMPLE: Let's say you have a trigger that will make sure all high school seniors graduate. That is, when a senior's grade is 12, and we increase it to 13, we want to set the grade to NULL.

For a statement level trigger, you'd say, after the increase-grade statement runs, check the whole table once to update any nows with grade 13 to NULL.

For a row-level trigger, you'd say, after every row that is updated, update the new row's grade to NULL if it is 13.

A statement-level trigger would look like this:

create trigger stmt_level_trigger
after update on Highschooler
begin
    update Highschooler
    set grade = NULL
    where grade = 13;
end;

and a row-level trigger would look like this:

create trigger row_level_trigger
after update on Highschooler
for each row
when New.grade = 13
begin
    update Highschooler
    set grade = NULL
    where New.ID = Highschooler.ID;
end;

Note that SQLite doesn't support statement-level triggers, so in SQLite, the FOR EACH ROW is optional.

Simple way to get element by id within a div tag?

A given ID can be only used once in a page. It's invalid HTML to have multiple objects with the same ID, even if they are in different parts of the page.

You could change your HTML to this:

<div id="div1" >
    <input type="text" class="edit1" />
    <input type="text" class="edit2" />
</div>
<div id="div2" >
    <input type="text" class="edit1" />
    <input type="text" class="edit2" />
</div>

Then, you could get the first item in div1 with a CSS selector like this:

#div1 .edit1

On in jQuery:

$("#div1 .edit1")

Or, if you want to iterate the items in one of your divs, you can do it like this:

$("#div1 input").each(function(index) {
    // do something with one of the input objects
});

If I couldn't use a framework like jQuery or YUI, I'd go get Sizzle and include that for it's selector logic (it's the same selector engine as is inside of jQuery) because DOM manipulation is massively easier with a good selector library.

If I couldn't use even Sizzle (which would be a massive drop in developer productivity), you could use plain DOM functions to traverse the children of a given element.

You would use DOM functions like childNodes or firstChild and nextSibling and you'd have to check the nodeType to make sure you only got the kind of elements you wanted. I never write code that way because it's so much less productive than using a selector library.

What datatype to use when storing latitude and longitude data in SQL databases?

You can easily store a lat/lon decimal number in an unsigned integer field, instead of splitting them up in a integer and decimal part and storing those separately as somewhat suggested here using the following conversion algorithm:

as a stored mysql function:

CREATE DEFINER=`r`@`l` FUNCTION `PositionSmallToFloat`(s INT) 
RETURNS decimal(10,7)
DETERMINISTIC
RETURN if( ((s > 0) && (s >> 31)) , (-(0x7FFFFFFF - 
(s & 0x7FFFFFFF))) / 600000, s / 600000)

and back

CREATE DEFINER=`r`@`l` FUNCTION `PositionFloatToSmall`(s DECIMAL(10,7)) 
RETURNS int(10)
DETERMINISTIC
RETURN s * 600000

That needs to be stored in an unsigned int(10), this works in mysql as well as in sqlite which is typeless.

through experience, I find that this works really fast, if all you need to to is store coordinates and retrieve those to do some math with.

in php those 2 functions look like

function LatitudeSmallToFloat($LatitudeSmall){
   if(($LatitudeSmall>0)&&($LatitudeSmall>>31)) 
     $LatitudeSmall=-(0x7FFFFFFF-($LatitudeSmall&0x7FFFFFFF))-1;
   return (float)$LatitudeSmall/(float)600000;
}

and back again:

function LatitudeFloatToSmall($LatitudeFloat){
   $Latitude=round((float)$LatitudeFloat*(float)600000);
   if($Latitude<0) $Latitude+=0xFFFFFFFF;
   return $Latitude;
}

This has some added advantage as well in term of creating for example memcached unique keys with integers. (ex: to cache a geocode result). Hope this adds value to the discussion.

Another application could be when you are without GIS extensions and simply want to keep a few million of those lat/lon pairs, you can use partitions on those fields in mysql to benefit from the fact they are integers:

Create Table: CREATE TABLE `Locations` (
  `lat` int(10) unsigned NOT NULL,
  `lon` int(10) unsigned NOT NULL,
  `location` text,
  PRIMARY KEY (`lat`,`lon`) USING BTREE,
  KEY `index_location` (`locationText`(30))
) ENGINE=InnoDB DEFAULT CHARSET=utf8
/*!50100 PARTITION BY KEY ()
PARTITIONS 100 */

C++ Remove new line from multiline string

About answer 3 removing only the last \n off string code :

if (!s.empty() && s[s.length()-1] == '\n') {
    s.erase(s.length()-1);
}

Will the if condition not fail if the string is really empty ?

Is it not better to do :

if (!s.empty())
{
    if (s[s.length()-1] == '\n')
        s.erase(s.length()-1);
}

How to get access to job parameters from ItemReader, in Spring Batch?

Did you declare the jobparameters as map properly as bean?

Or did you perhaps accidently instantiate a JobParameters object, which has no getter for the filename?

For more on expression language you can find information in Spring documentation here.

How do I position one image on top of another in HTML?

Ok, after some time, here's what I landed on:

_x000D_
_x000D_
.parent {_x000D_
  position: relative;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
}_x000D_
.image1 {_x000D_
  position: relative;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  border: 1px red solid;_x000D_
}_x000D_
.image2 {_x000D_
  position: absolute;_x000D_
  top: 30px;_x000D_
  left: 30px;_x000D_
  border: 1px green solid;_x000D_
}
_x000D_
<div class="parent">_x000D_
  <img class="image1" src="https://placehold.it/50" />_x000D_
  <img class="image2" src="https://placehold.it/100" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

As the simplest solution. That is:

Create a relative div that is placed in the flow of the page; place the base image first as relative so that the div knows how big it should be; place the overlays as absolutes relative to the upper left of the first image. The trick is to get the relatives and absolutes correct.

How do Python functions handle the types of the parameters that you pass in?

The other answers have done a good job at explaining duck typing and the simple answer by tzot:

Python does not have variables, like other languages where variables have a type and a value; it has names pointing to objects, which know their type.

However, one interesting thing has changed since 2010 (when the question was first asked), namely the implementation of PEP 3107 (implemented in Python 3). You can now actually specify the type of a parameter and the type of the return type of a function like this:

def pick(l: list, index: int) -> int:
    return l[index]

We can here see that pick takes 2 parameters, a list l and an integer index. It should also return an integer.

So here it is implied that l is a list of integers which we can see without much effort, but for more complex functions it can be a bit confusing as to what the list should contain. We also want the default value of index to be 0. To solve this you may choose to write pick like this instead:

def pick(l: "list of ints", index: int = 0) -> int:
    return l[index]

Note that we now put in a string as the type of l, which is syntactically allowed, but it is not good for parsing programmatically (which we'll come back to later).

It is important to note that Python won't raise a TypeError if you pass a float into index, the reason for this is one of the main points in Python's design philosophy: "We're all consenting adults here", which means you are expected to be aware of what you can pass to a function and what you can't. If you really want to write code that throws TypeErrors you can use the isinstance function to check that the passed argument is of the proper type or a subclass of it like this:

def pick(l: list, index: int = 0) -> int:
    if not isinstance(l, list):
        raise TypeError
    return l[index]

More on why you should rarely do this and what you should do instead is talked about in the next section and in the comments.

PEP 3107 does not only improve code readability but also has several fitting use cases which you can read about here.


Type annotation got a lot more attention in Python 3.5 with the introduction of PEP 484 which introduces a standard module for type hints.

These type hints came from the type checker mypy (GitHub), which is now PEP 484 compliant.

With the typing module comes with a pretty comprehensive collection of type hints, including:

  • List, Tuple, Set, Map - for list, tuple, set and map respectively.
  • Iterable - useful for generators.
  • Any - when it could be anything.
  • Union - when it could be anything within a specified set of types, as opposed to Any.
  • Optional - when it might be None. Shorthand for Union[T, None].
  • TypeVar - used with generics.
  • Callable - used primarily for functions, but could be used for other callables.

These are the most common type hints. A complete listing can be found in the documentation for the typing module.

Here is the old example using the annotation methods introduced in the typing module:

from typing import List

def pick(l: List[int], index: int) -> int:
    return l[index]

One powerful feature is the Callable which allows you to type annotate methods that take a function as an argument. For example:

from typing import Callable, Any, Iterable

def imap(f: Callable[[Any], Any], l: Iterable[Any]) -> List[Any]:
    """An immediate version of map, don't pass it any infinite iterables!"""
    return list(map(f, l))

The above example could become more precise with the usage of TypeVar instead of Any, but this has been left as an exercise to the reader since I believe I've already filled my answer with too much information about the wonderful new features enabled by type hinting.


Previously when one documented Python code with for example Sphinx some of the above functionality could be obtained by writing docstrings formatted like this:

def pick(l, index):
    """
    :param l: list of integers
    :type l: list
    :param index: index at which to pick an integer from *l*
    :type index: int
    :returns: integer at *index* in *l*
    :rtype: int
    """
    return l[index]

As you can see, this takes a number of extra lines (the exact number depends on how explicit you want to be and how you format your docstring). But it should now be clear to you how PEP 3107 provides an alternative that is in many (all?) ways superior. This is especially true in combination with PEP 484 which, as we have seen, provides a standard module that defines a syntax for these type hints/annotations that can be used in such a way that it is unambiguous and precise yet flexible, making for a powerful combination.

In my personal opinion, this is one of the greatest features in Python ever. I can't wait for people to start harnessing the power of it. Sorry for the long answer, but this is what happens when I get excited.


An example of Python code which heavily uses type hinting can be found here.

Should I declare Jackson's ObjectMapper as a static field?

Yes, that is safe and recommended.

The only caveat from the page you referred is that you can't be modifying configuration of the mapper once it is shared; but you are not changing configuration so that is fine. If you did need to change configuration, you would do that from the static block and it would be fine as well.

EDIT: (2013/10)

With 2.0 and above, above can be augmented by noting that there is an even better way: use ObjectWriter and ObjectReader objects, which can be constructed by ObjectMapper. They are fully immutable, thread-safe, meaning that it is not even theoretically possible to cause thread-safety issues (which can occur with ObjectMapper if code tries to re-configure instance).

How to find the cumulative sum of numbers in a list?

You can calculate the cumulative sum list in linear time with a simple for loop:

def csum(lst):
    s = lst.copy()
    for i in range(1, len(s)):
        s[i] += s[i-1]
    return s

time_interval = [4, 6, 12]
print(csum(time_interval))  # [4, 10, 22]

The standard library's itertools.accumulate may be a faster alternative (since it's implemented in C):

from itertools import accumulate
time_interval = [4, 6, 12]
print(list(accumulate(time_interval)))  # [4, 10, 22]

How to select different app.config for several build configurations

After some research on managing configs for development and builds etc, I decided to roll my own, I have made it available on bitbucket at: https://bitbucket.org/brightertools/contemplate/wiki/Home

This multiple configuration files for multiple environments, its a basic configuration entry replacement tool that will work with any text based file format.

Hope this helps.

COALESCE with Hive SQL

Since 0.11 hive has a NVL function nvl(T value, T default_value)

which says Returns default value if value is null else returns value

When is each sorting algorithm used?

What the provided links to comparisons/animations do not consider is when the amount of data exceed available memory --- at which point the number of passes over the data, i.e. I/O-costs, dominate the runtime. If you need to do that, read up on "external sorting" which usually cover variants of merge- and heap sorts.

http://corte.si/posts/code/visualisingsorting/index.html and http://corte.si/posts/code/timsort/index.html also have some cool images comparing various sorting algorithms.

Android: How to enable/disable option menu item on button click?

Generally can change the properties of your views in runtime:

(Button) item = (Button) findViewById(R.id.idBut);

and then...

item.setVisibility(false)

but

if you want to modify de visibility of the options from the ContextMenu, on press your button, you can activate a flag, and then in onCreateContextMenu you can do something like this:

 @Override
        public void onCreateContextMenu(ContextMenu menu, 
                View v,ContextMenu.ContextMenuInfo menuInfo) {

            super.onCreateContextMenu(menu, v, menuInfo);

                menu.setHeaderTitle(R.string.context_title);

                if (flagIsOn()) {
                    addMenuItem(menu, "Option available", true);
                } else {
                    Toast.makeText(this, "Option not available", 500).show();
                }

        }

I hope this helps

How do I pull from a Git repository through an HTTP proxy?

It looks like you're using a mingw compile of Git on windows (or possibly another one I haven't heard about). There are ways to debug this: I believe all of the http proxy work for git is done by curl. Set this environment variable before running git:

GIT_CURL_VERBOSE=1

This should at least give you an idea of what is going on behind the scenes.

C++ error: undefined reference to 'clock_gettime' and 'clock_settime'

I encountered the same error. My linker command did have the rt library included -lrt which is correct and it was working for a while. After re-installing Kubuntu it stopped working.

A separate forum thread suggested the -lrt needed to come after the project object files. Moving the -lrt to the end of the command fixed this problem for me although I don't know the details of why.

How do I auto size a UIScrollView to fit its content

Here's a Swift 3 adaptation of @leviatan's answer :

EXTENSION

import UIKit


extension UIScrollView {

    func resizeScrollViewContentSize() {

        var contentRect = CGRect.zero

        for view in self.subviews {

            contentRect = contentRect.union(view.frame)

        }

        self.contentSize = contentRect.size

    }

}

USAGE

scrollView.resizeScrollViewContentSize()

Very easy to use !

How to give a pattern for new line in grep?

grep patterns are matched against individual lines so there is no way for a pattern to match a newline found in the input.

However you can find empty lines like this:

grep '^$' file
grep '^[[:space:]]*$' file # include white spaces 

What does it mean by command cd /d %~dp0 in Windows

Let's dissect it. There are three parts:

  1. cd -- This is change directory command.
  2. /d -- This switch makes cd change both drive and directory at once. Without it you would have to do cd %~d0 & cd %~p0. (%~d0 Changs active drive, cd %~p0 change the directory).
  3. %~dp0 -- This can be dissected further into three parts:
    1. %0 -- This represents zeroth parameter of your batch script. It expands into the name of the batch file itself.
    2. %~0 -- The ~ there strips double quotes (") around the expanded argument.
    3. %dp0 -- The d and p there are modifiers of the expansion. The d forces addition of a drive letter and the p adds full path.

Convert Python dict into a dataframe

I have run into this several times and have an example dictionary that I created from a function get_max_Path(), and it returns the sample dictionary:

{2: 0.3097502930247044, 3: 0.4413177909384636, 4: 0.5197224051562838, 5: 0.5717654946470984, 6: 0.6063959031223476, 7: 0.6365209824708223, 8: 0.655918861281035, 9: 0.680844386645206}

To convert this to a dataframe, I ran the following:

df = pd.DataFrame.from_dict(get_max_path(2), orient = 'index').reset_index()

Returns a simple two column dataframe with a separate index:

index 0 0 2 0.309750 1 3 0.441318

Just rename the columns using f.rename(columns={'index': 'Column1', 0: 'Column2'}, inplace=True)

Use jQuery to navigate away from page

window.location = myUrl;

Anyway, this is not jQuery: it's plain javascript

How to create an empty R vector to add new items

I've also seen

x <- {}

Now you can concatenate or bind a vector of any dimension to x

rbind(x, 1:10)
cbind(x, 1:10)
c(x, 10)

How to set and reference a variable in a Jenkinsfile

According to the documentation, you can also set global environment variables if you later want to use the value of the variable in other parts of your script. In your case, it would be setting it in the root pipeline:

pipeline {
  ...
  environment {
    FILENAME = readFile ...
  }
  ...
}

Overwriting txt file in java

The easiest way to overwrite a text file is to use a public static field.

this will overwrite the file every time because your only using false the first time through.`

public static boolean appendFile;

Use it to allow only one time through the write sequence for the append field of the write code to be false.

// use your field before processing the write code

appendFile = False;

File fnew=new File("../playlist/"+existingPlaylist.getText()+".txt");
String source = textArea.getText();
System.out.println(source);
FileWriter f2;

try {
     //change this line to read this

    // f2 = new FileWriter(fnew,false);

    // to read this
    f2 = new FileWriter(fnew,appendFile); // important part
    f2.write(source);

    // change field back to true so the rest of the new data will
    // append to the new file.

    appendFile = true;

    f2.close();
 } catch (IOException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
 }           

How do I change TextView Value inside Java Code?

First, add a textView in the XML file

<TextView  
    android:id="@+id/rate_id"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/what_U_want_to_display_in_first_time"
    />

then add a button in xml file with id btn_change_textView and write this two line of code in onCreate() method of activity

Button btn= (Button) findViewById(R.id. btn_change_textView);
TextView textView=(TextView)findViewById(R.id.rate_id);

then use clickListener() on button object like this

btn.setOnClickListener(new View.OnClickListener {
    public void onClick(View v) {
      
        textView.setText("write here what u want to display after button click in string");
    }
});

How can I refresh or reload the JFrame?

Try this code. I also faced the same problem, but some how I solved it.

public class KitchenUserInterface {

    private JFrame frame;
    private JPanel main_panel, northpanel , southpanel;
    private JLabel label;
    private JButton nextOrder;
    private JList list;

    private static KitchenUserInterface kitchenRunner ;

    public void setList(String[] order){
        kitchenRunner.frame.dispose();
        kitchenRunner.frame.setVisible(false);
        kitchenRunner= new KitchenUserInterface(order);

    }

    public KitchenUserInterface getInstance() {
        if(kitchenRunner == null) {
            synchronized(KitchenUserInterface.class) {
                if(kitchenRunner == null) {
                    kitchenRunner = new KitchenUserInterface();
                }
            }
        }


        return this.kitchenRunner;
    }

    private KitchenUserInterface() {


        frame = new JFrame("Lullaby's Kitchen");
        main_panel = new JPanel();
        main_panel.setLayout(new BorderLayout());
        frame.setContentPane(main_panel);



        northpanel = new JPanel();
        northpanel.setLayout(new FlowLayout());


        label = new JLabel("Kitchen");

        northpanel.add(label);


        main_panel.add(northpanel , BorderLayout.NORTH);


        frame.setSize(500 , 500 );
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    private KitchenUserInterface (String[] order){
        this();
        list = new JList<String>(order);
        main_panel.add(list , BorderLayout.CENTER);

        southpanel = new JPanel();
         southpanel.setLayout(new FlowLayout());

         nextOrder = new JButton("Next Order Set");
         nextOrder.addActionListener(new OrderUpListener(list));
         southpanel.add(nextOrder);
         main_panel.add(southpanel, BorderLayout.SOUTH);



    }

    public static void main(String[] args) {
        KitchenUserInterface dat = kitchenRunner.getInstance();
        try{

        Thread.sleep(1500);
        System.out.println("Ready");
        dat.setList(OrderArray.getInstance().getOrders());
        }
        catch(Exception event) {
            System.out.println("Error sleep");
            System.out.println(event);
        }


        }

}

How to parse a CSV file in Bash?

You need to use IFS instead of -d:

while IFS=, read -r col1 col2
do
    echo "I got:$col1|$col2"
done < myfile.csv

Note that for general purpose CSV parsing you should use a specialized tool which can handle quoted fields with internal commas, among other issues that Bash can't handle by itself. Examples of such tools are cvstool and csvkit.

How to implement Android Pull-to-Refresh

Nobody have mention the new type of "Pull to refresh" which shows on top of the action bar like in the Google Now or Gmail application.

There is a library ActionBar-PullToRefresh which works exactly the same.

Python script to convert from UTF-8 to ASCII

UTF-8 is a superset of ASCII. Either your UTF-8 file is ASCII, or it can't be converted without loss.

How to make Bootstrap carousel slider use mobile left/right swipe

Checked solution is not accurate, sometimes mouse-right-click triggers right-swipe. after trying different plugins for swipe i found an almost perfect one.

touchSwipe

i said "almost" because this plugin does not support future elements. so we would have to reinitialize the swipe call when the swipe content is changed by ajax or something. this plugin have lots of options to play with touch events like multi-finger-touch,pinch etc.

http://labs.rampinteractive.co.uk/touchSwipe/demos/index.html

solution 1 :

$("#myCarousel").swipe( {
            swipe:function(event, direction, distance, duration, fingerCount, fingerData) {

                if(direction=='left'){
                    $(this).carousel('next');
                }else if(direction=='right'){
                    $(this).carousel('prev');
                }

            }
        });

solution 2:(for future element case)

function addSwipeTo(selector){
            $(selector).swipe("destroy");
            $(selector).swipe( {
                swipe:function(event, direction, distance, duration, fingerCount, fingerData) {
                    if(direction=='left'){
                        $(this).carousel('next');
                    }else if(direction=='right'){
                        $(this).carousel('prev');
                    }
                }
            });
}
addSwipeTo("#myCarousel");

Ubuntu - Run command on start-up with "sudo"

Edit the tty configuration in /etc/init/tty*.conf with a shellscript as a parameter :

(...)
exec /sbin/getty -n -l  theInputScript.sh -8 38400 tty1
(...)

This is assuming that we're editing tty1 and the script that reads input is theInputScript.sh.

A word of warning this script is run as root, so when you are inputing stuff to it you have root priviliges. Also append a path to the location of the script.

Important: the script when it finishes, has to invoke the /sbin/login otherwise you wont be able to login in the terminal.

How to directly initialize a HashMap (in a literal way)?

Unfortunately, using varargs if the type of the keys and values are not the same is not very reasonable as you'd have to use Object... and lose type safety completely. If you always want to create e.g. a Map<String, String>, of course a toMap(String... args) would be possible though, but not very pretty as it would be easy to mix up keys and values, and an odd number of arguments would be invalid.

You could create a sub-class of HashMap that has a chainable method like

public class ChainableMap<K, V> extends HashMap<K, V> {
  public ChainableMap<K, V> set(K k, V v) {
    put(k, v);
    return this;
  }
}

and use it like new ChainableMap<String, Object>().set("a", 1).set("b", "foo")

Another approach is to use the common builder pattern:

public class MapBuilder<K, V> {
  private Map<K, V> mMap = new HashMap<>();

  public MapBuilder<K, V> put(K k, V v) {
    mMap.put(k, v);
    return this;
  }

  public Map<K, V> build() {
    return mMap;
  }
}

and use it like new MapBuilder<String, Object>().put("a", 1).put("b", "foo").build();

However, the solution I've used now and then utilizes varargs and the Pair class:

public class Maps {
  public static <K, V> Map<K, V> of(Pair<K, V>... pairs) {
    Map<K, V> = new HashMap<>();

    for (Pair<K, V> pair : pairs) {
      map.put(pair.first, pair.second);
    }

    return map;
  }
}

Map<String, Object> map = Maps.of(Pair.create("a", 1), Pair.create("b", "foo");

The verbosity of Pair.create() bothers me a bit, but this works quite fine. If you don't mind static imports you could of course create a helper:

public <K, V> Pair<K, V> p(K k, V v) {
  return Pair.create(k, v);
}

Map<String, Object> map = Maps.of(p("a", 1), p("b", "foo");

(Instead of Pair one could imagine using Map.Entry, but since it's an interface it requires an implementing class and/or a helper factory method. It's also not immutable, and contains other logic not useful for this task.)

How do I parse JSON in Android?

  1. Writing JSON Parser Class

    public class JSONParser {
    
        static InputStream is = null;
        static JSONObject jObj = null;
        static String json = "";
    
        // constructor
        public JSONParser() {}
    
        public JSONObject getJSONFromUrl(String url) {
    
            // Making HTTP request
            try {
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
    
                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
    
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                json = sb.toString();
            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }
    
            // try parse the string to a JSON object
            try {
                jObj = new JSONObject(json);
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }
    
            // return JSON String
            return jObj;
    
        }
    }
    
  2. Parsing JSON Data
    Once you created parser class next thing is to know how to use that class. Below i am explaining how to parse the json (taken in this example) using the parser class.

    2.1. Store all these node names in variables: In the contacts json we have items like name, email, address, gender and phone numbers. So first thing is to store all these node names in variables. Open your main activity class and declare store all node names in static variables.

    // url to make request
    private static String url = "http://api.9android.net/contacts";
    
    // JSON Node names
    private static final String TAG_CONTACTS = "contacts";
    private static final String TAG_ID = "id";
    private static final String TAG_NAME = "name";
    private static final String TAG_EMAIL = "email";
    private static final String TAG_ADDRESS = "address";
    private static final String TAG_GENDER = "gender";
    private static final String TAG_PHONE = "phone";
    private static final String TAG_PHONE_MOBILE = "mobile";
    private static final String TAG_PHONE_HOME = "home";
    private static final String TAG_PHONE_OFFICE = "office";
    
    // contacts JSONArray
    JSONArray contacts = null;
    

    2.2. Use parser class to get JSONObject and looping through each json item. Below i am creating an instance of JSONParser class and using for loop i am looping through each json item and finally storing each json data in variable.

    // Creating JSON Parser instance
    JSONParser jParser = new JSONParser();
    
    // getting JSON string from URL
    JSONObject json = jParser.getJSONFromUrl(url);
    
        try {
        // Getting Array of Contacts
        contacts = json.getJSONArray(TAG_CONTACTS);
    
        // looping through All Contacts
        for(int i = 0; i < contacts.length(); i++){
            JSONObject c = contacts.getJSONObject(i);
    
            // Storing each json item in variable
            String id = c.getString(TAG_ID);
            String name = c.getString(TAG_NAME);
            String email = c.getString(TAG_EMAIL);
            String address = c.getString(TAG_ADDRESS);
            String gender = c.getString(TAG_GENDER);
    
            // Phone number is agin JSON Object
            JSONObject phone = c.getJSONObject(TAG_PHONE);
            String mobile = phone.getString(TAG_PHONE_MOBILE);
            String home = phone.getString(TAG_PHONE_HOME);
            String office = phone.getString(TAG_PHONE_OFFICE);
    
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    

Benefits of inline functions in C++?

Inline functions are faster because you don't need to push and pop things on/off the stack like parameters and the return address; however, it does make your binary slightly larger.

Does it make a significant difference? Not noticeably enough on modern hardware for most. But it can make a difference, which is enough for some people.

Marking something inline does not give you a guarantee that it will be inline. It's just a suggestion to the compiler. Sometimes it's not possible such as when you have a virtual function, or when there is recursion involved. And sometimes the compiler just chooses not to use it.

I could see a situation like this making a detectable difference:

inline int aplusb_pow2(int a, int b) {
  return (a + b)*(a + b) ;
}

for(int a = 0; a < 900000; ++a)
    for(int b = 0; b < 900000; ++b)
        aplusb_pow2(a, b);

Javascript ajax call on page onload

This is really easy using a JavaScript library, e.g. using jQuery you could write:

$(document).ready(function(){
$.ajax({ url: "database/update.html",
        context: document.body,
        success: function(){
           alert("done");
        }});
});

Without jQuery, the simplest version might be as follows, but it does not account for browser differences or error handling:

<html>
  <body onload="updateDB();">
  </body>
  <script language="javascript">
    function updateDB() {
      var xhr = new XMLHttpRequest();
      xhr.open("POST", "database/update.html", true);
      xhr.send(null);
      /* ignore result */
    }
  </script>
</html>

See also:

How can I extract substrings from a string in Perl?

You could use a regular expression such as the following:

/([-a-z0-9]+)\s*\((.*?)\)\s*(\*)?/

So for example:

$s = "abc-456-hu5t10 (High priority) *";
$s =~ /([-a-z0-9]+)\s*\((.*?)\)\s*(\*)?/;
print "$1\n$2\n$3\n";

prints

abc-456-hu5t10
High priority
*

How to generate unique IDs for form labels in React?

Following up as of 2019-04-04, this seems to be able to be accomplished with the React Hooks' useState:

import React, { useState } from 'react'
import uniqueId from 'lodash/utility/uniqueId'

const Field = props => {
  const [ id ] = useState(uniqueId('myprefix-'))

  return (
    <div>
      <label htmlFor={id}>{props.label}</label>
      <input id={id} type="text"/>
    </div>
  )      
}

export default Field

As I understand it, you ignore the second array item in the array destructuring that would allow you to update id, and now you've got a value that won't be updated again for the life of the component.

The value of id will be myprefix-<n> where <n> is an incremental integer value returned from uniqueId. If that's not unique enough for you, consider making your own like

function gen4() {
  return Math.random().toString(16).slice(-4)
}

function simpleUniqueId(prefix) {
  return (prefix || '').concat([
    gen4(),
    gen4(),
    gen4(),
    gen4(),
    gen4(),
    gen4(),
    gen4(),
    gen4()
  ].join(''))
}

or check out the library I published with this here: https://github.com/rpearce/simple-uniqueid. There are also hundreds or thousands of other unique ID things out there, but lodash's uniqueId with a prefix should be enough to get the job done.


Update 2019-07-10

Thanks to @Huong Hk for pointing me to hooks lazy initial state, the sum of which is that you can pass a function to useState that will only be run on the initial mount.

// before
const [ id ] = useState(uniqueId('myprefix-'))

// after
const [ id ] = useState(() => uniqueId('myprefix-'))

use jQuery's find() on JSON object

This works for me on [{"id":"data"},{"id":"data"}]

function getObjects(obj, key, val) 
{
    var newObj = false; 
    $.each(obj, function()
    {
        var testObject = this; 
        $.each(testObject, function(k,v)
        {
            //alert(k);
            if(val == v && k == key)
            {
                newObj = testObject;
            }
        });
    });

    return newObj;
}

Python: Tuples/dictionaries as keys, select, sort

You could have a dictionary where the entries are a list of other dictionaries:

fruit_dict = dict()
fruit_dict['banana'] = [{'yellow': 24}]
fruit_dict['apple'] = [{'red': 12}, {'green': 14}]
print fruit_dict

Output:

{'banana': [{'yellow': 24}], 'apple': [{'red': 12}, {'green': 14}]}

Edit: As eumiro pointed out, you could use a dictionary of dictionaries:

fruit_dict = dict()
fruit_dict['banana'] = {'yellow': 24}
fruit_dict['apple'] = {'red': 12, 'green': 14}
print fruit_dict

Output:

{'banana': {'yellow': 24}, 'apple': {'green': 14, 'red': 12}}

How to plot two histograms together in R?

Here's a function I wrote that uses pseudo-transparency to represent overlapping histograms

plotOverlappingHist <- function(a, b, colors=c("white","gray20","gray50"),
                                breaks=NULL, xlim=NULL, ylim=NULL){

  ahist=NULL
  bhist=NULL

  if(!(is.null(breaks))){
    ahist=hist(a,breaks=breaks,plot=F)
    bhist=hist(b,breaks=breaks,plot=F)
  } else {
    ahist=hist(a,plot=F)
    bhist=hist(b,plot=F)

    dist = ahist$breaks[2]-ahist$breaks[1]
    breaks = seq(min(ahist$breaks,bhist$breaks),max(ahist$breaks,bhist$breaks),dist)

    ahist=hist(a,breaks=breaks,plot=F)
    bhist=hist(b,breaks=breaks,plot=F)
  }

  if(is.null(xlim)){
    xlim = c(min(ahist$breaks,bhist$breaks),max(ahist$breaks,bhist$breaks))
  }

  if(is.null(ylim)){
    ylim = c(0,max(ahist$counts,bhist$counts))
  }

  overlap = ahist
  for(i in 1:length(overlap$counts)){
    if(ahist$counts[i] > 0 & bhist$counts[i] > 0){
      overlap$counts[i] = min(ahist$counts[i],bhist$counts[i])
    } else {
      overlap$counts[i] = 0
    }
  }

  plot(ahist, xlim=xlim, ylim=ylim, col=colors[1])
  plot(bhist, xlim=xlim, ylim=ylim, col=colors[2], add=T)
  plot(overlap, xlim=xlim, ylim=ylim, col=colors[3], add=T)
}

Here's another way to do it using R's support for transparent colors

a=rnorm(1000, 3, 1)
b=rnorm(1000, 6, 1)
hist(a, xlim=c(0,10), col="red")
hist(b, add=T, col=rgb(0, 1, 0, 0.5) )

The results end up looking something like this: alt text

What does elementFormDefault do in XSD?

I have noticed that XMLSpy(at least 2011 version)needs a targetNameSpace defined if elementFormDefault="qualified" is used. Otherwise won't validate. And also won't generate xmls with namespace prefixes

PHP function to get the subdomain of a URL

What I found the best and short solution is

array_shift(explode(".",$_SERVER['HTTP_HOST']));

IntelliJ, can't start simple web application: Unable to ping server at localhost:1099

Setting project's SDK in IntelliJ (File > Project Structure > Project:Project SDK) worked for me

How to correct "TypeError: 'NoneType' object is not subscriptable" in recursive function?

This simply means that either tree, tree[otu], or tree[otu][0] evaluates to None, and as such is not subscriptable. Most likely tree[otu] or tree[otu][0]. Track it down with some simple debugging like this:

def Ancestors (otu,tree):
    try:
        tree[otu][0][0]
    except TypeError:
        print otu, tre[otu]
        raise
    #etc...

or pdb

Error message "Forbidden You don't have permission to access / on this server"

After changing the configuration files don't forget to Restart All Services.

I wasted three hours of my time on it.

MySQL - Selecting data from multiple tables all with same structure but different data

The column is ambiguous because it appears in both tables you would need to specify the where (or sort) field fully such as us_music.genre or de_music.genre but you'd usually specify two tables if you were then going to join them together in some fashion. The structure your dealing with is occasionally referred to as a partitioned table although it's usually done to separate the dataset into distinct files as well rather than to just split the dataset arbitrarily. If you're in charge of the database structure and there's no good reason to partition the data then I'd build one big table with an extra "origin" field that contains a country code but you're probably doing it for legitimate performance reason. Either use a union to join the tables you're interested in http://dev.mysql.com/doc/refman/5.0/en/union.html or by using the Merge database engine http://dev.mysql.com/doc/refman/5.1/en/merge-storage-engine.html.

Override default Spring-Boot application.properties settings in Junit Test

Simple explanation:

If you are like me and you have the same application.properties in src/main/resources and src/test/resources, and you are wondering why the application.properties in your test folder is not overriding the application.properties in your main resources, read on...

If you have application.properties under src/main/resources and the same application.properties under src/test/resources, which application.properties gets picked up, depends on how you are running your tests. The folder structure src/main/resources and src/test/resources, is a Maven architectural convention, so if you run your test like mvnw test or even gradlew test, the application.properties in src/test/resources will get picked up, as test classpath will precede main classpath. But, if you run your test like Run as JUnit Test in Eclipse/STS, the application.properties in src/main/resources will get picked up, as main classpath precedes test classpath.

You can check it out by opening the menu bar Run > Run Configurations > JUnit > *your_run_configuration* > Click on "Show Command Line".

You will see something like this:

XXXbin\javaw.exe -ea -Dfile.encoding=UTF-8 -classpath
XXX\workspace-spring-tool-suite-4-4.5.1.RELEASE\project_name\bin\main;
XXX\workspace-spring-tool-suite-4-4.5.1.RELEASE\project_name\bin\test;

Do you see that classpath xxx\main comes first, and then xxx\test? Right, it's all about classpath :-)

Side-note: Be mindful that properties overridden in the Launch Configuration(In Spring Tool Suite IDE, for example) takes priority over application.properties.

When is the finalize() method called in Java?

An Object becomes eligible for Garbage collection or GC if its not reachable from any live threads or any static refrences in other words you can say that an object becomes eligible for garbage collection if its all references are null. Cyclic dependencies are not counted as reference so if Object A has reference of object B and object B has reference of Object A and they don't have any other live reference then both Objects A and B will be eligible for Garbage collection. Generally an object becomes eligible for garbage collection in Java on following cases:

  1. All references of that object explicitly set to null e.g. object = null
  2. Object is created inside a block and reference goes out scope once control exit that block.
  3. Parent object set to null, if an object holds reference of another object and when you set container object's reference null, child or contained object automatically becomes eligible for garbage collection.
  4. If an object has only live references via WeakHashMap it will be eligible for garbage collection.

No resource found - Theme.AppCompat.Light.DarkActionBar

In xamarin if you face this issue when you add any new sdk. The simple solution is Open your styles file and add this line.

<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar"></style>

It's better solution rather than adding appcompat.

Pretty-print an entire Pandas Series / DataFrame

If you are using Ipython Notebook (Jupyter). You can use HTML

from IPython.core.display import HTML
display(HTML(df.to_html()))

Business logic in MVC

Fist of all:
I believe that you are mixing up the MVC pattern and n-tier-based design principles.

Using an MVC approach does not mean that you shouldn't layer your application.
It might help if you see MVC more like an extension of the presentation layer.

If you put non-presentation code inside the MVC pattern you might very soon end up in a complicated design.
Therefore I would suggest that you put your business logic into a separate business layer.

Just have a look at this: Wikipedia article about multitier architecture

It says:

Today, MVC and similar model-view-presenter (MVP) are Separation of Concerns design patterns that apply exclusively to the presentation layer of a larger system.

Anyway ... when talking about an enterprise web application the calls from the UI to the business logic layer should be placed inside the (presentation) controller.

That is because the controller actually handles the calls to a specific resource, queries the data by making calls to the business logic and links the data (model) to the appropriate view.

Mud told you that the business rules go into the model.
That is also true, but he mixed up the (presentation) model (the 'M' in MVC) and the data layer model of a tier-based application design.
So it is valid to place your database related business rules in the model (data layer) of your application.
But you should not place them in the model of your MVC-structured presentation layer as this only applies to a specific UI.

This technique is independent of whether you use a domain driven design or a transaction script based approach.

Let me visualize that for you:


Presentation layer: Model - View - Controller


Business layer: Domain logic - Application logic


Data layer: Data repositories - Data access layer


The model that you see above means that you have an application that uses MVC, DDD and a database-independed data layer.
This is a common approach to design a larger enterprise web application.

But you can also shrink it down to use a simple non-DDD business layer (a business layer without domain logic) and a simple data layer that writes directly to a specific database.
You could even drop the whole data-layer and access the database directly from the business layer, though I do not recommend it.

Thats' the trick...I hope this helps...

[Note:] You should also be aware of the fact that nowadays there is more than just one "model" in an application. Commonly, each layer of an application has it's own model. The model of the presentation layer is view specific but often independent of the used controls. The business layer can also have a model, called the "domain-model". This is typically the case when you decide to take a domain-driven approach. This "domain-model" contains of data as well as business logic (the main logic of your program) and is usually independent of the presentation layer. The presentation layer usually calls the business layer on a certain "event" (button pressed etc.) to read data from or write data to the data layer. The data layer might also have it's own model, which is typically database related. It often contains a set of entity classes as well as data-access-objects (DAOs).

The question is: how does this fit into the MVC concept?

Answer -> It doesn't!
Well - it kinda does, but not completely.
This is because MVC is an approach that was developed in the late 1970's for the Smalltalk-80 programming language. At that time GUIs and personal computers were quite uncommon and the world wide web was not even invented! Most of today's programming languages and IDEs were developed in the 1990s. At that time computers and user interfaces were completely different from those in the 1970s.
You should keep that in mind when you talk about MVC.
Martin Fowler has written a very good article about MVC, MVP and today's GUIs.

How to set date format in HTML date input tag?

I made a lot of research and I don't think one can force format of the <input type="date">. The browser select the local format, and depending on user settings, if the user's language is in English, the date will be displayed to the English format (mm/dd/yyyy).

In my opinion, the best solution is to use a plugin to control the display.

Jquery DatePicker seems a good option since you can force the localization, date format ...

Elasticsearch error: cluster_block_exception [FORBIDDEN/12/index read-only / allow delete (api)], flood stage disk watermark exceeded

By default, Elasticsearch installed goes into read-only mode when you have less than 5% of free disk space. If you see errors similar to this:

Elasticsearch::Transport::Transport::Errors::Forbidden: [403] {"error":{"root_cause":[{"type":"cluster_block_exception","reason":"blocked by: [FORBIDDEN/12/index read-only / allow delete (api)];"}],"type":"cluster_block_exception","reason":"blocked by: [FORBIDDEN/12/index read-only / allow delete (api)];"},"status":403}

Or in /usr/local/var/log/elasticsearch.log you can see logs similar to:

flood stage disk watermark [95%] exceeded on [nCxquc7PTxKvs6hLkfonvg][nCxquc7][/usr/local/var/lib/elasticsearch/nodes/0] free: 15.3gb[4.1%], all indices on this node will be marked read-only

Then you can fix it by running the following commands:

curl -XPUT -H "Content-Type: application/json" http://localhost:9200/_cluster/settings -d '{ "transient": { "cluster.routing.allocation.disk.threshold_enabled": false } }'
curl -XPUT -H "Content-Type: application/json" http://localhost:9200/_all/_settings -d '{"index.blocks.read_only_allow_delete": null}'

Does Python SciPy need BLAS?

For Windows users there is a nice binary package by Chris (warning: it's a pretty large download, 191 MB):

Add ArrayList to another ArrayList in java

Very first will declare outer Arraylist which will contain another inner Arraylist inside it

ArrayList> CompletesystemStatusArrayList; ArrayList systemStatusArrayList

CompletesystemStatusArrayList=new ArrayList

systemStatusArrayList=new ArrayList();

    systemStatusArrayList.add("1");
    systemStatusArrayList.add("2");
    systemStatusArrayList.add("3");
    systemStatusArrayList.add("4");
    systemStatusArrayList.add("5");
    systemStatusArrayList.add("6");
    systemStatusArrayList.add("7");
    systemStatusArrayList.add("8");

    CompletesystemStatusArrayList.add(systemStatusArrayList);

Download a file by jQuery.Ajax

Use window.open https://developer.mozilla.org/en-US/docs/Web/API/Window/open

For example, you can put this line of code in a click handler:

window.open('/file.txt', '_blank');

It will open a new tab (because of the '_blank' window-name) and that tab will open the URL.

Your server-side code should also have something like this:

res.set('Content-Disposition', 'attachment; filename=file.txt');

And that way, the browser should prompt the user to save the file to disk, instead of just showing them the file. It will also automatically close the tab that it just opened.

Check if table exists in SQL Server

select name from SysObjects where xType='U' and name like '%xxx%' order by name

How to insert date values into table

Since dob is DATE data type, you need to convert the literal to DATE using TO_DATE and the proper format model. The syntax is:

TO_DATE('<date_literal>', '<format_model>')

For example,

SQL> CREATE TABLE t(dob DATE);

Table created.

SQL> INSERT INTO t(dob) VALUES(TO_DATE('17/12/2015', 'DD/MM/YYYY'));

1 row created.

SQL> COMMIT;

Commit complete.

SQL> SELECT * FROM t;

DOB
----------
17/12/2015

A DATE data type contains both date and time elements. If you are not concerned about the time portion, then you could also use the ANSI Date literal which uses a fixed format 'YYYY-MM-DD' and is NLS independent.

For example,

SQL> INSERT INTO t(dob) VALUES(DATE '2015-12-17');

1 row created.

Size of Matrix OpenCV

A complete C++ code example, may be helpful for the beginners

#include <iostream>
#include <string>
#include "opencv/highgui.h"

using namespace std;
using namespace cv;

int main()
{
    cv:Mat M(102,201,CV_8UC1);
    int rows = M.rows;
    int cols = M.cols;

    cout<<rows<<" "<<cols<<endl;

    cv::Size sz = M.size();
    rows = sz.height;
    cols = sz.width;

    cout<<rows<<" "<<cols<<endl;
    cout<<sz<<endl;
    return 0;
}

How do I convert csv file to rdd

How about this?

val Delimeter = ","
val textFile = sc.textFile("data.csv").map(line => line.split(Delimeter))

How to convert Java String to JSON Object

The string that you pass to the constructor JSONObject has to be escaped with quote():

public static java.lang.String quote(java.lang.String string)

Your code would now be:

JSONObject jsonObj = new JSONObject.quote(jsonString.toString());
System.out.println(jsonString);
System.out.println("---------------------------");
System.out.println(jsonObj);

SQL Server: Extract Table Meta-Data (description, fields and their data types)

To get the description data, you unfortunately have to use sysobjects/syscolumns to get the ids:

SELECT      u.name + '.' + t.name AS [table],
            td.value AS [table_desc],
            c.name AS [column],
            cd.value AS [column_desc]
FROM        sysobjects t
INNER JOIN  sysusers u
    ON      u.uid = t.uid
LEFT OUTER JOIN sys.extended_properties td
    ON      td.major_id = t.id
    AND     td.minor_id = 0
    AND     td.name = 'MS_Description'
INNER JOIN  syscolumns c
    ON      c.id = t.id
LEFT OUTER JOIN sys.extended_properties cd
    ON      cd.major_id = c.id
    AND     cd.minor_id = c.colid
    AND     cd.name = 'MS_Description'
WHERE t.type = 'u'
ORDER BY    t.name, c.colorder

You can do it with info-schema, but you'd have to concatenate etc to call OBJECT_ID() - so what would be the point?

How do I install the ext-curl extension with PHP 7?

If You have 404 or errors while sudo apt-get install php-curl just try

sudo apt-get update

and again try

sudo apt-get install php-curl

But notice what version was installed (i use php7.3 and php7.4-curl was installed - so it will not work)

try then

sudo apt-get install php7.3-curl

At the end You may want to restart services like: apache2 or php-fpm:

sudo apache2 restart
sudo service php7.3-fpm restart

this worked for me.

Check if curl is on the installed modules list for current php:

php -m

enter image description here

What does the JSLint error 'body of a for in should be wrapped in an if statement' mean?

First of all, never use a for in loop to enumerate over an array. Never. Use good old for(var i = 0; i<arr.length; i++).

The reason behind this is the following: each object in JavaScript has a special field called prototype. Everything you add to that field is going to be accessible on every object of that type. Suppose you want all arrays to have a cool new function called filter_0 that will filter zeroes out.

Array.prototype.filter_0 = function() {
    var res = [];
    for (var i = 0; i < this.length; i++) {
        if (this[i] != 0) {
            res.push(this[i]);
        }
    }
    return res;
};

console.log([0, 5, 0, 3, 0, 1, 0].filter_0());
//prints [5,3,1]

This is a standard way to extend objects and add new methods. Lots of libraries do this. However, let's look at how for in works now:

var listeners = ["a", "b", "c"];
for (o in listeners) {
    console.log(o);
}
//prints:
//  0
//  1
//  2
//  filter_0

Do you see? It suddenly thinks filter_0 is another array index. Of course, it is not really a numeric index, but for in enumerates through object fields, not just numeric indexes. So we're now enumerating through every numeric index and filter_0. But filter_0 is not a field of any particular array object, every array object has this property now.

Luckily, all objects have a hasOwnProperty method, which checks if this field really belongs to the object itself or if it is simply inherited from the prototype chain and thus belongs to all the objects of that type.

for (o in listeners) {
    if (listeners.hasOwnProperty(o)) {
       console.log(o);
    }
}
 //prints:
 //  0
 //  1
 //  2

Note, that although this code works as expected for arrays, you should never, never, use for in and for each in for arrays. Remember that for in enumerates the fields of an object, not array indexes or values.

var listeners = ["a", "b", "c"];
listeners.happy = "Happy debugging";

for (o in listeners) {
    if (listeners.hasOwnProperty(o)) {
       console.log(o);
    }
}

 //prints:
 //  0
 //  1
 //  2
 //  happy

How to check if a stored procedure exists before creating it

I know it is a very old post, but since this appears in the top search results hence adding the latest update for those using SQL Server 2016 SP1 -

create or alter procedure procTest
as
begin
 print (1)
end;
go

This creates a Stored Procedure if does not already exist, but alters it if exists.

Reference

Postgresql : Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

The error you quote has nothing to do with pg_hba.conf; it's failing to connect, not failing to authorize the connection.

Do what the error message says:

Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

You haven't shown the command that produces the error. Assuming you're connecting on localhost port 5432 (the defaults for a standard PostgreSQL install), then either:

  • PostgreSQL isn't running

  • PostgreSQL isn't listening for TCP/IP connections (listen_addresses in postgresql.conf)

  • PostgreSQL is only listening on IPv4 (0.0.0.0 or 127.0.0.1) and you're connecting on IPv6 (::1) or vice versa. This seems to be an issue on some older Mac OS X versions that have weird IPv6 socket behaviour, and on some older Windows versions.

  • PostgreSQL is listening on a different port to the one you're connecting on

  • (unlikely) there's an iptables rule blocking loopback connections

(If you are not connecting on localhost, it may also be a network firewall that's blocking TCP/IP connections, but I'm guessing you're using the defaults since you didn't say).

So ... check those:

  • ps -f -u postgres should list postgres processes

  • sudo lsof -n -u postgres |grep LISTEN or sudo netstat -ltnp | grep postgres should show the TCP/IP addresses and ports PostgreSQL is listening on

BTW, I think you must be on an old version. On my 9.3 install, the error is rather more detailed:

$ psql -h localhost -p 12345
psql: could not connect to server: Connection refused
        Is the server running on host "localhost" (::1) and accepting
        TCP/IP connections on port 12345?

Pass react component as props

As noted in the accepted answer - you can use the special { props.children } property. However - you can just pass a component as a prop as the title requests. I think this is cleaner sometimes as you might want to pass several components and have them render in different places. Here's the react docs with an example of how to do it:

https://reactjs.org/docs/composition-vs-inheritance.html

Make sure you are actually passing a component and not an object (this tripped me up initially).

The code is simply this:

const Parent = () => { 
  return (
    <Child  componentToPassDown={<SomeComp />}  />
  )
}

const Child = ({ componentToPassDown }) => { 
  return (
    <>
     {componentToPassDown}  
    </>
  )
}

How to get info on sent PHP curl request

curl_getinfo() must be added before closing the curl handler

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://example.com/bar");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "someusername:secretpassword");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_exec($ch);
$info = curl_getinfo($ch);
print_r($info['request_header']);
curl_close($ch);

Create line after text with css

There's no need for extra wrappers or span elements anymore. Flexbox and Grid can handle this easily.

_x000D_
_x000D_
h2 {_x000D_
  display: flex;_x000D_
  align-items: center;_x000D_
}_x000D_
_x000D_
h2::after {_x000D_
  content: '';_x000D_
  flex: 1;_x000D_
  margin-left: 1rem;_x000D_
  height: 1px;_x000D_
  background-color: #000;_x000D_
}
_x000D_
<h2>Heading</h2>
_x000D_
_x000D_
_x000D_

How to add a downloaded .box file to Vagrant?

Try to change directory to where the .box is saved

Run vagrant box add my-box downloaded.box, this may work as it avoids absolute path (on Windows?).

Delete all but the most recent X files in bash

All these answers fail when there are directories in the current directory. Here's something that works:

find . -maxdepth 1 -type f | xargs -x ls -t | awk 'NR>5' | xargs -L1 rm

This:

  1. works when there are directories in the current directory

  2. tries to remove each file even if the previous one couldn't be removed (due to permissions, etc.)

  3. fails safe when the number of files in the current directory is excessive and xargs would normally screw you over (the -x)

  4. doesn't cater for spaces in filenames (perhaps you're using the wrong OS?)

SQL query to find record with ID not in another table

There are basically 3 approaches to that: not exists, not in and left join / is null.

LEFT JOIN with IS NULL

SELECT  l.*
FROM    t_left l
LEFT JOIN
        t_right r
ON      r.value = l.value
WHERE   r.value IS NULL

NOT IN

SELECT  l.*
FROM    t_left l
WHERE   l.value NOT IN
        (
        SELECT  value
        FROM    t_right r
        )

NOT EXISTS

SELECT  l.*
FROM    t_left l
WHERE   NOT EXISTS
        (
        SELECT  NULL
        FROM    t_right r
        WHERE   r.value = l.value
        )

Which one is better? The answer to this question might be better to be broken down to major specific RDBMS vendors. Generally speaking, one should avoid using select ... where ... in (select...) when the magnitude of number of records in the sub-query is unknown. Some vendors might limit the size. Oracle, for example, has a limit of 1,000. Best thing to do is to try all three and show the execution plan.

Specifically form PostgreSQL, execution plan of NOT EXISTS and LEFT JOIN / IS NULL are the same. I personally prefer the NOT EXISTS option because it shows better the intent. After all the semantic is that you want to find records in A that its pk do not exist in B.

Old but still gold, specific to PostgreSQL though: https://explainextended.com/2009/09/16/not-in-vs-not-exists-vs-left-join-is-null-postgresql/

Uint8Array to string in Javascript

TextEncoder and TextDecoder from the Encoding standard, which is polyfilled by the stringencoding library, converts between strings and ArrayBuffers:

var uint8array = new TextEncoder("utf-8").encode("¢");
var string = new TextDecoder("utf-8").decode(uint8array);

Looping over elements in jQuery

I have used the following before:

var my_form = $('#form-id');
var data = {};

$('input:not([type=checkbox]), input[type=checkbox]:selected, select, textarea', my_form).each(
    function() {
        var name = $(this).attr('name');
        var val = $(this).val();

        if (!data.hasOwnProperty(name)) {
            data[name] = new Array;
        }

        data[name].push(val);
    }
);

This is just written from memory, so might contain mistakes, but this should make an object called data that contains the values for all your inputs.

Note that you have to deal with checkboxes in a special way, to avoid getting the values of unchecked checkboxes. The same is probably true of radio inputs.

Also note using arrays for storing the values, as for one input name, you might have values from several inputs (checkboxes in particular).

How to find the port for MS SQL Server 2008?

You can use this two commands: tasklist and netstat -oan

Tasklist.exe is like taskmgr.exe but in text mode.

With tasklist.exe or taskmgr.exe you can obtain a PID of sqlservr.exe

With netstat -oan, it shows a connection PID, and you can filter it.

Example:

C:\>tasklist | find /i "sqlservr.exe"
sqlservr.exe  1184 Services    0 3.181.800 KB

C:\>netstat -oan | find /i "1184"
TCP  0.0.0.0:1280  0.0.0.0:0  LISTENING  1184

In this example, the SQLServer port is 1280

Extracted from: http://www.sysadmit.com/2016/03/mssql-ver-puerto-de-una-instancia.html

Get index of element as child relative to parent

Delegate and Live are easy to use but if you won't have any more li:s added dynamically you could use event delagation with normal bind/click as well. There should be some performance gain using this method since the DOM won't have to be monitored for new matching elements. Haven't got any actual numbers but it makes sense :)

$("#wizard").click(function (e) {
    var source = $(e.target);
    if(source.is("li")){
        // alert index of li relative to ul parent
        alert(source.index());
    }
});

You could test it at jsFiddle: http://jsfiddle.net/jimmysv/4Sfdh/1/

How to clone ArrayList and also clone its contents?

I have used this option always:

ArrayList<Dog> clonedList = new ArrayList<Dog>(name_of_arraylist_that_you_need_to_Clone);

XSLT getting last element

You need to put the last() indexing on the nodelist result, rather than as part of the selection criteria. Try:

(//element[@name='D'])[last()]

Is there a typical state machine implementation pattern?

For a simple state machine just use a switch statement and an enum type for your state. Do your transitions inside the switch statement based on your input. In a real program you would obviously change the "if(input)" to check for your transition points. Hope this helps.

typedef enum
{
    STATE_1 = 0,
    STATE_2,
    STATE_3
} my_state_t;

my_state_t state = STATE_1;

void foo(char input)
{
    ...
    switch(state)
    {
        case STATE_1:
            if(input)
                state = STATE_2;
            break;
        case STATE_2:
            if(input)
                state = STATE_3;
            else
                state = STATE_1;
            break;
        case STATE_3:
            ...
            break;
    }
    ...
}

Convert Mercurial project to Git

I had a similar task to do, but it contained some aspects that were not sufficiently covered by the other answers here:

  • I wanted to convert all (in my case: two, or in general: more than one) branches of my repo.
  • I had non-ASCII and (being a Windows user) non-UTF8-encoded characters (for the curious: German umlaute) in my commit messages and file names.

I did not try fast-export and hg-fast-export, since they require that you have Python and some Mercurial Python modules on your machine, which I didn't have.

I did try hg-init with TortoiseHG, and this answer gave me a good start. But it looked like it only converts the current branch, not all at once (*). So I read the hg-init docs and this blog post and added

[git]  
branch_bookmark_suffix=_bookmark

to my mercurial.ini, and did

hg bookmarks -r default master  
hg bookmarks -r my_branch my_branch_bookmark  
hg gexport

(Repeat the 2nd line for every branch you want to convert, and repeat it again if you should happen to do another commit before executing the 3rd line). This creates a folder git within .hg, which turns out to be a bare Git repo with all the exported branches. I could clone this repo and had a working copy as desired.

Or almost...

Running

git status

on my working copy showed all files with non-ASCII characters in their names as untracked files. So I continued researching and followed this advice:

git rm -rf --cached \*  
git add --all
git commit 

And finally the repo was ready to be pushed up to Bitbucket :-)

I also tried the Github importer as mentioned in this answer. I used Bitbucket as the source system, and Github did quite a good job, i.e. it converted all branches automatically. However, it showed '?'-characters for all non-ASCII characters in my commit messages (Web-UI and locally) and filenames (Web-UI only), and while I could fix the filenames as described above, I had no idea what to do with the commit messages, and so I'd prefer the hg-init approach. Without the encoding issue the Github importer would have been a perfect and fast solution (as long as you have a paid Github account or can tolerate that your repo is public for as long as it takes to pull it from Github to your local machine).


(*) So it looked like before I discovered that I have to bookmark all the branches I want to export. If you do and push to a bare (!) repo, like the linked answer says, you get all the branches.

using "if" and "else" Stored Procedures MySQL

The problem is you either haven't closed your if or you need an elseif:

create procedure checando(
    in nombrecillo varchar(30),
    in contrilla varchar(30), 
    out resultado int)
begin 

    if exists (select * from compas where nombre = nombrecillo and contrasenia = contrilla) then
        set resultado = 0;
    elseif exists (select * from compas where nombre = nombrecillo) then
        set resultado = -1;
    else 
        set resultado = -2;
    end if;
end;

Angularjs autocomplete from $http

the easiest way to do that in angular or angularjs without external modules or directives is using list and datalist HTML5. You just get a json and use ng-repeat for feeding the options in datalist. The json you can fetch it from ajax.

in this example:

  • ctrl.query is the query that you enter when you type.
  • ctrl.msg is the message that is showing in the placeholder
  • ctrl.dataList is the json fetched

then you can add filters and orderby in the ng-reapet

!! list and datalist id must have the same name !!

 <input type="text" list="autocompleList" ng-model="ctrl.query" placeholder={{ctrl.msg}}>
<datalist id="autocompleList">
        <option ng-repeat="Ids in ctrl.dataList value={{Ids}}  >
</datalist>

UPDATE : is native HTML5 but be carreful with the type browser and version. check it out : https://caniuse.com/#search=datalist.

The OutputPath property is not set for this project

The error shown in visual studio for the project (Let's say A) does not have issues. When I looked at the output window for the build line by line for each project, I saw that it was complaining about another project (B) that had been referred as assembly in project A. Project B added into the solution. But it had not been referred in the project A as project reference instead as assembly reference from different location. That location contains the assembly which compiled for Platform AnyCpu. Then I removed the assembly reference from the project A and added project B as a reference. It started compiling. Not sure though how this fix worked.

GCC dump preprocessor defines

The simple approach (gcc -dM -E - < /dev/null) works fine for gcc but fails for g++. Recently I required a test for a C++11/C++14 feature. Recommendations for their corresponding macro names are published at https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations. But:

g++ -dM -E - < /dev/null | fgrep __cpp_alias_templates

always fails, because it silently invokes the C-drivers (as if invoked by gcc). You can see this by comparing its output against that of gcc or by adding a g++-specific command line option like (-std=c++11) which emits the error message cc1: warning: command line option ‘-std=c++11’ is valid for C++/ObjC++ but not for C.

Because (the non C++) gcc will never support "Templates Aliases" (see http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2258.pdf) you must add the -x c++ option to force the invocation of the C++ compiler (Credits for using the -x c++ options instead of an empty dummy file go to yuyichao, see below):

g++ -dM -E -x c++ /dev/null | fgrep __cpp_alias_templates

There will be no output because g++ (revision 4.9.1, defaults to -std=gnu++98) does not enable C++11-features by default. To do so, use

g++ -dM -E -x c++ -std=c++11 /dev/null | fgrep __cpp_alias_templates

which finally yields

#define __cpp_alias_templates 200704

noting that g++ 4.9.1 does support "Templates Aliases" when invoked with -std=c++11.

Defining a HTML template to append using JQuery

You could decide to make use of a templating engine in your project, such as:

If you don't want to include another library, John Resig offers a jQuery solution, similar to the one below.


Browsers and screen readers ignore unrecognized script types:

<script id="hidden-template" type="text/x-custom-template">
    <tr>
        <td>Foo</td>
        <td>Bar</td>
    <tr>
</script>

Using jQuery, adding rows based on the template would resemble:

var template = $('#hidden-template').html();

$('button.addRow').click(function() {
    $('#targetTable').append(template);
});

What is the most efficient way to create a dictionary of two pandas Dataframe columns?

In Python 3.6 the fastest way is still the WouterOvermeire one. Kikohs' proposal is slower than the other two options.

import timeit

setup = '''
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(32, 120, 100000).reshape(50000,2),columns=list('AB'))
df['A'] = df['A'].apply(chr)
'''

timeit.Timer('dict(zip(df.A,df.B))', setup=setup).repeat(7,500)
timeit.Timer('pd.Series(df.A.values,index=df.B).to_dict()', setup=setup).repeat(7,500)
timeit.Timer('df.set_index("A").to_dict()["B"]', setup=setup).repeat(7,500)

Results:

1.1214002349999777 s  # WouterOvermeire
1.1922008498571748 s  # Jeff
1.7034366211428602 s  # Kikohs

Convert Json Array to normal Java list

we starting from conversion [ JSONArray -> List < JSONObject > ]

public static List<JSONObject> getJSONObjectListFromJSONArray(JSONArray array) 
        throws JSONException {
  ArrayList<JSONObject> jsonObjects = new ArrayList<>();
  for (int i = 0; 
           i < (array != null ? array.length() : 0);           
           jsonObjects.add(array.getJSONObject(i++)) 
       );
  return jsonObjects;
}

next create generic version replacing array.getJSONObject(i++) with POJO

example :

public <T> static List<T> getJSONObjectListFromJSONArray(Class<T> forClass, JSONArray array) 
        throws JSONException {
  ArrayList<Tt> tObjects = new ArrayList<>();
  for (int i = 0; 
           i < (array != null ? array.length() : 0);           
           tObjects.add( (T) createT(forClass, array.getJSONObject(i++))) 
       );
  return tObjects;
}

private static T createT(Class<T> forCLass, JSONObject jObject) {
   // instantiate via reflection / use constructor or whatsoever 
   T tObject = forClass.newInstance(); 
   // if not using constuctor args  fill up 
   // 
   // return new pojo filled object 
   return tObject;
}

What is the bower (and npm) version syntax?

Based on semver, you can use

  • Hyphen Ranges X.Y.Z - A.B.C 1.2.3-2.3.4 Indicates >=1.2.3 <=2.3.4

  • X-Ranges 1.2.x 1.X 1.2.*

  • Tilde Ranges ~1.2.3 ~1.2 Indicates allowing patch-level changes or minor version changes.

  • Caret Ranges ^1.2.3 ^0.2.5 ^0.0.4

    Allows changes that do not modify the left-most non-zero digit in the [major, minor, patch] tuple

    • ^1.2.x (means >=1.2.0 <2.0.0)
    • ^0.0.x (means >=0.0.0 <0.1.0)
    • ^0.0 (means >=0.0.0 <0.1.0)

Bash write to file without echo?

The way to do this in bash is

zsh <<< '> test <<< "Hello World!"'

This is one of the interesting differences between zsh and bash: given an unchained > or >>, zsh has the good sense to hook it up to stdin, while bash does not. It would be downright useful - if it were only standard. I tried to use this to send & append my ssh key over ssh to a remote authorized_keys file, but the remote host was bash, of course, and quietly did nothing.

And that's why you should just use cat.

How to get current timestamp in string format in Java? "yyyy.MM.dd.HH.mm.ss"

Use java.util.Date class instead of Timestamp.

String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());

This will get you the current date in the format specified.

Pass PDO prepared statement to variables

Instead of using ->bindParam() you can pass the data only at the time of ->execute():

$data = [   ':item_name' => $_POST['item_name'],   ':item_type' => $_POST['item_type'],   ':item_price' => $_POST['item_price'],   ':item_description' => $_POST['item_description'],   ':image_location' => 'images/'.$_FILES['file']['name'],   ':status' => 0,   ':id' => 0, ];  $stmt->execute($data); 

In this way you would know exactly what values are going to be sent.

You seem to not be depending on "@angular/core". This is an error

Delete your node modules , Check your package.json file should have the @angular/core and reinstall it with npm i.

What is the use of System.in.read()?

It allows you to read from the standard input (mainly, the console). This SO question may helps you.

How to make PyCharm always show line numbers

Version 2.6 and above:
PyCharm (far left menu) -> Preferences... -> Editor (bottom left section) -> General -> Appearance -> Show line numbers checkbox

enter image description here

Version 2.5 and below:
Settings -> Editor -> General -> Appearance -> Show line numbers checkbox

Created Button Click Event c#

if your button is inside your form class:

buttonOk.Click += new EventHandler(your_click_method);

(might not be exactly EventHandler)

and in your click method:

this.Close();

If you need to show a message box:

MessageBox.Show("test");

Is object empty?

No need for a library.

function(){ //must be within a function
 var obj = {}; //the object to test

 for(var isNotEmpty in obj) //will loop through once if there is a property of some sort, then
    return alert('not empty')//what ever you are trying to do once

 return alert('empty'); //nope obj was empty do this instead;
}

WPF C# button style

Here's my attempt. Looks more similar to the OP's sample and provides settable properties for icon (FrameworkElement), title (string) and subtitle (string). The output looks like this:

enter image description here

Here's XAML:

<Button x:Class="Controls.FancyButton"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:Controls"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300" Width="300" Height="80"
          BorderBrush="{x:Null}" BorderThickness="0">
  <Button.Effect>
    <DropShadowEffect BlurRadius="12" Color="Gray" Direction="270" Opacity=".8" ShadowDepth="3" />
  </Button.Effect>

  <Button.Template>
    <ControlTemplate TargetType="Button">
      <Grid Width="{Binding RelativeSource={RelativeSource AncestorType=Button}, Path=ActualWidth}"
        Height="{Binding RelativeSource={RelativeSource AncestorType=Button}, Path=ActualHeight}">

        <Border x:Name="MainBorder" CornerRadius="3" Grid.ColumnSpan="2" Margin="0,0,4,4" BorderBrush="Black" BorderThickness="1">
          <Border.Background>
            <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
              <GradientStop Color="#FF5E5E5E" Offset="0" />
              <GradientStop Color="#FF040404" Offset="1" />
            </LinearGradientBrush>
          </Border.Background>

          <Grid >
            <Grid.ColumnDefinitions>
              <ColumnDefinition Width="1.2*"/>
              <ColumnDefinition Width="3*"/>
            </Grid.ColumnDefinitions>

            <Border CornerRadius="2" Margin="0" BorderBrush="LightGray" BorderThickness="0,1,0,0" Grid.ColumnSpan="2" Grid.RowSpan="2" />

            <Line X1="10" Y1="0" X2="10" Y2="10" Stretch="Fill" Grid.Column="0" HorizontalAlignment="Right" Stroke="#0C0C0C" Grid.RowSpan="2" />
            <Line X1="10" Y1="0" X2="10" Y2="10" Stretch="Fill" Grid.Column="1" HorizontalAlignment="Left" Grid.RowSpan="2">
              <Line.Stroke>
                <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
                  <GradientStop Color="#4D4D4D" Offset="0" />
                  <GradientStop Color="#2C2C2C" Offset="1" />
                </LinearGradientBrush>
              </Line.Stroke>
            </Line>

            <ContentControl HorizontalAlignment="Center" VerticalAlignment="Center" Grid.RowSpan="2">
              <ContentControl.Content>
                <Binding RelativeSource="{RelativeSource TemplatedParent}" Path="Image">
                  <Binding.FallbackValue>
                    <Path Data="M0,0 L30,15 L0,30Z">
                      <Path.Effect>
                        <DropShadowEffect Direction="50" ShadowDepth="2" />
                      </Path.Effect>
                      <Path.Fill>
                        <LinearGradientBrush StartPoint="0,0.5" EndPoint="1,0.5">
                          <GradientStop Color="#4B86B2" Offset="0" />
                          <GradientStop Color="#477FA8" Offset="1" />
                        </LinearGradientBrush>
                      </Path.Fill>
                    </Path>
                  </Binding.FallbackValue>
                </Binding>
              </ContentControl.Content>
            </ContentControl>


            <Grid Grid.Column="1" HorizontalAlignment="Left" VerticalAlignment="Center">
              <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
              </Grid.RowDefinitions>

              <TextBlock x:Name="Title" Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Title, FallbackValue='Watch Now'}" Grid.Column="1" VerticalAlignment="Bottom" FontFamily="Calibri" FontWeight="Bold" FontSize="28" Foreground="White" Margin="20,0,0,0" />
              <TextBlock x:Name="SubTitle" Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=SubTitle, FallbackValue='Duration: 50 min'}" Grid.Column="1" Grid.Row="1" VerticalAlignment="top" FontFamily="Calibri" FontSize="14" Foreground="White" Margin="20,0,0,0" />
            </Grid>
          </Grid>
        </Border>
      </Grid>

      <ControlTemplate.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
          <Setter TargetName="Title" Property="TextDecorations" Value="Underline" />
          <Setter TargetName="SubTitle" Property="TextDecorations" Value="Underline" />
        </Trigger>
        <Trigger Property="IsPressed" Value="True">
          <Setter TargetName="MainBorder" Property="Background">
            <Setter.Value>
              <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
                <GradientStop Color="#FF5E5E5E" Offset="0" />
                <GradientStop Color="#FFA4A4A4" Offset="1" />
              </LinearGradientBrush>
            </Setter.Value>
          </Setter>
        </Trigger>
      </ControlTemplate.Triggers>
    </ControlTemplate>
  </Button.Template>
</Button>

Here's the code-behind:

using System.Windows;
using System.Windows.Controls;

namespace Controls
{
  public partial class FancyButton : Button
  {
    public FancyButton()
    {
      InitializeComponent();
    }

    public string Title
    {
      get { return (string)GetValue(TitleProperty); }
      set { SetValue(TitleProperty, value); }
    }

    public static readonly DependencyProperty TitleProperty =
        DependencyProperty.Register("Title", typeof(string), typeof(FancyButton), new FrameworkPropertyMetadata("Title", FrameworkPropertyMetadataOptions.AffectsRender));

    public string SubTitle
    {
      get { return (string)GetValue(SubTitleProperty); }
      set { SetValue(SubTitleProperty, value); }
    }

    public static readonly DependencyProperty SubTitleProperty =
        DependencyProperty.Register("SubTitle", typeof(string), typeof(FancyButton), new FrameworkPropertyMetadata("SubTitle", FrameworkPropertyMetadataOptions.AffectsRender));

    public FrameworkElement Image
    {
      get { return (FrameworkElement)GetValue(ImageProperty); }
      set { SetValue(ImageProperty, value); }
    }

    public static readonly DependencyProperty ImageProperty =
        DependencyProperty.Register("Image", typeof(FrameworkElement), typeof(FancyButton), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender));
  }
}

Here is how to use it:

<controls:FancyButton Grid.Row="1" HorizontalAlignment="Right" Margin="3" Title="Watch Now" SubTitle="Duration: 50 min">
  <controls:FancyButton.Image>
    <Path Data="M0,0 L30,15 L0,30Z">
      <Path.Effect>
        <DropShadowEffect Direction="50" ShadowDepth="2" />
      </Path.Effect>
      <Path.Fill>
        <LinearGradientBrush StartPoint="0,0.5" EndPoint="1,0.5">
          <GradientStop Color="#4B86B2" Offset="0" />
          <GradientStop Color="#477FA8" Offset="1" />
        </LinearGradientBrush>
      </Path.Fill>
    </Path>
  </controls:FancyButton.Image>
</controls:FancyButton>

jquery to loop through table rows and cells, where checkob is checked, concatenate

UPDATED

I've updated your demo: http://jsfiddle.net/terryyounghk/QS56z/18/

Also, I've changed two ^= to *=. See http://api.jquery.com/category/selectors/

And note the :checked selector. See http://api.jquery.com/checked-selector/

function createcodes() {

    //run through each row
    $('.authors-list tr').each(function (i, row) {

        // reference all the stuff you need first
        var $row = $(row),
            $family = $row.find('input[name*="family"]'),
            $grade = $row.find('input[name*="grade"]'),
            $checkedBoxes = $row.find('input:checked');

        $checkedBoxes.each(function (i, checkbox) {
            // assuming you layout the elements this way, 
            // we'll take advantage of .next()
            var $checkbox = $(checkbox),
                $line = $checkbox.next(),
                $size = $line.next();

            $line.val(
                $family.val() + ' ' + $size.val() + ', ' + $grade.val()
            );

        });

    });
}

NSOperation vs Grand Central Dispatch

GCD is indeed lower-level than NSOperationQueue, its major advantage is that its implementation is very light-weight and focused on lock-free algorithms and performance.

NSOperationQueue does provide facilities that are not available in GCD, but they come at non-trivial cost, the implementation of NSOperationQueue is complex and heavy-weight, involves a lot of locking, and uses GCD internally only in a very minimal fashion.

If you need the facilities provided by NSOperationQueue by all means use it, but if GCD is sufficient for your needs, I would recommend using it directly for better performance, significantly lower CPU and power cost and more flexibility.

Calling variable defined inside one function from another function

Everything in python is considered as object so functions are also objects. So you can use this method as well.

def fun1():
    fun1.var = 100
    print(fun1.var)

def fun2():
    print(fun1.var)

fun1()
fun2()

print(fun1.var)

How to install the JDK on Ubuntu Linux

You can use the sudo apt-get install default-jdk terminal command to install the default JDK version.

Before installing Java, type the sudo apt-get update terminal command and then type the install terminal command. You can get more information from here.

get keys of json-object in JavaScript

[What you have is just an object, not a "json-object". JSON is a textual notation. What you've quoted is JavaScript code using an array initializer and an object initializer (aka, "object literal syntax").]

If you can rely on having ECMAScript5 features available, you can use the Object.keys function to get an array of the keys (property names) in an object. All modern browsers have Object.keys (including IE9+).

Object.keys(jsonData).forEach(function(key) {
    var value = jsonData[key];
    // ...
});

The rest of this answer was written in 2011. In today's world, A) You don't need to polyfill this unless you need to support IE8 or earlier (!), and B) If you did, you wouldn't do it with a one-off you wrote yourself or grabbed from an SO answer (and probably shouldn't have in 2011, either). You'd use a curated polyfill, possibly from es5-shim or via a transpiler like Babel that can be configured to include polyfills (which may come from es5-shim).

Here's the rest of the answer from 2011:

Note that older browsers won't have it. If not, this is one of the ones you can supply yourself:

if (typeof Object.keys !== "function") {
    (function() {
        var hasOwn = Object.prototype.hasOwnProperty;
        Object.keys = Object_keys;
        function Object_keys(obj) {
            var keys = [], name;
            for (name in obj) {
                if (hasOwn.call(obj, name)) {
                    keys.push(name);
                }
            }
            return keys;
        }
    })();
}

That uses a for..in loop (more info here) to loop through all of the property names the object has, and uses Object.prototype.hasOwnProperty to check that the property is owned directly by the object rather than being inherited.

(I could have done it without the self-executing function, but I prefer my functions to have names, and to be compatible with IE you can't use named function expressions [well, not without great care]. So the self-executing function is there to avoid having the function declaration create a global symbol.)

How do I import a .sql file in mysql database using PHP?

If you are using PHP version 7 or higher, try below script,

// Name of the file
$filename = 'sql.sql';
// MySQL host
$mysql_host = 'localhost';
// MySQL username
$mysql_username = 'username';
// MySQL password
$mysql_password = 'password';
// Database name
$mysql_database = 'database';
// Connect to MySQL server
$con = @new mysqli($mysql_host,$mysql_username,$mysql_password,$mysql_database);
// Check connection
if ($con->connect_errno) {
   echo "Failed to connect to MySQL: " . $con->connect_errno;
   echo "<br/>Error: " . $con->connect_error;
}
// Temporary variable, used to store current query
$templine = '';
// Read in entire file
$lines = file($filename);
// Loop through each line
foreach ($lines as $line) {
// Skip it if it's a comment
if (substr($line, 0, 2) == '--' || $line == '')
    continue;
// Add this line to the current segment
$templine .= $line;
// If it has a semicolon at the end, it's the end of the query
if (substr(trim($line), -1, 1) == ';') {
// Perform the query
$con->query($templine) or print('Error performing query \'<strong>' . $templine . '\': ' . $con->error() . '<br /><br />');
    // Reset temp variable to empty
    $templine = '';
}
}
echo "Tables imported successfully";
$con->close($con);

Android - java.lang.SecurityException: Permission Denial: starting Intent

If you are trying to test your app coded in android studio through your android phone, its generally the issue of your phone. Just uncheck all the USB debugging options and toggle the developer options to OFF. Then restart your phone and switch the developer and USB debugging on. You are ready to go!

How to break a while loop from an if condition inside the while loop?

while(something.hasnext())
do something...
   if(contains something to process){
      do something...
      break;
   }
}

Just use the break statement;

For eg:this just prints "Breaking..."

while (true) {
     if (true) {
         System.out.println("Breaking...");
         break;
     }
     System.out.println("Did this print?");
}

C# switch statement limitations - why?

Judah's answer above gave me an idea. You can "fake" the OP's switch behavior above using a Dictionary<Type, Func<T>:

Dictionary<Type, Func<object, string,  string>> typeTable = new Dictionary<Type, Func<object, string, string>>();
typeTable.Add(typeof(int), (o, s) =>
                    {
                        return string.Format("{0}: {1}", s, o.ToString());
                    });

This allows you to associate behavior with a type in the same style as the switch statement. I believe it has the added benefit of being keyed instead of a switch-style jump table when compiled to IL.

Logging POST data from $request_body

The solution below was the best format I found.

log_format postdata escape=json '$remote_addr - $remote_user [$time_local] '
                       '"$request" $status $bytes_sent '
                       '"$http_referer" "$http_user_agent" "$request_body"';
server {
        listen 80;

        server_name api.some.com;

        location / {
         access_log  /var/log/nginx/postdata.log  postdata;
         proxy_pass      http://127.0.0.1:8080;
        }

}

For this input

curl -d '{"key1":"value1", "key2":"value2"}' -H "Content-Type: application/json" -X POST http://api.deprod.com/postEndpoint

Generate that great result

201.23.89.149 -  [22/Aug/2019:15:58:40 +0000] "POST /postEndpoint HTTP/1.1" 200 265 "" "curl/7.64.0" "{\"key1\":\"value1\", \"key2\":\"value2\"}"

Is it possible to compile a program written in Python?

python compile on the fly when you run it.

Run a .py file by(linux): python abc.py

How can I change default dialog button text color in android 5

Using styles.xml (value)

Very Easy solution , change colorPrimary as your choice and it will change color of button text of alert box.

<style name="MyAlertDialogStyle" parent="android:Theme.Material.Dialog.Alert">


        <!-- Used for the buttons -->
        <item name="colorAccent">@android:color/white</item>
        <!-- Used for the title and text -->
        <item name="android:textColorPrimary">@color/black</item>

        <!-- Used for the background -->
        <item name="android:background">#ffffff</item>
        <item name="android:colorPrimary">@color/white</item>
        <item name="android:colorAccent">@color/white</item>
        <item name="android:windowEnterAnimation">@anim/bottom_left_enter</item>
    </style>

Alternative (Using Java)

 @SuppressLint("ResourceAsColor")
            public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {

                AlertDialog dialog = new AlertDialog.Builder(view.getContext(), R.style.MyAlertDialogStyle)

                        .setTitle("Royal Frolics")
                        .setIcon(R.mipmap.ic_launcher)
                        .setMessage(message)
                        .setPositiveButton("OK", (dialog1, which) -> {
                            //do nothing
                            result.confirm();
                        }).create();

                Objects.requireNonNull(dialog.getWindow()).getAttributes().windowAnimations = R.style.MyAlertDialogStyle;
                dialog.show();
                
                dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(R.color.white);
                return true;

            }

How to change Vagrant 'default' machine name?

I found the multiple options confusing, so I decided to test all of them to see exactly what they do.

I'm using VirtualBox 4.2.16-r86992 and Vagrant 1.3.3.

I created a directory called nametest and ran

vagrant init precise64 http://files.vagrantup.com/precise64.box

to generate a default Vagrantfile. Then I opened the VirtualBox GUI so I could see what names the boxes I create would show up as.

  1. Default Vagrantfile

    Vagrant.configure('2') do |config|
        config.vm.box = "precise64"
        config.vm.box_url = "http://files.vagrantup.com/precise64.box"
    end
    

    VirtualBox GUI Name: "nametest_default_1386347922"

    Comments: The name defaults to the format DIRECTORY_default_TIMESTAMP.

  2. Define VM

    Vagrant.configure('2') do |config|
        config.vm.box = "precise64"
        config.vm.box_url = "http://files.vagrantup.com/precise64.box"
        config.vm.define "foohost"
    end
    

    VirtualBox GUI Name: "nametest_foohost_1386347922"

    Comments: If you explicitly define a VM, the name used replaces the token 'default'. This is the name vagrant outputs on the console. Simplifying based on zook's (commenter) input

  3. Set Provider Name

    Vagrant.configure('2') do |config|
        config.vm.box = "precise64"
        config.vm.box_url = "http://files.vagrantup.com/precise64.box"
        config.vm.provider :virtualbox do |vb|
            vb.name = "foohost"
        end
    end
    

    VirtualBox GUI Name: "foohost"

    Comments: If you set the name attribute in a provider configuration block, that name will become the entire name displayed in the VirtualBox GUI.

    Combined Example: Define VM -and- Set Provider Name

    Vagrant.configure('2') do |config|
        config.vm.box = "precise64"
        config.vm.box_url = "http://files.vagrantup.com/precise64.box"
        config.vm.define "foohost"
        config.vm.provider :virtualbox do |vb|
            vb.name = "barhost"
        end
    end
    

    VirtualBox GUI Name: "barhost"

    Comments: If you use both methods at the same time, the value assigned to name in the provider configuration block wins. Simplifying based on zook's (commenter) input

  4. Set hostname (BONUS)

    Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
      config.vm.hostname = "buzbar"
    end
    

    Comments: This sets the hostname inside the VM. This would be the output of hostname command in the VM and also this is what's visible in the prompt like vagrant@<hostname>, here it will look like vagrant@buzbar

Final Code

    Vagrant.configure('2') do |config|
        config.vm.box = "precise64"
        config.vm.box_url = "http://files.vagrantup.com/precise64.box"
        config.vm.hostname = "buzbar"
        config.vm.define "foohost"
        config.vm.provider :virtualbox do |vb|
            vb.name = "barhost"
        end
    end

So there it is. You now know 3 different options you can set and the effects they have. I guess it's a matter of preference at this point? (I'm new to Vagrant, so I can't speak to best practices yet.)

How to increment datetime by custom months in python without using library

Well with some tweaks and use of timedelta here we go:

from datetime import datetime, timedelta


def inc_date(origin_date):
    day = origin_date.day
    month = origin_date.month
    year = origin_date.year
    if origin_date.month == 12:
        delta = datetime(year + 1, 1, day) - origin_date
    else:
        delta = datetime(year, month + 1, day) - origin_date
    return origin_date + delta

final_date = inc_date(datetime.today())
print final_date.date()

add title attribute from css

It is possible to imitate this with HTML & CSS

If you really really want dynamically applied tooltips to work, this (not so performance and architecture friendly) solution can allow you to use browser rendered tooltips without resorting to JS. I can imagine situations where this would be better than JS.

If you have a fixed subset of title attribute values, then you can generate additional elements server-side and let the browser read title from another element positioned above the original one using CSS.

Example:

_x000D_
_x000D_
div{_x000D_
  position: relative;_x000D_
}_x000D_
div > span{_x000D_
  display: none;_x000D_
}_x000D_
_x000D_
.pick-tooltip-1 > .tooltip-1, .pick-tooltip-2 > .tooltip-2{_x000D_
  display: block;_x000D_
  position: absolute;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
}
_x000D_
<div class="pick-tooltip-1">_x000D_
  Hover to see first tooltip_x000D_
  <span class="tooltip-1" title="Tooltip 1"></span>_x000D_
  <span class="tooltip-2" title="Tooltip 2"></span>_x000D_
</div>_x000D_
_x000D_
<div class="pick-tooltip-2">_x000D_
  Hover to see second tooltip_x000D_
  <span class="tooltip-1" title="Tooltip 1"></span>_x000D_
  <span class="tooltip-2" title="Tooltip 2"></span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Note: It's not recommended for large scale applications because of unnecessary HTML, possible content repetitions and the fact that your extra elements for tooltip would steal mouse events (text selection, etc)

How to initialize all members of an array to the same value?

You can do the whole static initializer thing as detailed above, but it can be a real bummer when your array size changes (when your array embiggens, if you don't add the appropriate extra initializers you get garbage).

memset gives you a runtime hit for doing the work, but no code size hit done right is immune to array size changes. I would use this solution in nearly all cases when the array was larger than, say, a few dozen elements.

If it was really important that the array was statically declared, I'd write a program to write the program for me and make it part of the build process.

Get month name from number

For arbitaray range of month numbers

month_integer=range(0,100)
map(lambda x: calendar.month_name[x%12+start],month_integer)

will yield correct list. Adjust start-parameter from where January begins in the month-integer list.

How to alter SQL in "Edit Top 200 Rows" in SSMS 2008

You can also change the pop-up options themselves, to be more convenient for your normal use. Summary:

  1. Run the SQL Management Studio Express 2008
  2. Click the Tools -> Options
  3. Select SQL Server Object Explorer . Now you should be able to see the options

    • Value for Edit Top Rows Command
    • Value for Select Top Rows Command
  4. Give the Values 0 here to select/ Edit all the Records

Full Instructions with screenshots are here: http://m-elshazly.blogspot.com/2011/01/sql-server-2008-change-edit-top-200.html

Including jars in classpath on commandline (javac or apt)

In windows:

java -cp C:/.../jardir1/*;C:/.../jardir2/* class_with_main_method

make sure that the class with the main function is in one of the included jars

How do I reverse an int array in Java?

int[] arrTwo = {5, 8, 18, 6, 20, 50, 6};

    for (int i = arrTwo.length-1; i > 0; i--)
    {
        System.out.print(arrTwo[i] + " ");
    }

Error HRESULT E_FAIL has been returned from a call to a COM component VS2012 when debugging

  1. Add on development initiated on x86 architecture or 64 bit system then it will run on 32bit system also.
  2. but if you Add on development initiated on 32 bit system and then you want to do changes on source code in 64 bit Note: if you are connected SAP Licence on server system then set the port and set server name through service manager otherwise System will give error:

Connection Context :- Retrieving the COM class factory for component with CLSID {632F4591-AA62-4219-8FB6-22BCF5F60090} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).

Change Default branch in gitlab

See also GitLab 13.6 (November 2020)

Customize the initial branch name for new projects within a group

When creating a new Git repository, the first branch created is named master by default.

In coordination with the Git project, broader community, and other Git vendors, GitLab has been listening to the development community’s feedback on determining a more descriptive and inclusive name for the default branch, and is now offering users options to change the name of the default branch name for their repositories.

Previously, we shipped the ability to customize the initial branch name at the instance-level and as part of 13.6, GitLab now allows group administrators to configure the default branch name for new repositories created through the GitLab interface.

See Documentation and Issue.

https://gitlab.com/gitlab-org/gitlab/uploads/2959ef65431bf4ffac659992360d6d8d/image.png


GitLab 13.9 (Feb 2021) details:

Git default branch name change

Every Git repository has an initial branch. It’s the first branch to be created automatically when you create a new repository.
By default, this initial branch is named master.

Git version 2.31.0 (scheduled for release March 15, 2021) will change the default branch name in Git from master to main.

In coordination with the Git project and the broader community, GitLab will be changing the default branch name for new projects on both our SaaS (GitLab.com) and self-managed offerings starting with GitLab 14.0.
This will not affect existing projects.

For more information, see the related epic and the Git mailing list discussion.

Deprecation date: Apr 22, 2021

Outputting data from unit test in Python

The method I use is really simple. I just log it as a warning so it will actually show up.

import logging

class TestBar(unittest.TestCase):
    def runTest(self):

       #this line is important
       logging.basicConfig()
       log = logging.getLogger("LOG")

       for t1, t2 in testdata:
         f = Foo(t1)
         self.assertEqual(f.bar(t2), 2)
         log.warning(t1)

Setting Inheritance and Propagation flags with set-acl and powershell

Here's the MSDN page describing the flags and what is the result of their various combinations.

Flag combinations => Propagation results
=========================================
No Flags => Target folder.
ObjectInherit => Target folder, child object (file), grandchild object (file).
ObjectInherit and NoPropagateInherit => Target folder, child object (file).
ObjectInherit and InheritOnly => Child object (file), grandchild object (file).
ObjectInherit, InheritOnly, and NoPropagateInherit => Child object (file).
ContainerInherit => Target folder, child folder, grandchild folder.
ContainerInherit, and NoPropagateInherit => Target folder, child folder.
ContainerInherit, and InheritOnly => Child folder, grandchild folder.
ContainerInherit, InheritOnly, and NoPropagateInherit => Child folder.
ContainerInherit, and ObjectInherit => Target folder, child folder, child object (file), grandchild folder, grandchild object (file).
ContainerInherit, ObjectInherit, and NoPropagateInherit => Target folder, child folder, child object (file).
ContainerInherit, ObjectInherit, and InheritOnly => Child folder, child object (file), grandchild folder, grandchild object (file).
ContainerInherit, ObjectInherit, NoPropagateInherit, InheritOnly => Child folder, child object (file).

To have it apply the permissions to the directory, as well as all child directories and files recursively, you'll want to use these flags:

InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit 
PropagationFlags.None

So the specific code change you need to make for your example is:

$PropagationFlag = [System.Security.AccessControl.PropagationFlags]::None

How to define partitioning of DataFrame?

So to start with some kind of answer : ) - You can't

I am not an expert, but as far as I understand DataFrames, they are not equal to rdd and DataFrame has no such thing as Partitioner.

Generally DataFrame's idea is to provide another level of abstraction that handles such problems itself. The queries on DataFrame are translated into logical plan that is further translated to operations on RDDs. The partitioning you suggested will probably be applied automatically or at least should be.

If you don't trust SparkSQL that it will provide some kind of optimal job, you can always transform DataFrame to RDD[Row] as suggested in of the comments.

PHP post_max_size overrides upload_max_filesize

The normal method to send a file upload is POST, thus also post_max_size should be 16 Mb or more.

Incidentally, also memory_limit plays a role. It should be bigger than 16Mb, but since the default value is 128Mb, you won't see this problem. Example php.ini configuration:

post_max_size = 16M
upload_max_filesize = 16M
memory_limit = 128M

Change these value in php.ini if you've access to it, otherwise you can try to change them in an .htaccess file.

php_value upload_max_filesize 16M
php_value post_max_size 16M 

This will work only if the AllowOverride settings permit it. Otherwise, you've to ask to your hosting company.

Send PHP variable to javascript function

Your JavaScript would have to be defined within a PHP-parsed file.

For example, in index.php you could place

<?php
$time = time();
?>
<script>
    document.write(<?php echo $time; ?>);
</script>

Synchronous Requests in Node.js

In 2018, you can program the "usual" style using async and await in Node.js.

Below is an example, that wraps request callback in a promise and then uses await to get the resolved value.

const request = require('request');

// wrap a request in an promise
function downloadPage(url) {
    return new Promise((resolve, reject) => {
        request(url, (error, response, body) => {
            if (error) reject(error);
            if (response.statusCode != 200) {
                reject('Invalid status code <' + response.statusCode + '>');
            }
            resolve(body);
        });
    });
}

// now to program the "usual" way
// all you need to do is use async functions and await
// for functions returning promises
async function myBackEndLogic() {
    try {
        const html = await downloadPage('https://microsoft.com')
        console.log('SHOULD WORK:');
        console.log(html);

        // try downloading an invalid url
        await downloadPage('http://      .com')
    } catch (error) {
        console.error('ERROR:');
        console.error(error);
    }
}

// run your async function
myBackEndLogic();

Check if a string is a valid Windows directory (folder) path

Call Path.GetFullPath; it will throw exceptions if the path is invalid.

To disallow relative paths (such as Word), call Path.IsPathRooted.

Fetching distinct values on a column using Spark DataFrame

Well to obtain all different values in a Dataframe you can use distinct. As you can see in the documentation that method returns another DataFrame. After that you can create a UDF in order to transform each record.

For example:

val df = sc.parallelize(Array((1, 2), (3, 4), (1, 6))).toDF("age", "salary")

// I obtain all different values. If you show you must see only {1, 3}
val distinctValuesDF = df.select(df("age")).distinct

// Define your udf. In this case I defined a simple function, but they can get complicated.
val myTransformationUDF = udf(value => value / 10)

// Run that transformation "over" your DataFrame
val afterTransformationDF = distinctValuesDF.select(myTransformationUDF(col("age")))

Deleting an element from an array in PHP

  // Our initial array
  $arr = array("blue", "green", "red", "yellow", "green", "orange", "yellow", "indigo", "red");
  print_r($arr);

  // Remove the elements who's values are yellow or red
  $arr = array_diff($arr, array("yellow", "red"));
  print_r($arr);

This is the output from the code above:

Array
(
    [0] => blue
    [1] => green
    [2] => red
    [3] => yellow
    [4] => green
    [5] => orange
    [6] => yellow
    [7] => indigo
    [8] => red
)

Array
(
    [0] => blue
    [1] => green
    [4] => green
    [5] => orange
    [7] => indigo
)

Now, array_values() will reindex a numerical array nicely, but it will remove all key strings from the array and replace them with numbers. If you need to preserve the key names (strings), or reindex the array if all keys are numerical, use array_merge():

$arr = array_merge(array_diff($arr, array("yellow", "red")));
print_r($arr);

Outputs

Array
(
    [0] => blue
    [1] => green
    [2] => green
    [3] => orange
    [4] => indigo
)

How to break out of jQuery each Loop

"each" uses callback function. Callback function execute irrespective of the calling function,so it is not possible to return to calling function from callback function.

use for loop if you have to stop the loop execution based on some condition and remain in to the same function.

How to check syslog in Bash on Linux?

If you like Vim, it has built-in syntax highlighting for the syslog file, e.g. it will highlight error messages in red.

vi +'syntax on' /var/log/syslog

Compress images on client side before uploading

You might be able to resize the image with canvas and export it using dataURI. Not sure about compression, though.

Take a look at this: Resizing an image in an HTML5 canvas

How to catch a click event on a button?

Taken from: http://developer.android.com/guide/topics/ui/ui-events.html

// Create an anonymous implementation of OnClickListener
private OnClickListener mCorkyListener = new OnClickListener() {
    public void onClick(View v) {
      // do something when the button is clicked
    }
};

protected void onCreate(Bundle savedValues) {
    ...
    // Capture our button from layout
    Button button = (Button)findViewById(R.id.corky);
    // Register the onClick listener with the implementation above
    button.setOnClickListener(mCorkyListener);
    ...
}

How to maximize a plt.show() window using Python

This makes the window take up the full screen for me, under Ubuntu 12.04 with the TkAgg backend:

    mng = plt.get_current_fig_manager()
    mng.resize(*mng.window.maxsize())

Python coding standards/best practices

Yes, I try to follow it as closely as possible.

I don't follow any other coding standards.

Change bar plot colour in geom_bar with ggplot2 in r

If you want all the bars to get the same color (fill), you can easily add it inside geom_bar.

ggplot(data=df, aes(x=c1+c2/2, y=c3)) + 
geom_bar(stat="identity", width=c2, fill = "#FF6666")

enter image description here

Add fill = the_name_of_your_var inside aes to change the colors depending of the variable :

c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2)

enter image description here

Use scale_fill_manual() if you want to manually the change of colors.

ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2) + 
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))

enter image description here

Call a REST API in PHP

You can use file_get_contents to issue any http POST/PUT/DELETE/OPTIONS/HEAD methods, in addition to the GET method as the function name suggests.

How to post data in PHP using file_get_contents?

endsWith in JavaScript

Its been many years for this question. Let me add an important update for the users who wants to use the most voted chakrit's answer.

'endsWith' functions is already added to JavaScript as part of ECMAScript 6 (experimental technology)

Refer it here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith

Hence it is highly recommended to add check for the existence of native implementation as mentioned in the answer.

Display fullscreen mode on Tkinter

I think if you are looking for fullscreen only, no need to set geometry or maxsize etc.

You just need to do this:

-If you are working on ubuntu:

root=tk.Tk()
root.attributes('-zoomed', True)

-and if you are working on windows:

root.state('zoomed')

Now for toggling between fullscreen, for minimising it to taskbar you can use:

Root.iconify()

How do I make a https post in Node Js without any third party module?

For example, like this:

const querystring = require('querystring');
const https = require('https');

var postData = querystring.stringify({
    'msg' : 'Hello World!'
});

var options = {
  hostname: 'posttestserver.com',
  port: 443,
  path: '/post.php',
  method: 'POST',
  headers: {
       'Content-Type': 'application/x-www-form-urlencoded',
       'Content-Length': postData.length
     }
};

var req = https.request(options, (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (d) => {
    process.stdout.write(d);
  });
});

req.on('error', (e) => {
  console.error(e);
});

req.write(postData);
req.end();

Absolute vs relative URLs

If it is for use within your website, it's better practice to use relative URL, like this if you need to move the website to another domain name or just debug locally, you can.

Take a look at what's stackoverflow is doing (ctrl+U in firefox):

<a href="/users/recent/90691"> // Link to an internal element

In some cases they use absolute urls :

<link rel="stylesheet" href="http://sstatic.net/so/all.css?v=5934">

... but this is only it's a best practice to improve speed. In your case, it doesn't look like you're doing anything like that so I wouldn't worry about it.

How can I show a hidden div when a select option is selected?

Check this code. It awesome code for hide div using select item.

HTML

<select name="name" id="cboOptions" onchange="showDiv('div',this)" class="form-control" >
    <option value="1">YES</option>
    <option value="2">NO</option>
</select>

<div id="div1" style="display:block;">
    <input type="text" id="customerName" class="form-control" placeholder="Type Customer Name...">
    <input type="text" style="margin-top: 3px;" id="customerAddress" class="form-control" placeholder="Type Customer Address...">
    <input type="text" style="margin-top: 3px;" id="customerMobile" class="form-control" placeholder="Type Customer Mobile...">
</div>
<div id="div2" style="display:none;">
    <input type="text" list="cars" id="customerID" class="form-control" placeholder="Type Customer Name...">
    <datalist id="cars">
        <option>Value 1</option>
        <option>Value 2</option>
        <option>Value 3</option>
        <option>Value 4</option>
    </datalist>
</div>

JS

<script>
    function showDiv(prefix,chooser) 
    {
            for(var i=0;i<chooser.options.length;i++) 
            {
                var div = document.getElementById(prefix+chooser.options[i].value);
                div.style.display = 'none';
            }

            var selectedOption = (chooser.options[chooser.selectedIndex].value);

            if(selectedOption == "1")
            {
                displayDiv(prefix,"1");
            }
            if(selectedOption == "2")
            {
                displayDiv(prefix,"2");
            }
    }

    function displayDiv(prefix,suffix) 
    {
            var div = document.getElementById(prefix+suffix);
            div.style.display = 'block';
    }
</script>

Get last n lines of a file, similar to tail

Here is a pretty simple implementation:

with open('/etc/passwd', 'r') as f:
  try:
    f.seek(0,2)
    s = ''
    while s.count('\n') < 11:
      cur = f.tell()
      f.seek((cur - 10))
      s = f.read(10) + s
      f.seek((cur - 10))
    print s
  except Exception as e:
    f.readlines()

Installing PHP Zip Extension

You may have several php.ini files, one for CLI and one for apache. Run php --ini to see where the CLI ini location is.

Short circuit Array.forEach like calling break

If you don't need to access your array after iteration you can bail out by setting the array's length to 0. If you do still need it after your iteration you could clone it using slice..

[1,3,4,5,6,7,8,244,3,5,2].forEach(function (item, index, arr) {
  if (index === 3) arr.length = 0;
});

Or with a clone:

var x = [1,3,4,5,6,7,8,244,3,5,2];

x.slice().forEach(function (item, index, arr) {
  if (index === 3) arr.length = 0;
});

Which is a far better solution then throwing random errors in your code.

How to convert ISO8859-15 to UTF8?

in my case, the file command tells a wrong encoding, so i tried converting with all the possible encodings, and found out the right one.

execute this script and check the result file.

for i in `iconv -l`
do
   echo $i
   iconv -f $i -t UTF-8 yourfile | grep "hint to tell converted success or not"
done &>/tmp/converted

Dynamically create Bootstrap alerts box through JavaScript

function bootstrap_alert() {
        create = function (message, color) {
            $('#alert_placeholder')
                .html('<div class="alert alert-' + color
                    + '" role="alert"><a class="close" data-dismiss="alert">×</a><span>' + message
                    + '</span></div>');
        };
        warning = function (message) {
            create(message, "warning");
        };
        info = function (message) {
            create(message, "info");
        };
        light = function (message) {
            create(message, "light");
        };
        transparent = function (message) {
            create(message, "transparent");
        };
        return {
            warning: warning,
            info: info,
            light: light,
            transparent: transparent
        };
    }

C# refresh DataGridView when updating or inserted on another form

Create a small function and use it anywhere

public SqlConnection con = "Your connection string"; 
public void gridviewUpdate()
{
    con.Open();
    string select = "SELECT * from table_name";
    SqlDataAdapter da = new SqlDataAdapter(select, con);
    DataSet ds = new DataSet();
    da.Fill(ds, "table_name");
    datagridview.DataSource = ds;
    datagridview.DataMember = "table_name";
    con.Close();
}

In STL maps, is it better to use map::insert than []?

The two have different semantics when it comes to the key already existing in the map. So they aren't really directly comparable.

But the operator[] version requires default constructing the value, and then assigning, so if this is more expensive then copy construction, then it will be more expensive. Sometimes default construction doesn't make sense, and then it would be impossible to use the operator[] version.

tar: Error is not recoverable: exiting now

The problem is that you do not have bzip2 installed. The tar program relies upon this external program to do compression. For installing bzip2, it depends on the system you are using. For example, with Ubuntu that would be on Ubuntu

sudo apt-get install bzip2

The GNU tar program does not know how to compress an existing file such as user-logs.tar (bzip2 does that). The tar program can use external compression programs gzip, bzip2, xz by opening a pipe to those programs, sending a tar archive via the pipe to the compression utility, which compresses the data which it reads from tar and writes the result to the filename which the tar program specifies.

Alternatively, the tar and compression utility could be the same program. BSD tar does its compression using lib archive (they're not really distinct except in name).

Check orientation on Android phone

Some time has passed since most of these answers have been posted and some use now deprecated methods and constants.

I've updated Jarek's code to not use these methods and constants anymore:

protected int getScreenOrientation()
{
    Display getOrient = getWindowManager().getDefaultDisplay();
    Point size = new Point();

    getOrient.getSize(size);

    int orientation;
    if (size.x < size.y)
    {
        orientation = Configuration.ORIENTATION_PORTRAIT;
    }
    else
    {
        orientation = Configuration.ORIENTATION_LANDSCAPE;
    }
    return orientation;
}

Note that the mode Configuration.ORIENTATION_SQUARE isn't supported anymore.

I found this to be reliable on all devices I've tested it on in contrast to the method suggesting the usage of getResources().getConfiguration().orientation

Change the color of cells in one column when they don't match cells in another column

you could try this:

I have these two columns (column "A" and column "B"). I want to color them when the values between cells in the same row mismatch.

Follow these steps:

  1. Select the elements in column "A" (excluding A1);

  2. Click on "Conditional formatting -> New Rule -> Use a formula to determine which cells to format";

  3. Insert the following formula: =IF(A2<>B2;1;0);

  4. Select the format options and click "OK";

  5. Select the elements in column "B" (excluding B1) and repeat the steps from 2 to 4.

Composer: The requested PHP extension ext-intl * is missing from your system

To enable intl extension follow the instructions below.

You need enable extension by uncommenting the following line extension=php_intl.dll in the C:\xampp\php\php.ini file. Once you uncomment the extension=php_intl.dll, then you must restart apache server using XAMPP control panel.

//about line 998
;extension=php_intl.dll 
change as
extension=php_intl.dll

(Note: php.ini file mostly in the following directory C:\xampp\php)

Restart xampp

How do I display image in Alert/confirm box in Javascript?

I created a function that might help. All it does is imitate the alert but put an image instead of text.

function alertImage(imgsrc) {
$('.d').css({
    'position': 'absolute',
    'top': '0',
    'left': '50%',
    '-webkit-transform': 'translate(-50%, 0)'
});
$('.d').animate({
    opacity: 0
}, 0)
$('.d').animate({
    opacity: 1,
    top: "10px"
}, 250)
$('.d').append('An embedded page on this page says')
$('.d').append('<br><img src="' + imgsrc + '">')
$('.b').css({
  'position':'absolute',
  '-webkit-transform': 'translate(-100%, -100%)',
  'top':'100%',
  'left':'100%',
  'display':'inline',
  'background-color':'#598cbd',
  'border-radius':'4px',
  'color':'white',
  'border':'none',
  'width':'66',
  'height':'33'
})
}
<script type="text/javascript" src="https://code.jquery.com/jquery-latest.min.js"></script>
<div class="d"><button onclick="$('.d').html('')" class="b">OK</button></div>
.d{
font-size: 17px;
  font-family: sans-serif;
}
.b{
  display: none;
}

How can I find all of the distinct file extensions in a folder hierarchy?

Adding my own variation to the mix. I think it's the simplest of the lot and can be useful when efficiency is not a big concern.

find . -type f | grep -o -E '\.[^\.]+$' | sort -u

What does it mean when MySQL is in the state "Sending data"?

In this state:

The thread is reading and processing rows for a SELECT statement, and sending data to the client.

Because operations occurring during this this state tend to perform large amounts of disk access (reads).

That's why it takes more time to complete and so is the longest-running state over the lifetime of a given query.

Search and replace a particular string in a file using Perl

You could also do this:

#!/usr/bin/perl

use strict;
use warnings;

$^I = '.bak'; # create a backup copy 

while (<>) {
   s/<PREF>/ABCD/g; # do the replacement
   print; # print to the modified file
}

Invoke the script with by

./script.pl input_file

You will get a file named input_file, containing your changes, and a file named input_file.bak, which is simply a copy of the original file.

XOR operation with two strings in java

Note: this only works for low characters i.e. below 0x8000, This works for all ASCII characters.

I would do an XOR each charAt() to create a new String. Like

String s, key;

StringBuilder sb = new StringBuilder();
for(int i = 0; i < s.length(); i++)
    sb.append((char)(s.charAt(i) ^ key.charAt(i % key.length())));
String result = sb.toString();

In response to @user467257's comment

If your input/output is utf-8 and you xor "a" and "æ", you are left with an invalid utf-8 string consisting of one character (decimal 135, a continuation character).

It is the char values which are being xor'ed, but the byte values and this produces a character whichc an be UTF-8 encoded.

public static void main(String... args) throws UnsupportedEncodingException {
    char ch1 = 'a';
    char ch2 = 'æ';
    char ch3 = (char) (ch1 ^ ch2);
    System.out.println((int) ch3 + " UTF-8 encoded is " + Arrays.toString(String.valueOf(ch3).getBytes("UTF-8")));
}

prints

135 UTF-8 encoded is [-62, -121]

Does `anaconda` create a separate PYTHONPATH variable for each new environment?

Anaconda does not use the PYTHONPATH. One should however note that if the PYTHONPATH is set it could be used to load a library that is not in the anaconda environment. That is why before activating an environment it might be good to do a

unset PYTHONPATH

For instance this PYTHONPATH points to an incorrect pandas lib:

export PYTHONPATH=/home/john/share/usr/anaconda/lib/python
source activate anaconda-2.7
python
>>>> import pandas as pd
/home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/hashtable.so: undefined symbol: PyUnicodeUCS2_DecodeUTF8
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/__init__.py", line 6, in <module>
    from . import hashtable, tslib, lib
ImportError: /home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/hashtable.so: undefined symbol: PyUnicodeUCS2_DecodeUTF8

unsetting the PYTHONPATH prevents the wrong pandas lib from being loaded:

unset PYTHONPATH
source activate anaconda-2.7
python
>>>> import pandas as pd
>>>>

How to downgrade to older version of Gradle

got it resolved:

uninstall the entire android studio

uninstalling android with the following commands

rm -Rf /Applications/Android\ Studio.app  
rm -Rf ~/Library/Preferences/AndroidStudio*  
rm -Rf ~/Library/Preferences/com.google.android.*  
rm -Rf ~/Library/Preferences/com.android.*  
rm -Rf ~/Library/Application\ Support/AndroidStudio*  
rm -Rf ~/Library/Logs/AndroidStudio*  
rm -Rf ~/Library/Caches/AndroidStudio*  
rm -Rf ~/.AndroidStudio*  
rm -Rf ~/.gradle  
rm -Rf ~/.android  
rm -Rf ~/Library/Android*  
rm -Rf /usr/local/var/lib/android-sdk/  
rm -Rf /Users/<username>/.tooling/gradle

Remove your project and clone it again and then goto Gradle Scripts and open gradle-wrapper.properties and change the below url which ever version you need

distributionUrl=https\://services.gradle.org/distributions/gradle-4.2-all.zip

how to make a jquery "$.post" request synchronous

From the Jquery docs: you specify the async option to be false to get a synchronous Ajax request. Then your callback can set some data before your mother function proceeds.

Here's what your code would look like if changed as suggested:

beforecreate: function(node,targetNode,type,to) {
    jQuery.ajax({
         url:    url,
         success: function(result) {
                      if(result.isOk == false)
                          alert(result.message);
                  },
         async:   false
    });          
}

this is because $.ajax is the only request type that you can set the asynchronousity for

How to get current working directory using vba?

It would seem likely that the ActiveWorkbook has not been saved...

Try CurDir() instead.

Reload a DIV without reloading the whole page

Your code works, but the fadeIn doesn't, because it's already visible. I think the effect you want to achieve is: fadeOutloadfadeIn:

var auto_refresh = setInterval(function () {
    $('.View').fadeOut('slow', function() {
        $(this).load('/echo/json/', function() {
            $(this).fadeIn('slow');
        });
    });
}, 15000); // refresh every 15000 milliseconds

Try it here: http://jsfiddle.net/kelunik/3qfNn/1/

Additional notice: As Khanh TO mentioned, you may need to get rid of the browser's internal cache. You can do so using $.ajax and $.ajaxSetup ({ cache: false }); or the random-hack, he mentioned.

How to reverse a 'rails generate'

Suppose I have created a controller named "sample" like:

rails generate controller sample

If I have to destroy this controller, all I have to do is swap generate with destroy, as in

rails destroy controller sample.

If you want to reverse the generation, all you have to do is swap generate with destroy.

UIButton: set image for selected-highlighted state

If you have a good reason to do that, this will do the trick

add these targets:

[button addTarget:self action:@selector(buttonTouchDown:) forControlEvents:UIControlEventTouchDown];
[button addTarget:self action:@selector(buttonTouchUp:) forControlEvents:UIControlEventTouchUpInside];


-(void)buttonTouchDown:(id)sender{
    UIButton *button=(UIButton *)sender;
    if(button.selected){
        [button setImage:[UIImage imageNamed:@"pressed.png"] forState:UIControlStateNormal];
    }
}

-(void)buttonTouchUp:(id)sender{
    UIButton *button=(UIButton *)sender;
    [button setImage:[UIImage imageNamed:@"normal.png"] forState:UIControlStateNormal];
}

Is there a way to include commas in CSV columns without breaking the formatting?

The problem with the CSV format, is there's not one spec, there are several accepted methods, with no way of distinguishing which should be used (for generate/interpret). I discussed all the methods to escape characters (newlines in that case, but same basic premise) in another post. Basically it comes down to using a CSV generation/escaping process for the intended users, and hoping the rest don't mind.

Reference spec document.

Trigger change event <select> using jquery

$('#edit_user_details').find('select').trigger('change');

It would change the select html tag drop-down item with id="edit_user_details".

Simple function to sort an array of objects

var people = 
[{"name": 'a75',"item1": "false","item2":"false"}, 
{"name": 'z32',"item1": "true","item2":  "false"}, 
{"name": 'e77',"item1": "false","item2": "false"}]; 

function mycomparator(a,b) {   return parseInt(a.name) - parseInt(b.name);  } 
people.sort(mycomparator); 

something along the lines of this maybe (or as we used to say, this should work).

Unicode (UTF-8) reading and writing to files in Python

Now all you need in Python3 is open(Filename, 'r', encoding='utf-8')

[Edit on 2016-02-10 for requested clarification]

Python3 added the encoding parameter to its open function. The following information about the open function is gathered from here: https://docs.python.org/3/library/functions.html#open

open(file, mode='r', buffering=-1, 
      encoding=None, errors=None, newline=None, 
      closefd=True, opener=None)

Encoding is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent (whatever locale.getpreferredencoding() returns), but any text encoding supported by Python can be used. See the codecs module for the list of supported encodings.

So by adding encoding='utf-8' as a parameter to the open function, the file reading and writing is all done as utf8 (which is also now the default encoding of everything done in Python.)

IE Driver download location Link for Selenium

Use the below link to download IE Driver latest version

IE Driver

How to iterate through a String

If you want to use enhanced loop, you can convert the string to charArray

for (char ch : exampleString.toCharArray()) {
  System.out.println(ch);
}

Passing variables, creating instances, self, The mechanics and usage of classes: need explanation

class Foo          (object):
    # ^class name  #^ inherits from object

    bar = "Bar" #Class attribute.

    def __init__(self):
        #        #^ The first variable is the class instance in methods.  
        #        #  This is called "self" by convention, but could be any name you want.
        #^ double underscore (dunder) methods are usually special.  This one 
        #  gets called immediately after a new instance is created.

        self.variable = "Foo" #instance attribute.
        print self.variable, self.bar  #<---self.bar references class attribute
        self.bar = " Bar is now Baz"   #<---self.bar is now an instance attribute
        print self.variable, self.bar  

    def method(self, arg1, arg2):
        #This method has arguments.  You would call it like this:  instance.method(1, 2)
        print "in method (args):", arg1, arg2
        print "in method (attributes):", self.variable, self.bar


a = Foo() # this calls __init__ (indirectly), output:
                 # Foo bar
                 # Foo  Bar is now Baz
print a.variable # Foo
a.variable = "bar"
a.method(1, 2) # output:
               # in method (args): 1 2
               # in method (attributes): bar  Bar is now Baz
Foo.method(a, 1, 2) #<--- Same as a.method(1, 2).  This makes it a little more explicit what the argument "self" actually is.

class Bar(object):
    def __init__(self, arg):
        self.arg = arg
        self.Foo = Foo()

b = Bar(a)
b.arg.variable = "something"
print a.variable # something
print b.Foo.variable # Foo

WebAPI Multiple Put/Post parameters

Nice question and comments - learnt much from the replies here :)

As an additional example, note that you can also mix body and routes e.g.

[RoutePrefix("api/test")]
public class MyProtectedController 
{
    [Authorize]
    [Route("id/{id}")]
    public IEnumerable<object> Post(String id, [FromBody] JObject data)
    {
        /*
          id                                      = "123"
          data.GetValue("username").ToString()    = "user1"
          data.GetValue("password").ToString()    = "pass1"
         */
    }
}

Calling like this:

POST /api/test/id/123 HTTP/1.1
Host: localhost
Accept: application/json
Content-Type: application/x-www-form-urlencoded
Authorization: Bearer x.y.z
Cache-Control: no-cache

username=user1&password=pass1


enter code here

Check if cookie exists else set cookie to Expire in 10 days

You need to read and write document.cookie

if (document.cookie.indexOf("visited=") >= 0) {
  // They've been here before.
  alert("hello again");
}
else {
  // set a new cookie
  expiry = new Date();
  expiry.setTime(expiry.getTime()+(10*60*1000)); // Ten minutes

  // Date()'s toGMTSting() method will format the date correctly for a cookie
  document.cookie = "visited=yes; expires=" + expiry.toGMTString();
  alert("this is your first time");
}

Get current date/time in seconds

 Date.now()

gives milliseconds since epoch. No need to use new.

Check out the reference here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now

(Not supported in IE8.)

Annotation @Transactional. How to rollback?

You can throw an unchecked exception from the method which you wish to roll back. This will be detected by spring and your transaction will be marked as rollback only.

I'm assuming you're using Spring here. And I assume the annotations you refer to in your tests are the spring test based annotations.

The recommended way to indicate to the Spring Framework's transaction infrastructure that a transaction's work is to be rolled back is to throw an Exception from code that is currently executing in the context of a transaction.

and note that:

please note that the Spring Framework's transaction infrastructure code will, by default, only mark a transaction for rollback in the case of runtime, unchecked exceptions; that is, when the thrown exception is an instance or subclass of RuntimeException.

Remove first 4 characters of a string with PHP

You can use this by php function with substr function

<?php
function removeChar($value) {
    $value2 = substr($value, 4); 
    return $value2;
}

echo removeChar("Dummy Text. Sample Text.");
?>

You get this result: " y Text. Sample Text. "