Programs & Examples On #Sqlite

SQLite is a software library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine.

Execute SQLite script

In order to execute simple queries and return to my shell script, I think this works well:

$ sqlite3 example.db 'SELECT * FROM some_table;'

Modify a Column's Type in sqlite3

It is possible by dumping, editing and reimporting the table.

This script will do it for you (Adapt the values at the start of the script to your needs):

#!/bin/bash

DB=/tmp/synapse/homeserver.db
TABLE="public_room_list_stream"
FIELD=visibility
OLD="BOOLEAN NOT NULL"
NEW="INTEGER NOT NULL"
TMP=/tmp/sqlite_$TABLE.sql

echo "### create dump"
echo ".dump '$TABLE'" | sqlite3 "$DB" >$TMP

echo "### editing the create statement"
sed -i "s|$FIELD $OLD|$FIELD $NEW|g" $TMP

read -rsp $'Press any key to continue deleting and recreating the table $TABLE ...\n' -n1 key 

echo "### rename the original to '$TABLE"_backup"'"
sqlite3 "$DB" "PRAGMA busy_timeout=20000; ALTER TABLE '$TABLE' RENAME TO '$TABLE"_backup"'"

echo "### delete the old indexes"
for idx in $(echo "SELECT name FROM sqlite_master WHERE type == 'index' AND tbl_name LIKE '$TABLE""%';" | sqlite3 $DB); do
  echo "DROP INDEX '$idx';" | sqlite3 $DB
done

echo "### reinserting the edited table"
cat $TMP | sqlite3 $DB

getting " (1) no such column: _id10 " error

I think you missed a equal sign at:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);  

Change to:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null); 

Difference between 2 dates in SQLite

This answer is a little long-winded, and the documentation will not tell you this (because they assume you are storing your dates as UTC dates in the database), but the answer to this question depends largely on the timezone that your dates are stored in. You also don't use Date('now'), but use the julianday() function, to calculate both dates back against a common date, then subtract the difference of those results from each other.

If your dates are stored in UTC:

SELECT julianday('now') - julianday(DateCreated) FROM Payment;

This is what the top-ranked answer has, and is also in the documentation. It is only part of the picture, and a very simplistic answer, if you ask me.

If your dates are stored in local time, using the above code will make your answer WRONG by the number of hours your GMT offset is. If you are in the Eastern U.S. like me, which is GMT -5, your result will have 5 hours added onto it. And if you try making DateCreated conform to UTC because julianday('now') goes against a GMT date:

SELECT julianday('now') - julianday(DateCreated, 'utc') FROM Payment;

This has a bug where it will add an hour for a DateCreated that is during Daylight Savings Time (March-November). Say that "now" is at noon on a non-DST day, and you created something back in June (during DST) at noon, your result will give 1 hour apart, instead of 0 hours, for the hours portion. You'd have to write a function in your application's code that is displaying the result to modify the result and subtract an hour from DST dates. I did that, until I realized there's a better solution to that problem that I was having: SQLite vs. Oracle - Calculating date differences - hours

Instead, as was pointed out to me, for dates stored in local time, make both match to local time:

SELECT julianday('now', 'localtime') - julianday(DateCreated) FROM Payment;

Or append 'Z' to local time:

julianday(datetime('now', 'localtime')||'Z') - julianday(CREATED_DATE||'Z')

Both of these seem to compensate and do not add the extra hour for DST dates and do straight subtraction - so that item created at noon on a DST day, when checking at noon on a non-DST day, will not get an extra hour when performing the calculation.

And while I recognize most will say don't store dates in local time in your database, and to store them in UTC so you don't run into this, well not every application has a world-wide audience, and not every programmer wants to go through the conversion of EVERY date in their system to UTC and back again every time they do a GET or SET in the database and deal with figuring out if something is local or in UTC.

Escape single quote character for use in an SQLite query

In bash scripts, I found that escaping double quotes around the value was necessary for values that could be null or contained characters that require escaping (like hyphens).

In this example, columnA's value could be null or contain hyphens.:

sqlite3 $db_name "insert into foo values (\"$columnA\", $columnB)";

Python SQLite: database is locked

The database is locked by another process that is writing to it. You have to wait until the other transaction is committed. See the documentation of connect()

How to concatenate strings with padding in sqlite

Just one more line for @tofutim answer ... if you want custom field name for concatenated row ...

SELECT 
  (
    col1 || '-' || SUBSTR('00' || col2, -2, 2) | '-' || SUBSTR('0000' || col3, -4, 4)
  ) AS my_column 
FROM
  mytable;

Tested on SQLite 3.8.8.3, Thanks!

Convert NSData to String?

Swift 5:

String(data: data!, encoding: String.Encoding.utf8)

SQLite string contains other string query

While LIKE is suitable for this case, a more general purpose solution is to use instr, which doesn't require characters in the search string to be escaped. Note: instr is available starting from Sqlite 3.7.15.

SELECT *
  FROM TABLE  
 WHERE instr(column, 'cats') > 0;

Also, keep in mind that LIKE is case-insensitive, whereas instr is case-sensitive.

Truncate a SQLite table if it exists?

I got it to work with:

SQLiteDatabase db= this.getWritableDatabase();
        db.delete(TABLE_NAME, null, null);

How to set Sqlite3 to be case insensitive when string comparing?

you can use the like query for comparing the respective string with table vales.

select column name from table_name where column name like 'respective comparing value';

How to do IF NOT EXISTS in SQLite

You can also set a Constraint on a Table with the KEY fields and set On Conflict "Ignore"

When an applicable constraint violation occurs, the IGNORE resolution algorithm skips the one row that contains the constraint violation and continues processing subsequent rows of the SQL statement as if nothing went wrong. Other rows before and after the row that contained the constraint violation are inserted or updated normally. No error is returned when the IGNORE conflict resolution algorithm is used.

SQLite Documentation

SQLite Query in Android to count rows

DatabaseUtils.queryNumEntries (since api:11) is useful alternative that negates the need for raw SQL(yay!).

SQLiteDatabase db = getReadableDatabase();
DatabaseUtils.queryNumEntries(db, "users",
                "uname=? AND pwd=?", new String[] {loginname,loginpass});

How do I view the SQLite database on an Android device?

First post (https://stackoverflow.com/a/21151598/4244605) does not working for me.

I wrote own script for get DB file from device. Without root. Working OK.

  1. Copy script to directory with adb (e.g.:~/android-sdk/platform-tools).
  2. Device have to be connected to PC.
  3. Use ./getDB.sh -p <packageName> for get name of databases.

Usage: ./getDB.sh -p <packageName> -n <name of DB> -s <store in mobile device> for get DB file to this (where script is executed) directory.

I recommend you set filename of DB as *.sqlite and open it with Firefox addon: SQLite Manager.

(It's a long time, when i have written something in Bash. You can edit this code.)

#!/bin/sh
# Get DB from Android device.
#

Hoption=false
Poption=false
Noption=false
Soption=false
Parg=""
Narg=""
Sarg=""

#-----------------------FUNCTION--------------------------:
helpFunc(){ #help
echo "Get names of DB's files in your Android app.
Usage: ./getDB -h
       ./getDB -p packageName -n nameOfDB -s storagePath
Options:
   -h                                           Show help.
   -p packageName                               List of databases for package name.
   -p packageName -n nameOfDB -s storagePath    Save DB from device to this directory."
}


#--------------------------MAIN--------------------------:
while getopts 'p:n:s:h' options; do
    case $options in

        p) Poption=true
            Parg=$OPTARG;;

        n) Noption=true
            Narg=$OPTARG;;

        s) Soption=true
            Sarg=$OPTARG;;

        h) Hoption=true;;
    esac
done

#echo "-------------------------------------------------------
#Hoption: $Hoption
#Poption: $Poption
#Noption: $Noption
#Soption: $Soption
#Parg: $Parg
#Narg: $Narg
#Sarg: $Sarg
#-------------------------------------------------------"\\n
#echo $#    #count of params

if [ $Hoption = true ];then
    helpFunc
elif [ $# -eq 2 -a $Poption = true ];then #list
    ./adb -d shell run-as $Parg ls /data/data/$Parg/databases/
    exit 0
elif [ $# -eq 6 -a $Poption = true -a $Noption = true -a $Soption = true ];then #get DB file
    #Change permissions
    ./adb shell run-as $Parg chmod 777 /data/data/$Parg/databases/
    ./adb shell run-as $Parg chmod 777 /data/data/$Parg/databases/$Narg
    #Copy
    ./adb shell cp /data/data/$Parg/databases/$Narg $Sarg
    #Pull file to this machine
    ./adb pull $Sarg/$Narg
    exit 0
else
    echo "Wrong params or arguments. Use -h for help."
    exit 1;
fi

exit 0;

How to insert double and float values to sqlite?

SQL Supports following types of affinities:

  • TEXT
  • NUMERIC
  • INTEGER
  • REAL
  • BLOB

If the declared type for a column contains any of these "REAL", "FLOAT", or "DOUBLE" then the column has 'REAL' affinity.

Insert new column into table in sqlite?

You can add new column with the query

ALTER TABLE TableName ADD COLUMN COLNew CHAR(25)

But it will be added at the end, not in between the existing columns.

How do I add multiple "NOT LIKE '%?%' in the WHERE clause of sqlite3?

SELECT word FROM table WHERE word NOT LIKE '%a%' 
AND word NOT LIKE '%b%' 
AND word NOT LIKE '%c%';

Multiple SQL joins

 SELECT
 B.Title, B.Edition, B.Year, B.Pages, B.Rating     --from Books
, C.Category                                        --from Categories
, P.Publisher                                       --from Publishers
, W.LastName                                        --from Writers

FROM Books B

JOIN Categories_Books CB ON B._ISBN = CB._Books_ISBN
JOIN Categories_Books CB ON CB.__Categories_Category_ID = C._CategoryID
JOIN Publishers P ON B.PublisherID = P._Publisherid
JOIN Writers_Books WB ON B._ISBN = WB._Books_ISBN
JOIN Writers W ON WB._Writers_WriterID = W._WriterID

SQLite DateTime comparison

Below are the methods to compare the dates but before that we need to identify the format of date stored in DB

I have dates stored in MM/DD/YYYY HH:MM format so it has to be compared in that format

  1. Below query compares the convert the date into MM/DD/YYY format and get data from last five days till today. BETWEEN operator will help and you can simply specify start date AND end date.

    select * from myTable where myColumn BETWEEN strftime('%m/%d/%Y %H:%M', datetime('now','localtime'), '-5 day') AND strftime('%m/%d/%Y %H:%M',datetime('now','localtime')); 
    
  2. Below query will use greater than operator (>).

      select * from myTable where myColumn > strftime('%m/%d/%Y %H:%M', datetime('now','localtime'), '-5 day');  

All the computation I have done is using current time, you can change the format and date as per your need.

Hope this will help you

Summved

How to import load a .sql or .csv file into SQLite?

To import from an SQL file use the following:

sqlite> .read <filename>

To import from a CSV file you will need to specify the file type and destination table:

sqlite> .mode csv <table>
sqlite> .import <filename> <table>

How do I add a foreign key to an existing SQLite table?

If you are using the Firefox add-on sqlite-manager you can do the following:

Instead of dropping and creating the table again one can just modify it like this.

In the Columns text box, right click on the last column name listed to bring up the context menu and select Edit Column. Note that if the last column in the TABLE definition is the PRIMARY KEY then it will be necessary to first add a new column and then edit the column type of the new column in order to add the FOREIGN KEY definition. Within the Column Type box , append a comma and the

FOREIGN KEY (parent_id) REFERENCES parent(id)

definition after data type. Click on the Change button and then click the Yes button on the Dangerous Operation dialog box.

Reference: Sqlite Manager

Import CSV to SQLite

before .import command, type ".mode csv"

SQlite - Android - Foreign key syntax

As you can see in the error description your table contains the columns (_id, tast_title, notes, reminder_date_time) and you are trying to add a foreign key from a column "taskCat" but it does not exist in your table!

Is there a .NET/C# wrapper for SQLite?

Here are the ones I can find:

Sources:

How can I select rows by range?

Following your clarification you're looking for limit:

SELECT * FROM `table` LIMIT 0, 10 

This will display the first 10 results from the database.

SELECT * FROM `table` LIMIT 5, 5 .

Will display 5-9 (5,6,7,8,9)

The syntax follows the pattern:

SELECT * FROM `table` LIMIT [row to start at], [how many to include] .

The SQL for selecting rows where a column is between two values is:

SELECT column_name(s)
FROM table_name
WHERE column_name
BETWEEN value1 AND value2

See: http://www.w3schools.com/sql/sql_between.asp

If you want to go on the row number you can use rownum:

SELECT column_name(s)
FROM table_name
WHERE rownum 
BETWEEN x AND y

However we need to know which database engine you are using as rownum is different for most.

How to perform an SQLite query within an Android application?

This will return you the required cursor

Cursor cursor = db.query(TABLE_NAME, new String[] {"_id", "title", "title_raw"}, 
                "title_raw like " + "'%Smith%'", null, null, null, null);

SQLite equivalent to ISNULL(), NVL(), IFNULL() or COALESCE()

Try this

ifnull(X,Y)  

e.g

select ifnull(InfoDetail,'') InfoDetail; -- this will replace null with ''
select ifnull(NULL,'THIS IS NULL');-- More clearly....

The ifnull() function returns a copy of its first non-NULL argument, or NULL if both arguments are NULL. Ifnull() must have exactly 2 arguments. The ifnull() function is equivalent to coalesce() with two arguments.

SQLite - getting number of rows in a database

Extension of VolkerK's answer, to make code a little more readable, you can use AS to reference the count, example below:

SELECT COUNT(*) AS c from profile

This makes for much easier reading in some frameworks, for example, i'm using Exponent's (React Native) Sqlite integration, and without the AS statement, the code is pretty ugly.

sqlite3.OperationalError: unable to open database file

import sqlite3

connection = sqlite3.connect("d:\\pythonAPI\\data.db")
cursor = connection.cursor()
create_table = "CREATE TABLE users (id int, username text, password text)"
cursor.execute(create_table)


for clearer full path if you didn't get it clear

How do I join two SQLite tables in my Android application?

An alternate way is to construct a view which is then queried just like a table. In many database managers using a view can result in better performance.

CREATE VIEW xyz SELECT q.question, a.alternative  
   FROM tbl_question AS q, tbl_alternative AS a
  WHERE q.categoryid = a.categoryid 
    AND q._id = a.questionid;

This is from memory so there may be some syntactic issues. http://www.sqlite.org/lang_createview.html

I mention this approach because then you can use SQLiteQueryBuilder with the view as you implied that it was preferred.

SQLite table constraint - unique on multiple columns

Well, your syntax doesn't match the link you included, which specifies:

 CREATE TABLE name (column defs) 
    CONSTRAINT constraint_name    -- This is new
    UNIQUE (col_name1, col_name2) ON CONFLICT REPLACE

How to insert a SQLite record with a datetime set to 'now' in Android application?

In my code I use DATETIME DEFAULT CURRENT_TIMESTAMP as the type and constraint of the column.

In your case your table definition would be

create table notes (
  _id integer primary key autoincrement, 
  created_date date default CURRENT_DATE
)

Declare variable in SQLite and use it

Herman's solution works, but it can be simplified because Sqlite allows to store any value type on any field.

Here is a simpler version that uses one Value field declared as TEXT to store any value:

CREATE TEMP TABLE IF NOT EXISTS Variables (Name TEXT PRIMARY KEY, Value TEXT);

INSERT OR REPLACE INTO Variables VALUES ('VarStr', 'Val1');
INSERT OR REPLACE INTO Variables VALUES ('VarInt', 123);
INSERT OR REPLACE INTO Variables VALUES ('VarBlob', x'12345678');

SELECT Value
  FROM Variables
 WHERE Name = 'VarStr'
UNION ALL
SELECT Value
  FROM Variables
 WHERE Name = 'VarInt'
UNION ALL
SELECT Value
  FROM Variables
 WHERE Name = 'VarBlob';

SQLite select where empty?

It looks like you can simply do:

SELECT * FROM your_table WHERE some_column IS NULL OR some_column = '';

Test case:

CREATE TABLE your_table (id int, some_column varchar(10));

INSERT INTO your_table VALUES (1, NULL);
INSERT INTO your_table VALUES (2, '');
INSERT INTO your_table VALUES (3, 'test');
INSERT INTO your_table VALUES (4, 'another test');
INSERT INTO your_table VALUES (5, NULL);

Result:

SELECT id FROM your_table WHERE some_column IS NULL OR some_column = '';

id        
----------
1         
2         
5    

INSERT IF NOT EXISTS ELSE UPDATE?

I believe you want UPSERT.

"INSERT OR REPLACE" without the additional trickery in that answer will reset any fields you don't specify to NULL or other default value. (This behavior of INSERT OR REPLACE is unlike UPDATE; it's exactly like INSERT, because it actually is INSERT; however if what you wanted is UPDATE-if-exists you probably want the UPDATE semantics and will be unpleasantly surprised by the actual result.)

The trickery from the suggested UPSERT implementation is basically to use INSERT OR REPLACE, but specify all fields, using embedded SELECT clauses to retrieve the current value for fields you don't want to change.

Attempt to write a readonly database - Django w/ SELinux error

In short, it happens when the application which writes to the sqlite database does not have write permission.

This can be solved in three ways:

  1. Granting ownership of db.sqlite3 file and its parent directory (thereby write access also) to the user using chown (Eg: chown username db.sqlite3 )
  2. Running the webserver (often gunicorn) as root user (run the command sudo -i before you run gunicorn or django runserver)
  3. Allowing read and write access to all users by running command chmod 777 db.sqlite3 (Dangerous option)

Never go for the third option unless you are running the webserver in a local machine or the data in the database is not at all important for you.

Second option is also not recommended. But you can go for it, if you are sure that your application is not vulnerable for code injection attack.

Sqlite primary key on multiple columns

Yes. But remember that such primary key allow NULL values in both columns multiple times.

Create a table as such:

    sqlite> CREATE TABLE something (
column1, column2, value, PRIMARY KEY (column1, column2));

Now this works without any warning:

sqlite> insert into something (value) VALUES ('bla-bla');
sqlite> insert into something (value) VALUES ('bla-bla');
sqlite> select * from something;
NULL|NULL|bla-bla
NULL|NULL|bla-bla

Sqlite convert string to date

convert a string into date little issue think with indexing mmm 3,3 but works added a month on to the date string

SELECT substr('12Jan20',1,2) as dday,
date(substr('12Jan20',6,7) ||'00-' || case substr('12Jan20',3,3) when 'Jan' then '01'
when 'Feb' then '02'
when 'Mar' then '03'
when 'Apr' then '04'
when 'May' then '05' 
when 'Jun' then '06'
when 'Jul' then '07'
when 'Aug' then '08'
when 'Sep' then '09'
when 'Oct' then '10'
when 'Nov' then '11'
when 'Dec' then '12' end  || '-'||substr('12Jan20',1,2), '+1 month') as tt

SQLite "INSERT OR REPLACE INTO" vs. "UPDATE ... WHERE"

I'm currently working on such a statement and figured out another fact to notice: INSERT OR REPLACE will replace any values not supplied in the statement. For instance if your table contains a column "lastname" which you didn't supply a value for, INSERT OR REPLACE will nullify the "lastname" if possible (constraints allow it) or fail.

How do I unlock a SQLite database?

I was having "database is locked" errors in a multi-threaded application as well, which appears to be the SQLITE_BUSY result code, and I solved it with setting sqlite3_busy_timeout to something suitably long like 30000.

(On a side-note, how odd that on a 7 year old question nobody found this out already! SQLite really is a peculiar and amazing project...)

How do I order my SQLITE database in descending order, for an android app?

Cursor c = scoreDb.query(Table_Name, score, null, null, null, null, Column+" DESC");

Try this

How can I get dict from sqlite query?

You could use row_factory, as in the example in the docs:

import sqlite3

def dict_factory(cursor, row):
    d = {}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d

con = sqlite3.connect(":memory:")
con.row_factory = dict_factory
cur = con.cursor()
cur.execute("select 1 as a")
print cur.fetchone()["a"]

or follow the advice that's given right after this example in the docs:

If returning a tuple doesn’t suffice and you want name-based access to columns, you should consider setting row_factory to the highly-optimized sqlite3.Row type. Row provides both index-based and case-insensitive name-based access to columns with almost no memory overhead. It will probably be better than your own custom dictionary-based approach or even a db_row based solution.

How to retrieve inserted id after inserting row in SQLite using Python?

You could use cursor.lastrowid (see "Optional DB API Extensions"):

connection=sqlite3.connect(':memory:')
cursor=connection.cursor()
cursor.execute('''CREATE TABLE foo (id integer primary key autoincrement ,
                                    username varchar(50),
                                    password varchar(50))''')
cursor.execute('INSERT INTO foo (username,password) VALUES (?,?)',
               ('test','test'))
print(cursor.lastrowid)
# 1

If two people are inserting at the same time, as long as they are using different cursors, cursor.lastrowid will return the id for the last row that cursor inserted:

cursor.execute('INSERT INTO foo (username,password) VALUES (?,?)',
               ('blah','blah'))

cursor2=connection.cursor()
cursor2.execute('INSERT INTO foo (username,password) VALUES (?,?)',
               ('blah','blah'))

print(cursor2.lastrowid)        
# 3
print(cursor.lastrowid)
# 2

cursor.execute('INSERT INTO foo (id,username,password) VALUES (?,?,?)',
               (100,'blah','blah'))
print(cursor.lastrowid)
# 100

Note that lastrowid returns None when you insert more than one row at a time with executemany:

cursor.executemany('INSERT INTO foo (username,password) VALUES (?,?)',
               (('baz','bar'),('bing','bop')))
print(cursor.lastrowid)
# None

SQL string value spanning multiple lines in query

SQL Server allows the following (be careful to use single quotes instead of double)

UPDATE User
SET UserId = 12345
   , Name = 'J Doe'
   , Location = 'USA'
   , Bio='my bio
spans 
multiple
lines!'
WHERE UserId = 12345

Android - Pulling SQlite database android device

Using Android Studio 3.0 or later version it is possible to pull database (also shared preference, cache directory and others) if application runs in debug mode on non-rooted device.

To pull database using android studio follow these steps.

  1. Click View > Tool Windows > Device File Explorer.
  2. Expand /data/data/[package-name] nodes.

Steps followed in Android Studio 3.0

how to drop database in sqlite?

If you want to delete database programatically you can use deleteDatabase from Context class:

deleteDatabase(String name)
Delete an existing private SQLiteDatabase associated with this Context's application package.

SQLite add Primary Key

You can do it like this:

CREATE TABLE mytable (
field1 text,
field2 text,
field3 integer,
PRIMARY KEY (field1, field2)
);

How to convert image file data in a byte array to a Bitmap?

The answer of Uttam didnt work for me. I just got null when I do:

Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata, 0, bitmapdata.length);

In my case, bitmapdata only has the buffer of the pixels, so it is imposible for the function decodeByteArray to guess which the width, the height and the color bits use. So I tried this and it worked:

//Create bitmap with width, height, and 4 bytes color (RGBA)    
Bitmap bmp = Bitmap.createBitmap(imageWidth, imageHeight, Bitmap.Config.ARGB_8888);
ByteBuffer buffer = ByteBuffer.wrap(bitmapdata);
bmp.copyPixelsFromBuffer(buffer);

Check https://developer.android.com/reference/android/graphics/Bitmap.Config.html for different color options

SQLite UPSERT / UPDATE OR INSERT

Option 1: Insert -> Update

If you like to avoid both changes()=0 and INSERT OR IGNORE even if you cannot afford deleting the row - You can use this logic;

First, insert (if not exists) and then update by filtering with the unique key.

Example

-- Table structure
CREATE TABLE players (
    id        INTEGER       PRIMARY KEY AUTOINCREMENT,
    user_name VARCHAR (255) NOT NULL
                            UNIQUE,
    age       INTEGER       NOT NULL
);

-- Insert if NOT exists
INSERT INTO players (user_name, age)
SELECT 'johnny', 20
WHERE NOT EXISTS (SELECT 1 FROM players WHERE user_name='johnny' AND age=20);

-- Update (will affect row, only if found)
-- no point to update user_name to 'johnny' since it's unique, and we filter by it as well
UPDATE players 
SET age=20 
WHERE user_name='johnny';

Regarding Triggers

Notice: I haven't tested it to see the which triggers are being called, but I assume the following:

if row does not exists

  • BEFORE INSERT
  • INSERT using INSTEAD OF
  • AFTER INSERT
  • BEFORE UPDATE
  • UPDATE using INSTEAD OF
  • AFTER UPDATE

if row does exists

  • BEFORE UPDATE
  • UPDATE using INSTEAD OF
  • AFTER UPDATE

Option 2: Insert or replace - keep your own ID

in this way you can have a single SQL command

-- Table structure
CREATE TABLE players (
    id        INTEGER       PRIMARY KEY AUTOINCREMENT,
    user_name VARCHAR (255) NOT NULL
                            UNIQUE,
    age       INTEGER       NOT NULL
);

-- Single command to insert or update
INSERT OR REPLACE INTO players 
(id, user_name, age) 
VALUES ((SELECT id from players WHERE user_name='johnny' AND age=20),
        'johnny',
        20);

Edit: added option 2.

SQLite error 'attempt to write a readonly database' during insert?

I got this error when I tried to write to a database on an Android system.

Apparently sqlite3 not only needs write permissions to the database file and the containing directory (as @austin-hyde already said in his answer) but also the environment variable TMPDIR has to point to a (possibly writable) directory.

On my Android system I set it to TMPDIR="/data/local/tmp" and now my script runs as expected :)

Edit:

If you can't set environment variables you can use one of the other methods listed here: https://www.sqlite.org/tempfiles.html#temporary_file_storage_locations like PRAGMA temp_store_directory = 'directory-name';

How do I rename a column in a SQLite database table?

One option, if you need it done in a pinch, and if your initial column was created with a default, is to create the new column you want, copy the contents over to it, and basically "abandon" the old column (it stays present, but you just don't use/update it, etc.)

ex:

alter table TABLE_NAME ADD COLUMN new_column_name TYPE NOT NULL DEFAULT '';
update TABLE_NAME set new_column_name = old_column_name;
update TABLE_NAME set old_column_name = ''; -- abandon old column, basically

This leaves behind a column (and if it was created with NOT NULL but without a default, then future inserts that ignore it might fail), but if it's just a throwaway table, the tradeoffs might be acceptable. Otherwise use one of the other answers mentioned here, or a different database that allows columns to be renamed.

SQLite Reset Primary Key Field

You can reset by update sequence after deleted rows in your-table

UPDATE SQLITE_SEQUENCE SET SEQ=0 WHERE NAME='table_name';

How to have an automatic timestamp in SQLite?

If you use the SQLite DB-Browser you can change the default value in this way:

  1. Choose database structure
  2. select the table
  3. modify table
  4. in your column put under 'default value' the value: =(datetime('now','localtime'))

I recommend to make an update of your database before, because a wrong format in the value can lead to problems in the SQLLite Browser.

OperationalError: database is locked

The practical reason for this is often that the python or django shells have opened a request to the DB and it wasn't closed properly; killing your terminal access often frees it up. I had this error on running command line tests today.

Edit: I get periodic upvotes on this. If you'd like to kill access without rebooting the terminal, then from commandline you can do:

from django import db
db.connections.close_all()

Simple export and import of a SQLite database on Android

I use this code in the SQLiteOpenHelper in one of my applications to import a database file.

EDIT: I pasted my FileUtils.copyFile() method into the question.

SQLiteOpenHelper

public static String DB_FILEPATH = "/data/data/{package_name}/databases/database.db";

/**
 * Copies the database file at the specified location over the current
 * internal application database.
 * */
public boolean importDatabase(String dbPath) throws IOException {

    // Close the SQLiteOpenHelper so it will commit the created empty
    // database to internal storage.
    close();
    File newDb = new File(dbPath);
    File oldDb = new File(DB_FILEPATH);
    if (newDb.exists()) {
        FileUtils.copyFile(new FileInputStream(newDb), new FileOutputStream(oldDb));
        // Access the copied database so SQLiteHelper will cache it and mark
        // it as created.
        getWritableDatabase().close();
        return true;
    }
    return false;
}

FileUtils

public class FileUtils {
    /**
     * Creates the specified <code>toFile</code> as a byte for byte copy of the
     * <code>fromFile</code>. If <code>toFile</code> already exists, then it
     * will be replaced with a copy of <code>fromFile</code>. The name and path
     * of <code>toFile</code> will be that of <code>toFile</code>.<br/>
     * <br/>
     * <i> Note: <code>fromFile</code> and <code>toFile</code> will be closed by
     * this function.</i>
     * 
     * @param fromFile
     *            - FileInputStream for the file to copy from.
     * @param toFile
     *            - FileInputStream for the file to copy to.
     */
    public static void copyFile(FileInputStream fromFile, FileOutputStream toFile) throws IOException {
        FileChannel fromChannel = null;
        FileChannel toChannel = null;
        try {
            fromChannel = fromFile.getChannel();
            toChannel = toFile.getChannel();
            fromChannel.transferTo(0, fromChannel.size(), toChannel);
        } finally {
            try {
                if (fromChannel != null) {
                    fromChannel.close();
                }
            } finally {
                if (toChannel != null) {
                    toChannel.close();
                }
            }
        }
    }
}

Don't forget to delete the old database file if necessary.

Drop all tables command

I'd like to add to other answers involving dropping tables and not deleting the file, that you can also execute delete from sqlite_sequence to reset auto-increment sequences.

Create table in SQLite only if it doesn't exist already

From http://www.sqlite.org/lang_createtable.html:

CREATE TABLE IF NOT EXISTS some_table (id INTEGER PRIMARY KEY AUTOINCREMENT, ...);

How to connect SQLite with Java?

I'm using Eclipse and I copied your code and got the same error. I then opened up the project properties->Java Build Path -> Libraries->Add External JARs... c:\jrun4\lib\sqlitejdbc-v056.jar Worked like a charm. You may need to restart your web server if you've just copied the .jar file.

How to delete all records from table in sqlite with Android?

use Sqlit delete function with last two null parameters.

db.delete(TABLE_NAME,null,null)

"Insert if not exists" statement in SQLite

If you have a table called memos that has two columns id and text you should be able to do like this:

INSERT INTO memos(id,text) 
SELECT 5, 'text to insert' 
WHERE NOT EXISTS(SELECT 1 FROM memos WHERE id = 5 AND text = 'text to insert');

If a record already contains a row where text is equal to 'text to insert' and id is equal to 5, then the insert operation will be ignored.

I don't know if this will work for your particular query, but perhaps it give you a hint on how to proceed.

I would advice that you instead design your table so that no duplicates are allowed as explained in @CLs answer below.

What 'additional configuration' is necessary to reference a .NET 2.0 mixed mode assembly in a .NET 4.0 project?

Also i had this issue with the class library, If any one have the issue with the class library added to your main application. Just add

<startup useLegacyV2RuntimeActivationPolicy="true">

to you main application which would then be picked by the class library.

SQLite - UPSERT *not* INSERT or REPLACE

If you are generally doing updates I would ..

  1. Begin a transaction
  2. Do the update
  3. Check the rowcount
  4. If it is 0 do the insert
  5. Commit

If you are generally doing inserts I would

  1. Begin a transaction
  2. Try an insert
  3. Check for primary key violation error
  4. if we got an error do the update
  5. Commit

This way you avoid the select and you are transactionally sound on Sqlite.

What are the best practices for SQLite on Android?

after struggling with this for a couple of hours, I've found that you can only use one db helper object per db execution. For example,

for(int x = 0; x < someMaxValue; x++)
{
    db = new DBAdapter(this);
    try
    {

        db.addRow
        (
                NamesStringArray[i].toString(), 
                StartTimeStringArray[i].toString(),
                EndTimeStringArray[i].toString()
        );

    }
    catch (Exception e)
    {
        Log.e("Add Error", e.toString());
        e.printStackTrace();
    }
    db.close();
}

as apposed to:

db = new DBAdapter(this);
for(int x = 0; x < someMaxValue; x++)
{

    try
    {
        // ask the database manager to add a row given the two strings
        db.addRow
        (
                NamesStringArray[i].toString(), 
                StartTimeStringArray[i].toString(),
                EndTimeStringArray[i].toString()
        );

    }
    catch (Exception e)
    {
        Log.e("Add Error", e.toString());
        e.printStackTrace();
    }

}
db.close();

creating a new DBAdapter each time the loop iterates was the only way I could get my strings into a database through my helper class.

ALTER COLUMN in sqlite

SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows the user to rename a table or to add a new column to an existing table. It is not possible to rename a column, remove a column, or add or remove constraints from a table. But you can alter table column datatype or other property by the following steps.

  1. BEGIN TRANSACTION;
  2. CREATE TEMPORARY TABLE t1_backup(a,b);
  3. INSERT INTO t1_backup SELECT a,b FROM t1;
  4. DROP TABLE t1;
  5. CREATE TABLE t1(a,b);
  6. INSERT INTO t1 SELECT a,b FROM t1_backup;
  7. DROP TABLE t1_backup;
  8. COMMIT

For more detail you can refer the link.

Most simple code to populate JTable from ResultSet

This is my approach:

String[] columnNames = {"id", "Nome", "Sobrenome","Email"};

List<Student> students = _repo.getAll();

Object[][] data = new Object[students.size()][4];

int index = 0;
for(Student s : students) {
    data[index][0] = s.getId();
    data[index][1] = s.getFirstName();
    data[index][2] = s.getLastName();
    data[index][3] = s.getEmail();
    index++;
}

DefaultTableModel model = new DefaultTableModel(data, columnNames);

table = new JTable(model);

When does SQLiteOpenHelper onCreate() / onUpgrade() run?

onCreate is called for the first time when creation of tables are needed. We need to override this method where we write the script for table creation which is executed by SQLiteDatabase. execSQL method. After executing in first time deployment, this method will not be called onwards.

onUpgrade This method is called when database version is upgraded. Suppose for the first time deployment , database version was 1 and in second deployment there was change in database structure like adding extra column in table. Suppose database version is 2 now.

Create SQLite database in android

this is the full source code to direct use,

    public class CardDBDAO {

        protected SQLiteDatabase database;
        private DataBaseHelper dbHelper;
        private Context mContext;

        public CardDBDAO(Context context) {
            this.mContext = context;
            dbHelper = DataBaseHelper.getHelper(mContext);
            open();

        }

        public void open() throws SQLException {
            if(dbHelper == null)
                dbHelper = DataBaseHelper.getHelper(mContext);
            database = dbHelper.getWritableDatabase();
        }

    }



    public class DataBaseHelper extends SQLiteOpenHelper {

        private static final String DATABASE_NAME = "mydbnamedb";
        private static final int DATABASE_VERSION = 1;

        public static final String CARDS_TABLE = "tbl_cards";
        public static final String POICATEGORIES_TABLE = "tbl_poicategories";
        public static final String POILANGS_TABLE = "tbl_poilangs";

        public static final String ID_COLUMN = "id";

        public static final String POI_ID = "poi_id";
        public static final String POICATEGORIES_COLUMN = "poi_categories";

        public static final String POILANGS_COLUMN = "poi_langs";

        public static final String CARDS = "cards";
        public static final String CARD_ID = "card_id";
        public static final String CARDS_PCAT_ID = "pcat_id";

        public static final String CREATE_PLANG_TABLE = "CREATE TABLE "
                + POILANGS_TABLE + "(" + ID_COLUMN + " INTEGER PRIMARY KEY,"
                + POILANGS_COLUMN + " TEXT, " + POI_ID + " TEXT)";

        public static final String CREATE_PCAT_TABLE = "CREATE TABLE "
                + POICATEGORIES_TABLE + "(" + ID_COLUMN + " INTEGER PRIMARY KEY,"
                + POICATEGORIES_COLUMN + " TEXT, " + POI_ID + " TEXT)";

        public static final String CREATE_CARDS_TABLE = "CREATE TABLE "
                + CARDS_TABLE + "(" + ID_COLUMN + " INTEGER PRIMARY KEY," + CARD_ID
                + " TEXT, " + CARDS_PCAT_ID + " TEXT, " + CARDS + " TEXT)";

        private static DataBaseHelper instance;

        public static synchronized DataBaseHelper getHelper(Context context) {
            if (instance == null)
                instance = new DataBaseHelper(context);
            return instance;
        }

        private DataBaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onOpen(SQLiteDatabase db) {
            super.onOpen(db);
            if (!db.isReadOnly()) {
                // Enable foreign key constraints
                // db.execSQL("PRAGMA foreign_keys=ON;");
            }
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(CREATE_PCAT_TABLE);
            db.execSQL(CREATE_PLANG_TABLE);
            db.execSQL(CREATE_CARDS_TABLE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        }
    }




    public class PoiLangDAO extends CardDBDAO {

            private static final String WHERE_ID_EQUALS = DataBaseHelper.ID_COLUMN
                    + " =?";

            public PoiLangDAO(Context context) {
                super(context);
            }

            public long save(PLang plang_data) {

                ContentValues values = new ContentValues();
                values.put(DataBaseHelper.POI_ID, plang_data.getPoi_id());
                values.put(DataBaseHelper.POILANGS_COLUMN, plang_data.getLangarr());

                return database
                        .insert(DataBaseHelper.POILANGS_TABLE, null, values);
            }

            public long update(PLang plang_data) {
                ContentValues values = new ContentValues();
                values.put(DataBaseHelper.POI_ID, plang_data.getPoi_id());
                values.put(DataBaseHelper.POILANGS_COLUMN, plang_data.getLangarr());

                long result = database.update(DataBaseHelper.POILANGS_TABLE,
                        values, WHERE_ID_EQUALS,
                        new String[] { String.valueOf(plang_data.getId()) });
                Log.d("Update Result:", "=" + result);
                return result;

            }

            public int deleteDept(PLang plang_data) {
                return database.delete(DataBaseHelper.POILANGS_TABLE,
                        WHERE_ID_EQUALS, new String[] { plang_data.getId() + "" });
            }

            public List<PLang> getPLangs1() {
                List<PLang> plang_list = new ArrayList<PLang>();
                Cursor cursor = database.query(DataBaseHelper.POILANGS_TABLE,
                        new String[] { DataBaseHelper.ID_COLUMN, DataBaseHelper.POI_ID,
                                DataBaseHelper.POILANGS_COLUMN }, null, null, null,
                        null, null);

                while (cursor.moveToNext()) {
                    PLang plang_bin = new PLang();
                    plang_bin.setId(cursor.getInt(0));
                    plang_bin.setPoi_id(cursor.getString(1));
                    plang_bin.setLangarr(cursor.getString(2));
                    plang_list.add(plang_bin);
                }
                return plang_list;
            }

            public List<PLang> getPLangs(String pid) {
                List<PLang> plang_list = new ArrayList<PLang>();

                String selection = DataBaseHelper.POI_ID + "=?";
                String[] selectionArgs = { pid };

                Cursor cursor = database.query(DataBaseHelper.POILANGS_TABLE,
                        new String[] { DataBaseHelper.ID_COLUMN, DataBaseHelper.POI_ID,
                                DataBaseHelper.POILANGS_COLUMN }, selection,
                        selectionArgs, null, null, null);

                while (cursor.moveToNext()) {
                    PLang plang_bin = new PLang();
                    plang_bin.setId(cursor.getInt(0));
                    plang_bin.setPoi_id(cursor.getString(1));
                    plang_bin.setLangarr(cursor.getString(2));
                    plang_list.add(plang_bin);
                }
                return plang_list;
            }

            public void loadPLangs(String poi_id, String langarrs) {
                PLang plangbin = new PLang(poi_id, langarrs);

                List<PLang> plang_arr = new ArrayList<PLang>();
                plang_arr.add(plangbin);

                for (PLang dept : plang_arr) {
                    ContentValues values = new ContentValues();
                    values.put(DataBaseHelper.POI_ID, dept.getPoi_id());
                    values.put(DataBaseHelper.POILANGS_COLUMN, dept.getLangarr());
                    database.insert(DataBaseHelper.POILANGS_TABLE, null, values);
                }
            }

        }




        public class PLang {

            public PLang() {
                super();
            }

            public PLang(String poi_id, String langarrs) {
                // TODO Auto-generated constructor stub

                this.poi_id = poi_id;
                this.langarr = langarrs;
            }

            public int getId() {
                return id;
            }

            public void setId(int id) {
                this.id = id;
            }

            public String getPoi_id() {
                return poi_id;
            }

            public void setPoi_id(String poi_id) {
                this.poi_id = poi_id;
            }

            public String getLangarr() {
                return langarr;
            }

            public void setLangarr(String langarr) {
                this.langarr = langarr;
            }

            private int id;
            private String poi_id;
            private String langarr;

    }

How to retrieve data from sqlite database in android and display it in TextView

TextView tekst = (TextView) findViewById(R.id.editText1); 

You cannot cast EditText to TextView.

SELECT *, COUNT(*) in SQLite

SELECT *, COUNT(*) FROM my_table is not what you want, and it's not really valid SQL, you have to group by all the columns that's not an aggregate.

You'd want something like

SELECT somecolumn,someothercolumn, COUNT(*) 
   FROM my_table 
GROUP BY somecolumn,someothercolumn

Android SQLite Example

Using Helper class you can access SQLite Database and can perform the various operations on it by overriding the onCreate() and onUpgrade() methods.

http://technologyguid.com/android-sqlite-database-app-example/

Set default value of an integer column SQLite

Use the SQLite keyword default

db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" 
    + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
    + KEY_NAME + " TEXT NOT NULL, "
    + KEY_WORKED + " INTEGER, "
    + KEY_NOTE + " INTEGER DEFAULT 0);");

This link is useful: http://www.sqlite.org/lang_createtable.html

auto create database in Entity Framework Core

If you want both of EnsureCreated and Migrate use this code:

     using (var context = new YourDbContext())
            {
                if (context.Database.EnsureCreated())
                {
                    //auto migration when database created first time

                    //add migration history table

                    string createEFMigrationsHistoryCommand = $@"
USE [{context.Database.GetDbConnection().Database}];
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
CREATE TABLE [dbo].[__EFMigrationsHistory](
    [MigrationId] [nvarchar](150) NOT NULL,
    [ProductVersion] [nvarchar](32) NOT NULL,
 CONSTRAINT [PK___EFMigrationsHistory] PRIMARY KEY CLUSTERED 
(
    [MigrationId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY];
";
                    context.Database.ExecuteSqlRaw(createEFMigrationsHistoryCommand);

                    //insert all of migrations
                    var dbAssebmly = context.GetType().GetAssembly();
                    foreach (var item in dbAssebmly.GetTypes())
                    {
                        if (item.BaseType == typeof(Migration))
                        {
                            string migrationName = item.GetCustomAttributes<MigrationAttribute>().First().Id;
                            var version = typeof(Migration).Assembly.GetName().Version;
                            string efVersion = $"{version.Major}.{version.Minor}.{version.Build}";
                            context.Database.ExecuteSqlRaw("INSERT INTO __EFMigrationsHistory(MigrationId,ProductVersion) VALUES ({0},{1})", migrationName, efVersion);
                        }
                    }
                }
                context.Database.Migrate();
            }

SQLite with encryption/password protection

Keep in mind, the following is not intended to be a substitute for a proper security solution.

After playing around with this for four days, I've put together a solution using only the open source System.Data.SQLite package from NuGet. I don't know how much protection this provides. I'm only using it for my own course of study. This will create the DB, encrypt it, create a table, and add data.

using System.Data.SQLite;

namespace EncryptDB
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectionString = @"C:\Programming\sqlite3\db.db";
            string passwordString = "password";
            byte[] passwordBytes = GetBytes(passwordString);
            SQLiteConnection.CreateFile(connectionString);
            SQLiteConnection conn = new SQLiteConnection("Data Source=" + connectionString + ";Version=3;");
            conn.SetPassword(passwordBytes);
            conn.Open();
            SQLiteCommand sqlCmd = new SQLiteCommand("CREATE TABLE data(filename TEXT, filepath TEXT, filelength INTEGER, directory TEXT)", conn);
            sqlCmd.ExecuteNonQuery();
            sqlCmd = new SQLiteCommand("INSERT INTO data VALUES('name', 'path', 200, 'dir')", conn);
            sqlCmd.ExecuteNonQuery();
            conn.Close();
        }
        static byte[] GetBytes(string str)
        {
            byte[] bytes = new byte[str.Length * sizeof(char)];
            bytes = System.Text.Encoding.Default.GetBytes(str);
            return bytes;
        }
    }
}

Optionally, you can remove conn.SetPassword(passwordBytes);, and replace it with conn.ChangePassword("password"); which needs to be placed after conn.Open(); instead of before. Then you won't need the GetBytes method.

To decrypt, it's just a matter of putting the password in your connection string before the call to open.

        string filename = @"C:\Programming\sqlite3\db.db";
        string passwordString = "password";
        SQLiteConnection conn = new SQLiteConnection("Data Source=" + filename + ";Version=3;Password=" + passwordString + ";");
        conn.Open();

Opening database file from within SQLite command-line shell

Older SQLite command-line shells (sqlite3.exe) do not appear to offer the .open command or any readily identifiable alternative.

Although I found no definitive reference it seems that the .open command was introduced around version 3.15. The SQLite Release History first mentions the .open command with 2016-10-14 (3.15.0).

How to open .SQLite files

My favorite:

https://inloop.github.io/sqlite-viewer/

No installation needed. Just drop the file.

How to list the tables in a SQLite database file that was opened with ATTACH?

Via a union all, combine all tables into one list.

select name
from sqlite_master 
where type='table'

union all 

select name 
from sqlite_temp_master 
where type='table'

Importing a CSV file into a sqlite3 database table using Python

import csv, sqlite3

con = sqlite3.connect(":memory:") # change to 'sqlite:///your_filename.db'
cur = con.cursor()
cur.execute("CREATE TABLE t (col1, col2);") # use your column names here

with open('data.csv','r') as fin: # `with` statement available in 2.5+
    # csv.DictReader uses first line in file for column headings by default
    dr = csv.DictReader(fin) # comma is default delimiter
    to_db = [(i['col1'], i['col2']) for i in dr]

cur.executemany("INSERT INTO t (col1, col2) VALUES (?, ?);", to_db)
con.commit()
con.close()

ALTER TABLE ADD COLUMN IF NOT EXISTS in SQLite

I took the answer above in C#/.Net, and rewrote it for Qt/C++, not to much changed, but I wanted to leave it here for anyone in the future looking for a C++'ish' answer.

    bool MainWindow::isColumnExisting(QString &table, QString &columnName){

    QSqlQuery q;

    try {
        if(q.exec("PRAGMA table_info("+ table +")"))
            while (q.next()) {
                QString name = q.value("name").toString();     
                if (columnName.toLower() == name.toLower())
                    return true;
            }

    } catch(exception){
        return false;
    }
    return false;
}

How to view data saved in android database(SQLite)?

If you are able to copy the actual SQLite database file to your desktop, you can use this tools to browse the data.

sqlite database default time value 'now'

according to dr. hipp in a recent list post:

CREATE TABLE whatever(
     ....
     timestamp DATE DEFAULT (datetime('now','localtime')),
     ...
);

How do I UPDATE a row in a table or INSERT it if it doesn't exist?

I would do something like the following:

INSERT INTO cache VALUES (key, generation)
ON DUPLICATE KEY UPDATE (key = key, generation = generation + 1);

Setting the generation value to 0 in code or in the sql but the using the ON DUP... to increment the value. I think that's the syntax anyway.

Sqlite or MySql? How to decide?

SQLite out-of-the-box is not really feature-full regarding concurrency. You will get into trouble if you have hundreds of web requests hitting the same SQLite database.

You should definitely go with MySQL or PostgreSQL.

If it is for a single-person project, SQLite will be easier to setup though.

Copying data from one SQLite database to another

First scenario: DB1.sqlite and DB2.sqlite have the same table(t1), but DB1 is more "up to date" than DB2. If it's small, drop the table from DB2 and recreate it with the data:

> DROP TABLE IF EXISTS db2.t1; CREATE TABLE db2.t1 AS SELECT * FROM db1.t1;

Second scenario: If it's a large table, you may be better off with an INSERT if not exists type solution. If you have a Unique Key column it's more straight forward, otherwise you'd need to use a combination of fields (maybe every field) and at some point it's still faster to just drop and re-create the table; it's always more straight forward (less thinking required).


THE SETUP: open SQLite without a DB which creates a temporary in memory main database, then attach DB1.sqlite and DB2.sqlite

> sqlite3
sqlite> ATTACH "DB1.sqlite" AS db1
sqlite> ATTACH "DB2.sqlite" AS db2

and use .databases to see the attached databases and their files.

sqlite> .databases
main: 
db1: /db/DB1.sqlite
db2: /db/DB2.sqlite

Update multiple rows with different values in a single SQL query

There's a couple of ways to accomplish this decently efficiently.

First -
If possible, you can do some sort of bulk insert to a temporary table. This depends somewhat on your RDBMS/host language, but at worst this can be accomplished with a simple dynamic SQL (using a VALUES() clause), and then a standard update-from-another-table. Most systems provide utilities for bulk load, though

Second -
And this is somewhat RDBMS dependent as well, you could construct a dynamic update statement. In this case, where the VALUES(...) clause inside the CTE has been created on-the-fly:

WITH Tmp(id, px, py) AS (VALUES(id1, newsPosX1, newPosY1), 
                               (id2, newsPosX2, newPosY2),
                               ......................... ,
                               (idN, newsPosXN, newPosYN))

UPDATE TableToUpdate SET posX = (SELECT px
                                 FROM Tmp
                                 WHERE TableToUpdate.id = Tmp.id),
                         posY = (SELECT py
                                 FROM Tmp
                                 WHERE TableToUpdate.id = Tmp.id)


WHERE id IN (SELECT id
             FROM Tmp)

(According to the documentation, this should be valid SQLite syntax, but I can't get it to work in a fiddle)

How to get Last record from Sqlite?

I think it would be better if you use the method query from SQLiteDatabase class instead of the whole SQL string, which would be:

 Cursor cursor = sqLiteDatabase.query(TABLE, allColluns, null, null, null, null, ID +" DESC", "1");

The last two parameters are ORDER BY and LIMIT.

You can see more at: http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html

Android SQLite SELECT Query

Try trimming the string to make sure there is no extra white space:

Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE TRIM(name) = '"+name.trim()+"'", null);

Also use c.moveToFirst() like @thinksteep mentioned.


This is a complete code for select statements.

SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT column1,column2,column3 FROM table ", null);
if (c.moveToFirst()){
    do {
        // Passing values 
        String column1 = c.getString(0);
        String column2 = c.getString(1);
        String column3 = c.getString(2); 
        // Do something Here with values
    } while(c.moveToNext());
}
c.close();
db.close();

No module named _sqlite3

  1. Install the sqlite-devel package:

    yum install sqlite-devel -y

  2. Recompile python from the source:

    ./configure
    make
    make altinstall
    

Store boolean value in SQLite

SQLite Boolean Datatype:
SQLite does not have a separate Boolean storage class. Instead, Boolean values are stored as integers 0 (false) and 1 (true).

You can convert boolean to int in this way:

int flag = (boolValue)? 1 : 0;

You can convert int back to boolean as follows:

 // Select COLUMN_NAME  values from db. 
 // This will be integer value, you can convert this int value back to Boolean as follows
Boolean flag2 = (intValue == 1)? true : false;

If you want to explore sqlite, here is a tutorial.
I have given one answer here. It is working for them.

Android SQLite: Update Statement

You can use the code below.

String strFilter = "_id=" + Id;
ContentValues args = new ContentValues();
args.put(KEY_TITLE, title);
myDB.update("titles", args, strFilter, null);

Password Protect a SQLite DB. Is it possible?

Why do you need to encrypt the database? The user could easily disassemble your program and figure out the key. If you're encrypting it for network transfer, then consider using PGP instead of squeezing an encryption layer into a database layer.

python 3.2 UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 9629: character maps to <undefined>

for me , using export PYTHONIOENCODING=UTF-8 before executing python command worked .

Sqlite in chrome

Chrome supports WebDatabase API (which is powered by sqlite), but looks like W3C stopped its development.

SQL Select between dates

Or you can cast your string to Date format with date function. Even the date is stored as TEXT in the DB. Like this (the most workable variant):

SELECT * FROM test WHERE date(date) 
BETWEEN date('2011-01-11') AND date('2011-8-11')

Android: upgrading DB version and adding new table

You can use SQLiteOpenHelper's onUpgrade method. In the onUpgrade method, you get the oldVersion as one of the parameters.

In the onUpgrade use a switch and in each of the cases use the version number to keep track of the current version of database.

It's best that you loop over from oldVersion to newVersion, incrementing version by 1 at a time and then upgrade the database step by step. This is very helpful when someone with database version 1 upgrades the app after a long time, to a version using database version 7 and the app starts crashing because of certain incompatible changes.

Then the updates in the database will be done step-wise, covering all possible cases, i.e. incorporating the changes in the database done for each new version and thereby preventing your application from crashing.

For example:

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    switch (oldVersion) {
    case 1:
        String sql = "ALTER TABLE " + TABLE_SECRET + " ADD COLUMN " + "name_of_column_to_be_added" + " INTEGER";
        db.execSQL(sql);
        break;

    case 2:
        String sql = "SOME_QUERY";
        db.execSQL(sql);
        break;
    }

}

List of tables, db schema, dump etc using the Python sqlite3 API

If someone wants to do the same thing with Pandas

import pandas as pd
import sqlite3
conn = sqlite3.connect("db.sqlite3")
table = pd.read_sql_query("SELECT name FROM sqlite_master WHERE type='table'", conn)
print(table)

How can I add the sqlite3 module to Python?

For Python version 3:

pip install pysqlite3 

SQLiteDatabase.query method

This is a more general answer meant to be a quick reference for future viewers.

Example

SQLiteDatabase db = helper.getReadableDatabase();

String table = "table2";
String[] columns = {"column1", "column3"};
String selection = "column3 =?";
String[] selectionArgs = {"apple"};
String groupBy = null;
String having = null;
String orderBy = "column3 DESC";
String limit = "10";

Cursor cursor = db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit);

Explanation from the documentation

  • table String: The table name to compile the query against.
  • columns String: A list of which columns to return. Passing null will return all columns, which is discouraged to prevent reading data from storage that isn't going to be used.
  • selection String: A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given table.
  • selectionArgs String: You may include ?s in selection, which will be replaced by the values from selectionArgs, in order that they appear in the selection. The values will be bound as Strings.
  • groupBy String: A filter declaring how to group rows, formatted as an SQL GROUP BY clause (excluding the GROUP BY itself). Passing null will cause the rows to not be grouped.
  • having String: A filter declare which row groups to include in the cursor, if row grouping is being used, formatted as an SQL HAVING clause (excluding the HAVING itself). Passing null will cause all row groups to be included, and is required when row grouping is not being used.
  • orderBy String: How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered.
  • limit String: Limits the number of rows returned by the query, formatted as LIMIT clause. Passing null denotes no LIMIT clause.

Best way to work with dates in Android SQLite

I prefer this. This is not the best way, but a fast solution.

//Building the table includes:
StringBuilder query= new StringBuilder();
query.append("CREATE TABLE "+TABLE_NAME+ " (");
query.append(COLUMN_ID+"int primary key autoincrement,");
query.append(COLUMN_CREATION_DATE+" DATE)");

//Inserting the data includes this:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
values.put(COLUMN_CREATION_DATE,dateFormat.format(reactionGame.getCreationDate())); 

// Fetching the data includes this:
try {
   java.util.Date creationDate = dateFormat.parse(cursor.getString(0);
   YourObject.setCreationDate(creationDate));
} catch (Exception e) {
   YourObject.setCreationDate(null);
}

How do I change an HTML selected option using JavaScript?

Your own answer technically wasn't incorrect, but you got the index wrong since indexes start at 0, not 1. That's why you got the wrong selection.

document.getElementById('personlist').getElementsByTagName('option')[**10**].selected = 'selected';

Also, your answer is actually a good one for cases where the tags aren't entirely English or numeric.

If they use, for example, Asian characters, the other solutions telling you to use .value() may not always function and will just not do anything. Selecting by tag is a good way to ignore the actual text and select by the element itself.

How to add an image to the emulator gallery in android studio?

Although you can have logat on a real device too, if you need to use an emulator try transferring the images through the Android Device Monitor, accessible from the toolbar in Android Studio (it's in eclipse too, of course).

Once you select the device from ADM, you can see the folders tree and copy things inside

How to append text to an existing file in Java?

1.7 Approach:

void appendToFile(String filePath, String content) throws IOException{

    Path path = Paths.get(filePath);

    try (BufferedWriter writer = 
            Files.newBufferedWriter(path, 
                    StandardOpenOption.APPEND)) {
        writer.newLine();
        writer.append(content);
    }

    /*
    //Alternative:
    try (BufferedWriter bWriter = 
            Files.newBufferedWriter(path, 
                    StandardOpenOption.WRITE, StandardOpenOption.APPEND);
            PrintWriter pWriter = new PrintWriter(bWriter)
            ) {
        pWriter.println();//to have println() style instead of newLine();   
        pWriter.append(content);//Also, bWriter.append(content);
    }*/
}

How to compile .c file with OpenSSL includes?

You need to include the library path (-L/usr/local/lib/)

gcc -o Opentest Opentest.c -L/usr/local/lib/ -lssl -lcrypto

It works for me.

How to delete a selected DataGridViewRow and update a connected database table?

Well, this is how I usually delete checked rows by the user from a DataGridView, if you are associating it with a DataTable from a Dataset (ex: DataGridView1.DataSource = Dataset1.Tables["x"]), then once you will make any updates (delete, insert,update) in the Dataset, it will automatically happen in your DataGridView.

if (MessageBox.Show("Are you sure you want to delete this record(s)", "confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == System.Windows.Forms.DialogResult.Yes)
        {
            try
            {
                for (int i = dgv_Championnat.RowCount -1; i > -1; i--)
                {
                    if (Convert.ToBoolean(dgv_Championnat.Rows[i].Cells[0].Value) == true)
                    {
                        Program.set.Tables["Champ"].Rows[i].Delete();
                    }
                }
                Program.command = new SqlCommandBuilder(Program.AdapterChampionnat);
                if (Program.AdapterChampionnat.Update(Program.TableChampionnat) > 0)
                {
                    MessageBox.Show("Well Deleted");
                }
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

How to Decode Json object in laravel and apply foreach loop on that in laravel

your string is NOT a valid json to start with.

a valid json will be,

{
    "area": [
        {
            "area": "kothrud"
        },
        {
            "area": "katraj"
        }
    ]
}

if you do a json_decode, it will yield,

stdClass Object
(
    [area] => Array
        (
            [0] => stdClass Object
                (
                    [area] => kothrud
                )

            [1] => stdClass Object
                (
                    [area] => katraj
                )

        )

)

Update: to use

$string = '

{
    "area": [
        {
            "area": "kothrud"
        },
        {
            "area": "katraj"
        }
    ]
}

';
            $area = json_decode($string, true);

            foreach($area['area'] as $i => $v)
            {
                echo $v['area'].'<br/>';
            }

Output:

kothrud
katraj

Update #2:

for that true:

When TRUE, returned objects will be converted into associative arrays. for more information, click here

How to create byte array from HttpPostedFile

It won't work if your file InputStream.Position is set to the end of the stream. My additional lines:

Stream stream = file.InputStream;
stream.Position = 0;

Disable asp.net button after click to prevent double clicking

Disable the button on the OnClick event, then re-enable on the AJAX callback event handler. Here is how I do it with jQuery.

<script>
$(document).ready(function() {

    $('#buttonId').click(function() {
         $(this).attr('disabled', 'disabled');
         callAjax();
    });

});

function callAjax()
{
    $.ajax({
      url: 'ajax/test.html',
      success: function(data) {
         //enable button
         $('#buttonId').removeAttr('disabled');

      }
    });
}
</script>

Why is width: 100% not working on div {display: table-cell}?

How about this? (jsFiddle link)

CSS

ul {
    background: #CCC;
    height: 1000%;
    width: 100%;
    list-style-position: outside;
    margin: 0; padding: 0;
    position: absolute;
}
li {
 background-color: #EBEBEB;
    border-bottom: 1px solid #CCCCCC;
    border-right: 1px solid #CCCCCC;
    display: table;
    height: 180px;
    overflow: hidden;
    width: 200px;
}
.divone{
    display: table-cell;
    margin: 0 auto;
    text-align: center;
    vertical-align: middle;
    width: 100%; 

}
img {
    width: 100%;
    height: 410px;
}
.wrapper {
  position: absolute;
}

mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource

If you don't have any MySQL Error appearing while checking, make sure that you properly created your database table. This happened to me. Look for any unwanted commas or quotes.

Convert hex string (char []) to int?

Use strtol if you have libc available like the top answer suggests. However if you like custom stuff or are on a microcontroller without libc or so, you may want a slightly optimized version without complex branching.

#include <inttypes.h>


/**
 * xtou64
 * Take a hex string and convert it to a 64bit number (max 16 hex digits).
 * The string must only contain digits and valid hex characters.
 */
uint64_t xtou64(const char *str)
{
    uint64_t res = 0;
    char c;

    while ((c = *str++)) {
        char v = (c & 0xF) + (c >> 6) | ((c >> 3) & 0x8);
        res = (res << 4) | (uint64_t) v;
    }

    return res;
} 

The bit shifting magic boils down to: Just use the last 4 bits, but if it is an non digit, then also add 9.

Entity Framework Core: A second operation started on this context before a previous operation completed

In my case I was using a lock which does not allow the use of await and does not create compiler warning when you don't await an async.

The problem:

lock (someLockObject) {
    // do stuff
    context.SaveChangesAsync();
}

// some other code somewhere else doing await context.SaveChangesAsync() shortly after the lock gets the concurrency error

The fix: Wait for the async inside the lock by making it blocking with a .Wait()

lock (someLockObject) {
    // do stuff
    context.SaveChangesAsync().Wait();
}

Android Gradle Could not reserve enough space for object heap

Add the following line in MyApplicationDir\gradle.properties

org.gradle.jvmargs=-Xmx1024m

If two cells match, return value from third

I think what you want is something like:

=INDEX(B:B,MATCH(C2,A:A,0))  

I should mention that MATCH checks the position at which the value can be found within A:A (given the 0, or FALSE, parameter, it looks only for an exact match and given its nature, only the first instance found) then INDEX returns the value at that position within B:B.

How to use target in location.href

The problem is that some versions of explorer don't support the window.open javascript function

Say what? Can you provide a reference for that statement? With respect, I think you must be mistaken. This works on IE6 and IE9, for instance.

Most modern browsers won't let your code use window.open except in direct response to a user event, in order to keep spam pop-ups and such at bay; perhaps that's what you're thinking of. As long as you only use window.open when responding to a user event, you should be fine using window.open — with all versions of IE.

There is no way to use location to open a new window. Just window.open or, of course, the user clicking a link with target="_blank".

"Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP

The best way for getting input string is:

$value = filter_input(INPUT_POST, 'value');

This one-liner is almost equivalent to:

if (!isset($_POST['value'])) {
    $value = null;
} elseif (is_array($_POST['value'])) {
    $value = false;
} else {
    $value = $_POST['value'];
}

If you absolutely want string value, just like:

$value = (string)filter_input(INPUT_POST, 'value');

How to correctly assign a new string value?

The first example doesn't work because you can't assign values to arrays - arrays work (sort of) like const pointers in this respect. What you can do though is copy a new value into the array:

strcpy(p.name, "Jane");

Char arrays are fine to use if you know the maximum size of the string in advance, e.g. in the first example you are 100% sure that the name will fit into 19 characters (not 20 because one character is always needed to store the terminating zero value).

Conversely, pointers are better if you don't know the possible maximum size of your string, and/or you want to optimize your memory usage, e.g. avoid reserving 512 characters for the name "John". However, with pointers you need to dynamically allocate the buffer they point to, and free it when not needed anymore, to avoid memory leaks.

Update: example of dynamically allocated buffers (using the struct definition in your 2nd example):

char* firstName = "Johnnie";
char* surname = "B. Goode";
person p;

p.name = malloc(strlen(firstName) + 1);
p.surname = malloc(strlen(surname) + 1);

p.age = 25;
strcpy(p.name, firstName);
strcpy(p.surname, surname);

printf("Name: %s; Age: %d\n",p.name,p.age);

free(p.surname);
free(p.name);

Excel: Can I create a Conditional Formula based on the Color of a Cell?

You can use this function (I found it here: http://excelribbon.tips.net/T010780_Colors_in_an_IF_Function.html):

Function GetFillColor(Rng As Range) As Long
    GetFillColor = Rng.Interior.ColorIndex
End Function

Here is an explanation, how to create user-defined functions: http://www.wikihow.com/Create-a-User-Defined-Function-in-Microsoft-Excel

In your worksheet, you can use the following: =GetFillColor(B5)

How can I put a database under git (version control)?

This question is pretty much answered but I would like to complement X-Istence's and Dana the Sane's answer with a small suggestion.

If you need revision control with some degree of granularity, say daily, you could couple the text dump of both the tables and the schema with a tool like rdiff-backup which does incremental backups. The advantage is that instead of storing snapshots of daily backups, you simply store the differences from the previous day.

With this you have both the advantage of revision control and you don't waste too much space.

In any case, using git directly on big flat files which change very frequently is not a good solution. If your database becomes too big, git will start to have some problems managing the files.

Use of def, val, and var in scala

There are three ways of defining things in Scala:

  • def defines a method
  • val defines a fixed value (which cannot be modified)
  • var defines a variable (which can be modified)

Looking at your code:

def person = new Person("Kumar",12)

This defines a new method called person. You can call this method only without () because it is defined as parameterless method. For empty-paren method, you can call it with or without '()'. If you simply write:

person

then you are calling this method (and if you don't assign the return value, it will just be discarded). In this line of code:

person.age = 20

what happens is that you first call the person method, and on the return value (an instance of class Person) you are changing the age member variable.

And the last line:

println(person.age)

Here you are again calling the person method, which returns a new instance of class Person (with age set to 12). It's the same as this:

println(person().age)

Rails: Get Client IP address

I found request.env['HTTP_X_FORWARDED_FOR'] very useful too in cases when request.remote_ip returns 127.0.0.1

How do I read CSV data into a record array in NumPy?

This work as a charm...

import csv
with open("data.csv", 'r') as f:
    data = list(csv.reader(f, delimiter=";"))

import numpy as np
data = np.array(data, dtype=np.float)

Link to add to Google calendar

For the next person Googling this topic, I've written a small NPM package to make it simple to generate Google Calendar URLs. It includes TypeScript type definitions, for those who need that. Hope it helps!

https://www.npmjs.com/package/google-calendar-url

Checking if a variable is defined?

defined? is great, but if you are in a Rails environment you can also use try, especially in cases where you want to check a dynamic variable name:

foo = 1
my_foo = "foo"
my_bar = "bar"
try(:foo)        # => 1
try(:bar)        # => nil
try(my_foo)      # => 1
try(my_bar)      # => nil

PUT vs. POST in REST

POST means "create new" as in "Here is the input for creating a user, create it for me".

PUT means "insert, replace if already exists" as in "Here is the data for user 5".

You POST to example.com/users since you don't know the URL of the user yet, you want the server to create it.

You PUT to example.com/users/id since you want to replace/create a specific user.

POSTing twice with the same data means create two identical users with different ids. PUTing twice with the same data creates the user the first and updates him to the same state the second time (no changes). Since you end up with the same state after a PUT no matter how many times you perform it, it is said to be "equally potent" every time - idempotent. This is useful for automatically retrying requests. No more 'are you sure you want to resend' when you push the back button on the browser.

A general advice is to use POST when you need the server to be in control of URL generation of your resources. Use PUT otherwise. Prefer PUT over POST.

How do you change the character encoding of a postgres database?

First off, Daniel's answer is the correct, safe option.

For the specific case of changing from SQL_ASCII to something else, you can cheat and simply poke the pg_database catalogue to reassign the database encoding. This assumes you've already stored any non-ASCII characters in the expected encoding (or that you simply haven't used any non-ASCII characters).

Then you can do:

update pg_database set encoding = pg_char_to_encoding('UTF8') where datname = 'thedb'

This will not change the collation of the database, just how the encoded bytes are converted into characters (so now length('£123') will return 4 instead of 5). If the database uses 'C' collation, there should be no change to ordering for ASCII strings. You'll likely need to rebuild any indices containing non-ASCII characters though.

Caveat emptor. Dumping and reloading provides a way to check your database content is actually in the encoding you expect, and this doesn't. And if it turns out you did have some wrongly-encoded data in the database, rescuing is going to be difficult. So if you possibly can, dump and reinitialise.

How do I center floated elements?

Using Flex

_x000D_
_x000D_
.pagination {_x000D_
  text-align: center;_x000D_
  display:flex;_x000D_
  justify-content:center;_x000D_
}_x000D_
.pagination a {_x000D_
  display: block;_x000D_
  width: 30px;_x000D_
  height: 30px;_x000D_
  float: left;_x000D_
  margin-left: 3px;_x000D_
  background: url(/images/structure/pagination-button.png);_x000D_
}_x000D_
.pagination a.last {_x000D_
  width: 90px;_x000D_
  background: url(/images/structure/pagination-button-last.png);_x000D_
}_x000D_
.pagination a.first {_x000D_
  width: 60px;_x000D_
  background: url(/images/structure/pagination-button-first.png);_x000D_
}
_x000D_
<div class='pagination'>_x000D_
  <a class='first' href='#'>First</a>_x000D_
  <a href='#'>1</a>_x000D_
  <a href='#'>2</a>_x000D_
  <a href='#'>3</a>_x000D_
  <a class='last' href='#'>Last</a>_x000D_
</div>_x000D_
<!-- end: .pagination -->
_x000D_
_x000D_
_x000D_

Android: combining text & image on a Button or ImageButton

You can use drawableTop (also drawableLeft, etc) for the image and set text below the image by adding the gravity left|center_vertical

<Button
            android:id="@+id/btn_video"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:background="@null"
            android:drawableTop="@drawable/videos"
            android:gravity="left|center_vertical"
            android:onClick="onClickFragment"
            android:text="Videos"
            android:textColor="@color/white" />

How to cherry pick a range of commits and merge into another branch?

When it comes to a range of commits, cherry-picking is was not practical.

As mentioned below by Keith Kim, Git 1.7.2+ introduced the ability to cherry-pick a range of commits (but you still need to be aware of the consequence of cherry-picking for future merge)

git cherry-pick" learned to pick a range of commits
(e.g. "cherry-pick A..B" and "cherry-pick --stdin"), so did "git revert"; these do not support the nicer sequencing control "rebase [-i]" has, though.

damian comments and warns us:

In the "cherry-pick A..B" form, A should be older than B.
If they're the wrong order the command will silently fail.

If you want to pick the range B through D (including B) that would be B^..D (instead of B..D).
See "Git create branch from range of previous commits?" as an illustration.

As Jubobs mentions in the comments:

This assumes that B is not a root commit; you'll get an "unknown revision" error otherwise.

Note: as of Git 2.9.x/2.10 (Q3 2016), you can cherry-pick a range of commit directly on an orphan branch (empty head): see "How to make existing branch an orphan in git".


Original answer (January 2010)

A rebase --onto would be better, where you replay the given range of commit on top of your integration branch, as Charles Bailey described here.
(also, look for "Here is how you would transplant a topic branch based on one branch to another" in the git rebase man page, to see a practical example of git rebase --onto)

If your current branch is integration:

# Checkout a new temporary branch at the current location
git checkout -b tmp

# Move the integration branch to the head of the new patchset
git branch -f integration last_SHA-1_of_working_branch_range

# Rebase the patchset onto tmp, the old location of integration
git rebase --onto tmp first_SHA-1_of_working_branch_range~1 integration

That will replay everything between:

  • after the parent of first_SHA-1_of_working_branch_range (hence the ~1): the first commit you want to replay
  • up to "integration" (which points to the last commit you want to replay, from the working branch)

to "tmp" (which points to where integration was pointing before)

If there is any conflict when one of those commits is replayed:

  • either solve it and run "git rebase --continue".
  • or skip this patch, and instead run "git rebase --skip"
  • or cancel the all thing with a "git rebase --abort" (and put back the integration branch on the tmp branch)

After that rebase --onto, integration will be back at the last commit of the integration branch (that is "tmp" branch + all the replayed commits)

With cherry-picking or rebase --onto, do not forget it has consequences on subsequent merges, as described here.


A pure "cherry-pick" solution is discussed here, and would involve something like:

If you want to use a patch approach then "git format-patch|git am" and "git cherry" are your options.
Currently, git cherry-pick accepts only a single commit, but if you want to pick the range B through D that would be B^..D in git lingo, so

git rev-list --reverse --topo-order B^..D | while read rev 
do 
  git cherry-pick $rev || break 
done 

But anyway, when you need to "replay" a range of commits, the word "replay" should push you to use the "rebase" feature of Git.

MySQL joins and COUNT(*) from another table

SELECT DISTINCT groups.id, 
       (SELECT COUNT(*) FROM group_members
        WHERE member_id = groups.id) AS memberCount
FROM groups

How to check for the type of a template parameter?

I think todays, it is better to use, but only with C++17.

#include <type_traits>

template <typename T>
void foo() {
    if constexpr (std::is_same_v<T, animal>) {
        // use type specific operations... 
    } 
}

If you use some type specific operations in if expression body without constexpr, this code will not compile.

Disable time in bootstrap date time picker

Check the below snippet

<div class="container">
<div class="row">
    <div class='col-sm-6'>
        <div class="form-group">
            <div class='input-group date' id='datetimepicker4'>
                <input type='text' class="form-control" />
                <span class="input-group-addon"><span class="glyphicon glyphicon-time"></span>
                </span>
            </div>
        </div>
    </div>
    <script type="text/javascript">
        $(function() {              
           // Bootstrap DateTimePicker v4
           $('#datetimepicker4').datetimepicker({
                 format: 'DD/MM/YYYY'
           });
        });      
    </script>
</div>

You can refer http://eonasdan.github.io/bootstrap-datetimepicker/ for documentation and other functions in detail. This should work.

Update to support i18n

Use localized formats of moment.js:

  • L for date only
  • LT for time only
  • L LT for date and time

See other localized formats in the moment.js documentation (https://momentjs.com/docs/#/displaying/format/)

Android EditText Hint

To complete Sunit's answer, you can use a selector, not to the text string but to the textColorHint. You must add this attribute on your editText:

android:textColorHint="@color/text_hint_selector"

And your text_hint_selector should be:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:color="@android:color/transparent" />
    <item android:color="@color/hint_color" />
</selector>

Is there a performance difference between CTE , Sub-Query, Temporary Table or Table Variable?

#temp is materalized and CTE is not.

CTE is just syntax so in theory it is just a subquery. It is executed. #temp is materialized. So an expensive CTE in a join that is execute many times may be better in a #temp. On the other side if it is an easy evaluation that is not executed but a few times then not worth the overhead of #temp.

The are some people on SO that don't like table variable but I like them as the are materialized and faster to create than #temp. There are times when the query optimizer does better with a #temp compared to a table variable.

The ability to create a PK on a #temp or table variable gives the query optimizer more information than a CTE (as you cannot declare a PK on a CTE).

How to determine the encoding of text?

It is, in principle, impossible to determine the encoding of a text file, in the general case. So no, there is no standard Python library to do that for you.

If you have more specific knowledge about the text file (e.g. that it is XML), there might be library functions.

Laravel Eloquent Sum of relation's column

you can do it using eloquent easily like this

$sum = Model::sum('sum_field');

its will return a sum of fields, if apply condition on it that is also simple

$sum = Model::where('status', 'paid')->sum('sum_field');

Is it possible to make Font Awesome icons larger than 'fa-5x'?

Easy — just use Font Awesome 5's default fa-[size]x classes. You can scale icons up to 10x of the parent element's font-size Read the docs about icon sizing.

Examples:

<span class="fas fa-info-circle fa-6x"></span>
<span class="fas fa-info-circle fa-7x"></span>
<span class="fas fa-info-circle fa-8x"></span>
<span class="fas fa-info-circle fa-9x"></span>
<span class="fas fa-info-circle fa-10x"></span>

Export SQL query data to Excel

I see that you’re trying to export SQL data to Excel to avoid copy-pasting your very large data set into Excel.

You might be interested in learning how to export SQL data to Excel and update the export automatically (with any SQL database: MySQL, Microsoft SQL Server, PostgreSQL).

To export data from SQL to Excel, you need to follow 2 steps:

  • Step 1: Connect Excel to your SQL database? (Microsoft SQL Server, MySQL, PostgreSQL...)
  • Step 2: Import your SQL data into Excel

The result will be the list of tables you want to query data from your SQL database into Excel:

?

Step1: Connect Excel to an external data source: your SQL database

  1. Install An ODBC
  2. Install A Driver
  3. Avoid A Common Error
  4. Create a DSN

Step 2: Import your SQL data into Excel

  1. Click Where You Want Your Pivot Table
  2. Click Insert
  3. Click Pivot Table
  4. Click Use an external data source, then Choose Connection
  5. Click on the System DSN tab
  6. Select the DSN created in ODBC Manager
  7. Fill the requested username and password
  8. Avoid a Common Error
  9. Access The Microsoft Query Dialog Box
  10. Click on the arrow to see the list of tables in your database
  11. Select the table you want to query data from your SQL database into Excel
  12. Click on Return Data when you’re done with your selection

To update the export automatically, there are 2 additional steps:

  1. Create a Pivot Table with an external SQL data source
  2. Automate Your SQL Data Update In Excel With The GETPIVOTDATA Function

I’ve created a step-by-step tutorial about this whole process, from connecting Excel to SQL, up to having the whole thing automatically updated. You might find the detailed explanations and screenshots useful.

How do I dispatch_sync, dispatch_async, dispatch_after, etc in Swift 3, Swift 4, and beyond?

Swift 4.1 and 5. We use queues in many places in our code. So, I created Threads class with all queues. If you don't want to use Threads class you can copy the desired queue code from class methods.

class Threads {

  static let concurrentQueue = DispatchQueue(label: "AppNameConcurrentQueue", attributes: .concurrent)
  static let serialQueue = DispatchQueue(label: "AppNameSerialQueue")

  // Main Queue
  class func performTaskInMainQueue(task: @escaping ()->()) {
    DispatchQueue.main.async {
      task()
    }
  }

  // Background Queue
  class func performTaskInBackground(task:@escaping () throws -> ()) {
    DispatchQueue.global(qos: .background).async {
      do {
        try task()
      } catch let error as NSError {
        print("error in background thread:\(error.localizedDescription)")
      }
    }
  }

  // Concurrent Queue
  class func perfromTaskInConcurrentQueue(task:@escaping () throws -> ()) {
    concurrentQueue.async {
      do {
        try task()
      } catch let error as NSError {
        print("error in Concurrent Queue:\(error.localizedDescription)")
      }
    }
  }

  // Serial Queue
  class func perfromTaskInSerialQueue(task:@escaping () throws -> ()) {
    serialQueue.async {
      do {
        try task()
      } catch let error as NSError {
        print("error in Serial Queue:\(error.localizedDescription)")
      }
    }
  }

  // Perform task afterDelay
  class func performTaskAfterDealy(_ timeInteval: TimeInterval, _ task:@escaping () -> ()) {
    DispatchQueue.main.asyncAfter(deadline: (.now() + timeInteval)) {
      task()
    }
  }
}

Example showing the use of main queue.

override func viewDidLoad() {
    super.viewDidLoad()
     Threads.performTaskInMainQueue {
        //Update UI
    }
}

AngularJS Error: $injector:unpr Unknown Provider

Be sure that you load controller outsideapp.config. The following code may cause this error:

app.config(["$stateProvider", "$urlRouterProvider", function ($stateProvider, $urlRouterProvider) {
       var AuthCtrl = require('components/auth/AuthCtrl'); //NOTICE HERE
       $stateProvider.state('login',{
            url: "/users/login",
            templateUrl: require("components/auth/login.tpl.html"),
            controller: AuthCtrl // ERROR
        })
}))

To fix this error, we must move AuthCtrl to outsideapp.config:

var AuthCtrl = require('components/auth/AuthCtrl'); //NOTICE HERE
app.config(["$stateProvider", "$urlRouterProvider", function ($stateProvider, $urlRouterProvider) {
       $stateProvider.state('login',{
            url: "/users/login",
            templateUrl: require("components/auth/login.tpl.html"),
            controller: AuthCtrl // WORK
        });
}))

NumPy array is not JSON serializable

Here is an implementation that work for me and removed all nans (assuming these are simple object (list or dict)):

from numpy import isnan

def remove_nans(my_obj, val=None):
    if isinstance(my_obj, list):
        for i, item in enumerate(my_obj):
            if isinstance(item, list) or isinstance(item, dict):
                my_obj[i] = remove_nans(my_obj[i], val=val)

            else:
                try:
                    if isnan(item):
                        my_obj[i] = val
                except Exception:
                    pass

    elif isinstance(my_obj, dict):
        for key, item in my_obj.iteritems():
            if isinstance(item, list) or isinstance(item, dict):
                my_obj[key] = remove_nans(my_obj[key], val=val)

            else:
                try:
                    if isnan(item):
                        my_obj[key] = val
                except Exception:
                    pass

    return my_obj

How to read a file in other directory in python

Looks like you are trying to open a directory for reading as if it's a regular file. Many OSs won't let you do that. You don't need to anyway, because what you want (judging from your description) is

x_file = open(os.path.join(direct, "5_1.txt"), "r")  

or simply

x_file = open(direct+"/5_1.txt", "r")

Contain form within a bootstrap popover?

Either replace double quotes around type="text" with single quotes, Like

"<form><input type='text'/></form>"

OR

replace double quotes wrapping data-content with singe quotes, Like

data-content='<form><input type="text"/></form>'

scp with port number specified

You know what's cooler than -P? nothing

If you use this server more than a few times, setup/create a ~/.ssh/config file with an entry like:

Host www.myserver.com
    Port 80

or

Host myserver myserver80 short any.name.u.want yes_anything well-within-reason
    HostName www.myserver.com
    Port 80
    User username

Then you can use:

scp [email protected]:/root/file.txt .

or

scp short:/root/file.txt .

You can use anything on the "Host" line with ssh, scp, rsync, git & more

There are MANY configuration option that you can use in config files, see:

man ssh_config

Bash: Echoing a echo command with a variable in bash

echo "echo "we are now going to work with ${ser}" " >> $servfile

Escape all " within quotes with \. Do this with variables like \$servicetest too:

echo "echo \"we are now going to work with \${ser}\" " >> $servfile    
echo "read -p \"Please enter a service: \" ser " >> $servfile
echo "if [ \$servicetest > /dev/null ];then " >> $servfile

How to calculate mean, median, mode and range from a set of numbers

Here's the complete clean and optimised code in JAVA 8

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

public class Solution {

public static void main(String[] args) {

    /*Take input from user*/
    Scanner sc = new Scanner(System.in);

    int n =0;
    n = sc.nextInt();
    
    int arr[] = new int[n];
    
    //////////////mean code starts here//////////////////
    int sum = 0;
    for(int i=0;i<n; i++)
    {
         arr[i] = sc.nextInt();
         sum += arr[i]; 
    }
    System.out.println((double)sum/n); 
    //////////////mean code ends here//////////////////


    //////////////median code starts here//////////////////
    Arrays.sort(arr);
    int val = arr.length/2;
    System.out.println((arr[val]+arr[val-1])/2.0); 
    //////////////median code ends here//////////////////


    //////////////mode code starts here//////////////////
    int maxValue=0;
    int maxCount=0;

    for(int i=0; i<n; ++i)
    {
        int count=0;

        for(int j=0; j<n; ++j)
        {
            if(arr[j] == arr[i])
            {
                ++count;
            }

            if(count > maxCount)
            {
                maxCount = count;
                maxValue = arr[i];
            }
        }
    } 
    System.out.println(maxValue);
   //////////////mode code ends here//////////////////

  }

}

Hibernate openSession() vs getCurrentSession()

If we talk about SessionFactory.openSession()

  • It always creates a new Session object.
  • You need to explicitly flush and close session objects.
  • In single threaded environment it is slower than getCurrentSession().
  • You do not need to configure any property to call this method.

And If we talk about SessionFactory.getCurrentSession()

  • It creates a new Session if not exists, else uses same session which is in current hibernate context.
  • You do not need to flush and close session objects, it will be automatically taken care by Hibernate internally.
  • In single threaded environment it is faster than openSession().
  • You need to configure additional property. "hibernate.current_session_context_class" to call getCurrentSession() method, otherwise it will throw an exception.

How to execute a java .class from the command line

If you have in your java source

package mypackage;

and your class is hello.java with

public class hello {

and in that hello.java you have

 public static void main(String[] args) {

Then (after compilation) changeDir (cd) to the directory where your hello.class is. Then

java -cp . mypackage.hello

Mind the current directory and the package name before the class name. It works for my on linux mint and i hope on the other os's also

Thanks Stack overflow for a wealth of info.

Reverse the ordering of words in a string

One way to do this is to parse each word of our input string and push it into a LIFO stack.

After whole string is processed, we pop out each word off the stack one by one and append it to a StringBuffer class object, which finally contains the reversed input string.

This is one possible solution in Java using StringTokenizer and Stack class. We need to import java.util.Stack.

public String revString(String input)
{
   StringTokenizer words=new StringTokenizer(input); //Split the string into words
   Stack<String> stack= new Stack<String>();
   while(words.hasMoreTokens())
   {
      stack.push(words.nextElement().toString()); // Push each word of the string onto stack. 
   }
   StringBuilder revString=new StringBuilder();
   while(!stack.empty())
   {
       revString.append(stack.pop()+" ");// pop the top item and append it to revString 
   }
   return revString.toString();
}

How can I convert a file pointer ( FILE* fp ) to a file descriptor (int fd)?

Even if fileno(FILE *) may return a file descriptor, be VERY careful not to bypass stdio's buffer. If there is buffer data (either read or unflushed write), reads/writes from the file descriptor might give you unexpected results.

To answer one of the side questions, to convert a file descriptor to a FILE pointer, use fdopen(3)

What is C# analog of C++ std::pair?

Unfortunately, there is none. You can use the System.Collections.Generic.KeyValuePair<K, V> in many situations.

Alternatively, you can use anonymous types to handle tuples, at least locally:

var x = new { First = "x", Second = 42 };

The last alternative is to create an own class.

Get lengths of a list in a jinja2 template

<span>You have {{products|length}} products</span>

You can also use this syntax in expressions like

{% if products|length > 1 %}

jinja2's builtin filters are documented here; and specifically, as you've already found, length (and its synonym count) is documented to:

Return the number of items of a sequence or mapping.

So, again as you've found, {{products|count}} (or equivalently {{products|length}}) in your template will give the "number of products" ("length of list")

ImportError: No module named google.protobuf

The reason for this would be mostly due to the evil command pip install google. I was facing a similar issue for google-cloud, but the same steps are true for protobuf as well. Both of our issues deal with a namespace conflict over the 'google' namespace.

If you executed the pip install google command like I did then you are in the correct place. The google package is actually not owned by Google which can be confirmed by the command pip show google which outputs:

 Name: google
 Version: 1.9.3
 Summary: Python bindings to the Google search engine.
 Home-page: http://breakingcode.wordpress.com/
 Author: Mario Vilas
 Author-email: [email protected]
 License: UNKNOWN
 Location: <Path where this package is installed>
 Requires: beautifulsoup4

Because of this package, the google namespace is reserved and coincidentally google-cloud also expects namespace google > cloud and it results in a namespace collision for these two packages.

See in below screenshot namespace of google-protobuf as google > protobuf

google-cloud namespace screenshot google > cloud > datastore

Solution :- Unofficial google package need to be uninstalled which can be done by using pip uninstall google after this you can reinstall google-cloud using pip install google-cloud or protobuf using pip install protobuf

FootNotes :- Assuming you have installed the unofficial google package by mistake and you don't actually need it along with google-cloud package. If you need both unofficial google and google-cloud above solution won't work.

Furthermore, the unofficial 'google' package installs with it 'soupsieve' and 'beautifulsoup4'. You may want to also uninstall those packages.

Let me know if this solves your particular issue.

Offline Speech Recognition In Android (JellyBean)

I would like to improve the guide that the answer https://stackoverflow.com/a/17674655/2987828 sends to its users, with images. It is the sentence "For those that it doesn't, this is the ‘guide’ I supply them with." that I want to improve.

The user should click on the four buttons highlighted in blue in these images:

Go to your Android Application Settings, select Languages and input, edit Settings of Google Voice typing, select Download Offline speech recognition, select your languages in the ALL tab.

Then the user can select any desired languages. When the download is done, he should disconnect from network, and then click on the "microphone" button of the keyboard.

It worked for me (android 4.1.2), then language recognition worked out of the box, without rebooting. I can now dictates instructions to the shell of Terminal Emulator ! And it is twice faster offline than online, on a padfone 2 from ASUS.

These images are licensed under cc by-sa 3.0 with attribution required to stackoverflow.com/a/21329845/2987828 ; you may hence add these images anywhere along with this attribution.

(This the standard policy of all images and texts at stackoverflow.com)

How to get Rails.logger printing to the console/stdout when running rspec?

For Rails 4.x the log level is configured a bit different than in Rails 3.x

Add this to config/environment/test.rb

# Enable stdout logger
config.logger = Logger.new(STDOUT)

# Set log level
config.log_level = :ERROR

The logger level is set on the logger instance from config.log_level at: https://github.com/rails/rails/blob/v4.2.4/railties/lib/rails/application/bootstrap.rb#L70

Environment variable

As a bonus, you can allow overwriting the log level using an environment variable with a default value like so:

# default :ERROR
config.log_level = ENV.fetch("LOG_LEVEL", "ERROR")

And then running tests from shell:

# Log level :INFO (the value is uppercased in bootstrap.rb)
$ LOG_LEVEL=info rake test

# Log level :ERROR
$ rake test

json_encode sparse PHP array as JSON array, not JSON object

json_decode($jsondata, true);

true turns all properties to array (sequential or not)

Share data between html pages

Well, you can actually send data via JavaScript - but you should know that this is the #1 exploit source in web pages as it's XSS :)

I personally would suggest to use an HTML formular instead and modify the javascript data on the server side.

But if you want to share between two pages (I assume they are not both on localhost, because that won't make sense to share between two both-backend-driven pages) you will need to specify the CORS headers to allow the browser to send data to the whitelisted domains.

These two links might help you, it shows the example via Node backend, but you get the point how it works:

Link 1

And, of course, the CORS spec:

Link 2

~Cheers

Getting Chrome to accept self-signed localhost certificate

None of the answers above helped me on Windows 10 when testing locally on

https://localhost:<port>.

However I found this page, indicating another flag to pass:

https://www.chromium.org/blink/serviceworker/service-worker-faq

If you want to test on https://localhost with a self-signed certificate, do:

$ ./chrome --allow-insecure-localhost https://localhost

That did not get rid of the red warning, but it did enable me to use https-only feature like service workers and web push notifications.

PHP foreach loop through multidimensional array

<?php
$first = reset($arr_nav); // Get the first element
$last  = end($arr_nav);   // Get the last element
// Ensure that we have a first element and that it's an array
if(is_array($first)) { 
   $first['class'] = 'first';
}
// Ensure we have a last element and that it differs from the first
if(is_array($last) && $last !== $first) {
   $last['class'] = 'last';
}

Now you could just echo the class inside you html-generator. Would probably need some kind of check to ensure that the class is set, or provide a default empty class to the array.

How do I call REST API from an android app?

  1. If you want to integrate Retrofit (all steps defined here):

Goto my blog : retrofit with kotlin

  1. Please use android-async-http library.

the link below explains everything step by step.

http://loopj.com/android-async-http/

Here are sample apps:

  1. http://www.techrepublic.com/blog/software-engineer/calling-restful-services-from-your-android-app/

  2. http://blog.strikeiron.com/bid/73189/Integrate-a-REST-API-into-Android-Application-in-less-than-15-minutes

Create a class :

public class HttpUtils {
  private static final String BASE_URL = "http://api.twitter.com/1/";
 
  private static AsyncHttpClient client = new AsyncHttpClient();

  public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.get(getAbsoluteUrl(url), params, responseHandler);
  }

  public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.post(getAbsoluteUrl(url), params, responseHandler);
  }
      
  public static void getByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.get(url, params, responseHandler);
  }

  public static void postByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.post(url, params, responseHandler);
  }

  private static String getAbsoluteUrl(String relativeUrl) {
      return BASE_URL + relativeUrl;
  }
}

Call Method :

    RequestParams rp = new RequestParams();
    rp.add("username", "aaa"); rp.add("password", "aaa@123");
                    
    HttpUtils.post(AppConstant.URL_FEED, rp, new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            // If the response is JSONObject instead of expected JSONArray
            Log.d("asd", "---------------- this is response : " + response);
            try {
                JSONObject serverResp = new JSONObject(response.toString());                                                
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }                   
        }
            
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
            // Pull out the first event on the public timeline
                    
        }
    });

Please grant internet permission in your manifest file.

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

you can add compile 'com.loopj.android:android-async-http:1.4.9' for Header[] and compile 'org.json:json:20160212' for JSONObject in build.gradle file if required.

jQuery Ajax POST example with PHP

If you want to send data using jQuery Ajax then there is no need of form tag and submit button

Example:

<script>
    $(document).ready(function () {
        $("#btnSend").click(function () {
            $.ajax({
                url: 'process.php',
                type: 'POST',
                data: {bar: $("#bar").val()},
                success: function (result) {
                    alert('success');
                }
            });
        });
    });
</script>

<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input id="btnSend" type="button" value="Send" />

List all virtualenv

Run workon with no argument to list available environments.

How to make popup look at the centre of the screen?

These are the changes to make:

CSS:

#container {
    width: 100%;
    height: 100%;
    top: 0;
    position: absolute;
    visibility: hidden;
    display: none;
    background-color: rgba(22,22,22,0.5); /* complimenting your modal colors */
}
#container:target {
    visibility: visible;
    display: block;
}
.reveal-modal {
    position: relative;
    margin: 0 auto;
    top: 25%;
}
    /* Remove the left: 50% */

HTML:

<a href="#container">Reveal</a>
<div id="container">
    <div id="exampleModal" class="reveal-modal">
    ........
    <a href="#">Close Modal</a>
    </div>
</div>

JSFiddle - Updated with CSS only

IPC performance: Named Pipe vs Socket

As often, numbers says more than feeling, here are some data: Pipe vs Unix Socket Performance (opendmx.net).

This benchmark shows a difference of about 12 to 15% faster speed for pipes.

How to add image that is on my computer to a site in css or html?

Upload the image on your server or in images hosting site where you get image link and then add the line on your website page where you get that image the line is

<img src="paste here your image full path"/>

What is mutex and semaphore in Java ? What is the main difference?

The object of synchronization Semaphore implements a classical traffic light. A traffic light controls access to a resource shared by a counter. If the counter is greater than zero, access is granted; If it is zero, access is denied. The counter counts the permissions that allow access to the shared resource. Then, to access the resource, a thread must receive permission from the traffic light. In general, to use a traffic light, the thread that wants to access the shared resource tries to acquire a permit. If the traffic light count is greater than zero, the thread acquires a permit, and the traffic light count is decremented. Otherwise the thread is locked until it can get a permission. When the thread no longer needs to access the shared resource, it releases the permission, so the traffic light count is increased. If there is another thread waiting for a permit, it acquires a permit at that time. The Semaphore class of Java implements this mechanism.

Semaphore has two builders:

Semaphore(int num)
Semaphore(int num, boolean come)

num specifies the initial count of the permit. Then num specifies the number of threads that can access a shared resource at a given time. If num is one, it can access the resource one thread at a time. By setting come as true, you can guarantee that the threads you are waiting for are granted permission in the order they requested.

laravel Eloquent ORM delete() method

At first,

You should know that destroy() is correct method for removing an entity directly via object or model and delete() can only be called in query builder.

In your case, You have not checked if record exists in database or not. Record can only be deleted if exists.

So, You can do it like follows.

$user = User::find($id);
    if($user){
        $destroy = User::destroy(2);
    }

The value or $destroy above will be 0 or 1 on fail or success respectively. So, you can alter the $data array like:

if ($destroy){

    $data=[
        'status'=>'1',
        'msg'=>'success'
    ];

}else{

    $data=[
        'status'=>'0',
        'msg'=>'fail'
    ];

}

Hope, you understand.

Passing variables in remote ssh command

If you use

ssh [email protected] "~/tools/run_pvt.pl $BUILD_NUMBER"

instead of

ssh [email protected] '~/tools/run_pvt.pl $BUILD_NUMBER'

your shell will interpolate the $BUILD_NUMBER before sending the command string to the remote host.

How to configure log4j with a properties file

I believe that the configure method expects an absolute path. Anyhow, you may also try to load a Properties object first:

Properties props = new Properties();
props.load(new FileInputStream("log4j.properties"));
PropertyConfigurator.configure(props);

If the properties file is in the jar, then you could do something like this:

Properties props = new Properties();
props.load(getClass().getResourceAsStream("/log4j.properties"));
PropertyConfigurator.configure(props);

The above assumes that the log4j.properties is in the root folder of the jar file.

Reducing video size with same format and reducing frame size

There is an application for both Mac & Windows call Handbrake, i know this isn't command line stuff but for a quick open file - select output file format & rough output size whilst keeping most of the good stuff about the video then this is good, it's a just a graphical view of ffmpeg at its best ... It does support command line input for those die hard texters.. https://handbrake.fr/downloads.php

How do I fetch lines before/after the grep result in bash?

The way to do this is near the top of the man page

grep -i -A 10 'error data'

Array of structs example

You've started right - now you just need to fill the each student structure in the array:

struct student
{
    public int s_id;
    public String s_name, c_name, dob;
}
class Program
{
    static void Main(string[] args)
    {
        student[] arr = new student[4];

        for(int i = 0; i < 4; i++)
        {
            Console.WriteLine("Please enter StudentId, StudentName, CourseName, Date-Of-Birth");


            arr[i].s_id = Int32.Parse(Console.ReadLine());
            arr[i].s_name = Console.ReadLine();
            arr[i].c_name = Console.ReadLine();
            arr[i].s_dob = Console.ReadLine();
       }
    }
}

Now, just iterate once again and write these information to the console. I will let you do that, and I will let you try to make program to take any number of students, and not just 4.

Error: allowDefinition='MachineToApplication' beyond application level

In Visual Studio 2013 I struggled with this for a while and it is pretty much easy to solve just follow what the exceptions says "virtual directory not being configured as an application in IIS"

In my case I had WebService planted inside IIS website so

  1. I opened the website in IIS manager
  2. right clicked the WCF folder
  3. clicked Convert to Application
  4. and then submitted with Ok

WCF is back and running.

How to render a DateTime object in a Twig template

Although you can use the

{{ game.gameDate|date('Y-m-d') }}

approach, keep in mind that this version does not honor the user locale, which should not be a problem with a site used by only users of one nationality. International users should display the game date totally different, like extending the \DateTime class, and adding a __toString() method to it that checks the locale and acts accordingly.

Edit:

As pointed out by @Nic in a comment, if you use the Intl extension of Twig, you will have a localizeddate filter available, which shows the date in the user’s locale. This way you can drop my previous idea of extending \DateTime.

Memcached vs. Redis?

One major difference that hasn't been pointed out here is that Memcache has an upper memory limit at all times, while Redis does not by default (but can be configured to). If you would always like to store a key/value for certain amount of time (and never evict it because of low memory) you want to go with Redis. Of course, you also risk the issue of running out of memory...

.bashrc at ssh login

I had similar situation like Hobhouse. I wanted to use command

 ssh myhost.com 'some_command'

and 'some_command' exists in '/var/some_location' so I tried to append '/var/some_location' in PATH environment by editing '$HOME/.bashrc'

but that wasn't working. because default .bashrc(Ubuntu 10.4 LTS) prevent from sourcing by code like below

# If not running interactively, don't do anything
[ -z "$PS1" ] && return

so If you want to change environment for ssh non-login shell. you should add code above that line.

How do I set the request timeout for one controller action in an asp.net mvc application

You can set this programmatically in the controller:-

HttpContext.Current.Server.ScriptTimeout = 300;

Sets the timeout to 5 minutes instead of the default 110 seconds (what an odd default?)

How can I list all collections in the MongoDB shell?

 1. show collections; // Display all collections
 2. show tables     // Display all collections
 3. db.getCollectionNames();   // Return array of collection. Example :[ "orders", "system.profile" ]

Detailed information for every collection:

db.runCommand( { listCollections: 1.0, authorizedCollections: true, nameOnly: true } )
  • For users with the required access (privileges that grant listCollections action on the database), the method lists the names of all collections for the database.
  • For users without the required access, the method lists only the collections for which the users has privileges. For example, if a user has find on a specific collection in a database, the method would return just that collection.

To list collections list based on a search string.

db.getCollectionNames().filter(function (CollectionName) { return /<Search String>/.test(CollectionName) })

Example: Find all collection having "import" in the name

db.getCollectionNames().filter(function (CollectionName) { return /import/.test(CollectionName) })

How to check if $? is not equal to zero in unix shell scripting?

<run your last command on this line>
a=${?}
if [ ${a} -ne 0 ]; then echo "do something"; fi

use whatever command you want to use instead of the echo "do something" command

Add horizontal scrollbar to html table

Insert the table inside a div, so the table will take full length

HTML

<div class="scroll">
 <table>  </table>
</div>   

CSS

.scroll{
    overflow-x: auto;
    white-space: nowrap;
}

How to convert webpage into PDF by using Python

thanks to below posts, and I am able to add on the webpage link address to be printed and present time on the PDF generated, no matter how many pages it has.

Add text to Existing PDF using Python

https://github.com/disflux/django-mtr/blob/master/pdfgen/doc_overlay.py

To share the script as below:

import time
from pyPdf import PdfFileWriter, PdfFileReader
import StringIO
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
from xhtml2pdf import pisa
import sys 
from PyQt4.QtCore import *
from PyQt4.QtGui import * 
from PyQt4.QtWebKit import * 

url = 'http://www.yahoo.com'
tem_pdf = "c:\\tem_pdf.pdf"
final_file = "c:\\younameit.pdf"

app = QApplication(sys.argv)
web = QWebView()
#Read the URL given
web.load(QUrl(url))
printer = QPrinter()
#setting format
printer.setPageSize(QPrinter.A4)
printer.setOrientation(QPrinter.Landscape)
printer.setOutputFormat(QPrinter.PdfFormat)
#export file as c:\tem_pdf.pdf
printer.setOutputFileName(tem_pdf)

def convertIt():
    web.print_(printer)
    QApplication.exit()

QObject.connect(web, SIGNAL("loadFinished(bool)"), convertIt)

app.exec_()
sys.exit

# Below is to add on the weblink as text and present date&time on PDF generated

outputPDF = PdfFileWriter()
packet = StringIO.StringIO()
# create a new PDF with Reportlab
can = canvas.Canvas(packet, pagesize=letter)
can.setFont("Helvetica", 9)
# Writting the new line
oknow = time.strftime("%a, %d %b %Y %H:%M")
can.drawString(5, 2, url)
can.drawString(605, 2, oknow)
can.save()

#move to the beginning of the StringIO buffer
packet.seek(0)
new_pdf = PdfFileReader(packet)
# read your existing PDF
existing_pdf = PdfFileReader(file(tem_pdf, "rb"))
pages = existing_pdf.getNumPages()
output = PdfFileWriter()
# add the "watermark" (which is the new pdf) on the existing page
for x in range(0,pages):
    page = existing_pdf.getPage(x)
    page.mergePage(new_pdf.getPage(0))
    output.addPage(page)
# finally, write "output" to a real file
outputStream = file(final_file, "wb")
output.write(outputStream)
outputStream.close()

print final_file, 'is ready.'

How does the bitwise complement operator (~ tilde) work?

It's easy:

Before starting please remember that 
 1  Positive numbers are represented directly into the memory.
 2. Whereas, negative numbers are stored in the form of 2's compliment.
 3. If MSB(Most Significant bit) is 1 then the number is negative otherwise number is 
    positive.

You are finding ~2:

Step:1 Represent 2 in a binary format 
       We will get, 0000 0010
Step:2 Now we have to find ~2(means 1's compliment of 2)
                  1's compliment       
       0000 0010 =================> 1111 1101 

       So, ~2 === 1111 1101, Here MSB(Most significant Bit) is 1(means negative value). So, 
       In memory it will be represented as 2's compliment(To find 2's compliment first we 
       have to find 1's compliment and then add 1 to it.)
Step3:  Finding 2's compliment of ~2 i.e 1111 1101

                   1's compliment                   Adding 1 to it
        1111 1101 =====================> 0000 0010 =================> 0000 0010
                                                                      +       1
                                                                      ---------
                                                                      0000 0011 
        So, 2's compliment of 1111 1101, is 0000 0011 

Step4:  Converting back to decimal format.
                   binary format
        0000 0011 ==============> 3
        
       In step2: we have seen that the number is negative number so the final answer would  
       be -3
                                    
                                So, ~2 === -3

TSQL DATETIME ISO 8601

When dealing with dates in SQL Server, the ISO-8601 format is probably the best way to go, since it just works regardless of your language and culture settings.

In order to INSERT data into a SQL Server table, you don't need any conversion codes or anything at all - just specify your dates as literal strings

INSERT INTO MyTable(DateColumn) VALUES('20090430 12:34:56.790')

and you're done.

If you need to convert a date column to ISO-8601 format on SELECT, you can use conversion code 126 or 127 (with timezone information) to achieve the ISO format.

SELECT CONVERT(VARCHAR(33), DateColumn, 126) FROM MyTable

should give you:

2009-04-30T12:34:56.790

How to vertical align an inline-block in a line of text?

display: inline-block is your friend you just need all three parts of the construct - before, the "block", after - to be one, then you can vertically align them all to the middle:

Working Example

(it looks like your picture anyway ;))

CSS:

p, div {
  display: inline-block; 
  vertical-align: middle;
}
p, div {
  display: inline !ie7; /* hack for IE7 and below */
}

table {
  background: #000; 
  color: #fff; 
  font-size: 16px; 
  font-weight: bold; margin: 0 10px;
}

td {
  padding: 5px; 
  text-align: center;
}

HTML:

<p>some text</p> 
<div>
  <table summary="">
  <tr><td>A</td></tr>
  <tr><td>B</td></tr>
  <tr><td>C</td></tr>
  <tr><td>D</td></tr>
  </table>
</div> 
<p>continues afterwards</p>

Access-control-allow-origin with multiple domains

There can only be one Access-Control-Allow-Origin response header, and that header can only have one origin value. Therefore, in order to get this to work, you need to have some code that:

  1. Grabs the Origin request header.
  2. Checks if the origin value is one of the whitelisted values.
  3. If it is valid, sets the Access-Control-Allow-Origin header with that value.

I don't think there's any way to do this solely through the web.config.

if (ValidateRequest()) {
    Response.Headers.Remove("Access-Control-Allow-Origin");
    Response.AddHeader("Access-Control-Allow-Origin", Request.UrlReferrer.GetLeftPart(UriPartial.Authority));

    Response.Headers.Remove("Access-Control-Allow-Credentials");
    Response.AddHeader("Access-Control-Allow-Credentials", "true");

    Response.Headers.Remove("Access-Control-Allow-Methods");
    Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
}

Extract parameter value from url using regular expressions

I use seperate custom functions which gets all URL Parameters and URL parts . For URL parameters, (which is the final part of an URI String, http://domain.tld/urlpart/?x=a&y=b

    function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
        vars[key] = value;
    });
    return vars;
    }

The above function will return an array consisting of url variables.

For URL Parts or functions, (which is http://domain.tld/urlpart/?x=a&y=b I use a simple uri split,

function getUrlParams() { 
    var vars = {};
    var parts = window.location.href.split('/' );
    return parts;
}

You can even combine them both to be able to use with a single call in a page or in javascript.

Add newly created specific folder to .gitignore in Git

It's /public_html/stats/*.

$ ~/myrepo> ls public_html/stats/
bar baz foo
$ ~/myrepo> cat .gitignore 
public_html/stats/*
$ ~/myrepo> git status
# On branch master
#
# Initial commit
#
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#   .gitignore
nothing added to commit but untracked files present (use "git add" to track)
$ ~/myrepo>

What is logits, softmax and softmax_cross_entropy_with_logits?

Whatever goes to softmax is logit, this is what J. Hinton repeats in coursera videos all the time.

How to include duplicate keys in HashMap?

Map does not supports duplicate keys. you can use collection as value against same key.

Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for the key, the old value is replaced by the specified value.

Documentation

you can use any kind of List or Set implementation according to your requirement.

If your values might be also duplicate you can go with ArrayList or LinkedList, in case values are unique you can use HashSet or TreeSet etc.


Also In google guava collection library Multimap is available, it is a collection that maps keys to values, similar to Map, but in which each key may be associated with multiple values. You can visualize the contents of a multimap either as a map from keys to nonempty collections of values:

a ? 1, 2
b ? 3  

Example -

ListMultimap<String, String> multimap = ArrayListMultimap.create();
multimap.put("a", "1");
multimap.put("a", "2");
multimap.put("c", "3");

Picasso v/s Imageloader v/s Fresco vs Glide

Fresco sources | off site
(-)

  • Huge size of library
  • No Callback with View, Bitmap parameters
  • SimpleDraweeView doesn't support wrap_content
  • Huge size of cache
    (+)
  • Pretty fast image loader (for small && medium images)
  • A lot of functionality(streaming, drawing tools, memory management, etc)
  • Possibility to setup directly in xml (for example round corners)
  • GIF support
  • WebP and Animated Webp support


Picasso sources | off site
(-)

  • Slow loading big images from internet into ListView
    (+)
  • Tinny size of library
  • Small size of cache
  • Simple to use
  • UI does not freeze
  • WebP support


Glide sources

(-)

  • Big size of library
    (+)
  • Tinny size of cache
  • Simple to use
  • GIF support
  • WebP support
  • Fast loading big images from internet into ListView
  • UI does not freeze
  • BitmapPool to re-use memory and thus lesser GC events


Universal Image Loader sources

(-)

  • Limited functionality (limited image processing)
  • Project support has stopped since 27.11.2015
    (+)
  • Tinny size of library
  • Simple to use

Tested by me on SGS2 (Android 4.1) (WiFi 8.43 Mbps)
Official versions for Java, not for Xamarin!
October 19 2015

I prefer to use Glide.
Read more here.
How to write cache to External Storage (SD Card) with Glide.

Selenium 2.53 not working on Firefox 47

I can confirm that selenium 2.53.6 works with firefox 44 for me on ubuntu 15.

How do I make Visual Studio pause after executing a console application in debug mode?

I just copied from http://social.msdn.microsoft.com/forums/en-US/Vsexpressvc/thread/1555ce45-8313-4669-a31e-b95b5d28c787/?prof=required:

The following works for me :-)

/////////////////////////////////////////////////////////////////////////////////////

Here is another reason the console may disappear. And the solution:

With the new Visual Studio 2010 you might see this behavior even when you use Ctrl + F5 aka "start without debugging". This is most likely because you created an "empty project" instead of a "Win32 console application". If you create the project as a "Win32 console application" you can disregard this as it does not apply.

In the older versions it would default to the console subsystem even if you selected "empty project", but not in Visual Studio 2010, so you have to set it manually. To do this select the project in the solution explorer on the right or left (probably is already selected so you don't have to worry about this).

Then select "project" from the menu bar drop down menus, then select "project_name properties" ? "configuration properties" ? "linker" ? "system" and set the first property, the drop down "subsystem" property to "console (/SUBSYSTEM:CONSOLE)". The console window should now stay open after execution as usual.

/////////////////////////////////////////////////////////////////////////////////////

How to avoid variable substitution in Oracle SQL Developer with 'trinidad & tobago'

Call this before the query:

set define off;

Alternatively, hacky:

update t set country = 'Trinidad and Tobago' where country = 'trinidad &' || ' tobago';

From Tuning SQL*Plus:

SET DEFINE OFF disables the parsing of commands to replace substitution variables with their values.

How to manually include external aar package using new Gradle Android Build System

before(default)

implementation fileTree(include: ['*.jar'], dir: 'libs')

just add '*.aar' in include array.

implementation fileTree(include: ['*.jar', '*.aar'], dir: 'libs')

it works well on Android Studio 3.x.

if you want ignore some library? do like this.

implementation fileTree(include: ['*.jar', '*.aar'], exclude: 'test_aar*', dir: 'libs')
debugImplementation files('libs/test_aar-debug.aar')
releaseImplementation files('libs/test_aar-release.aar')

Convert absolute path into relative path given a current directory using Bash

Guess this one shall do the trick too... (comes with built-in tests) :)

OK, some overhead expected, but we're doing Bourne shell here! ;)

#!/bin/sh

#
# Finding the relative path to a certain file ($2), given the absolute path ($1)
# (available here too http://pastebin.com/tWWqA8aB)
#
relpath () {
  local  FROM="$1"
  local    TO="`dirname  $2`"
  local  FILE="`basename $2`"
  local  DEBUG="$3"

  local FROMREL=""
  local FROMUP="$FROM"
  while [ "$FROMUP" != "/" ]; do
    local TOUP="$TO"
    local TOREL=""
    while [ "$TOUP" != "/" ]; do
      [ -z "$DEBUG" ] || echo 1>&2 "$DEBUG$FROMUP =?= $TOUP"
      if [ "$FROMUP" = "$TOUP" ]; then
        echo "${FROMREL:-.}/$TOREL${TOREL:+/}$FILE"
        return 0
      fi
      TOREL="`basename $TOUP`${TOREL:+/}$TOREL"
      TOUP="`dirname $TOUP`"
    done
    FROMREL="..${FROMREL:+/}$FROMREL"
    FROMUP="`dirname $FROMUP`"
  done
  echo "${FROMREL:-.}${TOREL:+/}$TOREL/$FILE"
  return 0
}

relpathshow () {
  echo " - target $2"
  echo "   from   $1"
  echo "   ------"
  echo "   => `relpath $1 $2 '      '`"
  echo ""
}

# If given 2 arguments, do as said...
if [ -n "$2" ]; then
  relpath $1 $2

# If only one given, then assume current directory
elif [ -n "$1" ]; then
  relpath `pwd` $1

# Otherwise perform a set of built-in tests to confirm the validity of the method! ;)
else

  relpathshow /usr/share/emacs22/site-lisp/emacs-goodies-el \
              /usr/share/emacs22/site-lisp/emacs-goodies-el/filladapt.el

  relpathshow /usr/share/emacs23/site-lisp/emacs-goodies-el \
              /usr/share/emacs22/site-lisp/emacs-goodies-el/filladapt.el

  relpathshow /usr/bin \
              /usr/share/emacs22/site-lisp/emacs-goodies-el/filladapt.el

  relpathshow /usr/bin \
              /usr/share/emacs22/site-lisp/emacs-goodies-el/filladapt.el

  relpathshow /usr/bin/share/emacs22/site-lisp/emacs-goodies-el \
              /etc/motd

  relpathshow / \
              /initrd.img
fi

is there a css hack for safari only NOT chrome?

I like to use the following method:

var isSafari = /Safari/.test(navigator.userAgent) && /Apple Computer/.test(navigator.vendor);
if (isSafari) { 
  $('head').append('<link rel="stylesheet" type="text/css" href="path/to/safari.css">') 
};

SQL left join vs multiple tables on FROM line?

Well the first and second queries may yield different results because a LEFT JOIN includes all records from the first table, even if there are no corresponding records in the right table.

Adding an item to an associative array

You can simply do this

$data += array($category => $question);

If your're running on php 5.4+

$data += [$category => $question];

Recommendations of Python REST (web services) framework?

I am not an expert on the python world but I have been using django which is an excellent web framework and can be used to create a restful framework.

Generate random string/characters in JavaScript

How about something like this: Date.now().toString(36) Not very random, but short and quite unique every time you call it.

How to hide Bootstrap previous modal when you opening new one?

You hide Bootstrap modals with:

$('#modal').modal('hide');

Saying $().hide() makes the matched element invisible, but as far as the modal-related code is concerned, it's still there. See the Methods section in the Modals documentation.

What is the best way to seed a database in Rails?

Rails has a built in way to seed data as explained here.

Another way would be to use a gem for more advanced or easy seeding such as: seedbank.

The main advantage of this gem and the reason I use it is that it has advanced capabilities such as data loading dependencies and per environment seed data.

Adding an up to date answer as this answer was first on google.

How to apply color in Markdown?

Run the following in zeppelin paragraph

%md ### <span style="color:red">text</span>

How to check compiler log in sql developer?

I can also use

show errors;

In sql worksheet.

GIT: Checkout to a specific folder

Adrian's answer threw "fatal: This operation must be run in a work tree." The following is what worked for us.

git worktree add <new-dir> --no-checkout --detach
cd <new-dir>
git checkout <some-ref> -- <existing-dir>

Notes:

  • --no-checkout Do not checkout anything into the new worktree.
  • --detach Do not create a new branch for the new worktree.
  • <some-ref> works with any ref, for instance, it works with HEAD~1.
  • Cleanup with git worktree prune.

ThreadStart with parameters

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ConsoleApp6
{
    class Program
    {
        static void Main(string[] args)
        {

            int x = 10;
            Thread t1 =new Thread(new ParameterizedThreadStart(order1));
            t1.Start(x);

            Thread t2=new Thread(order2);
            t2.Priority = ThreadPriority.Highest;
            t2.Start();

            Console.ReadKey();
        }//Main

        static void  order1(object args)
        {
            int x = (int)args;


            for (int i = 0; i < x; i++)
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.Write(i.ToString() + " ");
            }
        }

        static void order2()
        {
            for (int i = 100; i > 0; i--)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.Write(i.ToString() + " ");
            }
        }
    }
}

How to attach source or JavaDoc in eclipse for any jar file e.g. JavaFX?

This trick worked for me in Eclipse Luna (4.4.2): For a jar file I am using (htsjdk), I packed the source in a separate jar file (named htsjdk-2.0.1-src.jar; I could do this since htsjdk is open source) and stored it in the lib-src folder of my project. In my own Java source I selected an element I was using from the jar and hit F3 (Open declaration). Eclipse opened the class file and showed the button "Attach source". I clicked the button and pointed to the src jar file I had just put into the lib-src folder. Now I get the Javadoc when hovering over anything I’m using from the jar.

Markdown open a new window link

You can edit the generated markup and add

target = "_blank"

Archive the artifacts in Jenkins

An artifact can be any result of your build process. The important thing is that it doesn't matter on which client it was built it will be tranfered from the workspace back to the master (server) and stored there with a link to the build. The advantage is that it is versionized this way, you only have to setup backup on your master and that all artifacts are accesible via the web interface even if all build clients are offline.

It is possible to define a regular expression as the artifact name. In my case I zipped all the files I wanted to store in one file with a constant name during the build.

How to log cron jobs?

* * * * * myjob.sh >> /var/log/myjob.log 2>&1

will log all output from the cron job to /var/log/myjob.log

You might use mail to send emails. Most systems will send unhandled cron job output by email to root or the corresponding user.

What is the difference between synchronous and asynchronous programming (in node.js)

Synchronous functions are blocking while asynchronous functions are not. In synchronous functions, statements complete before the next statement is run. In this case, the program is evaluated exactly in order of the statements and execution of the program is paused if one of the statements take a very long time.

Asynchronous functions usually accept a callback as a parameter and execution continue on the next line immediately after the asynchronous function is invoked. The callback is only invoked when the asynchronous operation is complete and the call stack is empty. Heavy duty operations such as loading data from a web server or querying a database should be done asynchronously so that the main thread can continue executing other operations instead of blocking until that long operation to complete (in the case of browsers, the UI will freeze).

Orginal Posted on Github: Link

How to refresh an IFrame using Javascript?

You can use this:

Js:

function refreshFrame(){
    $('#myFrame').attr('src', "http://blablab.com?v=");
}

Html:

`<iframe id="myFrame" src=""></iframe>`

JS Fiddle : https://jsfiddle.net/wpb20vzx/

How to convert column with dtype as object to string in Pandas Dataframe

You could try using df['column'].str. and then use any string function. Pandas documentation includes those like split

Why am I getting error CS0246: The type or namespace name could not be found?

Edit: Oh ignore me, you're not using Visual Studio.

Have you added the reference to your project?

As in this sort of thing:

enter image description here

JList add/remove Item

The best and easiest way to clear a JLIST is:

myJlist.setListData(new String[0]);

Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class

The accounts property is defined like this:

"accounts":{"github":"sergiotapia"}

Your POCO states this:

public List<Account> Accounts { get; set; }

Try using this Json:

"accounts":[{"github":"sergiotapia"}]

An array of items (which is going to be mapped to the list) is always enclosed in square brackets.

Edit: The Account Poco will be something like this:

class Account {
    public string github { get; set; }
}

and maybe other properties.

Edit 2: To not have an array use the property as follows:

public Account Accounts { get; set; }

with something like the sample class I've posted in the first edit.

Safely casting long to int in Java

I think I'd do it as simply as:

public static int safeLongToInt(long l) {
    if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) {
        throw new IllegalArgumentException
            (l + " cannot be cast to int without changing its value.");
    }
    return (int) l;
}

I think that expresses the intent more clearly than the repeated casting... but it's somewhat subjective.

Note of potential interest - in C# it would just be:

return checked ((int) l);

'git' is not recognized as an internal or external command

After installation, open the GitHub app and on the top right corner you'd notice a setting icon. Select Options from the dropdown and choose "Default Shell" as Cmd.

Now try typing 'git shell' in the search (windows key and type) and choose Git Shell. It should open up in CMD and git should now be recognized.

excel delete row if column contains value from to-remove-list

I've found a more reliable method (at least on Excel 2016 for Mac) is:

Assuming your long list is in column A, and the list of things to be removed from this is in column B, then paste this into all the rows of column C:

= IF(COUNTIF($B$2:$B$99999,A2)>0,"Delete","Keep")

Then just sort the list by column C to find what you have to delete.

Assign multiple values to array in C

The old-school way:

GLfloat coordinates[8];
...

GLfloat *p = coordinates;
*p++ = 1.0f; *p++ = 0.0f; *p++ = 1.0f; *p++ = 1.0f;
*p++ = 0.0f; *p++ = 1.0f; *p++ = 0.0f; *p++ = 0.0f;

return coordinates;

MySQL Error 1264: out of range value for column

Work with:

ALTER TABLE `table` CHANGE `cust_fax` `cust_fax` VARCHAR(60) NULL DEFAULT NULL; 

How to remove stop words using nltk or python

from nltk.corpus import stopwords 

from nltk.tokenize import word_tokenize 

example_sent = "This is a sample sentence, showing off the stop words filtration."

  
stop_words = set(stopwords.words('english')) 
  
word_tokens = word_tokenize(example_sent) 
  
filtered_sentence = [w for w in word_tokens if not w in stop_words] 
  
filtered_sentence = [] 
  
for w in word_tokens: 
    if w not in stop_words: 
        filtered_sentence.append(w) 
  
print(word_tokens) 
print(filtered_sentence) 

How can I change the value of the elements in a vector?

Your code works fine. When I ran it I got the output:

The values in the file input.txt are:
1
2
3
4
5
6
7
8
9
10
The sum of the values is: 55
The mean value is: 5.5

But it could still be improved.

You are iterating over the vector using indexes. This is not the "STL Way" -- you should be using iterators, to wit:

typedef vector<double> doubles;
for( doubles::const_iterator it = v.begin(), it_end = v.end(); it != it_end; ++it )
{
    total += *it;
    mean = total / v.size();
}

This is better for a number of reasons discussed here and elsewhere, but here are two main reasons:

  1. Every container provides the iterator concept. Not every container provides random-access (eg, indexed access).
  2. You can generalize your iteration code.

Point number 2 brings up another way you can improve your code. Another thing about your code that isn't very STL-ish is the use of a hand-written loop. <algorithm>s were designed for this purpose, and the best code is the code you never write. You can use a loop to compute the total and mean of the vector, through the use of an accumulator:

#include <numeric>
#include <functional>
struct my_totals : public std::binary_function<my_totals, double, my_totals>
{
    my_totals() : total_(0), count_(0) {};
    my_totals operator+(double v) const
    {
        my_totals ret = *this;
        ret.total_ += v;
        ++ret.count_;
        return ret;
    }
    double mean() const { return total_/count_; }
    double total_;
    unsigned count_;
};

...and then:

my_totals ttls = std::accumulate(v.begin(), v.end(), my_totals());
cout << "The sum of the values is: " << ttls.total_ << endl;
cout << "The mean value is: " << ttls.mean() << endl;

EDIT:

If you have the benefit of a C++0x-compliant compiler, this can be made even simpler using std::for_each (within #include <algorithm>) and a lambda expression:

double total = 0;
for_each( v.begin(), v.end(), [&total](double  v) { total += v; });
cout << "The sum of the values is: " << total << endl;
cout << "The mean value is: " << total/v.size() << endl;

Most efficient way to prepend a value to an array

f you need to preserve the old array, slice the old one and unshift the new value(s) to the beginning of the slice.

var oldA=[4,5,6];
newA=oldA.slice(0);
newA.unshift(1,2,3)

oldA+'\n'+newA

/*  returned value:
4,5,6
1,2,3,4,5,6
*/

What does the 'L' in front a string mean in C++?

It means that it is a wide character, wchar_t.

Similar to 1L being a long value.

Convert cells(1,1) into "A1" and vice versa

The Address property of a cell can get this for you:

MsgBox Cells(1, 1).Address(RowAbsolute:=False, ColumnAbsolute:=False)

returns A1.

The other way around can be done with the Row and Column property of Range:

MsgBox Range("A1").Row & ", " & Range("A1").Column

returns 1,1.

IndentationError: unindent does not match any outer indentation level

IMPORTANT: Spaces are the preferred method - see PEP008 Indentation and Tabs or Spaces?. (Thanks to @Siha for this.)

For Sublime Text users:

Set Sublime Text to use tabs for indentation: View --> Indentation --> Convert Indentation to Tabs

Uncheck the Indent Using Spaces option as well in the same sub-menu above. This will immediately resolve this issue.

Get month and year from a datetime in SQL Server 2005

---Lalmuni Demos---
create table Users
(
userid int,date_of_birth date
)
---insert values---
insert into Users values(4,'9/10/1991')

select DATEDIFF(year,date_of_birth, getdate()) - (CASE WHEN (DATEADD(year, DATEDIFF(year,date_of_birth, getdate()),date_of_birth)) > getdate() THEN 1 ELSE 0 END) as Years, 
MONTH(getdate() - (DATEADD(year, DATEDIFF(year, date_of_birth, getdate()), date_of_birth))) - 1 as Months, 
DAY(getdate() - (DATEADD(year, DATEDIFF(year,date_of_birth, getdate()), date_of_birth))) - 1 as Days,
from users

How do I convert a string to a number in PHP?

You can always add zero to it!

Input             Output
'2' + 0           2 (int)
'2.34' + 0        2.34 (float)
'0.3454545' + 0   0.3454545 (float)

Native query with named parameter fails with "Not all named parameters have been set"

This was a bug fixed in version 4.3.11 https://hibernate.atlassian.net/browse/HHH-2851

EDIT: Best way to execute a native query is still to use NamedParameterJdbcTemplate It allows you need to retrieve a result that is not a managed entity ; you can use a RowMapper and even a Map of named parameters!

private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

@Autowired
public void setDataSource(DataSource dataSource) {
    this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
}

final List<Long> resultList = namedParameterJdbcTemplate.query(query, 
            mapOfNamedParamters, 
            new RowMapper<Long>() {
        @Override
        public Long mapRow(ResultSet rs, int rowNum) throws SQLException {
            return rs.getLong(1);
        }
    });

Is there a way to rollback my last push to Git?

First you need to determine the revision ID of the last known commit. You can use HEAD^ or HEAD~{1} if you know you need to reverse exactly one commit.

git reset --hard <revision_id_of_last_known_good_commit>
git push --force

Windows Bat file optional argument parsing

The selected answer works, but it could use some improvement.

  • The options should probably be initialized to default values.
  • It would be nice to preserve %0 as well as the required args %1 and %2.
  • It becomes a pain to have an IF block for every option, especially as the number of options grows.
  • It would be nice to have a simple and concise way to quickly define all options and defaults in one place.
  • It would be good to support stand-alone options that serve as flags (no value following the option).
  • We don't know if an arg is enclosed in quotes. Nor do we know if an arg value was passed using escaped characters. Better to access an arg using %~1 and enclose the assignment within quotes. Then the batch can rely on the absence of enclosing quotes, but special characters are still generally safe without escaping. (This is not bullet proof, but it handles most situations)

My solution relies on the creation of an OPTIONS variable that defines all of the options and their defaults. OPTIONS is also used to test whether a supplied option is valid. A tremendous amount of code is saved by simply storing the option values in variables named the same as the option. The amount of code is constant regardless of how many options are defined; only the OPTIONS definition has to change.

EDIT - Also, the :loop code must change if the number of mandatory positional arguments changes. For example, often times all arguments are named, in which case you want to parse arguments beginning at position 1 instead of 3. So within the :loop, all 3 become 1, and 4 becomes 2.

@echo off
setlocal enableDelayedExpansion

:: Define the option names along with default values, using a <space>
:: delimiter between options. I'm using some generic option names, but 
:: normally each option would have a meaningful name.
::
:: Each option has the format -name:[default]
::
:: The option names are NOT case sensitive.
::
:: Options that have a default value expect the subsequent command line
:: argument to contain the value. If the option is not provided then the
:: option is set to the default. If the default contains spaces, contains
:: special characters, or starts with a colon, then it should be enclosed
:: within double quotes. The default can be undefined by specifying the
:: default as empty quotes "".
:: NOTE - defaults cannot contain * or ? with this solution.
::
:: Options that are specified without any default value are simply flags
:: that are either defined or undefined. All flags start out undefined by
:: default and become defined if the option is supplied.
::
:: The order of the definitions is not important.
::
set "options=-username:/ -option2:"" -option3:"three word default" -flag1: -flag2:"

:: Set the default option values
for %%O in (%options%) do for /f "tokens=1,* delims=:" %%A in ("%%O") do set "%%A=%%~B"

:loop
:: Validate and store the options, one at a time, using a loop.
:: Options start at arg 3 in this example. Each SHIFT is done starting at
:: the first option so required args are preserved.
::
if not "%~3"=="" (
  set "test=!options:*%~3:=! "
  if "!test!"=="!options! " (
    rem No substitution was made so this is an invalid option.
    rem Error handling goes here.
    rem I will simply echo an error message.
    echo Error: Invalid option %~3
  ) else if "!test:~0,1!"==" " (
    rem Set the flag option using the option name.
    rem The value doesn't matter, it just needs to be defined.
    set "%~3=1"
  ) else (
    rem Set the option value using the option as the name.
    rem and the next arg as the value
    set "%~3=%~4"
    shift /3
  )
  shift /3
  goto :loop
)

:: Now all supplied options are stored in variables whose names are the
:: option names. Missing options have the default value, or are undefined if
:: there is no default.
:: The required args are still available in %1 and %2 (and %0 is also preserved)
:: For this example I will simply echo all the option values,
:: assuming any variable starting with - is an option.
::
set -

:: To get the value of a single parameter, just remember to include the `-`
echo The value of -username is: !-username!

There really isn't that much code. Most of the code above is comments. Here is the exact same code, without the comments.

@echo off
setlocal enableDelayedExpansion

set "options=-username:/ -option2:"" -option3:"three word default" -flag1: -flag2:"

for %%O in (%options%) do for /f "tokens=1,* delims=:" %%A in ("%%O") do set "%%A=%%~B"
:loop
if not "%~3"=="" (
  set "test=!options:*%~3:=! "
  if "!test!"=="!options! " (
      echo Error: Invalid option %~3
  ) else if "!test:~0,1!"==" " (
      set "%~3=1"
  ) else (
      set "%~3=%~4"
      shift /3
  )
  shift /3
  goto :loop
)
set -

:: To get the value of a single parameter, just remember to include the `-`
echo The value of -username is: !-username!


This solution provides Unix style arguments within a Windows batch. This is not the norm for Windows - batch usually has the options preceding the required arguments and the options are prefixed with /.

The techniques used in this solution are easily adapted for a Windows style of options.

  • The parsing loop always looks for an option at %1, and it continues until arg 1 does not begin with /
  • Note that SET assignments must be enclosed within quotes if the name begins with /.
    SET /VAR=VALUE fails
    SET "/VAR=VALUE" works. I am already doing this in my solution anyway.
  • The standard Windows style precludes the possibility of the first required argument value starting with /. This limitation can be eliminated by employing an implicitly defined // option that serves as a signal to exit the option parsing loop. Nothing would be stored for the // "option".


Update 2015-12-28: Support for ! in option values

In the code above, each argument is expanded while delayed expansion is enabled, which means that ! are most likely stripped, or else something like !var! is expanded. In addition, ^ can also be stripped if ! is present. The following small modification to the un-commented code removes the limitation such that ! and ^ are preserved in option values.

@echo off
setlocal enableDelayedExpansion

set "options=-username:/ -option2:"" -option3:"three word default" -flag1: -flag2:"

for %%O in (%options%) do for /f "tokens=1,* delims=:" %%A in ("%%O") do set "%%A=%%~B"
:loop
if not "%~3"=="" (
  set "test=!options:*%~3:=! "
  if "!test!"=="!options! " (
      echo Error: Invalid option %~3
  ) else if "!test:~0,1!"==" " (
      set "%~3=1"
  ) else (
      setlocal disableDelayedExpansion
      set "val=%~4"
      call :escapeVal
      setlocal enableDelayedExpansion
      for /f delims^=^ eol^= %%A in ("!val!") do endlocal&endlocal&set "%~3=%%A" !
      shift /3
  )
  shift /3
  goto :loop
)
goto :endArgs
:escapeVal
set "val=%val:^=^^%"
set "val=%val:!=^!%"
exit /b
:endArgs

set -

:: To get the value of a single parameter, just remember to include the `-`
echo The value of -username is: !-username!

How to retrieve the current value of an oracle sequence without increment it?

If your use case is that some backend code inserts a record, then the same code wants to retrieve the last insert id, without counting on any underlying data access library preset function to do this, then, as mentioned by others, you should just craft your SQL query using SEQ_MY_NAME.NEXTVAL for the column you want (usually the primary key), then just run statement SELECT SEQ_MY_NAME.CURRVAL FROM dual from the backend.

Remember, CURRVAL is only callable if NEXTVAL has been priorly invoked, which is all naturally done in the strategy above...

"fatal: Not a git repository (or any of the parent directories)" from git status

I suddenly got an error like in any directory I tried to run any git command from:

fatal: Not a git repository: /Users/me/Desktop/../../.git/modules/some-submodule

For me, turned out I had a hidden file .git on my Desktop with the content:

gitdir: ../../.git/modules/some-module

Removed that file and fixed.

get UTC time in PHP

You can use following to get UTC time:

date_default_timezone_set('Asia/Calcutta');

$current_date = date("Y/m/d g:i A");

$ist_date = DateTime::createFromFormat(
                        '"Y/m/d g:i A"',
                        $current_date,
                        new DateTimeZone('Asia/Calcutta')
                    );

$utc_date = clone $ist_date;
$utc_date->setTimeZone(new DateTimeZone('UTC'));

echo 'UTC:  ' . $utc_date->format('Y-m-d g:i A');

How to get http headers in flask?

just note, The different between the methods are, if the header is not exist

request.headers.get('your-header-name')

will return None or no exception, so you can use it like

if request.headers.get('your-header-name'):
    ....

but the following will throw an error

if request.headers['your-header-name'] # KeyError: 'your-header-name'
    ....

You can handle it by

if 'your-header-name' in request.headers:
   customHeader = request.headers['your-header-name']
   ....

Can't push image to Amazon ECR - fails with "no basic auth credentials"

Just adding to this as in case someone out there is suffering from never Reading The F Manual like me
I followed all the suggested steps from above such as

aws ecr get-login-password --region eu-west-1 | docker login --username AWS --password-stdin 123456789.dkr.ecr.eu-west-1.amazonaws.com

And always got the no basic auth credentials
I had created a registry named

123456789.dkr.ecr.eu-west-1.amazonaws.com/my.registry.com/namespace 

and was trying to push an image called alpine:latest

123456789.dkr.ecr.eu-west-1.amazonaws.com/my.registry.com/namespace/alpine:latest
2c6e8b76de: Preparing
9d4cb0c1e9: Preparing
1ca55f6ab4: Preparing
b6fd41c05e: Waiting
ad44a79b33: Waiting
2ce3c1888d: Waiting
no basic auth credentials   

Silly mistake on my behalf as I must create a registry in ecr using the full container path.
I created a new registry using the full container path, not ending on the namespace

123456789.dkr.ecr.eu-west-1.amazonaws.com/my.registry.com/namespace/alpine

and low and behold pushing to

123456789.dkr.ecr.eu-west-1.amazonaws.com/my.registry.com/namespace/alpine:latest 
The push refers to repository [123456789.dkr.ecr.eu-west-1.amazonaws.com/my.registry.com/namespace/alpine]
0c8667b5b: Pushed
730460948: Pushed
1.0: digest: sha256:e1f814f3818efea45267ebfb4918088a26a18c size: 7

works just fine

Map to String in Java

Use Object#toString().

String string = map.toString();

That's after all also what System.out.println(object) does under the hoods. The format for maps is described in AbstractMap#toString().

Returns a string representation of this map. The string representation consists of a list of key-value mappings in the order returned by the map's entrySet view's iterator, enclosed in braces ("{}"). Adjacent mappings are separated by the characters ", " (comma and space). Each key-value mapping is rendered as the key followed by an equals sign ("=") followed by the associated value. Keys and values are converted to strings as by String.valueOf(Object).

How do I open a URL from C++?

Use libcurl, here is a simple example.

EDIT: If this is about starting a web browser from C++, you can invoke a shell command with system on a POSIX system:

system("<mybrowser> http://google.com");

By replacing <mybrowser> with the browser you want to launch.

How do I return multiple values from a function in C?

Since one of your result types is a string (and you're using C, not C++), I recommend passing pointers as output parameters. Use:

void foo(int *a, char *s, int size);

and call it like this:

int a;
char *s = (char *)malloc(100); /* I never know how much to allocate :) */
foo(&a, s, 100);

In general, prefer to do the allocation in the calling function, not inside the function itself, so that you can be as open as possible for different allocation strategies.

How to set environment via `ng serve` in Angular 6

Angular no longer supports --env instead you have to use

ng serve -c dev

for development environment and,

ng serve -c prod 

for production.

NOTE: -c or --configuration

SQL Server 2008 Insert with WHILE LOOP

First of all I'd like to say that I 100% agree with John Saunders that you must avoid loops in SQL in most cases especially in production.

But occasionally as a one time thing to populate a table with a hundred records for testing purposes IMHO it's just OK to indulge yourself to use a loop.

For example in your case to populate your table with records with hospital ids between 16 and 100 and make emails and descriptions distinct you could've used

CREATE PROCEDURE populateHospitals
AS
DECLARE @hid INT;
SET @hid=16;
WHILE @hid < 100
BEGIN 
    INSERT hospitals ([Hospital ID], Email, Description) 
    VALUES(@hid, 'user' + LTRIM(STR(@hid)) + '@mail.com', 'Sample Description' + LTRIM(STR(@hid))); 
    SET @hid = @hid + 1;
END

And result would be

ID   Hospital ID Email            Description          
---- ----------- ---------------- ---------------------
1    16          [email protected]  Sample Description16 
2    17          [email protected]  Sample Description17 
...                                                    
84   99          [email protected]  Sample Description99 

How do you open a file in C++?

There are three ways to do this, depending on your needs. You could use the old-school C way and call fopen/fread/fclose, or you could use the C++ fstream facilities (ifstream/ofstream), or if you're using MFC, use the CFile class, which provides functions to accomplish actual file operations.

All of these are suitable for both text and binary, though none have a specific readline functionality. What you'd most likely do instead in that case is use the fstream classes (fstream.h) and use the stream operators (<< and >>) or the read function to read/write blocks of text:

int nsize = 10;
char *somedata;
ifstream myfile;
myfile.open("<path to file>");
myfile.read(somedata,nsize);
myfile.close();

Note that, if you're using Visual Studio 2005 or higher, traditional fstream may not be available (there's a new Microsoft implementation, which is slightly different, but accomplishes the same thing).

Android, landscape only orientation?

One thing I've not found through the answers is that there are two possible landscape orientations, and I wanted to let both be available! So android:screenOrientation="landscape" will lock your app only to one of the 2 possibilities, but if you want your app to be limited to both landscape orientations (for them whom is not clear, having device on portrait, one is rotating left and the other one rotating right) this is what is needed:

android:screenOrientation="sensorLandscape"

VBA Go to last empty row

This does it:

Do
   c = c + 1
Loop While Cells(c, "A").Value <> ""

'prints the last empty row
Debug.Print c

Append to string variable

var str1 = "add";
str1 = str1 + " ";

Hope that helps,

Dan

How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?

A picture is worth a thousand words:

PHP Double Equals == equality chart:

enter image description here

PHP Triple Equals === Equality chart:

enter image description here

Source code to create these images:

https://github.com/sentientmachine/php_equality_charts

Guru Meditation

Those who wish to keep their sanity, read no further because none of this will make any sense, except to say that this is how the insanity-fractal, of PHP was designed.

  1. NAN != NAN but NAN == true.

  2. == will convert left and right operands to numbers if left is a number. So 123 == "123foo", but "123" != "123foo"

  3. A hex string in quotes is occasionally a float, and will be surprise cast to float against your will, causing a runtime error.

  4. == is not transitive because "0"== 0, and 0 == "" but "0" != ""

  5. PHP Variables that have not been declared yet are false, even though PHP has a way to represent undefined variables, that feature is disabled with ==.

  6. "6" == " 6", "4.2" == "4.20", and "133" == "0133" but 133 != 0133. But "0x10" == "16" and "1e3" == "1000" exposing that surprise string conversion to octal will occur both without your instruction or consent, causing a runtime error.

  7. False == 0, "", [] and "0".

  8. If you add 1 to number and they are already holding their maximum value, they do not wrap around, instead they are cast to infinity.

  9. A fresh class is == to 1.

  10. False is the most dangerous value because False is == to most of the other variables, mostly defeating it's purpose.

Hope:

If you are using PHP, Thou shalt not use the double equals operator because if you use triple equals, the only edge cases to worry about are NAN and numbers so close to their datatype's maximum value, that they are cast to infinity. With double equals, anything can be surprise == to anything or, or can be surprise casted against your will and != to something of which it should obviously be equal.

Anywhere you use == in PHP is a bad code smell because of the 85 bugs in it exposed by implicit casting rules that seem designed by millions of programmers programming by brownian motion.

What does "for" attribute do in HTML <label> tag?

In a nutshell what it does is refer to the id of the input, that's all:

<label for="the-id-of-the-input">Input here:</label>
<input type="text" name="the-name-of-input" id="the-id-of-the-input">

How do I check if a Socket is currently connected in Java?

  • socket.isConnected() returns always true once the client connects (and even after the disconnect) weird !!
  • socket.getInputStream().read()
    • makes the thread wait for input as long as the client is connected and therefore makes your program not do anything - except if you get some input
    • returns -1 if the client disconnected
  • socket.getInetAddress().isReachable(int timeout): From isReachable(int timeout)

    Test whether that address is reachable. Best effort is made by the implementation to try to reach the host, but firewalls and server configuration may block requests resulting in a unreachable status while some specific ports may be accessible. A typical implementation will use ICMP ECHO REQUESTs if the privilege can be obtained, otherwise it will try to establish a TCP connection on port 7 (Echo) of the destination host.

How to break out from foreach loop in javascript

Use a for loop instead of .forEach()

var myObj = [{"a": "1","b": null},{"a": "2","b": 5}]
var result = false

for(var call of myObj) {
    console.log(call)
    
    var a = call['a'], b = call['b']
     
    if(a == null || b == null) {
        result = false
        break
    }
}

GIT fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree

I had this issue when having a custom display in my terminal when creating a new git project (I have my branch display before the pathname e.g. :/current/path). All I needed to do was do my initial commit to my master branch to get this message to go away.

In .NET, which loop runs faster, 'for' or 'foreach'?

In cases where you work with a collection of objects, foreach is better, but if you increment a number, a for loop is better.

Note that in the last case, you could do something like:

foreach (int i in Enumerable.Range(1, 10))...

But it certainly doesn't perform better, it actually has worse performance compared to a for.

Where is the Microsoft.IdentityModel dll

I had this problem, but fixed it by referencing the DLL from "C:\Program Files\Reference Assemblies\Microsoft\Windows Identity Foundation\v3.5\Microsoft.IdentityModel.dll"

Go to reference properties and set Copy Local to True for the DLL. The DLL will now be included in the azure package.

What is the best way to modify a list in a 'foreach' loop?

To add to Timo's answer LINQ can be used like this as well:

items = items.Select(i => {

     ...
     //perform some logic adding / updating.

     return i / return new Item();
     ...

     //To remove an item simply have logic to return null.

     //Then attach the Where to filter out nulls

     return null;
     ...


}).Where(i => i != null);

How to add List<> to a List<> in asp.net

Use .AddRange to append any Enumrable collection to the list.

What is Python used for?

Python is a dynamic, strongly typed, object oriented, multipurpose programming language, designed to be quick (to learn, to use, and to understand), and to enforce a clean and uniform syntax.

  1. Python is dynamically typed: it means that you don't declare a type (e.g. 'integer') for a variable name, and then assign something of that type (and only that type). Instead, you have variable names, and you bind them to entities whose type stays with the entity itself. a = 5 makes the variable name a to refer to the integer 5. Later, a = "hello" makes the variable name a to refer to a string containing "hello". Static typed languages would have you declare int a and then a = 5, but assigning a = "hello" would have been a compile time error. On one hand, this makes everything more unpredictable (you don't know what a refers to). On the other hand, it makes very easy to achieve some results a static typed languages makes very difficult.
  2. Python is strongly typed. It means that if a = "5" (the string whose value is '5') will remain a string, and never coerced to a number if the context requires so. Every type conversion in python must be done explicitly. This is different from, for example, Perl or Javascript, where you have weak typing, and can write things like "hello" + 5 to get "hello5".
  3. Python is object oriented, with class-based inheritance. Everything is an object (including classes, functions, modules, etc), in the sense that they can be passed around as arguments, have methods and attributes, and so on.
  4. Python is multipurpose: it is not specialised to a specific target of users (like R for statistics, or PHP for web programming). It is extended through modules and libraries, that hook very easily into the C programming language.
  5. Python enforces correct indentation of the code by making the indentation part of the syntax. There are no control braces in Python. Blocks of code are identified by the level of indentation. Although a big turn off for many programmers not used to this, it is precious as it gives a very uniform style and results in code that is visually pleasant to read.
  6. The code is compiled into byte code and then executed in a virtual machine. This means that precompiled code is portable between platforms.

Python can be used for any programming task, from GUI programming to web programming with everything else in between. It's quite efficient, as much of its activity is done at the C level. Python is just a layer on top of C. There are libraries for everything you can think of: game programming and openGL, GUI interfaces, web frameworks, semantic web, scientific computing...

Delete topic in Kafka 0.8.1.1

First, you run this command to delete your topic:

$ bin/kafka-topics.sh --delete --bootstrap-server localhost:9092 --topic <topic_name>

List active topics to check delete completely:

$ bin/kafka-topics.sh --list --bootstrap-server localhost:9092

GROUP BY + CASE statement

Your query would work already - except that you are running into naming conflicts or just confusing the output column (the CASE expression) with source column result, which has different content.

...
GROUP BY model.name, attempt.type, attempt.result
...

You need to GROUP BY your CASE expression instead of your source column:

...
GROUP BY model.name, attempt.type
       , CASE WHEN attempt.result = 0 THEN 0 ELSE 1 END
...

Or provide a column alias that's different from any column name in the FROM list - or else that column takes precedence:

SELECT ...
     , CASE WHEN attempt.result = 0 THEN 0 ELSE 1 END AS result1
...
GROUP BY model.name, attempt.type, result1
...

The SQL standard is rather peculiar in this respect. Quoting the manual here:

An output column's name can be used to refer to the column's value in ORDER BY and GROUP BY clauses, but not in the WHERE or HAVING clauses; there you must write out the expression instead.

And:

If an ORDER BY expression is a simple name that matches both an output column name and an input column name, ORDER BY will interpret it as the output column name. This is the opposite of the choice that GROUP BY will make in the same situation. This inconsistency is made to be compatible with the SQL standard.

Bold emphasis mine.

These conflicts can be avoided by using positional references (ordinal numbers) in GROUP BY and ORDER BY, referencing items in the SELECT list from left to right. See solution below.
The drawback is, that this may be harder to read and vulnerable to edits in the SELECT list (one might forget to adapt positional references accordingly).

But you do not have to add the column day to the GROUP BY clause, as long as it holds a constant value (CURRENT_DATE-1).

Rewritten and simplified with proper JOIN syntax and positional references it could look like this:

SELECT m.name
     , a.type
     , CASE WHEN a.result = 0 THEN 0 ELSE 1 END AS result
     , CURRENT_DATE - 1 AS day
     , count(*) AS ct
FROM   attempt    a
JOIN   prod_hw_id p USING (hard_id)
JOIN   model      m USING (model_id)
WHERE  ts >= '2013-11-06 00:00:00'  
AND    ts <  '2013-11-07 00:00:00'
GROUP  BY 1,2,3
ORDER  BY 1,2,3;

Also note that I am avoiding the column name time. That's a reserved word and should never be used as identifier. Besides, your "time" obviously is a timestamp or date, so that is rather misleading.

How do I install Keras and Theano in Anaconda Python on Windows?

In windows environment with Anconda. Go to anconda prompt from start. Then if you are behind proxy then .copndarc file needs to eb updated with the proxy details.

ssl_verify: false channels: - defaults proxy_servers: http: http://xx.xx.xx.xx:xxxx https: https://xx.xx.xx.xx:xxxx

I had ssl_verify initially marked as 'True' then I was getting ssl error. So i turned it to false as above and then ran the below commands

conda update conda conda update --all conda install --channel https://conda.anaconda.org/conda-forge keras conda install --channel https://conda.anaconda.org/conda-forge tensorflow

My python version is 3.6.7

How to use struct timeval to get the execution time?

Change:

struct timeval, tvalBefore, tvalAfter; /* Looks like an attempt to
                                          delcare a variable with
                                          no name. */

to:

struct timeval tvalBefore, tvalAfter;

It is less likely (IMO) to make this mistake if there is a single declaration per line:

struct timeval tvalBefore;
struct timeval tvalAfter;

It becomes more error prone when declaring pointers to types on a single line:

struct timeval* tvalBefore, tvalAfter;

tvalBefore is a struct timeval* but tvalAfter is a struct timeval.

How to restart Activity in Android

If you are calling from some fragment so do below code.

Intent intent = getActivity().getIntent();
getActivity().finish();
startActivity(intent);

CSS position:fixed inside a positioned element

If your close button is going to be text, this works very well for me:

#close {
  position: fixed;
  width: 70%; /* the width of the parent */
  text-align: right;
}
#close span {
  cursor: pointer;
}

Then your HTML can just be:

<div id="close"><span id="x">X</span></div>

Unclosed Character Literal error

Character only takes one value dude! like: char y = 'h'; and maybe you typed like char y = 'hello'; or smthg. good luck. for the question asked above the answer is pretty simple u have to use DOUBLE QUOTES to give a string value. easy enough;)

plot with custom text for x axis points

You can manually set xticks (and yticks) using pyplot.xticks:

import matplotlib.pyplot as plt
import numpy as np

x = np.array([0,1,2,3])
y = np.array([20,21,22,23])
my_xticks = ['John','Arnold','Mavis','Matt']
plt.xticks(x, my_xticks)
plt.plot(x, y)
plt.show()

What is the difference between Amazon SNS and Amazon SQS?

From the AWS documentation:

Amazon SNS allows applications to send time-critical messages to multiple subscribers through a “push” mechanism, eliminating the need to periodically check or “poll” for updates.

Amazon SQS is a message queue service used by distributed applications to exchange messages through a polling model, and can be used to decouple sending and receiving components—without requiring each component to be concurrently available.

Fanout to Amazon SQS queues

What is the best (idiomatic) way to check the type of a Python variable?

*sigh*

No, typechecking arguments in python is not necessary. It is never necessary.

If your code accepts either a string or a dict object, your design is broken.

That comes from the fact that if you don't know already the type of an object in your own program, then you're doing something wrong already.

Typechecking hurts code reuse and reduces performance. Having a function that performs different things depending on the type of the object passed is bug-prone and has a behavior harder to understand and maintain.

You have the following saner options:

1) Make a function unique_values that converts dicts in unique lists of values:

def unique_values(some_dict):
    return list(set(some_dict.values()))

Make your function assume the argument passed is always a list. That way, if you need to pass a string to the function, you just do:

myfunction([some_string])

If you need to pass it a dict, you do:

myfunction(unique_values(some_dict))

That's your best option, it is clean, easy to understand and maintain. Anyone reading the code immediatelly understands what is happening, and you don't have to typecheck.

2) Make two functions, one that accepts lists of strings and one that accepts dicts. You can make one call the other internally, in the most convenient way (myfunction_dict can create a list of strings and call myfunction_list).

In any case, don't typecheck. It is completely unnecessary and has only downsides. Refactor your code instead in a way you don't need to typecheck. You only get benefits in doing so, both in short and long run.

WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser

I had the same issue, but in my case chrome previously was installed in user temp folder, after that was reinstalled to Program files. So any of solution provided here was not help me. But if provide path to chrome.exe all works:

chromeOptions.setBinary("C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe");

I hope this helps someone =)

What does flex: 1 mean?

flex: 1 means the following:

flex-grow : 1;    ? The div will grow in same proportion as the window-size       
flex-shrink : 1;  ? The div will shrink in same proportion as the window-size 
flex-basis : 0;   ? The div does not have a starting value as such and will 
                     take up screen as per the screen size available for
                     e.g:- if 3 divs are in the wrapper then each div will take 33%.

remove double quotes from Json return data using Jquery

For niche needs when you know your data like your example ... this works :

JSON.parse(this_is_double_quoted);

JSON.parse("House");  // for example

Selecting Values from Oracle Table Variable / Array?

The sql array type is not neccessary. Not if the element type is a primitive one. (Varchar, number, date,...)

Very basic sample:

declare
  type TPidmList is table of sgbstdn.sgbstdn_pidm%type;
  pidms TPidmList;
begin
  select distinct sgbstdn_pidm
  bulk collect into pidms
  from sgbstdn
  where sgbstdn_majr_code_1 = 'HS04'
  and sgbstdn_program_1 = 'HSCOMPH';

  -- do something with pidms

  open :someCursor for
    select value(t) pidm
    from table(pidms) t;
end;

When you want to reuse it, then it might be interesting to know how that would look like. If you issue several commands than those could be grouped in a package. The private package variable trick from above has its downsides. When you add variables to a package, you give it state and now it doesn't act as a stateless bunch of functions but as some weird sort of singleton object instance instead.

e.g. When you recompile the body, it will raise exceptions in sessions that already used it before. (because the variable values got invalided)

However, you could declare the type in a package (or globally in sql), and use it as a paramter in methods that should use it.

create package Abc as
  type TPidmList is table of sgbstdn.sgbstdn_pidm%type;

  function CreateList(majorCode in Varchar, 
                      program in Varchar) return TPidmList;

  function Test1(list in TPidmList) return PLS_Integer;
  -- "in" to make it immutable so that PL/SQL can pass a pointer instead of a copy
  procedure Test2(list in TPidmList);
end;

create package body Abc as

  function CreateList(majorCode in Varchar, 
                      program in Varchar) return TPidmList is
    result TPidmList;
  begin
    select distinct sgbstdn_pidm
    bulk collect into result
    from sgbstdn
    where sgbstdn_majr_code_1 = majorCode
    and sgbstdn_program_1 = program;

    return result;
  end;

  function Test1(list in TPidmList) return PLS_Integer is
    result PLS_Integer := 0;
  begin
    if list is null or list.Count = 0 then
      return result;
    end if;

    for i in list.First .. list.Last loop
      if ... then
        result := result + list(i);
      end if;
    end loop;
  end;

  procedure Test2(list in TPidmList) as
  begin
    ...
  end;

  return result;
end;

How to call it:

declare
  pidms constant Abc.TPidmList := Abc.CreateList('HS04', 'HSCOMPH');
  xyz PLS_Integer;
begin
  Abc.Test2(pidms);
  xyz := Abc.Test1(pidms);
  ...

  open :someCursor for
    select value(t) as Pidm,
           xyz as SomeValue
    from   table(pidms) t;
end;

Connection refused to MongoDB errno 111

I follow this tutorial's instructions for installation

How to Install MongoDB on Ubuntu 16.04

I had the same mistake. Finally, I found out that I needed to set the port number

The default port number for the mongo command is 27017

But the default port number in mongo.conf is 29999

Find row number of matching value

For your first method change ws.Range("A") to ws.Range("A:A") which will search the entirety of column a, like so:

Sub Find_Bingo()

        Dim wb As Workbook
        Dim ws As Worksheet
        Dim FoundCell As Range
        Set wb = ActiveWorkbook
        Set ws = ActiveSheet

            Const WHAT_TO_FIND As String = "Bingo"

            Set FoundCell = ws.Range("A:A").Find(What:=WHAT_TO_FIND)
            If Not FoundCell Is Nothing Then
                MsgBox (WHAT_TO_FIND & " found in row: " & FoundCell.Row)
            Else
                MsgBox (WHAT_TO_FIND & " not found")
            End If
End Sub

For your second method, you are using Bingo as a variable instead of a string literal. This is a good example of why I add Option Explicit to the top of all of my code modules, as when you try to run the code it will direct you to this "variable" which is undefined and not intended to be a variable at all.

Additionally, when you are using With...End With you need a period . before you reference Cells, so Cells should be .Cells. This mimics the normal qualifying behavior (i.e. Sheet1.Cells.Find..)

Change Bingo to "Bingo" and change Cells to .Cells

With Sheet1
        Set FoundCell = .Cells.Find(What:="Bingo", After:=.Cells(1, 1), _
        LookIn:=xlValues, lookat:=xlPart, SearchOrder:=xlByRows, _
        SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
    End With

If Not FoundCell Is Nothing Then
        MsgBox ("""Bingo"" found in row " & FoundCell.Row)
Else
        MsgBox ("Bingo not found")
End If

Update

In my

With Sheet1
    .....
End With

The Sheet1 refers to a worksheet's code name, not the name of the worksheet itself. For example, say I open a new blank Excel workbook. The default worksheet is just Sheet1. I can refer to that in code either with the code name of Sheet1 or I can refer to it with the index of Sheets("Sheet1"). The advantage to using a codename is that it does not change if you change the name of the worksheet.

Continuing this example, let's say I renamed Sheet1 to Data. Using Sheet1 would continue to work, as the code name doesn't change, but now using Sheets("Sheet1") would return an error and that syntax must be updated to the new name of the sheet, so it would need to be Sheets("Data").

In the VB Editor you would see something like this:

code object explorer example

Notice how, even though I changed the name to Data, there is still a Sheet1 to the left. That is what I mean by codename.

The Data worksheet can be referenced in two ways:

Debug.Print Sheet1.Name
Debug.Print Sheets("Data").Name

Both should return Data

More discussion on worksheet code names can be found here.

IIS 7, HttpHandler and HTTP Error 500.21

I had the same problem and just solved it. I had posted my own question on stackoverflow:

Can't PUT to my IHttpHandler, GET works fine

The solution was to set runManagedModulesForWebDavRequests to true in the modules element. My guess is that once you install WebDAV then all PUT requests are associated with it. If you need the PUT to go to your handler, you need to remove the WebDAV module and set this attribute to true.

<modules runManagedModulesForWebDavRequests="true">
...
</modules>

So if you're running into the problem when you use the PUT verb and you have installed WebDAV then hopefully this solution will fix your problem.

Scatter plot with error bars

I put together start to finish code of a hypothetical experiment with ten measurement replicated three times. Just for fun with the help of other stackoverflowers. Thank you... Obviously loops are an option as applycan be used but I like to see what happens.

#Create fake data
x <-rep(1:10, each =3)
y <- rnorm(30, mean=4,sd=1)

#Loop to get standard deviation from data
sd.y = NULL
for(i in 1:10){
  sd.y[i] <- sd(y[(1+(i-1)*3):(3+(i-1)*3)])
}
sd.y<-rep(sd.y,each = 3)

#Loop to get mean from data
mean.y = NULL
for(i in 1:10){
  mean.y[i] <- mean(y[(1+(i-1)*3):(3+(i-1)*3)])
}
mean.y<-rep(mean.y,each = 3)

#Put together the data to view it so far
data <- cbind(x, y, mean.y, sd.y)

#Make an empty matrix to fill with shrunk data
data.1 = matrix(data = NA, nrow=10, ncol = 4)
colnames(data.1) <- c("X","Y","MEAN","SD")

#Loop to put data into shrunk format
for(i in 1:10){
  data.1[i,] <- data[(1+(i-1)*3),]
}

#Create atomic vectors for arrows
x <- data.1[,1]
mean.exp <- data.1[,3]
sd.exp <- data.1[,4]

#Plot the data
plot(x, mean.exp, ylim = range(c(mean.exp-sd.exp,mean.exp+sd.exp)))
abline(h = 4)
arrows(x, mean.exp-sd.exp, x, mean.exp+sd.exp, length=0.05, angle=90, code=3)

What is the difference between server side cookie and client side cookie?

You probably mean the difference between Http Only cookies and their counter part?

Http Only cookies cannot be accessed (read from or written to) in client side JavaScript, only server side. If the Http Only flag is not set, or the cookie is created in (client side) JavaScript, the cookie can be read from and written to in (client side) JavaScript as well as server side.

Is there an API to get bank transaction and bank balance?

Also check out the open financial exchange (ofx) http://www.ofx.net/

This is what apps like quicken, ms money etc use.

Better way to find control in ASP.NET

FindControl does not search within nested controls recursively. It does only find controls that's NamigContainer is the Control on that you are calling FindControl.

Theres a reason that ASP.Net does not look into your nested controls recursively by default:

  • Performance
  • Avoiding errors
  • Reusability

Consider you want to encapsulate your GridViews, Formviews, UserControls etc. inside of other UserControls for reusability reasons. If you would have implemented all logic in your page and accessed these controls with recursive loops, it'll very difficult to refactor that. If you have implemented your logic and access methods via the event-handlers(f.e. RowDataBound of GridView), it'll be much simpler and less error-prone.

How do I run a docker instance from a DockerFile?

Download the file and from the same directory run docker build -t nodebb .

This will give you an image on your local machine that's named nodebb that you can launch an container from with docker run -d nodebb (you can change nodebb to your own name).

pandas create new column based on values from other columns / apply a function of multiple columns, row-wise

try this,

df.loc[df['eri_white']==1,'race_label'] = 'White'
df.loc[df['eri_hawaiian']==1,'race_label'] = 'Haw/Pac Isl.'
df.loc[df['eri_afr_amer']==1,'race_label'] = 'Black/AA'
df.loc[df['eri_asian']==1,'race_label'] = 'Asian'
df.loc[df['eri_nat_amer']==1,'race_label'] = 'A/I AK Native'
df.loc[(df['eri_afr_amer'] + df['eri_asian'] + df['eri_hawaiian'] + df['eri_nat_amer'] + df['eri_white']) > 1,'race_label'] = 'Two Or More'
df.loc[df['eri_hispanic']==1,'race_label'] = 'Hispanic'
df['race_label'].fillna('Other', inplace=True)

O/P:

     lname   fname rno_cd  eri_afr_amer  eri_asian  eri_hawaiian  \
0      MOST    JEFF      E             0          0             0   
1    CRUISE     TOM      E             0          0             0   
2      DEPP  JOHNNY    NaN             0          0             0   
3     DICAP     LEO    NaN             0          0             0   
4    BRANDO  MARLON      E             0          0             0   
5     HANKS     TOM    NaN             0          0             0   
6    DENIRO  ROBERT      E             0          1             0   
7    PACINO      AL      E             0          0             0   
8  WILLIAMS   ROBIN      E             0          0             1   
9  EASTWOOD   CLINT      E             0          0             0   

   eri_hispanic  eri_nat_amer  eri_white rno_defined    race_label  
0             0             0          1       White         White  
1             1             0          0       White      Hispanic  
2             0             0          1     Unknown         White  
3             0             0          1     Unknown         White  
4             0             0          0       White         Other  
5             0             0          1     Unknown         White  
6             0             0          1       White   Two Or More  
7             0             0          1       White         White  
8             0             0          0       White  Haw/Pac Isl.  
9             0             0          1       White         White 

use .loc instead of apply.

it improves vectorization.

.loc works in simple manner, mask rows based on the condition, apply values to the freeze rows.

for more details visit, .loc docs

Performance metrics:

Accepted Answer:

def label_race (row):
   if row['eri_hispanic'] == 1 :
      return 'Hispanic'
   if row['eri_afr_amer'] + row['eri_asian'] + row['eri_hawaiian'] + row['eri_nat_amer'] + row['eri_white'] > 1 :
      return 'Two Or More'
   if row['eri_nat_amer'] == 1 :
      return 'A/I AK Native'
   if row['eri_asian'] == 1:
      return 'Asian'
   if row['eri_afr_amer']  == 1:
      return 'Black/AA'
   if row['eri_hawaiian'] == 1:
      return 'Haw/Pac Isl.'
   if row['eri_white'] == 1:
      return 'White'
   return 'Other'

df=pd.read_csv('dataser.csv')
df = pd.concat([df]*1000)

%timeit df.apply(lambda row: label_race(row), axis=1)

1.15 s ± 46.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

My Proposed Answer:

def label_race(df):
    df.loc[df['eri_white']==1,'race_label'] = 'White'
    df.loc[df['eri_hawaiian']==1,'race_label'] = 'Haw/Pac Isl.'
    df.loc[df['eri_afr_amer']==1,'race_label'] = 'Black/AA'
    df.loc[df['eri_asian']==1,'race_label'] = 'Asian'
    df.loc[df['eri_nat_amer']==1,'race_label'] = 'A/I AK Native'
    df.loc[(df['eri_afr_amer'] + df['eri_asian'] + df['eri_hawaiian'] + df['eri_nat_amer'] + df['eri_white']) > 1,'race_label'] = 'Two Or More'
    df.loc[df['eri_hispanic']==1,'race_label'] = 'Hispanic'
    df['race_label'].fillna('Other', inplace=True)
df=pd.read_csv('s22.csv')
df = pd.concat([df]*1000)

%timeit label_race(df)

24.7 ms ± 1.7 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Loop through columns and add string lengths as new columns

You can use lapply to pass each column to str_length, then cbind it to your original data.frame...

library(stringr)

out <- lapply( df , str_length )    
df <- cbind( df , out )

#     col1     col2 col1 col2
#1     abc adf qqwe    3    8
#2    abcd        d    4    1
#3       a        e    1    1
#4 abcdefg        f    7    1

How to include SCSS file in HTML

You can't have a link to SCSS File in your HTML page.You have to compile it down to CSS First. No there are lots of video tutorials you might want to check out. Lynda provides great video tutorials on SASS. there are also free screencasts you can google...

For official documentation visit this site http://sass-lang.com/documentation/file.SASS_REFERENCE.html And why have you chosen notepad to write Sass?? you can easily download some free text editors for better code handling.

Using HTTPS with REST in Java

Here's the painful route:

    SSLContext ctx = null;
    try {
        KeyStore trustStore;
        trustStore = KeyStore.getInstance("JKS");
        trustStore.load(new FileInputStream("C:\\truststore_client"),
                "asdfgh".toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory
                .getInstance("SunX509");
        tmf.init(trustStore);
        ctx = SSLContext.getInstance("SSL");
        ctx.init(null, tmf.getTrustManagers(), null);
    } catch (NoSuchAlgorithmException e1) {
        e1.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
    ClientConfig config = new DefaultClientConfig();
    config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
            new HTTPSProperties(null, ctx));

    WebResource service = Client.create(config).resource(
            "https://localhost:9999/");
    service.addFilter(new HTTPBasicAuthFilter(username, password));

    // Attempt to view the user's page.
    try {
        service.path("user/" + username).get(String.class);
    } catch (Exception e) {
        e.printStackTrace();
    }

Gotta love those six different caught exceptions :). There are certainly some refactoring to simplify the code a bit. But, I like delfuego's -D options on the VM. I wish there was a javax.net.ssl.trustStore static property that I could just set. Just two lines of code and done. Anyone know where that would be?

This may be too much to ask, but, ideally the keytool would not be used. Instead, the trustedStore would be created dynamically by the code and the cert is added at runtime.

There must be a better answer.

Array or List in Java. Which is faster?

The Java way is that you should consider what data abstraction most suits your needs. Remember that in Java a List is an abstract, not a concrete data type. You should declare the strings as a List, and then initialize it using the ArrayList implementation.

List<String> strings = new ArrayList<String>();

This separation of Abstract Data Type and specific implementation is one the key aspects of object oriented programming.

An ArrayList implements the List Abstract Data Type using an array as its underlying implementation. Access speed is virtually identical to an array, with the additional advantages of being able to add and subtract elements to a List (although this is an O(n) operation with an ArrayList) and that if you decide to change the underlying implementation later on you can. For example, if you realize you need synchronized access, you can change the implementation to a Vector without rewriting all your code.

In fact, the ArrayList was specifically designed to replace the low-level array construct in most contexts. If Java was being designed today, it's entirely possible that arrays would have been left out altogether in favor of the ArrayList construct.

Since arrays keep all the data in a contiguous chunk of memory (unlike Lists), would the use of an array to store thousands of strings cause problems ?

In Java, all collections store only references to objects, not the objects themselves. Both arrays and ArrayList will store a few thousand references in a contiguous array, so they are essentially identical. You can consider that a contiguous block of a few thousand 32-bit references will always be readily available on modern hardware. This does not guarantee that you will not run out of memory altogether, of course, just that the contiguous block of memory requirement is not difficult to fufil.

Excel Validation Drop Down list using VBA

based on examples above and examples found on other sites, I created a generic procedure and some examples.

'Simple helper procedure to create a dropdown in a cell based on a list of values in a range
'ValueSheetName : the name of the sheet containing the value range
'ValueRangeString : the range on the sheet with name ValueSheetName containing the values for the dropdown
'CreateOnSheetName : the name of the sheet where the dropdown needs to be created
'CreateInRangeString : the range where the dropdown needs to be created
'FieldName As String : a name of the dropdown, will be used in the inputMessage and ErrorMessage
'See example below ExampleCreateDropDown
Public Sub CreateDropDown(ValueSheetName As String, ValueRangeString As String, CreateOnSheetName As String, CreateInRangeString As String, FieldName As String)
    Dim ValueSheet As Worksheet
    Set ValueSheet = Worksheets(ValueSheetName) 'The sheet containing the values
    Dim ValueRange As Range: Set ValueRange = ValueSheet.Range(ValueRangeString) 'The range containing the values
    Dim CreateOnSheet As Worksheet
    Set CreateOnSheet = Worksheets(CreateOnSheetName) 'The sheet containing the values
    Dim CreateInRange As Range: Set CreateInRange = CreateOnSheet.Range(CreateInRangeString)
    Dim InputTitle As String:  InputTitle = "Please Select a Value"
    Dim InputMessage As String:  InputMessage = "for " & FieldName
    Dim ErrorTitle As String:  ErrorTitle = "Please Select a Value"
    Dim ErrorMessage As String:  ErrorMessage = "for " & FieldName
    Dim ShowInput As Boolean:  ShowInput = True 'Show input message on hover
    Dim ShowError As Boolean:  ShowError = True 'Show error message on error
    Dim ValidationType As XlDVType:  ValidationType = xlValidateList
    Dim ValidationAlertStyle As XlDVAlertStyle:  ValidationAlertStyle = xlValidAlertStop 'Stop on invalid value
    Dim ValidationOperator As XlFormatConditionOperator:  ValidationOperator = xlEqual 'Value must be equal to one of the Values from the ValidationFormula1
    Dim ValidationFormula1 As Variant:  ValidationFormula1 = "=" & ValueSheetName & "!" & ValueRange.Address 'Formula referencing the values from the ValueRange
    Dim ValidationFormula2 As Variant:  ValidationFormula2 = ""

    Call CreateDropDownWithValidationInCell(CreateInRange, InputTitle, InputMessage, ErrorTitle, ErrorMessage, ShowInput, ShowError, ValidationType, ValidationAlertStyle, ValidationOperator, ValidationFormula1, ValidationFormula2)
End Sub


'An example using the ExampleCreateDropDown
Private Sub ExampleCreateDropDown()
    Call CreateDropDown(ValueSheetName:="Test", ValueRangeString:="C1:C5", CreateOnSheetName:="Test", CreateInRangeString:="B1", FieldName:="test2")
End Sub


'The full option function if you need more configurable options
'To create a dropdown in a cell based on a list of values in a range
'Validation: https://msdn.microsoft.com/en-us/library/office/ff840078.aspx
'ValidationTypes: XlDVType  https://msdn.microsoft.com/en-us/library/office/ff840715.aspx
'ValidationAlertStyle:  XlDVAlertStyle  https://msdn.microsoft.com/en-us/library/office/ff841223.aspx
'XlFormatConditionOperator  https://msdn.microsoft.com/en-us/library/office/ff840923.aspx
'See example below ExampleCreateDropDownWithValidationInCell
Public Sub CreateDropDownWithValidationInCell(CreateInRange As Range, _
                                        Optional InputTitle As String = "", _
                                        Optional InputMessage As String = "", _
                                        Optional ErrorTitle As String = "", _
                                        Optional ErrorMessage As String = "", _
                                        Optional ShowInput As Boolean = True, _
                                        Optional ShowError As Boolean = True, _
                                        Optional ValidationType As XlDVType = xlValidateList, _
                                        Optional ValidationAlertStyle As XlDVAlertStyle = xlValidAlertStop, _
                                        Optional ValidationOperator As XlFormatConditionOperator = xlEqual, _
                                        Optional ValidationFormula1 As Variant = "", _
                                        Optional ValidationFormula2 As Variant = "")

    With CreateInRange.Validation
        .Delete
        .Add Type:=ValidationType, AlertStyle:=ValidationAlertStyle, Operator:=ValidationOperator, Formula1:=ValidationFormula1, Formula2:=ValidationFormula2
        .IgnoreBlank = True
        .InCellDropdown = True
        .InputTitle = InputTitle
        .ErrorTitle = ErrorTitle
        .InputMessage = InputMessage
        .ErrorMessage = ErrorMessage
        .ShowInput = ShowInput
        .ShowError = ShowError
    End With
End Sub


'An example using the CreateDropDownWithValidationInCell
Private Sub ExampleCreateDropDownWithValidationInCell()
    Dim ValueSheetName As String: ValueSheetName = "Hidden" 'The sheet containing the values
    Dim ValueRangeString As String: ValueRangeString = "C7:C9" 'The range containing the values
    Dim CreateOnSheetName As String: CreateOnSheetName = "Test"  'The sheet containing the dropdown
    Dim CreateInRangeString As String: CreateInRangeString = "A1" 'The range containing the dropdown

    Dim ValueSheet As Worksheet
    Set ValueSheet = Worksheets(ValueSheetName)
    Dim ValueRange As Range: Set ValueRange = ValueSheet.Range(ValueRangeString)
    Dim CreateOnSheet As Worksheet
    Set CreateOnSheet = Worksheets(CreateOnSheetName)
    Dim CreateInRange As Range: Set CreateInRange = CreateOnSheet.Range(CreateInRangeString)
    Dim FieldName As String: FieldName = "Testing Dropdown"
    Dim InputTitle As String:  InputTitle = "Please Select a value"
    Dim InputMessage As String:  InputMessage = "for " & FieldName
    Dim ErrorTitle As String:  ErrorTitle = "Please Select a value"
    Dim ErrorMessage As String:  ErrorMessage = "for " & FieldName
    Dim ShowInput As Boolean:  ShowInput = True
    Dim ShowError As Boolean:  ShowError = True
    Dim ValidationType As XlDVType:  ValidationType = xlValidateList
    Dim ValidationAlertStyle As XlDVAlertStyle:  ValidationAlertStyle = xlValidAlertStop
    Dim ValidationOperator As XlFormatConditionOperator:  ValidationOperator = xlEqual
    Dim ValidationFormula1 As Variant:  ValidationFormula1 = "=" & ValueSheetName & "!" & ValueRange.Address
    Dim ValidationFormula2 As Variant:  ValidationFormula2 = ""

    Call CreateDropDownWithValidationInCell(CreateInRange, InputTitle, InputMessage, ErrorTitle, ErrorMessage, ShowInput, ShowError, ValidationType, ValidationAlertStyle, ValidationOperator, ValidationFormula1, ValidationFormula2)

End Sub

How to disable Paste (Ctrl+V) with jQuery?

This now works for IE FF Chrome properly... I have not tested for other browsers though

$(document).ready(function(){
   $('#txtInput').on("cut copy paste",function(e) {
      e.preventDefault();
   });
});

Edit: As pointed out by webeno, .bind() is deprecated hence it is recommended to use .on() instead.

How to improve performance of ngRepeat over a huge dataset (angular.js)?

Virtual scrolling is another way to improve scrolling performance when dealing with huge lists and large dataset.

One way to implement this is by using Angular Material md-virtual-repeat as it is demonstrated on this Demo with 50,000 items

Taken straight from the documentation of virtual repeat:

Virtual repeat is a limited substitute for ng-repeat that renders only enough dom nodes to fill the container and recycling them as the user scrolls.

using BETWEEN in WHERE condition

I think we can write like this : $this->db->where('accommodation >=', minvalue); $this->db->where('accommodation <=', maxvalue);

//without dollar($) sign It's work for me :)

How to create timer events using C++ 11?

Made a simple implementation of what I believe to be what you want to achieve. You can use the class later with the following arguments:

  • int (milliseconds to wait until to run the code)
  • bool (if true it returns instantly and runs the code after specified time on another thread)
  • variable arguments (exactly what you'd feed to std::bind)

You can change std::chrono::milliseconds to std::chrono::nanoseconds or microseconds for even higher precision and add a second int and a for loop to specify for how many times to run the code.

Here you go, enjoy:

#include <functional>
#include <chrono>
#include <future>
#include <cstdio>

class later
{
public:
    template <class callable, class... arguments>
    later(int after, bool async, callable&& f, arguments&&... args)
    {
        std::function<typename std::result_of<callable(arguments...)>::type()> task(std::bind(std::forward<callable>(f), std::forward<arguments>(args)...));

        if (async)
        {
            std::thread([after, task]() {
                std::this_thread::sleep_for(std::chrono::milliseconds(after));
                task();
            }).detach();
        }
        else
        {
            std::this_thread::sleep_for(std::chrono::milliseconds(after));
            task();
        }
    }

};

void test1(void)
{
    return;
}

void test2(int a)
{
    printf("%i\n", a);
    return;
}

int main()
{
    later later_test1(1000, false, &test1);
    later later_test2(1000, false, &test2, 101);

    return 0;
}

Outputs after two seconds:

101

How to list npm user-installed packages?

Use npm list and filter by contains using grep

Example:

npm list -g | grep name-of-package

How to get text box value in JavaScript

Set the id attribute of the input to txtJob. Your browser is acting quirky when you call getElementById.

How to determine equality for two JavaScript objects?

This is a simple Javascript function to compare two objects having simple key-value pairs. The function will return an array of strings, where each string is a path to an inequality between the two objects.

function compare(a,b) {
    var paths = [];
    [...new Set(Object.keys(a).concat(Object.keys(b)))].forEach(key=>{
        if(typeof a[key] === 'object' && typeof b[key] === 'object') {
            var results = compare(a[key], b[key]);
            if(JSON.stringify(results)!=='[]') {
                paths.push(...results.map(result=>key.concat("=>"+result)));
            }
        }
        else if (a[key]!==b[key]) {
            paths.push(key);
        }
    })
    return paths;
}

If you only want to compare two objects without knowing the paths to inequalities, you can do it as follows:

if(JSON.stringify(compare(object1, object2))==='[]') {
   // the two objects are equal
} else {
   // the two objects are not equal
}

How to create a new component in Angular 4 using CLI

1) first go to your Project Directory

2) then Run below Command in terminal.

ng generate component componentname

OR

ng g component componentname

3) after that you will see output like this,

create src/app/test/componentname.component.css (0 bytes)
create src/app/test/componentname.component.html (23 bytes)
create src/app/test/componentname.component.spec.ts (614 bytes)
create src/app/test/componentname.component.ts (261 bytes)
update src/app/app.module.ts (1087 bytes)

Mockito How to mock and assert a thrown exception?

If you want to test the exception message as well you can use JUnit's ExpectedException with Mockito:

@Rule
public ExpectedException expectedException = ExpectedException.none();

@Test
public void testExceptionMessage() throws Exception {
    expectedException.expect(AnyException.class);
    expectedException.expectMessage("The expected message");

    given(foo.bar()).willThrow(new AnyException("The expected message"));
}

Remove duplicates from dataframe, based on two columns A,B, keeping row with max value in another column C

You can do it with drop_duplicates as you wanted

# initialisation
d = pd.DataFrame({'A' : [1,1,2,3,3], 'B' : [2,2,7,4,4],  'C' : [1,4,1,0,8]})

d = d.sort_values("C", ascending=False)
d = d.drop_duplicates(["A","B"])

If it's important to get the same order

d = d.sort_index()