Programs & Examples On #Alter table

The "ALTER TABLE" is a SQL statement that allows you to make schema changes to a database table (i.e. add or drop columns from an existing table).

How do I alter the position of a column in a PostgreSQL database table?

I don't think you can at present: see this article on the Postgresql wiki.

The three workarounds from this article are:

  1. Recreate the table
  2. Add columns and move data
  3. Hide the differences with a view.

How to delete a column from a table in MySQL

Use ALTER TABLE with DROP COLUMN to drop a column from a table, and CHANGE or MODIFY to change a column.

ALTER TABLE tbl_Country DROP COLUMN IsDeleted;
ALTER TABLE tbl_Country MODIFY IsDeleted tinyint(1) NOT NULL;
ALTER TABLE tbl_Country CHANGE IsDeleted IsDeleted tinyint(1) NOT NULL;

How to change MySQL column definition?

This should do it:

ALTER TABLE test MODIFY locationExpert VARCHAR(120) 

Rename column SQL Server 2008

Sql Server management studio has some system defined Stored Procedures(SP)
One of which is used to rename a column.The SP is sp_rename

Syntax: sp_rename '[table_name].old_column_name', 'new_column_name'
For further help refer this article: sp_rename by Microsoft Docs

Note: On execution of this SP the sql server will give you a caution message as 'Caution: Changing any part of an object name could break scripts and stored procedures'.This is critical only if you have written your own sp which involves the column in the table you are about to change.

How to rename a table in SQL Server?

When using sp_rename which works like in above answers, check also which objects are affected after renaming, that reference that table, because you need to change those too

I took a code example for table dependencies at Pinal Dave's blog here

USE AdventureWorks
GO
SELECT
referencing_schema_name = SCHEMA_NAME(o.SCHEMA_ID),
referencing_object_name = o.name,
referencing_object_type_desc = o.type_desc,
referenced_schema_name,
referenced_object_name = referenced_entity_name,
referenced_object_type_desc = o1.type_desc,
referenced_server_name, referenced_database_name
--,sed.* -- Uncomment for all the columns
FROM
sys.sql_expression_dependencies sed
INNER JOIN
sys.objects o ON sed.referencing_id = o.[object_id]
LEFT OUTER JOIN
sys.objects o1 ON sed.referenced_id = o1.[object_id]
WHERE
referenced_entity_name = 'Customer'

So, all these dependent objects needs to be updated also

Or use some add-in if you can, some of them have feature to rename object, and all depend,ent objects too

how to modify the size of a column

Regardless of what error Oracle SQL Developer may indicate in the syntax highlighting, actually running your alter statement exactly the way you originally had it works perfectly:

ALTER TABLE TEST_PROJECT2 MODIFY proj_name VARCHAR2(300);

You only need to add parenthesis if you need to alter more than one column at once, such as:

ALTER TABLE TEST_PROJECT2 MODIFY (proj_name VARCHAR2(400), proj_desc VARCHAR2(400));

Alter column, add default constraint

I use the stored procedure below to update the defaults on a column.

It automatically removes any prior defaults on the column, before adding the new default.

Examples of usage:

-- Update default to be a date.
exec [dbo].[AlterDefaultForColumn] '[dbo].[TableName]','Column','getdate()';
-- Update default to be a number.
exec [dbo].[AlterDefaultForColumn] '[dbo].[TableName]','Column,'6';
-- Update default to be a string. Note extra quotes, as this is not a function.
exec [dbo].[AlterDefaultForColumn] '[dbo].[TableName]','Column','''MyString''';

Stored procedure:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- Sample function calls:
--exec [dbo].[AlterDefaultForColumn] '[dbo].[TableName]','ColumnName','getdate()';
--exec [dbol].[AlterDefaultForColumn] '[dbo].[TableName]','Column,'6';
--exec [dbo].[AlterDefaultForColumn] '[dbo].[TableName]','Column','''MyString''';
create PROCEDURE [dbo].[ColumnDefaultUpdate]
    (
        -- Table name, including schema, e.g. '[dbo].[TableName]'
        @TABLE_NAME VARCHAR(100), 
        -- Column name, e.g. 'ColumnName'.
        @COLUMN_NAME VARCHAR(100),
        -- New default, e.g. '''MyDefault''' or 'getdate()'
        -- Note that if you want to set it to a string constant, the contents
        -- must be surrounded by extra quotes, e.g. '''MyConstant''' not 'MyConstant'
        @NEW_DEFAULT VARCHAR(100)
    )
AS 
BEGIN       
    -- Trim angle brackets so things work even if they are included.
    set @COLUMN_NAME = REPLACE(@COLUMN_NAME, '[', '')
    set @COLUMN_NAME = REPLACE(@COLUMN_NAME, ']', '')

    print 'Table name: ' + @TABLE_NAME;
    print 'Column name: ' + @COLUMN_NAME;
    DECLARE @ObjectName NVARCHAR(100)
    SELECT @ObjectName = OBJECT_NAME([default_object_id]) FROM SYS.COLUMNS
    WHERE [object_id] = OBJECT_ID(@TABLE_NAME) AND [name] = @COLUMN_NAME;

    IF @ObjectName <> '' 
    begin
        print 'Removed default: ' + @ObjectName;
        --print('ALTER TABLE ' + @TABLE_NAME + ' DROP CONSTRAINT ' + @ObjectName)
        EXEC('ALTER TABLE ' + @TABLE_NAME + ' DROP CONSTRAINT ' + @ObjectName)
    end

    EXEC('ALTER TABLE ' + @TABLE_NAME + ' ADD  DEFAULT (' + @NEW_DEFAULT + ') FOR ' + @COLUMN_NAME)
    --print('ALTER TABLE ' + @TABLE_NAME + ' ADD  DEFAULT (' + @NEW_DEFAULT + ') FOR ' + @COLUMN_NAME)
    print 'Added default of: ' + @NEW_DEFAULT;
END

Errors this stored procedure eliminates

If you attempt to add a default to a column when one already exists, you will get the following error (something you will never see if using this stored proc):

-- Using the stored procedure eliminates this error:
Msg 1781, Level 16, State 1, Line 1
Column already has a DEFAULT bound to it.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint. See previous errors.

How do you change the datatype of a column in SQL Server?

The syntax to modify a column in an existing table in SQL Server (Transact-SQL) is:

ALTER TABLE table_name
    ALTER COLUMN column_name column_type;

For example:

ALTER TABLE employees
    ALTER COLUMN last_name VARCHAR(75) NOT NULL;

This SQL Server ALTER TABLE example will modify the column called last_name to be a data type of VARCHAR(75) and force the column to not allow null values.

see here

Alter a MySQL column to be AUTO_INCREMENT

You can apply the atuto_increment constraint to the data column by the following query:

ALTER TABLE customers MODIFY COLUMN customer_id BIGINT NOT NULL AUTO_INCREMENT;

But, if the columns are part of a foreign key constraint you, will most probably receive an error. Therefore, it is advised to turn off foreign_key_checks by using the following query:

SET foreign_key_checks = 0;

Therefore, use the following query instead:

SET foreign_key_checks = 0;
ALTER TABLE customers MODIFY COLUMN customer_id BIGINT NOT NULL AUTO_INCREMENT;
SET foreign_key_checks = 1;

How can I add a column that doesn't allow nulls in a Postgresql database?

Or, create a new table as temp with the extra column, copy the data to this new table while manipulating it as necessary to fill the non-nullable new column, and then swap the table via a two-step name change.

Yes, it is more complicated, but you may need to do it this way if you don't want a big UPDATE on a live table.

How do I add more members to my ENUM-type column in MySQL?

FYI: A useful simulation tool - phpMyAdmin with Wampserver 3.0.6 - Preview SQL: I use 'Preview SQL' to see the SQL code that would be generated before you save the column with the change to ENUM. Preview SQL

Above you see that I have entered 'Ford','Toyota' into the ENUM but I am getting syntax ENUM(0) which is generating syntax error Query error 1064#

I then copy and paste and alter the SQL and run it through SQL with a positive result.

SQL changed

This is a quickfix that I use often and can also be used on existing ENUM values that need to be altered. Thought this might be useful.

Adding an identity to an existing column

Simple explanation

Rename the existing column using sp_RENAME

EXEC sp_RENAME 'Table_Name.Existing_ColumnName' , 'New_ColumnName', 'COLUMN'

Example for Rename :

The existing column UserID is renamed as OldUserID

EXEC sp_RENAME 'AdminUsers.UserID' , 'OldUserID', 'COLUMN'

Then add a new column using alter query to set as primary key and identity value

ALTER TABLE TableName ADD Old_ColumnName INT NOT NULL PRIMARY KEY IDENTITY(1,1)

Example for Set Primary key

The new created column name is UserID

ALTER TABLE Users ADD UserID INT NOT NULL PRIMARY KEY IDENTITY(1,1)

then Drop the Renamed Column

ALTER TABLE Table_Name DROP COLUMN Renamed_ColumnName

Example for Drop renamed column

ALTER TABLE Users DROP COLUMN OldUserID

Now we've adding a primarykey and identity to the existing column on the table.

How do I Alter Table Column datatype on more than 1 column?

Use the following syntax:

  ALTER TABLE your_table
  MODIFY COLUMN column1 datatype,
  MODIFY COLUMN column2 datatype,
  ... ... ... ... ... 
  ... ... ... ... ...

Based on that, your ALTER command should be:

  ALTER TABLE webstore.Store
  MODIFY COLUMN ShortName VARCHAR(100),
  MODIFY COLUMN UrlShort VARCHAR(100)

Note that:

  1. There are no second brackets around the MODIFY statements.
  2. I used two separate MODIFY statements for two separate columns.

This is the standard format of the MODIFY statement for an ALTER command on multiple columns in a MySQL table.

Take a look at the following: http://dev.mysql.com/doc/refman/5.1/en/alter-table.html and Alter multiple columns in a single statement

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

sqlite3 yourdb .dump > /tmp/db.txt
edit /tmp/db.txt change column name in Create line
sqlite2 yourdb2 < /tmp/db.txt
mv/move yourdb2 yourdb

Alter MySQL table to add comments on columns

try:

 ALTER TABLE `user` CHANGE `id` `id` INT( 11 ) COMMENT 'id of user'  

insert a NOT NULL column to an existing table

If you aren't allowing the column to be Null you need to provide a default to populate existing rows. e.g.

ALTER TABLE dbo.YourTbl ADD
    newcol int NOT NULL CONSTRAINT DF_YourTbl_newcol DEFAULT 0

On Enterprise Edition this is a metadata only change since 2012

How to add a column in TSQL after a specific column?

In SQL Enterprise Management Studio, open up your table, add the column where you want it, and then -- instead of saving the change -- generate the change script. You can see how it's done in SQL.

In short, what others have said is right. SQL Management studio pulls all your data into a temp table, drops the table, recreates it with columns in the right order, and puts the temp table data back in there. There is no simple syntax for adding a column in a specific position.

How can I modify the size of column in a MySQL table?

Have you tried this?

ALTER TABLE <table_name> MODIFY <col_name> VARCHAR(65353);

This will change the col_name's type to VARCHAR(65353)

How to alter a column's data type in a PostgreSQL table?

Cool @derek-kromm, Your answer is accepted and correct, But I am wondering if we need to alter more than the column. Here is how we can do.

ALTER TABLE tbl_name 
ALTER COLUMN col_name TYPE varchar (11), 
ALTER COLUMN col_name2 TYPE varchar (11),
ALTER COLUMN col_name3 TYPE varchar (11);

Documentation

Cheers!! Read Simple Write Simple

How to add a boolean datatype column to an existing table in sql?

The answer given by P????? creates a nullable bool, not a bool, which may be fine for you. For example in C# it would create: bool? AdminApprovednot bool AdminApproved.

If you need to create a bool (defaulting to false):

    ALTER TABLE person
    ADD AdminApproved BIT
    DEFAULT 0 NOT NULL;

ALTER TABLE ADD COLUMN IF NOT EXISTS in SQLite

All these answers are fine if you execute one line at a time. However, the original question was to input a sql script that would be executed by a single db execute and all the solutions ( like checking to see if the column is there ahead of time ) would require the executing program either have knowledge of what tables and columns are being altered/added or do pre-processing and parsing of the input script to determine this information. Typically you are not going to run this in realtime or often. So the idea of catching an exception is acceptable and then moving on. Therein lies the problem...how to move on. Luckily the error message gives us all the information we need to do this. The idea is to execute the sql if it exceptions on an alter table call we can find the alter table line in the sql and return the remaining lines and execute until it either succeeds or no more matching alter table lines can be found. Heres some example code where we have sql scripts in an array. We iterate the array executing each script. We call it twice to get the alter table command to fail but the program succeeds because we remove the alter table command from the sql and re-execute the updated code.

#!/bin/sh
# the next line restarts using wish \

exec /opt/usr8.6.3/bin/tclsh8.6  "$0" ${1+"$@"}
foreach pkg {sqlite3 } {
    if { [ catch {package require {*}$pkg } err ] != 0 } {
    puts stderr "Unable to find package $pkg\n$err\n ... adjust your auto_path!";
    }
}
array set sqlArray {
    1 {
    CREATE TABLE IF NOT EXISTS Notes (
                      id INTEGER PRIMARY KEY AUTOINCREMENT,
                      name text,
                      note text,
                      createdDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) ,
                      updatedDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) 
                      );
    CREATE TABLE IF NOT EXISTS Version (
                        id INTEGER PRIMARY KEY AUTOINCREMENT,
                        version text,
                        createdDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) ,
                        updatedDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) )
                        );
    INSERT INTO Version(version) values('1.0');
    }
    2 {
    CREATE TABLE IF NOT EXISTS Tags (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name text,
        tag text,
        createdDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) ,
        updatedDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) 
        );
    ALTER TABLE Notes ADD COLUMN dump text;
    INSERT INTO Version(version) values('2.0');
    }
    3 {
    ALTER TABLE Version ADD COLUMN sql text;
    INSERT INTO Version(version) values('3.0');
    }
}

# create db command , use in memory database for demonstration purposes
sqlite3 db :memory:

proc createSchema { sqlArray } {
    upvar $sqlArray sql
    # execute each sql script in order 
    foreach version [lsort -integer [array names sql ] ] {
    set cmd $sql($version)
    set ok 0
    while { !$ok && [string length $cmd ] } {  
        try {
        db eval $cmd
        set ok 1  ;   # it succeeded if we get here
        } on error { err backtrace } {
        if { [regexp {duplicate column name: ([a-zA-Z0-9])} [string trim $err ] match columnname ] } {
            puts "Error:  $err ... trying again" 
            set cmd [removeAlterTable $cmd $columnname ]
        } else {
            throw DBERROR "$err\n$backtrace"
        }
        }
    }
    }
}
# return sqltext with alter table command with column name removed
# if no matching alter table line found or result is no lines then
# returns ""
proc removeAlterTable { sqltext columnname } {
    set mode skip
    set result [list]
    foreach line [split $sqltext \n ] {
    if { [string first "alter table" [string tolower [string trim $line] ] ] >= 0 } {
        if { [string first $columnname $line ] } {
        set mode add
        continue;
        }
    }
    if { $mode eq "add" } {
        lappend result $line
    }
    }
    if { $mode eq "skip" } {
    puts stderr "Unable to find matching alter table line"
    return ""
    } elseif { [llength $result ] }  { 
    return [ join $result \n ]
    } else {
    return ""
    }
}
               
proc printSchema { } {
    db eval { select * from sqlite_master } x {
    puts "Table: $x(tbl_name)"
    puts "$x(sql)"
    puts "-------------"
    }
}
createSchema sqlArray
printSchema
# run again to see if we get alter table errors 
createSchema sqlArray
printSchema

expected output

Table: Notes
CREATE TABLE Notes (
                      id INTEGER PRIMARY KEY AUTOINCREMENT,
                      name text,
                      note text,
                      createdDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) ,
                      updatedDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) 
                      , dump text)
-------------
Table: sqlite_sequence
CREATE TABLE sqlite_sequence(name,seq)
-------------
Table: Version
CREATE TABLE Version (
                        id INTEGER PRIMARY KEY AUTOINCREMENT,
                        version text,
                        createdDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) ,
                        updatedDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) )
                        , sql text)
-------------
Table: Tags
CREATE TABLE Tags (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name text,
        tag text,
        createdDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) ,
        updatedDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) 
        )
-------------
Error:  duplicate column name: dump ... trying again
Error:  duplicate column name: sql ... trying again
Table: Notes
CREATE TABLE Notes (
                      id INTEGER PRIMARY KEY AUTOINCREMENT,
                      name text,
                      note text,
                      createdDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) ,
                      updatedDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) 
                      , dump text)
-------------
Table: sqlite_sequence
CREATE TABLE sqlite_sequence(name,seq)
-------------
Table: Version
CREATE TABLE Version (
                        id INTEGER PRIMARY KEY AUTOINCREMENT,
                        version text,
                        createdDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) ,
                        updatedDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) )
                        , sql text)
-------------
Table: Tags
CREATE TABLE Tags (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name text,
        tag text,
        createdDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) ,
        updatedDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) 
        )
-------------

ALTER TABLE on dependent column

If your constraint is on a user type, then don't forget to see if there is a Default Constraint, usually something like DF__TableName__ColumnName__6BAEFA67, if so then you will need to drop the Default Constraint, like this:

ALTER TABLE TableName DROP CONSTRAINT [DF__TableName__ColumnName__6BAEFA67]

For more info see the comments by the brilliant Aaron Bertrand on this answer.

Postgresql - change the size of a varchar column to lower length

if you put the alter into a transaction the table should not be locked:

BEGIN;
  ALTER TABLE "public"."mytable" ALTER COLUMN "mycolumn" TYPE varchar(40);
COMMIT;

this worked for me blazing fast, few seconds on a table with more than 400k rows.

Check if a temporary table exists and delete if it exists before creating a temporary table

I think the problem is you need to add GO statement in between to separate the execution into batches. As the second drop script i.e. IF OBJECT_ID('tempdb..#Results') IS NOT NULL DROP TABLE #Results did not drop the temp table being part of single batch. Can you please try the below script.

IF OBJECT_ID('tempdb..#Results') IS NOT NULL
    DROP TABLE #Results

CREATE TABLE #Results
(
    Company                CHAR(3),
    StepId                TINYINT,
    FieldId                TINYINT,
)

GO

select company, stepid, fieldid from #Results

IF OBJECT_ID('tempdb..#Results') IS NOT NULL
DROP TABLE #Results

CREATE TABLE #Results
(
    Company                CHAR(3),
    StepId                TINYINT,
    FieldId                TINYINT,
    NewColumn            NVARCHAR(50)
)

GO

select company, stepid, fieldid, NewColumn from #Results

ALTER TABLE to add a composite primary key

You may simply want a UNIQUE CONSTRAINT. Especially if you already have a surrogate key. (example of an already existing surrogate key would be a single column that is an AUTO_INCREMENT )

Below is the sql code for a Unique Constraint

ALTER TABLE `MyDatabase`.`Provider`
    ADD CONSTRAINT CK_Per_Place_Thing_Unique UNIQUE (person,place,thing)
;

MySQL: ALTER TABLE if column not exists

Use PREPARE/EXECUTE and querying the schema. The host doesn't need to have permission to create or run procedures :

SET @dbname = DATABASE();
SET @tablename = "tableName";
SET @columnname = "colName";
SET @preparedStatement = (SELECT IF(
  (
    SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
    WHERE
      (table_name = @tablename)
      AND (table_schema = @dbname)
      AND (column_name = @columnname)
  ) > 0,
  "SELECT 1",
  CONCAT("ALTER TABLE ", @tablename, " ADD ", @columnname, " INT(11);")
));
PREPARE alterIfNotExists FROM @preparedStatement;
EXECUTE alterIfNotExists;
DEALLOCATE PREPARE alterIfNotExists;

Altering column size in SQL Server

Interesting approach could be found here: How To Enlarge Your Columns With No Downtime by spaghettidba

If you try to enlarge this column with a straight “ALTER TABLE” command, you will have to wait for SQLServer to go through all the rows and write the new data type

ALTER TABLE tab_name ALTER COLUMN col_name new_larger_data_type;

To overcome this inconvenience, there is a magic column enlargement pill that your table can take, and it’s called Row Compression. (...) With Row Compression, your fixed size columns can use only the space needed by the smallest data type where the actual data fits.

When table is compressed at ROW level, then ALTER TABLE ALTER COLUMN is metadata only operation.

Change a Nullable column to NOT NULL with Default Value

Try this

ALTER TABLE table_name ALTER COLUMN col_name data_type NOT NULL;

ALTER table - adding AUTOINCREMENT in MySQL

ALTER TABLE `ALLITEMS`
    CHANGE COLUMN `itemid` `itemid` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT;

Rails: How can I rename a database column in a Ruby on Rails migration?

Rails 5 migration changes

eg:

rails g model Student student_name:string age:integer

if you want to change student_name column as name

Note:- if you not run rails db:migrate

You can do following steps

rails d model Student student_name:string age:integer

This will remove generated migration file, Now you can correct your column name

rails g model Student name:string age:integer

If you migrated(rails db:migrate), following options to change column name

rails g migration RemoveStudentNameFromStudent student_name:string

rails g migration AddNameToStudent name:string

Hive Alter table change Column Name

Command works only if "use" -command has been first used to define the database where working in. Table column renaming syntax using DATABASE.TABLE throws error and does not work. Version: HIVE 0.12.

EXAMPLE:

hive> ALTER TABLE databasename.tablename CHANGE old_column_name new_column_name;

  MismatchedTokenException(49!=90)
        at org.antlr.runtime.BaseRecognizer.recoverFromMismatchedToken(BaseRecognizer.java:617)
        at org.antlr.runtime.BaseRecognizer.match(BaseRecognizer.java:115)
        at org.apache.hadoop.hive.ql.parse.HiveParser.alterStatementSuffixExchangePartition(HiveParser.java:11492)
        ...

hive> use databasename;

hive> ALTER TABLE tablename CHANGE old_column_name new_column_name;

OK

Error renaming a column in MySQL

There is a syntax problem, because the right syntax to alter command is ALTER TABLE tablename CHANGE OldColumnName NewColunmName DATATYPE;

SQL Server add auto increment primary key to existing table

Try something like this (on a test table first):

USE your_database_name
GO
WHILE (SELECT COUNT(*) FROM your_table WHERE your_id_field IS NULL) > 0
BEGIN
    SET ROWCOUNT 1
    UPDATE your_table SET your_id_field = MAX(your_id_field)+1
END
PRINT 'ALL DONE'

I have not tested this at all, so be careful!

Modify a Column's Type in sqlite3

If you prefer a GUI, DB Browser for SQLite will do this with a few clicks.

  1. "File" - "Open Database"
  2. In the "Database Structure" tab, click on the table content (not table name), then "Edit" menu, "Modify table", and now you can change the data type of any column with a drop down menu. I changed a 'text' field to 'numeric' in order to retrieve data in a number range.

DB Browser for SQLite is open source and free. For Linux it is available from the repository.

Alter table to modify default value of column

For Sql Azure the following query works :

ALTER TABLE [TableName] ADD  DEFAULT 'DefaultValue' FOR ColumnName
GO

Altering a column: null to not null

this worked for me:

ALTER TABLE [Table] 
Alter COLUMN [Column] VARCHAR(50) not null;

What is the difference between 'my' and 'our' in Perl?

Just try to use the following program :

#!/usr/local/bin/perl
use feature ':5.10';
#use warnings;
package a;
{
my $b = 100;
our $a = 10;


print "$a \n";
print "$b \n";
}

package b;

#my $b = 200;
#our $a = 20 ;

print "in package b value of  my b $a::b \n";
print "in package b value of our a  $a::a \n";

Convert MySQL to SQlite

If you have experience write simple scripts by Perl\Python\etc, and convert MySQL to SQLite. Read data from Mysql and write it on SQLite.

How to implement class constants?

You can mark properties with readonly modifier in your declaration:

export class MyClass {
  public static readonly MY_PUBLIC_CONSTANT = 10;
  private static readonly myPrivateConstant = 5;
}

@see TypeScript Deep Dive book - Readonly

How to iterate (keys, values) in JavaScript?

You can use JavaScript forEach Loop:

myMap.forEach((value, key) => {
    console.log('value: ', value);
    console.log('key: ', key);
});

Java equivalent to C# extension methods

One could be use the decorator object-oriented design pattern. An example of this pattern being used in Java's standard library would be the DataOutputStream.

Here's some code for augmenting the functionality of a List:

public class ListDecorator<E> implements List<E>
{
    public final List<E> wrapee;

    public ListDecorator(List<E> wrapee)
    {
        this.wrapee = wrapee;
    }

    // implementation of all the list's methods here...

    public <R> ListDecorator<R> map(Transform<E,R> transformer)
    {
        ArrayList<R> result = new ArrayList<R>(size());
        for (E element : this)
        {
            R transformed = transformer.transform(element);
            result.add(transformed);
        }
        return new ListDecorator<R>(result);
    }
}

P.S. I'm a big fan of Kotlin. It has extension methods and also runs on the JVM.

max value of integer

In C, the integer(for 32 bit machine) is 32 bit and it ranges from -32768 to +32767.

Wrong. 32-bit signed integer in 2's complement representation has the range -231 to 231-1 which is equal to -2,147,483,648 to 2,147,483,647.

Google Maps v2 - set both my location and zoom in

gmap.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(new LatLng(9.491327, 76.571404), 10, 30, 0)));

Pandas read in table without headers

Previous answers were good and correct, but in my opinion, an extra names parameter will make it perfect, and it should be the recommended way, especially when the csv has no headers.

Solution

Use usecols and names parameters

df = pd.read_csv(file_path, usecols=[3,6], names=['colA', 'colB'])

Additional reading

or use header=None to explicitly tells people that the csv has no headers (anyway both lines are identical)

df = pd.read_csv(file_path, usecols=[3,6], names=['colA', 'colB'], header=None)

So that you can retrieve your data by

# with `names` parameter
df['colA']
df['colB'] 

instead of

# without `names` parameter
df[0]
df[1]

Explain

Based on read_csv, when names are passed explicitly, then header will be behaving like None instead of 0, so one can skip header=None when names exist.

Get all parameters from JSP page

The fastest way should be:

<%@ page import="java.util.Map" %>
Map<String, String[]> parameters = request.getParameterMap();
for (Map.Entry<String, String[]> entry : parameters.entrySet()) {
    if (entry.getKey().startsWith("question")) {
        String[] values = entry.getValue();
        // etc.

Note that you can't do:

for (Map.Entry<String, String[]> entry : 
     request.getParameterMap().entrySet()) { // WRONG!

for reasons explained here.

How do I collapse sections of code in Visual Studio Code for Windows?

With JavaScript:

//#region REGION_NAME
   ...code here
//#endregion

Form inline inside a form horizontal in twitter bootstrap?

Don't nest <form> tags, that will not work. Just use Bootstrap classes.

Bootstrap 3

<form class="form-horizontal" role="form">
    <div class="form-group">
      <label for="inputType" class="col-md-2 control-label">Type</label>
      <div class="col-md-3">
          <input type="text" class="form-control" id="inputType" placeholder="Type">
      </div>
    </div>
    <div class="form-group">
        <span class="col-md-2 control-label">Metadata</span>
        <div class="col-md-6">
            <div class="form-group row">
                <label for="inputKey" class="col-md-1 control-label">Key</label>
                <div class="col-md-2">
                    <input type="text" class="form-control" id="inputKey" placeholder="Key">
                </div>
                <label for="inputValue" class="col-md-1 control-label">Value</label>
                <div class="col-md-2">
                    <input type="text" class="form-control" id="inputValue" placeholder="Value">
                </div>
            </div>
        </div>
    </div>
</form>

You can achieve that behaviour in many ways, that's just an example. Test it on this bootply

Bootstrap 2

<form class="form-horizontal">
    <div class="control-group">
        <label class="control-label" for="inputType">Type</label>
        <div class="controls">
            <input type="text" id="inputType" placeholder="Type">
        </div>
    </div>
    <div class="control-group">
        <span class="control-label">Metadata</span>
        <div class="controls form-inline">
            <label for="inputKey">Key</label>
            <input type="text" class="input-small" placeholder="Key" id="inputKey">
            <label for="inputValue">Value</label>
            <input type="password" class="input-small" placeholder="Value" id="inputValue">
        </div>
    </div>
</form>

Note that I'm using .form-inline to get the propper styling inside a .controls.
You can test it on this jsfiddle

Convert a Map<String, String> to a POJO

if you have generic types in your class you should use TypeReference with convertValue().

final ObjectMapper mapper = new ObjectMapper();
final MyPojo<MyGenericType> pojo = mapper.convertValue(map, new TypeReference<MyPojo<MyGenericType>>() {});

Also you can use that to convert a pojo to java.util.Map back.

final ObjectMapper mapper = new ObjectMapper();
final Map<String, Object> map = mapper.convertValue(pojo, new TypeReference<Map<String, Object>>() {});

What is the best way to add options to a select from a JavaScript object with jQuery?

Set your HTML select id into following line below. In here mySelect is used as the id of the select element.

   var options = $("#mySelect");

then get the object which is the selectValues in this scenario and sets it to the jquery for each loop. It will use the value and text of the objects accordingly and appends it into the option selections as follows.

$.each(selectValues, function(val, text) {
            options.append(
             $('<option></option>').val(val).html(text)
          );
      });

This will display text as the option list when drop down list is selected and once a text is selected value of the selected text will be used.

Eg.

"1": "test 1", "2": "test 2",

Dropdown,

display name: test 1 -> value is 1 display name: test 2 -> value is 2

Save PHP array to MySQL?

You can save your array as a json.
there is documentation for json data type: https://dev.mysql.com/doc/refman/5.7/en/json.html
I think this is the best solution, and will help you maintain your code more readable by avoiding crazy functions.
I expect this is helpful for you.

How to center a button within a div?

et voila:

button {
  width: 100px; // whatever your button's width
  margin: 0 auto; // auto left/right margins
  display: block;
}

Update: If OP is looking for horizontal and vertical centre, this answer will do it for a fixed width/height element.

DB2 SQL error sqlcode=-104 sqlstate=42601

You miss the from clause

SELECT *  from TCCAWZTXD.TCC_COIL_DEMODATA WHERE CURRENT_INSERTTIME  BETWEEN(CURRENT_TIMESTAMP)-5 minutes AND CURRENT_TIMESTAMP

How to yum install Node.JS on Amazon Linux

I just came across this. I tried a few of the more popular answers, but in the end, what worked for me was Amazon's quick setup guide.

Tutorial: Setting Up Node.js on an Amazon EC2 Instance

The gist of the tutorial is:

  1. Make sure you are ssh'd onto the instance.
  2. Grab nvm: curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.32.0/install.sh | bash
  3. Active . ~/.nvm/nvm.sh
  4. Install node using nvm nvm install 4.4.5 (NOTE: You can choose a different version. Check out the remote versions first by running $ nvm ls-remote)
  5. Finally, test that you have installed node Node correctly by running $ node -e "console.log('Running Node.js' + process.version)"

Hopefully this helps the next person.

java.net.SocketTimeoutException: Read timed out under Tomcat

Here are the basic instructions:-

  1. Locate the "server.xml" file in the "conf" folder beneath Tomcat's base directory (i.e. %CATALINA_HOME%/conf/server.xml).
  2. Open the file in an editor and search for <Connector.
  3. Locate the relevant connector that is timing out - this will typically be the HTTP connector, i.e. the one with protocol="HTTP/1.1".
  4. If a connectionTimeout value is set on the connector, it may need to be increased - e.g. from 20000 milliseconds (= 20 seconds) to 120000 milliseconds (= 2 minutes). If no connectionTimeout property value is set on the connector, the default is 60 seconds - if this is insufficient, the property may need to be added.
  5. Restart Tomcat

Regular Expression to get a string between parentheses in Javascript

_x000D_
_x000D_
let str = "Before brackets (Inside brackets) After brackets".replace(/.*\(|\).*/g, '');_x000D_
console.log(str) // Inside brackets
_x000D_
_x000D_
_x000D_

How to comment out particular lines in a shell script

for single line comment add # at starting of a line
for multiple line comments add ' (single quote) from where you want to start & add ' (again single quote) at the point where you want to end the comment line.

How to lose margin/padding in UITextView?

This workaround was written in 2009 when IOS 3.0 was released. It no longer applies.

I ran into the exact same problem, in the end I had to wind up using

nameField.contentInset = UIEdgeInsetsMake(-4,-8,0,0);

where nameField is a UITextView. The font I happened to be using was Helvetica 16 point. Its only a custom solution for the particular field size I was drawing. This makes the left offset flush with the left side, and the top offset where I want it for the box its draw in.

In addition, this only seems to apply to UITextViews where you are using the default aligment, ie.

nameField.textAlignment = NSTextAlignmentLeft;

Align to the right for example and the UIEdgeInsetsMake seems to have no impact on the right edge at all.

At very least, using the .contentInset property allows you to place your fields with the "correct" positions, and accommodate the deviations without offsetting your UITextViews.

C# ListView Column Width Auto

I made a program that cleared and refilled my listview multiple times. For some reason whenever I added columns with width = -2 I encountered a problem with the first column being way too long. What I did to fix this was create this method.

private void ResizeListViewColumns(ListView lv)
{
    foreach(ColumnHeader column in lv.Columns)
    {
        column.Width = -2;
    }
}

The great thing about this method is that you can pretty much put this anywhere to resize all your columns. Just pass in your ListView.

Stop Visual Studio from mixing line endings in files

On the File menu, choose Advanced Save Options, you can control it there.

Edit: Here's the documentation, you should have a file open first.

Line continue character in C#

In his excellent answer, StuartLC cites an answer to a related question and mentions that placing newlines inside the {expression} of an interpolated string "looks odd." Most would agree, but the unpleasant source code effect can be mitigated somewhat--and without any runtime consequences--by using dedicated {expression} blocks which resolve to default(String), that is, null (and specifically not String.Empty).

The (albeit minor) point is to not mess-up or pollute your actual expression content, by instead using a dedicated token for this purpose. So if you declare a constant, for example:

const String more = null;

...then a line which might be too long to look at in source code, such as...

var s1 = $"one: {99 + 1} two: {99 + 2} three: {99 + 3} four: {99 + 4} five: {99 + 5} six: {99 + 6}";

...can be instead written like this.

var s2 = $@"{more
    }one: {99 + 1} {more
    }two: {99 + 2} {more
    }three: {99 + 3} {more
    }four: {99 + 4} {more
    }five: {99 + 5} {more
    }six: {99 + 6}";

Or perhaps you prefer a different "odd" approach to the same thing:

// elsewhere:
public const String ? = null;  // Unicode '\u039E', Greek 'Capital Letter Xi'

// anywhere:
var s3 = $@"{
           ?}one: {99 + 1} {
           ?}two: {99 + 2} {
           ?}three: {99 + 3} {
           ?}four: {99 + 4} {
           ?}five: {99 + 5} {
           ?}six: {99 + 6}";

Actually, it looks like we can also do it without a continuation symbol:

var s4 = $@"one: {99 + 1
            }two: {99 + 2
            }three: {99 + 3
            }four: {99 + 4
            }five: {99 + 5
            }six: {99 + 6}";

All four examples produce the same string at runtime, which in this case is all on a single line:

one: 100 two: 101 three: 102 four: 103 five: 104 six: 105

As Stuart suggested, IL performance is preserved in both these examples by not using + to concatenate strings. Although the longer format string in my new example is indeed stored in the IL, and thus your executable, the null placeholders it references are not initialized, and there are no excess concatenations or function calls at runtime. For comparison, here is the IL for the above two examples.

IL for first example

ldstr "one: {0} two: {1} three: {2} four: {3} five: {4} six: {5}"
ldc.i4.6
newarr object
dup
ldc.i4.0
ldc.i4.s 100
box int32
stelem.ref
dup
ldc.i4.1
ldc.i4.s 101
box int32
stelem.ref
dup
ldc.i4.2
ldc.i4.s 102
box int32
stelem.ref
dup
ldc.i4.3
ldc.i4.s 103
box int32
stelem.ref
dup
ldc.i4.4
ldc.i4.s 104
box int32
stelem.ref
dup
ldc.i4.5
ldc.i4.s 105
box int32
stelem.ref
call string string::Format(string, object[])

IL for second example

ldstr "{0}one: {1} {2}two: {3} {4}three: {5} {6}four: {7} {8}five: {9} {10}six: {11}"
ldc.i4.s 12
newarr object
dup
ldc.i4.1
ldc.i4.s 100
box int32
stelem.ref
dup
ldc.i4.3
ldc.i4.s 101
box int32
stelem.ref
dup
ldc.i4.5
ldc.i4.s 102
box int32
stelem.ref
dup
ldc.i4.7
ldc.i4.s 103
box int32
stelem.ref
dup
ldc.i4.s 9
ldc.i4.s 104
box int32
stelem.ref
dup
ldc.i4.s 11
ldc.i4.s 105
box int32
stelem.ref
call string string::Format(string, object[])

Difference Between Schema / Database in MySQL

PostgreSQL supports schemas, which is a subset of a database: https://www.postgresql.org/docs/current/static/ddl-schemas.html

A database contains one or more named schemas, which in turn contain tables. Schemas also contain other kinds of named objects, including data types, functions, and operators. The same object name can be used in different schemas without conflict; for example, both schema1 and myschema can contain tables named mytable. Unlike databases, schemas are not rigidly separated: a user can access objects in any of the schemas in the database they are connected to, if they have privileges to do so.

Schemas are analogous to directories at the operating system level, except that schemas cannot be nested.

In my humble opinion, MySQL is not a reference database. You should never quote MySQL for an explanation. MySQL implements non-standard SQL and sometimes claims features that it does not support. For example, in MySQL, CREATE schema will only create a DATABASE. It is truely misleading users.

This kind of vocabulary is called "MySQLism" by DBAs.

How to make nginx to listen to server_name:port

The server_namedocs directive is used to identify virtual hosts, they're not used to set the binding.

netstat tells you that nginx listens on 0.0.0.0:80 which means that it will accept connections from any IP.

If you want to change the IP nginx binds on, you have to change the listendocs rule.
So, if you want to set nginx to bind to localhost, you'd change that to:

listen 127.0.0.1:80;

In this way, requests that are not coming from localhost are discarded (they don't even hit nginx).

Npm install failed with "cannot run in wd"

I fixed this by changing the ownership of /usr/local and ~/Users/user-name like so:

sudo chown -R my_name /usr/local

This allowed me to do everything without sudo

How to sort 2 dimensional array by column value?

Nothing special, just saving the cost it takes to return a value at certain index from an array.

function sortByCol(arr, colIndex){
    arr.sort(sortFunction)
    function sortFunction(a, b) {
        a = a[colIndex]
        b = b[colIndex]
        return (a === b) ? 0 : (a < b) ? -1 : 1
    }
}
// Usage
var a = [[12, 'AAA'], [58, 'BBB'], [28, 'CCC'],[18, 'DDD']]
sortByCol(a, 0)
console.log(JSON.stringify(a))
// "[[12,"AAA"],[18,"DDD"],[28,"CCC"],[58,"BBB"]]"

DD/MM/YYYY Date format in Moment.js

for anyone who's using react-moment:

simply use format prop to your needed format:

const now = new Date()
<Moment format="DD/MM/YYYY">{now}</Moment>

Executing set of SQL queries using batch file?

Save the commands in a .SQL file, ex: ClearTables.sql, say in your C:\temp folder.

Contents of C:\Temp\ClearTables.sql

Delete from TableA;
Delete from TableB;
Delete from TableC;
Delete from TableD;
Delete from TableE;

Then use sqlcmd to execute it as follows. Since you said the database is remote, use the following syntax (after updating for your server and database instance name).

sqlcmd -S <ComputerName>\<InstanceName> -i C:\Temp\ClearTables.sql

For example, if your remote computer name is SQLSVRBOSTON1 and Database instance name is MyDB1, then the command would be.

sqlcmd -E -S SQLSVRBOSTON1\MyDB1 -i C:\Temp\ClearTables.sql

Also note that -E specifies default authentication. If you have a user name and password to connect, use -U and -P switches.

You will execute all this by opening a CMD command window.

Using a Batch File.

If you want to save it in a batch file and double-click to run it, do it as follows.

Create, and save the ClearTables.bat like so.

echo off
sqlcmd -E -S SQLSVRBOSTON1\MyDB1 -i C:\Temp\ClearTables.sql
set /p delExit=Press the ENTER key to exit...:

Then double-click it to run it. It will execute the commands and wait until you press a key to exit, so you can see the command output.

Accessing Google Account Id /username via Android

String name = android.os.Build.USER;

if (!TextUtils.isEmpty(name)) {
    nameEdit.setText(name);
}

Excel VBA select range at last row and column

Is this what you are trying? I have commented the code so that you will not have any problem understanding it.

Sub Sample()
    Dim ws As Worksheet
    Dim lRow As Long, lCol As Long
    Dim rng As Range

    '~~> Set this to the relevant worksheet
    Set ws = [Sheet1]

    With ws
        '~~> Get the last row and last column
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row
        lCol = .Cells(1, .Columns.Count).End(xlToLeft).Column

        '~~> Set the range
        Set rng = .Range(.Cells(lRow, 1), .Cells(lRow, lCol))

        With rng
            Debug.Print .Address
            '
            '~~> What ever you want to do with the address
            '
        End With
    End With
End Sub

BTW I am assuming that LastRow is the same for all rows and same goes for the columns. If that is not the case then you will have use .Find to find the Last Row and the Last Column. You might want to see THIS

Split value from one field to two

UPDATE `salary_generation_tbl` SET
    `modified_by` = IF(
        LOCATE('$', `other_salary_string`) > 0,
        SUBSTRING(`other_salary_string`, 1, LOCATE('$', `other_salary_string`) - 1),
        `other_salary_string`
    ),
    `other_salary` = IF(
        LOCATE('$', `other_salary_string`) > 0,
        SUBSTRING(`other_salary_string`, LOCATE('$', `other_salary_string`) + 1),
        NULL
    );

How to frame two for loops in list comprehension python

return=[entry for tag in tags for entry in entries if tag in entry for entry in entry]

How to access site through IP address when website is on a shared host?

According with the HTTP/1.1 standard, the shared IP hosted site can be accessed by a GET request with the IP as URL and a header of the host.

Here there are two examples(wget and curl): $ wget --header 'Host:somerandomservice.com' http://67.225.235.59 $ curl --header 'Host:somerandomservice.com' http://67.225.235.59

Resources:

https://en.wikipedia.org/wiki/Shared_web_hosting_service

http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.23

How can I select multiple columns from a subquery (in SQL Server) that should have one record (select top 1) for each record in the main query?

i think that is what you want.

SELECT 
      A.SalesOrderID, 
      A.OrderDate, 
      FooFromB.*

FROM A,
     (SELECT TOP 1 B.Foo
      FROM B
      WHERE A.SalesOrderID = B.SalesOrderID
      ) AS FooFromB

WHERE A.Date BETWEEN '2000-1-4' AND '2010-1-4'

How do I clear inner HTML

The h1 tags unfortunately do not receive the onmouseout events.

The simple Javascript snippet below will work for all elements and uses only 1 mouse event.

Note: "The borders in the snippet are applied to provide a visual demarcation of the elements."

_x000D_
_x000D_
document.body.onmousemove = function(){ move("The dog is in its shed"); };_x000D_
_x000D_
document.body.style.border = "2px solid red";_x000D_
document.getElementById("h1Tag").style.border = "2px solid blue";_x000D_
_x000D_
function move(what) {_x000D_
    if(event.target.id == "h1Tag"){ document.getElementById("goy").innerHTML = "what"; } else { document.getElementById("goy").innerHTML = ""; }_x000D_
}
_x000D_
<h1 id="h1Tag">lalala</h1>_x000D_
<div id="goy"></div>
_x000D_
_x000D_
_x000D_

This can also be done in pure CSS by adding the hover selector css property to the h1 tag.

Difference of keywords 'typename' and 'class' in templates?

While there is no technical difference, I have seen the two used to denote slightly different things.

For a template that should accept any type as T, including built-ins (such as an array )

template<typename T>
class Foo { ... }

For a template that will only work where T is a real class.

template<class T>
class Foo { ... }

But keep in mind that this is purely a style thing some people use. Not mandated by the standard or enforced by compilers

How to store command results in a shell variable?

The syntax to store the command output into a variable is var=$(command).

So you can directly do:

result=$(ls -l | grep -c "rahul.*patle")

And the variable $result will contain the number of matches.

How to get the date from jQuery UI datepicker

Sometimes a lot of troubles with it. In attribute value of datapicker data is 28-06-2014, but datepicker is show or today or nothing. I decided it in a such way:

<input type="text" class="form-control datepicker" data-value="<?= date('d-m-Y', (!$event->date ? time() : $event->date)) ?>" value="<?= date('d-m-Y', (!$event->date ? time() : $event->date)) ?>" />

I added to the input of datapicker attribute data-value, because if call jQuery(this).val() OR jQuery(this).attr('value') - nothing works. I decided init in cycle each datapicker and take its value from attribute data-value:

 $("form .datepicker").each(function() {
        var time = jQuery(this).data('value');
        time = time.split('-');
        $(this).datepicker('setDate', new Date(time[2], time[1], time[0], 0, 0, 0));
    });

and it is works fine =)

Long vs Integer, long vs int, what to use and when?

When it comes to using a very long number that may exceed 32 bits to represent, you may use long to make sure that you'll not have strange behavior.

From Java 5 you can use in-boxing and out-boxing features to make the use of int and Integer completely the same. It means that you can do :

int myInt = new Integer(11);
Integer myInt2 = myInt;

The in and out boxing allow you to switch between int and Integer without any additional conversion (same for Long,Double,Short too)

You may use int all the time, but Integer contains some helper methods that can help you to do some complex operations with integers (such as Integer.parseInt(String) )

Display string multiple times

The accepted answer is short and sweet, but here is an alternate syntax allowing to provide a separator in Python 3.x.

print(*3*('-',), sep='_')

Reset/remove CSS styles for element only

BETTER SOLUTION

Download "copy/paste" stylesheet? to reset css properties to default (UA style):
https://github.com/monmomo04/resetCss.git

Thanks@Milche Patern!
I was really looking for reset/default style properties value. My first try was to copy the computed value from the browser Dev tool of the root(html) element. But as it computed, it would have looked/worked different on every system.
For those who encounter a browser crash when trying to use the asterisk * to reset the style of the children elements, and as I knew it didn't work for you, I have replaced the asterisk "*" with all the HTML tags name instead. The browser didn't crash; I am on Chrome Version 46.0.2490.71 m.
At last, it's good to mention that those properties will reset the style to the default style of topest root element but not to the initial value for each HTML element. ?So to correct this, I have taken the "user-agent" styles of webkit based browser and implemented it under the "reset-this" class.

Useful link:


Download "copy/paste" stylesheet? to reset css properties to default (UA style):
https://github.com/monmomo04/resetCss.git

User-agent style:
Browsers' default CSS for HTML elements
http://trac.webkit.org/browser/trunk/Source/WebCore/css/html.css

Css specifity (pay attention to specifity) :
https://css-tricks.com/specifics-on-css-specificity/

https://github.com/monmomo04/resetCss.git

What is the final version of the ADT Bundle?

You can also get an updated version of the Eclipse's ADT plugin (based on an unreleased 24.2.0 version) that I managed to patch and compile at https://github.com/khaledev/ADT.

Java to Jackson JSON serialization: Money fields

Instead of setting the @JsonSerialize on each member or getter you can configure a module that use a custome serializer for a certain type:

SimpleModule module = new SimpleModule();
module.addSerializer(BigInteger.class, new ToStringSerializer());
objectMapper.registerModule(module);

In the above example, I used the to string serializer to serialize BigIntegers (since javascript can not handle such numeric values).

How do I enable FFMPEG logging and where can I find the FFMPEG log file?

You must declare the reportfile as variable for console.

Problem is all the Dokumentations you can find are not running so .. I was give 1 day of my live to find the right way ....

Example: for batch/console

cmd.exe /K set FFREPORT=file='C:\ffmpeg\proto\test.log':level=32 && C:\ffmpeg\bin\ffmpeg.exe -loglevel warning -report -i inputfile f outputfile

Exemple Javascript:

var reortlogfile = "cmd.exe /K set FFREPORT=file='C:\ffmpeg\proto\" + filename + ".log':level=32 && C:\ffmpeg\bin\ffmpeg.exe" .......;

You can change the dir and filename how ever you want.

Frank from Berlin

Why use HttpClient for Synchronous Connection

In my case the accepted answer did not work. I was calling the API from an MVC application which had no async actions.

This is how I managed to make it work:

private static readonly TaskFactory _myTaskFactory = new TaskFactory(CancellationToken.None, TaskCreationOptions.None, TaskContinuationOptions.None, TaskScheduler.Default);
public static T RunSync<T>(Func<Task<T>> func)
    {           
        CultureInfo cultureUi = CultureInfo.CurrentUICulture;
        CultureInfo culture = CultureInfo.CurrentCulture;
        return _myTaskFactory.StartNew<Task<T>>(delegate
        {
            Thread.CurrentThread.CurrentCulture = culture;
            Thread.CurrentThread.CurrentUICulture = cultureUi;
            return func();
        }).Unwrap<T>().GetAwaiter().GetResult();
    }

Then I called it like this:

Helper.RunSync(new Func<Task<ReturnTypeGoesHere>>(async () => await AsyncCallGoesHere(myparameter)));

python multithreading wait till all threads finished

From the threading module documentation

There is a “main thread” object; this corresponds to the initial thread of control in the Python program. It is not a daemon thread.

There is the possibility that “dummy thread objects” are created. These are thread objects corresponding to “alien threads”, which are threads of control started outside the threading module, such as directly from C code. Dummy thread objects have limited functionality; they are always considered alive and daemonic, and cannot be join()ed. They are never deleted, since it is impossible to detect the termination of alien threads.

So, to catch those two cases when you are not interested in keeping a list of the threads you create:

import threading as thrd


def alter_data(data, index):
    data[index] *= 2


data = [0, 2, 6, 20]

for i, value in enumerate(data):
    thrd.Thread(target=alter_data, args=[data, i]).start()

for thread in thrd.enumerate():
    if thread.daemon:
        continue
    try:
        thread.join()
    except RuntimeError as err:
        if 'cannot join current thread' in err.args[0]:
            # catchs main thread
            continue
        else:
            raise

Whereupon:

>>> print(data)
[0, 4, 12, 40]

Creating csv file with php

Just in case if someone is wondering to save the CSV file to a specific path for email attachments. Then it can be done as follows

I know I have added a lot of comments just for newbies :)

I have added an example so that you can summarize well.

$activeUsers = /** Query to get the active users */

/** Following is the Variable to store the Users data as 
    CSV string with newline character delimiter, 

    its good idea of check the delimiter based on operating system */

$userCSVData = "Name,Email,CreatedAt\n";

/** Looping the users and appending to my earlier csv data variable */
foreach ( $activeUsers as $user ) {
    $userCSVData .= $user->name. "," . $user->email. "," . $user->created_at."\n";
}
/** Here you can use with H:i:s too. But I really dont care of my old file  */
$todayDate  = date('Y-m-d');
/** Create Filname and Path to Store */
$fileName   = 'Active Users '.$todayDate.'.csv';
$filePath   = public_path('uploads/'.$fileName); //I am using laravel helper, in case if your not using laravel then just add absolute or relative path as per your requirements and path to store the file

/** Just in case if I run the script multiple time 
    I want to remove the old file and add new file.

    And before deleting the file from the location I am making sure it exists */
if(file_exists($filePath)){
    unlink($filePath);
}
$fp = fopen($filePath, 'w+');
fwrite($fp, $userCSVData); /** Once the data is written it will be saved in the path given */
fclose($fp);

/** Now you can send email with attachments from the $filePath */

NOTE: The following is a very bad idea to increase the memory_limit and time limit, but I have only added to make sure if anyone faces the problem of connection time out or any other. Make sure to find out some alternative before sticking to it.

You have to add the following at the start of the above script.

ini_set("memory_limit", "10056M");
set_time_limit(0);
ini_set('mysql.connect_timeout', '0');
ini_set('max_execution_time', '0');

How do I parse JSON into an int?

You may use parseInt :

int id = Integer.parseInt(jsonObj.get("id"));

or better and more directly the getInt method :

int id = jsonObj.getInt("id");

Real world use of JMS/message queues?

I have used it for my academic project which was online retail website similar to Amazon. JMS was used to handle following features :

  1. Update the position of the orders placed by the customers, as the shipment travels from one location to another. This was done by continuously sending messages to JMS Queue.
  2. Alerting about any unusual events like shipment getting delayed and then sending email to customer.
  3. If the delivery is reached its destination, sending a delivery event.

We had multiple also implemented remote clients connected to main Server. If connection is available, they use to access the main database or if not use their own database. In order to handle data consistency, we had implemented 2PC mechanism. For this, we used JMS for exchange the messages between these systems i.e one acting as coordinator who will initiate the process by sending message on the queue and others will respond accordingly by sending back again a message on the queue. As others have already mentioned, this was similar to pub/sub model.

Hide div if screen is smaller than a certain width

I have the almost the same situation as yours; that if the screen width is less than the my specified width it should hide the div. This is the jquery code I used that worked for me.

$(window).resize(function() {

  if ($(this).width() < 1024) {

    $('.divIWantedToHide').hide();

  } else {

    $('.divIWantedToHide').show();

    }

});

Find a value in DataTable

A DataTable or DataSet object will have a Select Method that will return a DataRow array of results based on the query passed in as it's parameter.

Looking at your requirement your filterexpression will have to be somewhat general to make this work.

myDataTable.Select("columnName1 like '%" + value + "%'");

How to invoke the super constructor in Python?

Just to add an example with parameters:

class B(A):
    def __init__(self, x, y, z):
        A.__init__(self, x, y)

Given a derived class B that requires the variables x, y, z to be defined, and a superclass A that requires x, y to be defined, you can call the static method init of the superclass A with a reference to the current subclass instance (self) and then the list of expected arguments.

Excel - Using COUNTIF/COUNTIFS across multiple sheets/same column

I was looking to do the same thing, and I have a work around that seems to be less complicated using the Frequency and Index functions. I use this part of the function from averaging over multiple sheets while excluding the all the 0's.

=(FREQUENCY(Start:End!B1,-0.000001)+INDEX(FREQUENCY(Start:End!B1,0),2))

GitHub: invalid username or password

Disabling 2 factor authentication at github worked for me.

I see that there is a deleted answer that says this, with the deletion reason as "does not answer the question". If it works, then I think it answers the question...

Entity framework self referencing loop detected

Self-referencing as example

public class Employee {
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public int ManagerId { get; set; }
    public virtual Employee Manager { get; set; }

    public virtual ICollection<Employee> Employees { get; set; }

    public Employee() {
        Employees = new HashSet<Employee>();
    }
}
HasMany(e => e.Employees)
    .WithRequired(e => e.Manager)
    .HasForeignKey(e => e.ManagerId)
    .WillCascadeOnDelete(false);

How to exit from the application and show the home screen?

When u call finish onDestroy() of that activity will be called and it will go back to previous activity in the activity stack... So.. for exit do not call finish();

No line-break after a hyphen

Late to the party, but I think this is actually the most elegant. Use the WORD JOINER Unicode character &#8288; on either side of your hyphen, or em dash, or any character.

So, like so:

&#8288;—&#8288;

This will join the symbol on both ends to its neighbors (without adding a space) and prevent line breaking.

Best way to load module/class from lib folder in Rails 3?

config.autoload_paths does not work for me. I solve it in other way

Ruby on rails 3 do not automatic reload (autoload) code from /lib folder. I solve it by putting inside ApplicationController

Dir["lib/**/*.rb"].each do |path|
  require_dependency path
end 

Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply?

numba

For recursive calculations which are not vectorisable, numba, which uses JIT-compilation and works with lower level objects, often yields large performance improvements. You need only define a regular for loop and use the decorator @njit or (for older versions) @jit(nopython=True):

For a reasonable size dataframe, this gives a ~30x performance improvement versus a regular for loop:

from numba import jit

@jit(nopython=True)
def calculator_nb(a, b, d):
    res = np.empty(d.shape)
    res[0] = d[0]
    for i in range(1, res.shape[0]):
        res[i] = res[i-1] * a[i] + b[i]
    return res

df['C'] = calculator_nb(*df[list('ABD')].values.T)

n = 10**5
df = pd.concat([df]*n, ignore_index=True)

# benchmarking on Python 3.6.0, Pandas 0.19.2, NumPy 1.11.3, Numba 0.30.1
# calculator() is same as calculator_nb() but without @jit decorator
%timeit calculator_nb(*df[list('ABD')].values.T)  # 14.1 ms per loop
%timeit calculator(*df[list('ABD')].values.T)     # 444 ms per loop

Mockito How to mock and assert a thrown exception?

Assert by exception message:

    try {
        MyAgent.getNameByNode("d");
    } catch (Exception e) {
        Assert.assertEquals("Failed to fetch data.", e.getMessage());
    }

How do I execute a *.dll file

It should be mentioned that since it is entirely possible to run DLL's just as any other executable, it has long been considered a security issue. As such, there have been a number of security improvements and registry hacks (sorry no longer have ref-links) that prevents running DLL's from regular user space without extra privileges.

As a good example. I recall making these hacks, but since I no longer remember what exactly I did. I can no longer run any DLLs from normal user shell environment, even though starting various Win apps from GUI works just fine.

That said, one should definitely read "Dynamic-Link Library Security" and "Best Practices to Prevent DLL Hijacking".

Share data between AngularJS controllers

There are multiple ways to share data between controllers

  • Angular services
  • $broadcast, $emit method
  • Parent to child controller communication
  • $rootscope

As we know $rootscope is not preferable way for data transfer or communication because it is a global scope which is available for entire application

For data sharing between Angular Js controllers Angular services are best practices eg. .factory, .service
For reference

In case of data transfer from parent to child controller you can directly access parent data in child controller through $scope
If you are using ui-router then you can use $stateParmas to pass url parameters like id, name, key, etc

$broadcast is also good way to transfer data between controllers from parent to child and $emit to transfer data from child to parent controllers

HTML

<div ng-controller="FirstCtrl">
   <input type="text" ng-model="FirstName">
   <br>Input is : <strong>{{FirstName}}</strong>
</div>

<hr>

<div ng-controller="SecondCtrl">
   Input should also be here: {{FirstName}}
</div>

JS

myApp.controller('FirstCtrl', function( $rootScope, Data ){
    $rootScope.$broadcast('myData', {'FirstName': 'Peter'})
});

myApp.controller('SecondCtrl', function( $rootScope, Data ){
    $rootScope.$on('myData', function(event, data) {
       $scope.FirstName = data;
       console.log(data); // Check in console how data is coming
    });
});

Refer given link to know more about $broadcast

how to show lines in common (reverse diff)?

Easiest way to do is :

awk 'NR==FNR{a[$1]++;next} a[$1] ' file1 file2

Files are not necessary to be sorted.

Delete first character of a string in Javascript

Use .charAt() and .slice().

Example: http://jsfiddle.net/kCpNQ/

var myString = "0String";

if( myString.charAt( 0 ) === '0' )
    myString = myString.slice( 1 );

If there could be several 0 characters at the beginning, you can change the if() to a while().

Example: http://jsfiddle.net/kCpNQ/1/

var myString = "0000String";

while( myString.charAt( 0 ) === '0' )
    myString = myString.slice( 1 );

Laravel 5 - redirect to HTTPS

You can use RewriteRule to force ssl in .htaccess same folder with your index.php
Please add as picture attach, add it before all rule others setting ssl .htaccess

"Primary Filegroup is Full" in SQL Server 2008 Standard for no apparent reason

Ran into the same problem and at first defragmenting seemed to work. But it was for just a short while. Turns out the server the customer was using, was running the Express version and that has a licensing limit of about 10gb.

So even though the size was set to "unlimited", it wasn't.

ASP MVC href to a controller/view

You can also use this very simplified form:

@Html.ActionLink("Come back to Home", "Index", "Home")

Where :
Come back to Home is the text that will appear on the page
Index is the view name
Homeis the controller name

Why SQL Server throws Arithmetic overflow error converting int to data type numeric?

Precision and scale are often misunderstood. In numeric(3,2) you want 3 digits overall, but 2 to the right of the decimal. If you want 15 => 15.00 so the leading 1 causes the overflow (since if you want 2 digits to the right of the decimal, there is only room on the left for one more digit). With 4,2 there is no problem because all 4 digits fit.

Difference between readFile() and readFileSync()

readFileSync() is synchronous and blocks execution until finished. These return their results as return values. readFile() are asynchronous and return immediately while they function in the background. You pass a callback function which gets called when they finish. let's take an example for non-blocking.

following method read a file as a non-blocking way

var fs = require('fs');
fs.readFile(filename, "utf8", function(err, data) {
        if (err) throw err;
        console.log(data);
});

following is read a file as blocking or synchronous way.

var data = fs.readFileSync(filename);

LOL...If you don't want readFileSync() as blocking way then take reference from the following code. (Native)

var fs = require('fs');
function readFileAsSync(){
    new Promise((resolve, reject)=>{
        fs.readFile(filename, "utf8", function(err, data) {
                if (err) throw err;
                resolve(data);
        });
    });
}

async function callRead(){
    let data = await readFileAsSync();
    console.log(data);
}

callRead();

it's mean behind scenes readFileSync() work same as above(promise) base.

configuring project ':app' failed to find Build Tools revision

I found out that it also happens if you uninstalled some packages from your react-native project and there is still packages in your build gradle dependencies in the bottom of page like:

{
 project(':react-native-sound-player')
}

jQuery: get the file name selected from <input type="file" />

It is just such simple as writing:

$('input[type=file]').val()

Anyway, I suggest using name or ID attribute to select your input. And with event, it should look like this:

$('input[type=file]').change(function(e){
  $in=$(this);
  $in.next().html($in.val());
});

Export and import table dump (.sql) using pgAdmin

If you have Git bash installed, you can do something like this:

/c/Program\ Files\ \(x86\)/PostgreSQL/9.3/bin/psql -U <pg_role_name> -d <pg_database_name> < <path_to_your>.sql

Parsing command-line arguments in C

To my knowledge, the three most popular ways how to parse command line arguments in C are:

  • Getopt (#include <unistd.h> from the POSIX C Library), which can solve simple argument parsing tasks. If you're a bit familiar with bash, the getopt built-in of bash is based on Getopt from the GNU libc.
  • Argp (#include <argp.h> from the GNU C Library), which can solve more complex tasks and takes care of stuff like, for example:
    • -?, --help for help message, including email address
    • -V, --version for version information
    • --usage for usage message
  • Doing it yourself, which I don't recommend for programs that would be given to somebody else, as there is too much that could go wrong or lower quality. The popular mistake of forgetting about '--' to stop option parsing is just one example.

The GNU C Library documentation has some nice examples for Getopt and Argp.

Example for using Getopt

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
    bool isCaseInsensitive = false;
    int opt;
    enum { CHARACTER_MODE, WORD_MODE, LINE_MODE } mode = CHARACTER_MODE;

    while ((opt = getopt(argc, argv, "ilw")) != -1) {
        switch (opt) {
        case 'i': isCaseInsensitive = true; break;
        case 'l': mode = LINE_MODE; break;
        case 'w': mode = WORD_MODE; break;
        default:
            fprintf(stderr, "Usage: %s [-ilw] [file...]\n", argv[0]);
            exit(EXIT_FAILURE);
        }
    }

    // Now optind (declared extern int by <unistd.h>) is the index of the first non-option argument.
    // If it is >= argc, there were no non-option arguments.

    // ...
}

Example for using Argp

#include <argp.h>
#include <stdbool.h>

const char *argp_program_version = "programname programversion";
const char *argp_program_bug_address = "<[email protected]>";
static char doc[] = "Your program description.";
static char args_doc[] = "[FILENAME]...";
static struct argp_option options[] = { 
    { "line", 'l', 0, 0, "Compare lines instead of characters."},
    { "word", 'w', 0, 0, "Compare words instead of characters."},
    { "nocase", 'i', 0, 0, "Compare case insensitive instead of case sensitive."},
    { 0 } 
};

struct arguments {
    enum { CHARACTER_MODE, WORD_MODE, LINE_MODE } mode;
    bool isCaseInsensitive;
};

static error_t parse_opt(int key, char *arg, struct argp_state *state) {
    struct arguments *arguments = state->input;
    switch (key) {
    case 'l': arguments->mode = LINE_MODE; break;
    case 'w': arguments->mode = WORD_MODE; break;
    case 'i': arguments->isCaseInsensitive = true; break;
    case ARGP_KEY_ARG: return 0;
    default: return ARGP_ERR_UNKNOWN;
    }   
    return 0;
}

static struct argp argp = { options, parse_opt, args_doc, doc, 0, 0, 0 };

int main(int argc, char *argv[])
{
    struct arguments arguments;

    arguments.mode = CHARACTER_MODE;
    arguments.isCaseInsensitive = false;

    argp_parse(&argp, argc, argv, 0, 0, &arguments);

    // ...
}

Example for Doing it Yourself

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

int main(int argc, char *argv[])
{   
    bool isCaseInsensitive = false;
    enum { CHARACTER_MODE, WORD_MODE, LINE_MODE } mode = CHARACTER_MODE;
    size_t optind;
    for (optind = 1; optind < argc && argv[optind][0] == '-'; optind++) {
        switch (argv[optind][1]) {
        case 'i': isCaseInsensitive = true; break;
        case 'l': mode = LINE_MODE; break;
        case 'w': mode = WORD_MODE; break;
        default:
            fprintf(stderr, "Usage: %s [-ilw] [file...]\n", argv[0]);
            exit(EXIT_FAILURE);
        }   
    }   

    // *argv points to the remaining non-option arguments.
    // If *argv is NULL, there were no non-option arguments.

    // ...
}   

Disclaimer: I am new to Argp, the example might contain errors.

Datatable vs Dataset

It really depends on the sort of data you're bringing back. Since a DataSet is (in effect) just a collection of DataTable objects, you can return multiple distinct sets of data into a single, and therefore more manageable, object.

Performance-wise, you're more likely to get inefficiency from unoptimized queries than from the "wrong" choice of .NET construct. At least, that's been my experience.

How to sort a HashMap in Java

Seems like you might want a treemap.

http://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html

You can pass in a custom comparator to it if that applies.

window.location.reload with clear cache

In my case reload() doesn't work because the asp.net controls behavior. So, to solve this issue I've used this approach, despite seems a work around.

self.clear = function () {
    //location.reload(true); Doesn't work to IE neither Firefox;
    //also, hash tags must be removed or no postback will occur.
    window.location.href = window.location.href.replace(/#.*$/, '');
};

OpenMP set_num_threads() is not working

According to the GCC manual for omp_get_num_threads:

In a sequential section of the program omp_get_num_threads returns 1

So this:

cout<<"sum="<<sum<<endl;
cout<<"threads="<<omp_get_num_threads()<<endl;

Should be changed to something like:

#pragma omp parallel
{
    cout<<"sum="<<sum<<endl;
    cout<<"threads="<<omp_get_num_threads()<<endl;
}

The code I use follows Hristo's advice of disabling dynamic teams, too.

Number of elements in a javascript object

AFAIK, there is no way to do this reliably, unless you switch to an array. Which honestly, doesn't seem strange - it's seems pretty straight forward to me that arrays are countable, and objects aren't.

Probably the closest you'll get is something like this

// Monkey patching on purpose to make a point
Object.prototype.length = function()
{
  var i = 0;
  for ( var p in this ) i++;
  return i;
}

alert( {foo:"bar", bar: "baz"}.length() ); // alerts 3

But this creates problems, or at least questions. All user-created properties are counted, including the _length function itself! And while in this simple example you could avoid it by just using a normal function, that doesn't mean you can stop other scripts from doing this. so what do you do? Ignore function properties?

Object.prototype.length = function()
{
  var i = 0;
  for ( var p in this )
  {
      if ( 'function' == typeof this[p] ) continue;
      i++;
  }
  return i;
}

alert( {foo:"bar", bar: "baz"}.length() ); // alerts 2

In the end, I think you should probably ditch the idea of making your objects countable and figure out another way to do whatever it is you're doing.

AngularJs ReferenceError: angular is not defined

Always make sure that js file (angular.min.js) is referenced first in the HTML file. For example:

----------------- This reference will THROW error -------------------------

< script src="otherXYZ.js"></script>
< script src="angular.min.js"></script>

----------------- This reference will WORK as expected -------------------

< script src="angular.min.js"></script>
< script src="otherXYZ.js"></script>

Separating class code into a header and cpp file

A2DD.h

class A2DD
{
  private:
  int gx;
  int gy;

  public:
  A2DD(int x,int y);

  int getSum();
};

A2DD.cpp

  A2DD::A2DD(int x,int y)
  {
    gx = x;
    gy = y;
  }

  int A2DD::getSum()
  {
    return gx + gy;
  }

The idea is to keep all function signatures and members in the header file.
This will allow other project files to see how the class looks like without having to know the implementation.

And besides that, you can then include other header files in the implementation instead of the header. This is important because whichever headers are included in your header file will be included (inherited) in any other file that includes your header file.

Check play state of AVPlayer

For Swift:

AVPlayer:

let player = AVPlayer(URL: NSURL(string: "http://www.sample.com/movie.mov"))
if (player.rate != 0 && player.error == nil) {
   println("playing")
}

Update:
player.rate > 0 condition changed to player.rate != 0 because if video is playing in reverse it can be negative thanks to Julian for pointing out.
Note: This might look same as above(Maz's) answer but in Swift '!player.error' was giving me a compiler error so you have to check for error using 'player.error == nil' in Swift.(because error property is not of 'Bool' type)

AVAudioPlayer:

if let theAudioPlayer =  appDelegate.audioPlayer {
   if (theAudioPlayer.playing) {
       // playing
   }
}

AVQueuePlayer:

if let theAudioQueuePlayer =  appDelegate.audioPlayerQueue {
   if (theAudioQueuePlayer.rate != 0 && theAudioQueuePlayer.error == nil) {
       // playing
   }
}

Difference between pre-increment and post-increment in a loop?

a++ is known as postfix.

add 1 to a, returns the old value.

++a is known as prefix.

add 1 to a, returns the new value.

C#:

string[] items = {"a","b","c","d"};
int i = 0;
foreach (string item in items)
{
    Console.WriteLine(++i);
}
Console.WriteLine("");

i = 0;
foreach (string item in items)
{
    Console.WriteLine(i++);
}

Output:

1
2
3
4

0
1
2
3

foreach and while loops depend on which increment type you use. With for loops like below it makes no difference as you're not using the return value of i:

for (int i = 0; i < 5; i++) { Console.Write(i);}
Console.WriteLine("");
for (int i = 0; i < 5; ++i) { Console.Write(i); }

0 1 2 3 4
0 1 2 3 4

If the value as evaluated is used then the type of increment becomes significant:

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

What is the difference between "::" "." and "->" in c++

You have a pointer to an object. Therefore, you need to access a field of an object that's pointed to by the pointer. To dereference the pointer you use *, and to access a field, you use ., so you can use:

cout << (*kwadrat).val1;

Note that the parentheses are necessary. This operation is common enough that long ago (when C was young) they decided to create a "shorthand" method of doing it:

cout << kwadrat->val1;

These are defined to be identical. As you can see, the -> basically just combines a * and a . into a single operation. If you were dealing directly with an object or a reference to an object, you'd be able to use the . without dereferencing a pointer first:

Kwadrat kwadrat2(2,3,4);

cout << kwadrat2.val1;

The :: is the scope resolution operator. It is used when you only need to qualify the name, but you're not dealing with an individual object at all. This would be primarily to access a static data member:

struct something { 
    static int x; // this only declares `something::x`. Often found in a header
};

int something::x;  // this defines `something::x`. Usually in .cpp/.cc/.C file.

In this case, since x is static, it's not associated with any particular instance of something. In fact, it will exist even if no instance of that type of object has been created. In this case, we can access it with the scope resolution operator:

something::x = 10;

std::cout << something::x;

Note, however, that it's also permitted to access a static member as if it was a member of a particular object:

something s;

s.x = 1;

At least if memory serves, early in the history of C++ this wasn't allowed, but the meaning is unambiguous, so they decided to allow it.

good postgresql client for windows?

Actually there is a freeware version of EMS's SQL Manager which is quite powerful

PLS-00201 - identifier must be declared

When creating the TABLE under B2BOWNER, be sure to prefix the PL/SQL function with the Schema name; i.e. B2BOWNER.F_SSC_Page_Map_Insert.

I did not realize this until the DBAs pointed it out. I could have created the table under my root USER/SCHEMA and the PL/SQL function would have worked fine.

UIView touch event in controller

Swift 4.2:

@IBOutlet weak var viewLabel1: UIView!
@IBOutlet weak var viewLabel2: UIView!
  override func viewDidLoad() {
    super.viewDidLoad()

    let myView = UITapGestureRecognizer(target: self, action: #selector(someAction(_:)))
    self.viewLabel1.addGestureRecognizer(myView)
}

 @objc func someAction(_ sender:UITapGestureRecognizer){
   viewLabel2.isHidden = true
 }

SQL Server stored procedure Nullable parameter

You can/should set your parameter to value to DBNull.Value;

if (variable == "")
{
     cmd.Parameters.Add("@Param", SqlDbType.VarChar, 500).Value = DBNull.Value;
}
else
{
     cmd.Parameters.Add("@Param", SqlDbType.VarChar, 500).Value = variable;
}

Or you can leave your server side set to null and not pass the param at all.

How do I remove a substring from the end of a string in Python?

Python >= 3.9:

'abcdc.com'.removesuffix('.com')

Python < 3.9:

def remove_suffix(text, suffix):
    if text.endswith(suffix):
        text = text[:-len(suffix)]
    return text

remove_suffix('abcdc.com', '.com')

error: command 'gcc' failed with exit status 1 while installing eventlet

This page is gonna save your life, for all further lib issues that are forthcoming,

For Alpine(>=3.6),

use apk --update --upgrade add gcc musl-dev jpeg-dev zlib-dev libffi-dev cairo-dev pango-dev gdk-pixbuf-dev

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

The best that I've been able to do is

$(this).closest('.modal').modal('toggle');

This gets the modal holding the DOM object you triggered the event on (guessing you're clicking a button). Gets the closest parent '.modal' and toggles it. Obviously only works because it's inside the modal you clicked.

You can however do this:

$(".modal:visible").modal('toggle');

This gets the modal that is displaying (since you can only have one open at a time), and triggers the 'toggle' This would not work without ":visible"

SQL: Group by minimum value in one field while selecting distinct rows

I could get to your expected result just by doing this in :

 SELECT id, min(record_date), other_cols 
  FROM mytable
  GROUP BY id

Does this work for you?

Passing parameters from jsp to Spring Controller method

Your controller method should be like this:

@RequestMapping(value = " /<your mapping>/{id}", method=RequestMethod.GET)
public String listNotes(@PathVariable("id")int id,Model model) {
    Person person = personService.getCurrentlyAuthenticatedUser();
    int id = 2323;  // Currently passing static values for testing
    model.addAttribute("person", new Person());
    model.addAttribute("listPersons", this.personService.listPersons());
    model.addAttribute("listNotes",this.notesService.listNotesBySectionId(id,person));
    return "note";
}

Use the id in your code, call the controller method from your JSP as:

/{your mapping}/{your id}

UPDATE:

Change your jsp code to:

<c:forEach items="${listNotes}" var="notices" varStatus="status">
    <tr>
        <td>${notices.noticesid}</td>
        <td>${notices.notetext}</td>
        <td>${notices.notetag}</td>
        <td>${notices.notecolor}</td>
        <td>${notices.sectionid}</td>
        <td>${notices.canvasid}</td>
        <td>${notices.canvasnName}</td>
        <td>${notices.personid}</td>
        <td><a href="<c:url value='/editnote/${listNotes[status.index].noticesid}' />" >Edit</a></td>
        <td><a href="<c:url value='/removenote/${listNotes[status.index].noticesid}' />" >Delete</a></td>
    </tr>
</c:forEach>

How to make div appear in front of another?

Upper div use higher z-index and lower div use lower z-index then use absolute/fixed/relative position

Onclick javascript to make browser go back to previous page?

Shortest Yet!

<button onclick="history.go(-1);">Go back</button>

http://jsfiddle.net/qXrbx/

I prefer the .go(-number) method as then, for 1 or many 'backs' there's only 1 method to use/remember/update/search for, etc.

Also, using a tag for a back button seems more appropriate than tags with names and types...

Advantages of using display:inline-block vs float:left in CSS

In 3 words: inline-block is better.

Inline Block

The only drawback to the display: inline-block approach is that in IE7 and below an element can only be displayed inline-block if it was already inline by default. What this means is that instead of using a <div> element you have to use a <span> element. It's not really a huge drawback at all because semantically a <div> is for dividing the page while a <span> is just for covering a span of a page, so there's not a huge semantic difference. A huge benefit of display:inline-block is that when other developers are maintaining your code at a later point, it is much more obvious what display:inline-block and text-align:right is trying to accomplish than a float:left or float:right statement. My favorite benefit of the inline-block approach is that it's easy to use vertical-align: middle, line-height and text-align: center to perfectly center the elements, in a way that is intuitive. I found a great blog post on how to implement cross-browser inline-block, on the Mozilla blog. Here is the browser compatibility.

Float

The reason that using the float method is not suited for layout of your page is because the float CSS property was originally intended only to have text wrap around an image (magazine style) and is, by design, not best suited for general page layout purposes. When changing floated elements later, sometimes you will have positioning issues because they are not in the page flow. Another disadvantage is that it generally requires a clearfix otherwise it may break aspects of the page. The clearfix requires adding an element after the floated elements to stop their parent from collapsing around them which crosses the semantic line between separating style from content and is thus an anti-pattern in web development.

Any white space problems mentioned in the link above could easily be fixed with the white-space CSS property.

Edit:

SitePoint is a very credible source for web design advice and they seem to have the same opinion that I do:

If you’re new to CSS layouts, you’d be forgiven for thinking that using CSS floats in imaginative ways is the height of skill. If you have consumed as many CSS layout tutorials as you can find, you might suppose that mastering floats is a rite of passage. You’ll be dazzled by the ingenuity, astounded by the complexity, and you’ll gain a sense of achievement when you finally understand how floats work.

Don’t be fooled. You’re being brainwashed.

http://www.sitepoint.com/give-floats-the-flick-in-css-layouts/

2015 Update - Flexbox is a good alternative for modern browsers:

.container {
  display: flex; /* or inline-flex */
}

.item {
  flex: none | [ <'flex-grow'> <'flex-shrink'>? || <'flex-basis'> ]
}

More info

Dec 21, 2016 Update

Bootstrap 4 is removing support for IE9, and thus is getting rid of floats from rows and going full Flexbox.

Pull request #21389

converting epoch time with milliseconds to datetime

those are miliseconds, just divide them by 1000, since gmtime expects seconds ...

time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(1236472051807/1000.0))

convert 12-hour hh:mm AM/PM to 24-hour hh:mm

Tested for all the use cases

function timeConversion(s) {
let h24;
let m24;
let sec24;

const splittedDate = s.split(":");
const h = parseInt(splittedDate[0], 10);
const m = parseInt(splittedDate[1], 10);
const sec = parseInt(splittedDate[2][0] + splittedDate[2][1], 10); 
const meridiem = splittedDate[2][2] + splittedDate[2][3];

if (meridiem === "AM") {
    if (h === 12) {
        h24 = '00';
    } else {
        h24 = h;
        if (h24 < 10) {
            h24 = '0' + h24;
        }
    }
    m24 = m;
    sec24 = sec;
} else if (meridiem === "PM") {
    if (h === 12) {
        h24 = h
    } else {
        h24 = h + 12;
        if (h24 < 10) {
            h24 = '0' + h24;
        }
    }
    m24 = m;
    sec24 = sec;
}


if (m24 < 10) {
    m24 = '0' + m24; 
} 

if (sec24 < 10) {
    sec24 = '0' + sec24;
}

  return h24 + ":" + m24 + ":" + sec24; 
}

Here is the jsfiddle working example

How to cache Google map tiles for offline usage?

On http://www.google.com/earth/media/licensing.html there is a "Mobile" section containing :

Similar to our online terms, if you use our APIs or a mobile device’s native Google Maps implementation (such as on an Android-powered phone or iPhone), no special permission is required, but you must always keep the Google name visible. Offline caching of our content is never allowed.

How to Correctly handle Weak Self in Swift Blocks with Arguments

EDIT: Reference to an updated solution by LightMan

See LightMan's solution. Until now I was using:

input.action = { [weak self] value in
    guard let this = self else { return }
    this.someCall(value) // 'this' isn't nil
}

Or:

input.action = { [weak self] value in
    self?.someCall(value) // call is done if self isn't nil
}

Usually you don't need to specify the parameter type if it's inferred.

You can omit the parameter altogether if there is none or if you refer to it as $0 in the closure:

input.action = { [weak self] in
    self?.someCall($0) // call is done if self isn't nil
}

Just for completeness; if you're passing the closure to a function and the parameter is not @escaping, you don't need a weak self:

[1,2,3,4,5].forEach { self.someCall($0) }

Regular expression for extracting tag attributes

You cannot use the same name for multiple captures. Thus you cannot use a quantifier on expressions with named captures.

So either don’t use named captures:

(?:(\b\w+\b)\s*=\s*("[^"]*"|'[^']*'|[^"'<>\s]+)\s+)+

Or don’t use the quantifier on this expression:

(?<name>\b\w+\b)\s*=\s*(?<value>"[^"]*"|'[^']*'|[^"'<>\s]+)

This does also allow attribute values like bar=' baz='quux:

foo="bar=' baz='quux"

Well the drawback will be that you have to strip the leading and trailing quotes afterwards.

How can I tell jaxb / Maven to generate multiple schema packages?

This can also be achieved by specifying stale file name for schemas and not clearing output directory. The default out put directory is automatically included in classpath which is little convenient. If we specify different output directory one has to take care of classpath to use this code in IDE. For example -

<plugins>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>jaxb2-maven-plugin</artifactId>
            <version>1.3.1</version>
            <configuration>
                <quiet>true</quiet>
                <verbose>false</verbose>
                <clearOutputDir>false</clearOutputDir>
                <readOnly>true</readOnly>
                <arguments>-mark-generated</arguments>
            </configuration>
            <executions>
                <execution>
                    <id>reportingSchema</id>
                    <goals>
                        <goal>xjc</goal>
                    </goals>
                    <configuration>
                        <schemaDirectory>src/main/resources/schema/r17/schemaReporting</schemaDirectory>
                        <schemaIncludes>
                            <include>OCISchemaReporting.xsd</include>
                        </schemaIncludes>
                        <packageName>com.broadsoft.oci.r17.reporting</packageName>
                        <staleFile>${build.directory}/generated-sources/.jaxb-staleFlag-reporting</staleFile>
                    </configuration>
                </execution>
                <execution>
                    <id>schemaAS</id>
                    <goals>
                        <goal>xjc</goal>
                    </goals>
                    <configuration>
                        <schemaDirectory>src/main/resources/schema/r17/schemaAS</schemaDirectory>
                        <schemaIncludes>
                            <include>OCISchemaAS.xsd</include>
                        </schemaIncludes>
                        <packageName>com.broadsoft.oci.r17.as</packageName>
                        <staleFile>${build.directory}/generated-sources/.jaxb-staleFlag-as</staleFile>
                    </configuration>
                </execution>
            </executions>
        </plugin>
</plugins>

Source:Generating Code with JAXB Plugin

How to clean node_modules folder of packages that are not in package.json?

rimraf is an package for simulate linux command [rm -rf] in windows. which is useful for cross platform support. for install its CLI:

npm install rimraf -g

How to insert text with single quotation sql server 2005

INSERT INTO Table1 (Column1) VALUES ('John''s')

Or you can use a stored procedure and pass the parameter as -

usp_Proc1 @Column1 = 'John''s'

If you are using an INSERT query and not a stored procedure, you'll have to escape the quote with two quotes, else its OK if you don't do it.

How to clear gradle cache?

To clear your gradle cache in android studio:

  1. open terminal and
  2. run gradlew clean

Drop-down box dependent on the option selected in another drop-down box

In this jsfiddle you'll find a solution I deviced. The idea is to have a selector pair in html and use (plain) javascript to filter the options in the dependent selector, based on the selected option of the first. For example:

<select id="continents">
 <option value = 0>All</option>   
 <option value = 1>Asia</option>
 <option value = 2>Europe</option>
 <option value = 3>Africa</option>
</select> 
<select id="selectcountries"></select>

Uses (in the jsFiddle)

 MAIN.createRelatedSelector
     ( document.querySelector('#continents')           // from select element
      ,document.querySelector('#selectcountries')      // to select element
      ,{                                               // values object 
        Asia: ['China','Japan','North Korea',
               'South Korea','India','Malaysia',
               'Uzbekistan'],
        Europe: ['France','Belgium','Spain','Netherlands','Sweden','Germany'],
        Africa: ['Mali','Namibia','Botswana','Zimbabwe','Burkina Faso','Burundi']
      }
      ,function(a,b){return a>b ? 1 : a<b ? -1 : 0;}   // sort method
 );

[Edit 2021] or use data-attributes, something like:

_x000D_
_x000D_
document.addEventListener("change", checkSelect);

function checkSelect(evt) {
  const origin = evt.target;

  if (origin.dataset.dependentSelector) {
    const selectedOptFrom = origin.querySelector("option:checked")
      .dataset.dependentOpt || "n/a";
    const addRemove = optData => (optData || "") === selectedOptFrom 
      ? "add" : "remove";
    document.querySelectorAll(`${origin.dataset.dependentSelector} option`)
      .forEach( opt => 
        opt.classList[addRemove(opt.dataset.fromDependent)]("display") );
  }
}
_x000D_
[data-from-dependent] {
  display: none;
}

[data-from-dependent].display {
  display: initial;
}
_x000D_
<select id="source" name="source" data-dependent-selector="#status">
  <option>MANUAL</option>
  <option data-dependent-opt="ONLINE">ONLINE</option>
  <option data-dependent-opt="UNKNOWN">UNKNOWN</option>
</select>

<select id="status" name="status">
  <option>OPEN</option>
  <option>DELIVERED</option>
  <option data-from-dependent="ONLINE">SHIPPED</option>
  <option data-from-dependent="UNKNOWN">SHOULD SELECT</option>
  <option data-from-dependent="UNKNOWN">MAYBE IN TRANSIT</option>
</select>
_x000D_
_x000D_
_x000D_

Rename multiple files in a folder, add a prefix (Windows)

Based on @ofer.sheffer answer this command will mass rename and append the current date to the filename. ie "file.txt" becomes "20180329 - file.txt" for all files in the current folder

for %a in (*.*) do ren "%a" "%date:~-4,4%%date:~-7,2%%date:~-10,2% - %a"

Generating random integer from a range

A fast, somewhat better than yours, but still not properly uniform distributed solution is

output = min + (rand() % static_cast<int>(max - min + 1))

Except when the size of the range is a power of 2, this method produces biased non-uniform distributed numbers regardless the quality of rand(). For a comprehensive test of the quality of this method, please read this.

Why does this CSS margin-top style not work?

What @BoltClock mentioned are pretty solid. And Here I just want to add several more solutions for this problem. check this w3c_collapsing margin. The green parts are the potential thought how this problem can be solved.

Solution 1

Margins between a floated box and any other box do not collapse (not even between a float and its in-flow children).

that means I can add float:left to either #outer or #inner demo1.

also notice that float would invalidate the auto in margin.

Solution 2

Margins of elements that establish new block formatting contexts (such as floats and elements with 'overflow' other than 'visible') do not collapse with their in-flow children.

other than visible, let's put overflow: hidden into #outer. And this way seems pretty simple and decent. I like it.

#outer{
    width: 500px;
    height: 200px;
    background: #FFCCCC;
    margin: 50px auto;
    overflow: hidden;
}
#inner {
    background: #FFCC33;
    height: 50px;
    margin: 50px;
}

Solution 3

Margins of absolutely positioned boxes do not collapse (not even with their in-flow children).

#outer{
    width: 500px;
    height: 200px;
    background: #FFCCCC;
    margin: 50px auto;
    position: absolute; 
}
#inner{
    background: #FFCC33;
    height: 50px;
    margin: 50px;
}

or

#outer{
    width: 500px;
    height: 200px;
    background: #FFCCCC;
    margin: 50px auto;
    position: relative; 
}
#inner {
    background: #FFCC33;
    height: 50px;
    margin: 50px;
    position: absolute;
}

these two methods will break the normal flow of div

Solution 4

Margins of inline-block boxes do not collapse (not even with their in-flow children).

is the same as @enderskill

Solution 5

The bottom margin of an in-flow block-level element always collapses with the top margin of its next in-flow block-level sibling, unless that sibling has clearance.

This has not much work to do with the question since it is the collapsing margin between siblings. it generally means if a top-box has margin-bottom: 30px and a sibling-box has margin-top: 10px. The total margin between them is 30px instead of 40px.

Solution 6

The top margin of an in-flow block element collapses with its first in-flow block-level child's top margin if the element has no top border, no top padding, and the child has no clearance.

This is very interesting and I can just add one top border line

#outer{
    width: 500px;
    height: 200px;
    background: #FFCCCC;
    margin: 50px auto;
    border-top: 1px solid red;

}
#inner {
    background: #FFCC33;
    height: 50px;
    margin: 50px;

}

And Also <div> is block-level in default, so you don't have to declare it on purpose. Sorry for not being able to post more than 2 links and images due to my novice reputation. At least you know where the problem comes from next time you see something similar.

How can I drop a "not null" constraint in Oracle when I don't know the name of the constraint?

To discover any constraints used, use the code below:

-- Set the long data type for display purposes to 500000.

SET LONG 500000

-- Define a session scope variable.

VARIABLE output CLOB

-- Query the table definition through the <code>DBMS_METADATA</code> package.

SELECT dbms_metadata.get_ddl('TABLE','[Table Described]') INTO :output FROM dual;

This essentially shows a create statement for how the referenced table is made. By knowing how the table is created, you can see all of the table constraints.

Answer taken from Michael McLaughlin's blog: http://michaelmclaughlin.info/db1/lesson-5-querying-data/lab-5-querying-data/ From his Database Design I class.

Disable EditText blinking cursor

add android:focusableInTouchMode="true" in root layout, when edit text will be clicked at that time cursor will be shown.

How to loop through a plain JavaScript object with the objects as members?

_x000D_
_x000D_
var obj={_x000D_
name:"SanD",_x000D_
age:"27"_x000D_
}_x000D_
Object.keys(obj).forEach((key)=>console.log(key,obj[key]));
_x000D_
_x000D_
_x000D_

To loop through JavaScript Object we can use forEach and to optimize code we can use arrow function

Android: long click on a button -> perform actions

To get both functions working for a clickable image that will respond to both short and long clicks, I tried the following that seems to work perfectly:

    image = (ImageView) findViewById(R.id.imageViewCompass);
    image.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            shortclick();
        }
     });

    image.setOnLongClickListener(new View.OnLongClickListener() {
    public boolean onLongClick(View v) {
        longclick();
        return true;
    }
});

//Then the functions that are called:

 public void shortclick()
{
 Toast.makeText(this, "Why did you do that? That hurts!!!", Toast.LENGTH_LONG).show();

}

 public void longclick()
{
 Toast.makeText(this, "Why did you do that? That REALLY hurts!!!", Toast.LENGTH_LONG).show();

}

It seems that the easy way of declaring the item in XML as clickable and then defining a function to call on the click only applies to short clicks - you must have a listener to differentiate between short and long clicks.

Allowed memory size of X bytes exhausted

If by increasing the memory limit you have gotten rid of the error and your code now works, you'll need to take measures to decrease that memory usage. Here are a few things you could do to decrease it:

If you're reading files, read them line-by-line instead of reading in the complete file into memory. Look at fgets and SplFileObject::fgets. Upgrade to a new version of PHP if you're using PHP 5.3. PHP 5.4 and 5.5 use much less memory.

Avoid loading large datasets into in an array. Instead, go for processing smaller subsets of the larger dataset and, if necessary, persist your data into a database to relieve memory use.

Try the latest version or minor version of a third-party library (1.9.3 vs. your 1.8.2, for instance) and use whichever is more stable. Sometimes newer versions of libraries are written more efficiently.

If you have an uncommon or unstable PHP extension, try upgrading it. It might have a memory leak.

If you're dealing with large files and you simply can't read it line-by-line, try breaking the file into many smaller files and process those individually. Disable PHP extensions that you don't need.

In the problem area, unset variables which contain large amounts of data and aren't required later in the code.

FROM: https://www.airpair.com/php/fatal-error-allowed-memory-size

How to make "if not true condition"?

Here is an answer by way of example:

In order to make sure data loggers are online a cron script runs every 15 minutes that looks like this:

#!/bin/bash
#
if ! ping -c 1 SOLAR &>/dev/null
then
  echo "SUBJECT:  SOLAR is not responding to ping" | ssmtp [email protected]
  echo "SOLAR is not responding to ping" | ssmtp [email protected]
else
  echo "SOLAR is up"
fi
#
if ! ping -c 1 OUTSIDE &>/dev/null
then
  echo "SUBJECT:  OUTSIDE is not responding to ping" | ssmtp [email protected]
  echo "OUTSIDE is not responding to ping" | ssmtp [email protected]
else
  echo "OUTSIDE is up"
fi
#

...and so on for each data logger that you can see in the montage at http://www.SDsolarBlog.com/montage


FYI, using &>/dev/null redirects all output from the command, including errors, to /dev/null

(The conditional only requires the exit status of the ping command)

Also FYI, note that since cron jobs run as root there is no need to use sudo ping in a cron script.

Using PHP Replace SPACES in URLS with %20

Use urlencode() rather than trying to implement your own. Be lazy.

Why would an Enum implement an Interface?

Since Enums can implement interfaces they can be used for strict enforcing of the singleton pattern. Trying to make a standard class a singleton allows...

  • for the possibility of using reflection techniques to expose private methods as public
  • for inheriting from your singleton and overriding your singleton's methods with something else

Enums as singletons help to prevent these security issues. This might have been one of the contributing reasons to let Enums act as classes and implement interfaces. Just a guess.

See https://stackoverflow.com/questions/427902/java-enum-singleton and Singleton class in java for more discussion.

What is the exact location of MySQL database tables in XAMPP folder?

In Ubuntu the file path is ./opt/lampp/var/mysql

outline on only one border

Try with Shadow( Like border ) + Border

border-bottom: 5px solid #fff;
box-shadow: 0 5px 0 #ffbf0e;

Count occurrences of a char in a string using Bash

also check this out, for example we wanna count t

echo "test" | awk -v RS='t' 'END{print NR-1}'

or in python

python -c 'print "this is for test".count("t")'

or even better, we can make our script dynamic with awk

echo 'test' | awk '{for (i=1 ; i<=NF ; i++) array[$i]++ } END{ for (char in array) print char,array[char]}' FS=""

in this case output is like this :

e 1
s 1
t 2

Converting a string to a date in DB2

Okay, seems like a bit of a hack. I have got it to work using a substring, so that only the part of the string with the date (not the time) gets passed into the DATE function...

DATE(substr(SETTLEMENTDATE.VALUE,7,4)||'-'|| substr(SETTLEMENTDATE.VALUE,4,2)||'-'|| substr(SETTLEMENTDATE.VALUE,1,2))

I will still accept any answers that are better than this one!

How to get URL of current page in PHP

You can use $_SERVER['HTTP_REFERER'] this will give you whole URL for example:

suppose you want to get url of site name www.example.com then $_SERVER['HTTP_REFERER'] will give you https://www.example.com

Does VBA have Dictionary Structure?

VBA has the collection object:

    Dim c As Collection
    Set c = New Collection
    c.Add "Data1", "Key1"
    c.Add "Data2", "Key2"
    c.Add "Data3", "Key3"
    'Insert data via key into cell A1
    Range("A1").Value = c.Item("Key2")

The Collection object performs key-based lookups using a hash so it's quick.


You can use a Contains() function to check whether a particular collection contains a key:

Public Function Contains(col As Collection, key As Variant) As Boolean
    On Error Resume Next
    col(key) ' Just try it. If it fails, Err.Number will be nonzero.
    Contains = (Err.Number = 0)
    Err.Clear
End Function

Edit 24 June 2015: Shorter Contains() thanks to @TWiStErRob.

Edit 25 September 2015: Added Err.Clear() thanks to @scipilot.

How to outline text in HTML / CSS

Try CSS3 Textshadow.

.box_textshadow {
     text-shadow: 2px 2px 0px #FF0000; /* FF3.5+, Opera 9+, Saf1+, Chrome, IE10 */
}

Try it yourself on css3please.com.

Add a background image to shape in XML Android

This is a corner image

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:drawable="@drawable/img_main_blue"
        android:bottom="5dp"
        android:left="5dp"
        android:right="5dp"
        android:top="5dp" />

    <item>
        <shape
            android:padding="10dp"
            android:shape="rectangle">
            <corners android:radius="10dp" />
            <stroke
                android:width="5dp"
                android:color="@color/white" />
        </shape>

    </item>
</layer-list>

Python: Assign print output to a variable

The print statement in Python converts its arguments to strings, and outputs those strings to stdout. To save the string to a variable instead, only convert it to a string:

a = str(tag.getArtist())

post checkbox value

There are many links that lets you know how to handle post values from checkboxes in php. Look at this link: http://www.html-form-guide.com/php-form/php-form-checkbox.html

Single check box

HTML code:

<form action="checkbox-form.php" method="post">
    Do you need wheelchair access?
    <input type="checkbox" name="formWheelchair" value="Yes" />
    <input type="submit" name="formSubmit" value="Submit" />
</form>

PHP Code:

<?php

if (isset($_POST['formWheelchair']) && $_POST['formWheelchair'] == 'Yes') 
{
    echo "Need wheelchair access.";
}
else
{
    echo "Do not Need wheelchair access.";
}    

?>

Check box group

<form action="checkbox-form.php" method="post">
    Which buildings do you want access to?<br />
    <input type="checkbox" name="formDoor[]" value="A" />Acorn Building<br />
    <input type="checkbox" name="formDoor[]" value="B" />Brown Hall<br />
    <input type="checkbox" name="formDoor[]" value="C" />Carnegie Complex<br />
    <input type="checkbox" name="formDoor[]" value="D" />Drake Commons<br />
    <input type="checkbox" name="formDoor[]" value="E" />Elliot House

    <input type="submit" name="formSubmit" value="Submit" />
 /form>

<?php
  $aDoor = $_POST['formDoor'];
  if(empty($aDoor)) 
  {
    echo("You didn't select any buildings.");
  } 
  else
  {
    $N = count($aDoor);

    echo("You selected $N door(s): ");
    for($i=0; $i < $N; $i++)
    {
      echo($aDoor[$i] . " ");
    }
  }
?>

How to extract the n-th elements from a list of tuples?

n = 1 # N. . .
[x[n] for x in elements]

I can't understand why this JAXB IllegalAnnotationException is thrown

All below options worked for me.

Option 1: Annotation for FIELD at class & field level with getter/setter methods

 @XmlRootElement(name = "fields")
 @XmlAccessorType(XmlAccessType.FIELD)
    public class Fields {

        @XmlElement(name = "field")
        List<Field> fields = new ArrayList<Field>();
            //getter, setter
    }

Option 2: No Annotation for FIELD at class level(@XmlAccessorType(XmlAccessType.FIELD) and with only getter method. Adding Setter method will throw the error as we are not including the Annotation in this case. Remember, setter is not required when you explicitly set the values in your XML file.

@XmlRootElement(name = "fields")
    public class Fields {

        @XmlElement(name = "field")
        List<Field> fields = new ArrayList<Field>();
            //getter
    }

Option 3: Annotation at getter method alone. Remember we can also use the setter method here as we are not doing any FIELD level annotation in this case.

@XmlRootElement(name = "fields")
    public class Fields {

        List<Field> fields = new ArrayList<Field>();

        @XmlElement(name = "field")
        //getter

        //setter
    }

Hope this helps you!

How do servlets work? Instantiation, sessions, shared variables and multithreading

When the servlet container (like Apache Tomcat) starts up, it will read from the web.xml file (only one per application) if anything goes wrong or shows up an error at container side console, otherwise, it will deploy and load all web applications by using web.xml (so named it as deployment descriptor).

During instantiation phase of the servlet, servlet instance is ready but it cannot serve the client request because it is missing with two pieces of information:
1: context information
2: initial configuration information

Servlet engine creates servletConfig interface object encapsulating the above missing information into it servlet engine calls init() of the servlet by supplying servletConfig object references as an argument. Once init() is completely executed servlet is ready to serve the client request.

Q) In the lifetime of servlet how many times instantiation and initialization happens ??

A)only once (for every client request a new thread is created) only one instance of the servlet serves any number of the client request ie, after serving one client request server does not die. It waits for other client requests ie what CGI (for every client request a new process is created) limitation is overcome with the servlet (internally servlet engine creates the thread).

Q)How session concept works?

A)whenever getSession() is called on HttpServletRequest object

Step 1: request object is evaluated for incoming session ID.

Step 2: if ID not available a brand new HttpSession object is created and its corresponding session ID is generated (ie of HashTable) session ID is stored into httpservlet response object and the reference of HttpSession object is returned to the servlet (doGet/doPost).

Step 3: if ID available brand new session object is not created session ID is picked up from the request object search is made in the collection of sessions by using session ID as the key.

Once the search is successful session ID is stored into HttpServletResponse and the existing session object references are returned to the doGet() or doPost() of UserDefineservlet.

Note:

1)when control leaves from servlet code to client don't forget that session object is being held by servlet container ie, the servlet engine

2)multithreading is left to servlet developers people for implementing ie., handle the multiple requests of client nothing to bother about multithread code

Inshort form:

A servlet is created when the application starts (it is deployed on the servlet container) or when it is first accessed (depending on the load-on-startup setting) when the servlet is instantiated, the init() method of the servlet is called then the servlet (its one and only instance) handles all requests (its service() method being called by multiple threads). That's why it is not advisable to have any synchronization in it, and you should avoid instance variables of the servlet when the application is undeployed (the servlet container stops), the destroy() method is called.

Checking for a null int value from a Java ResultSet

With java 8 you can do this:

Long nVal = Optional.ofNullable(resultSet.getBigDecimal("col_name"))
                    .map(BigDecimal::longValue).orElse(null));

In that case you ensure that the nVal will be null (and not zero) if the SQL value is NULL

REACT - toggle class onclick

A good sample would help to understand things better:

HTML

<div id="root">
</div>

CSS

.box {
  display: block;
  width: 200px;
  height: 200px;
  background-color: gray;
  color: white;
  text-align: center;
  vertical-align: middle;
  cursor: pointer;
}
.box.green {
  background-color: green; 
}

React code

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {addClass: false}
  }
  toggle() {
    this.setState({addClass: !this.state.addClass});
  }
  render() {
    let boxClass = ["box"];
    if(this.state.addClass) {
      boxClass.push('green');
    }
    return(
        <div className={boxClass.join(' ')} onClick={this.toggle.bind(this)}>{this.state.addClass ? "Remove a class" : "Add a class (click the box)"}<br />Read the tutorial <a href="http://www.automationfuel.com" target="_blank">here</a>.</div>       
    );
  }
}
ReactDOM.render(<App />, document.getElementById("root"));

VSCode single to double quote automatic replace

I had the same issue in vscode. Just create a .prettierrc file in your root directory and add the following json. For single quotes add:

{
  "singleQuote": true
}

For double quotes add:

  {
      "singleQuote": false
  }

Laravel - Session store not set on request

Laravel 5.3+ web middleware group is automatically applied to your routes/web.php file by the RouteServiceProvider.

Unless you modify kernel $middlewareGroups array in an unsupported order, probably you are trying to inject requests as a regular dependency from the constructor.

Use request as

public function show(Request $request){

}

instead of

public function __construct(Request $request){

}

setContentView(R.layout.main); error

This problem usually happen if eclipse accidentally compile the main.xml incorrectly. The easiest solution is to delete R.java inside gen directory. Once we delete, than eclipse will generate the new R.java base on the latest main.xml

A Java collection of value pairs? (tuples?)

The preferred solution as you've described it is a List of Pairs (i.e. List).

To accomplish this you would create a Pair class for use in your collection. This is a useful utility class to add to your code base.

The closest class in the Sun JDK providing functionality similar to a typical Pair class is AbstractMap.SimpleEntry. You could use this class rather than creating your own Pair class, though you would have to live with some awkward restrictions and I think most people would frown on this as not really the intended role of SimpleEntry. For example SimpleEntry has no "setKey()" method and no default constructor, so you may find it too limiting.

Bear in mind that Collections are designed to contain elements of a single type. Related utility interfaces such as Map are not actually Collections (i.e. Map does not implement the Collection interface). A Pair would not implement the Collection interface either but is obviously a useful class in building larger data structures.

Left Join With Where Clause

For this problem, as for many others involving non-trivial left joins such as left-joining on inner-joined tables, I find it convenient and somewhat more readable to split the query with a with clause. In your example,

with settings_for_char as (
  select setting_id, value from character_settings where character_id = 1
)
select
  settings.*,
  settings_for_char.value
from
  settings
  left join settings_for_char on settings_for_char.setting_id = settings.id;

How to return value from an asynchronous callback function?

If you happen to be using jQuery, you might want to give this a shot: http://api.jquery.com/category/deferred-object/

It allows you to defer the execution of your callback function until the ajax request (or any async operation) is completed. This can also be used to call a callback once several ajax requests have all completed.

Changing Underline color

here we can create underline with color in text

_x000D_
_x000D_
<u style="text-decoration-color: red;">The color of the lines should now be red!</u>
_x000D_
_x000D_
_x000D_

or

The color of the lines should now be red!

_x000D_
_x000D_
<h1 style=" text-decoration:underline; text-decoration-color: red;">The color of the lines should now be red!</u>
_x000D_
_x000D_
_x000D_

Is Android using NTP to sync time?

Not an exact answer to your question, but a bit of information: if your device does use NTP for time (eg. if it is a tablet with no 3G or GPS capabilities), the server can be configured in /system/etc/gps.conf - obviously this file can only be edited with root access, but is viewable on non-rooted devices.

Stretch and scale a CSS image in the background - with CSS only

I wanted to center and scale a background image, without stretching it to the entire page, and I wanted the aspect ratio to be maintained. This worked for me, thanks to the variations suggested in other answers:

INLINE IMAGE: ------------------------

<div id="background">
    <img src="img.jpg" class="stretch" alt="" />
</div>

CSS ----------------------------------

html {
    height:100%;
}

#background {
    text-align: center;
    width: 100%; 
    height: 100%; 
    position: fixed;
    left: 0px; 
    top: 0px; 
    z-index: -1;
}

.stretch {
    margin: auto;
    height:100%;
}

Find methods calls in Eclipse project

You can also search for specific methods. For e.g. If you want to search for isEmpty() method of the string class you have to got to - Search -> Java -> type java.lang.String.isEmpty() and in the 'Search For' option use Method.

You can then select the scope that you require.

How do I create a timeline chart which shows multiple events? Eg. Metallica Band members timeline on wiki

A Stacked bar chart should suffice:

Setup data as follows

Name    Start       End         Duration (End - Start)
Fred    1/01/1981   1/06/1985    1612   
Bill    1/07/1985   1/11/2000    5602  
Joe     1/01/1980   1/12/2001    8005  
Jim     1/03/1999   1/01/2000    306  
  1. Plot Start and Duration as a stacked bar chart
  2. Set the X-Axis minimum to the desired start date
  3. Set the Fill Colour of thestart range to no fill
  4. Set the Fill of individual bars to suit

(example prepared in Excel 2010)

enter image description here

Generate random 5 characters string

I`ve aways use this:

<?php function fRand($len) {
    $str = '';
    $a = "abcdefghijklmnopqrstuvwxyz0123456789";
    $b = str_split($a);
    for ($i=1; $i <= $len ; $i++) { 
        $str .= $b[rand(0,strlen($a)-1)];
    }
    return $str;
} ?>

When you call it, sets the lenght of string.

<?php echo fRand([LENGHT]); ?>

You can also change the possible characters in the string $a.

What's the equivalent of Java's Thread.sleep() in JavaScript?

The simple answer is that there is no such function.

The closest thing you have is:

var millisecondsToWait = 500;
setTimeout(function() {
    // Whatever you want to do after the wait
}, millisecondsToWait);

Note that you especially don't want to busy-wait (e.g. in a spin loop), since your browser is almost certainly executing your JavaScript in a single-threaded environment.

Here are a couple of other SO questions that deal with threads in JavaScript:

And this question may also be helpful:

Linq select to new object

If you want to be able to perform a lookup on each type to get its frequency then you will need to transform the enumeration into a dictionary.

var types = new[] {typeof(string), typeof(string), typeof(int)};
var x = types
        .GroupBy(type => type)
        .ToDictionary(g => g.Key, g => g.Count());
foreach (var kvp in x) {
    Console.WriteLine("Type {0}, Count {1}", kvp.Key, kvp.Value);
}
Console.WriteLine("string has a count of {0}", x[typeof(string)]);

How to close current tab in a browser window?

Try this as well. Working for me on all three major browsers.

<!-- saved from url=(0014)about:internet -->
<a href="#" onclick="javascript:window.close();opener.window.focus();" >Close Window</a>

How to get date representing the first day of a month?

Get First Day of Last Month

Select ADDDATE(LAST_DAY(ADDDATE(now(), INTERVAL -2 MONTH)), INTERVAL 1 DAY);

Get Last Day of Last Month

Select LAST_DAY(ADDDATE(now(), INTERVAL -1 MONTH));

TLS 1.2 in .NET Framework 4.0

I meet the same issue on a Windows installed .NET Framework 4.0.
And I Solved this issue by installing .NET Framework 4.6.2.
Or you may download the newest package to have a try.

Setting action for back button in navigation controller

Here is Swift 3 version of @oneway's answer for catching navigation bar back button event before it gets fired. As UINavigationBarDelegate cannot be used for UIViewController, you need to create a delegate that will be triggered when navigationBar shouldPop is called.

@objc public protocol BackButtonDelegate {
      @objc optional func navigationShouldPopOnBackButton() -> Bool 
}

extension UINavigationController: UINavigationBarDelegate  {

    public func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool {

        if viewControllers.count < (navigationBar.items?.count)! {                
            return true
        }

        var shouldPop = true
        let vc = self.topViewController

        if vc.responds(to: #selector(vc.navigationShouldPopOnBackButton)) {
            shouldPop = vc.navigationShouldPopOnBackButton()
        }

        if shouldPop {
            DispatchQueue.main.async {
                self.popViewController(animated: true)
            }
        } else {
            for subView in navigationBar.subviews {
                if(0 < subView.alpha && subView.alpha < 1) {
                    UIView.animate(withDuration: 0.25, animations: {
                        subView.alpha = 1
                    })
                }
            }
        }

        return false
    }
}

And then, in your view controller add the delegate function:

class BaseVC: UIViewController, BackButtonDelegate {
    func navigationShouldPopOnBackButton() -> Bool {
        if ... {
            return true
        } else {
            return false
        }        
    }
}

I've realised that we often want to add an alert controller for users to decide whether they wanna go back. If so, you can always return false in navigationShouldPopOnBackButton() function and close your view controller by doing something like this:

func navigationShouldPopOnBackButton() -> Bool {
     let alert = UIAlertController(title: "Warning",
                                          message: "Do you want to quit?",
                                          preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { UIAlertAction in self.yes()}))
            alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: { UIAlertAction in self.no()}))
            present(alert, animated: true, completion: nil)
      return false
}

func yes() {
     print("yes")
     DispatchQueue.main.async {
            _ = self.navigationController?.popViewController(animated: true)
        }
}

func no() {
    print("no")       
}

What's the difference between subprocess Popen and call (how can I use them)?

The other answer is very complete, but here is a rule of thumb:

  • call is blocking:

    call('notepad.exe')
    print('hello')  # only executed when notepad is closed
    
  • Popen is non-blocking:

    Popen('notepad.exe')
    print('hello')  # immediately executed
    

Comparing strings in C# with OR in an if statement

use if (testString.Equals(testString2)).

How do I run a program from command prompt as a different user and as an admin

Open notepad and paste this code:

@echo off
powershell -Command "Start-Process cmd -Verb RunAs -ArgumentList '/c %*'"
@echo on

Then, save the file as sudo.cmd. Copy this file and paste it at C:\Windows\System32 or add the path where sudo.cmd is to your PATH Environment Variable.

When you open command prompt, you can now run something like sudo start ..

If you want the terminal window to stay open when you run the command, change the code in notepad to this:

@echo off
powershell -Command "Start-Process cmd -Verb RunAs -ArgumentList '/k %*'"
@echo on

Explanation:

powershell -Command runs a powershell command.

Start-Process is a powershell command that starts a process, in this case, command prompt.

-Verb RunAs runs the command as admin.

-Argument-List runs the command with arguments.

Our arguments are '/c %*'. %* means all arguments, so if you did sudo foo bar, it would run in command prompt foo bar because the parameters are foo and bar, and %* returns foo bar.

The /c is a cmd parameter for closing the window after the command is finished, and the /k is a cmd parameter for keeping the window open.

How can I find the location of origin/master in git, and how do I change it?

[ Solution ]

$ git push origin

^ this solved it for me. What it did, it synchronized my master (on laptop) with "origin" that's on the remote server.

What is a reasonable length limit on person "Name" fields?

I usually go with varchar(255) (255 being the maximum length of a varchar type in MySQL).

How to fix IndexError: invalid index to scalar variable

Basically, 1 is not a valid index of y. If the visitor is comming from his own code he should check if his y contains the index which he tries to access (in this case the index is 1).

Format date in a specific timezone

Use moment-timezone

moment(date).tz('Europe/Berlin').format(format)

Before being able to access a particular timezone, you will need to load it like so (or using alternative methods described here)

moment.tz.add('Europe/Berlin|CET CEST CEMT|-10 -20 -30')

ASP.NET MVC Razor render without encoding

Use @Html.Raw() with caution as you may cause more trouble with encoding and security. I understand the use case as I had to do this myself, but carefully... Just avoid allowing all text through. For example only preserve/convert specific character sequences and always encode the rest:

@Html.Raw(Html.Encode(myString).Replace("\n", "<br/>"))

Then you have peace of mind that you haven't created a potential security hole and any special/foreign characters are displayed correctly in all browsers.

What does "javascript:void(0)" mean?

There is a huge difference in the behaviour of # vs javascript:void(0);.

# scrolls you to the top of the page but javascript:void(0); does not.

This is very important if you are coding dynamic pages because the user does not want to go back to the top when they click a link on the page.

How to fix: Error device not found with ADB.exe

I switched to a different USB port and it suddenly got recognized...

Simple division in Java - is this a bug or a feature?

Please do not take this as an answer to the question. It is not, but an advice related to exploiting the difference of int and float. I would have put this under a comment except that the answer box allows me to format this comment.

This feature has been used in every respectable programming language since the days of fortran (or earlier) - I must confess I was once a Fortran and Cobol punch card programmer.

As an example, integer division of 10/3 yields integer value 3 since an integer has no facility to hold fractional residual .3333.. .

One of the ways we (old time ancient programmers) had been using this feature is loop control.

Let's say we wish to print an array of 1000 strings, but we wish to insert a line break after every 15th string, to insert some prettyfying chars at the end of the line and at the beginning of the next line. We exploit this, given that integer k is the position of a string in that array.

int(k/15)*15 == k

is true only when k is divisible by 15, an occurrence at a frequency of every 15th cell. Which is akin to what my friend said about his grandfather's dead watch being accurate twice a day.

int(1/15) = 0 -> int(1/15)*15 = 0
int(2/15) = 0 -> int(2/15)*15 = 0
...
int(14/15) = 0 -> int(14/15)*15 = 0
int(15/15) = 1 -> int(15/15)*15 = 15

int(16/15) = 1 -> int(16/15)*15 = 15
int(17/15) = 1 -> int(17/15)*15 = 15
...
int(29/15) = 1 -> int(29/15)*15 = 15
int(30/15) = 2 -> int(30/15)*15 = 30

Therefore, the loop,

leftPrettyfy();
for(int k=0; k<sa.length; k++){
  print(sa[k]);
  int z = k + 1;
  if ((z/15)*15 == z){
    rightPrettyfy();
    leftPrettyfy();
  }
}

By varying k in a fanciful way in the loop, we could print a triangular printout

1
2  3
4  5  6
7  8  9  10
11 12 13 14 15

That is to demonstrate that, if you consider this a bug, this "bug" is a useful feature that we would not want to be removed from any of the various languages that we have used thus far.

Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource

If the requested resource of the server is using Flask. Install Flask-CORS.

What are the recommendations for html <base> tag?

One thing to keep in mind:

If you develop a webpage to be displayed within UIWebView on iOS, then you have to use BASE tag. It simply won't work otherwise. Be that JavaScript, CSS, images - none of them will work with relative links under UIWebView, unless tag BASE is specified.

I've been caught by this before, till I found out.

How to convert array values to lowercase in PHP?

You can also use a combination of array_flip() and array_change_key_case(). See this post

How to check if a string contains only digits in Java

Try

String regex = "[0-9]+";

or

String regex = "\\d+";

As per Java regular expressions, the + means "one or more times" and \d means "a digit".

Note: the "double backslash" is an escape sequence to get a single backslash - therefore, \\d in a java String gives you the actual result: \d

References:


Edit: due to some confusion in other answers, I am writing a test case and will explain some more things in detail.

Firstly, if you are in doubt about the correctness of this solution (or others), please run this test case:

String regex = "\\d+";

// positive test cases, should all be "true"
System.out.println("1".matches(regex));
System.out.println("12345".matches(regex));
System.out.println("123456789".matches(regex));

// negative test cases, should all be "false"
System.out.println("".matches(regex));
System.out.println("foo".matches(regex));
System.out.println("aa123bb".matches(regex));

Question 1:

Isn't it necessary to add ^ and $ to the regex, so it won't match "aa123bb" ?

No. In java, the matches method (which was specified in the question) matches a complete string, not fragments. In other words, it is not necessary to use ^\\d+$ (even though it is also correct). Please see the last negative test case.

Please note that if you use an online "regex checker" then this may behave differently. To match fragments of a string in Java, you can use the find method instead, described in detail here:

Difference between matches() and find() in Java Regex

Question 2:

Won't this regex also match the empty string, "" ?*

No. A regex \\d* would match the empty string, but \\d+ does not. The star * means zero or more, whereas the plus + means one or more. Please see the first negative test case.

Question 3

Isn't it faster to compile a regex Pattern?

Yes. It is indeed faster to compile a regex Pattern once, rather than on every invocation of matches, and so if performance implications are important then a Pattern can be compiled and used like this:

Pattern pattern = Pattern.compile(regex);
System.out.println(pattern.matcher("1").matches());
System.out.println(pattern.matcher("12345").matches());
System.out.println(pattern.matcher("123456789").matches());

Java SimpleDateFormat for time zone with a colon separator?

Try setLenient(false).

Addendum: It looks like you're recognizing variously formatted Date strings. If you have to do entry, you might like looking at this example that extends InputVerifier.

Git merge reports "Already up-to-date" though there is a difference

A merge is always between the current HEAD and one or more commits (usually, branch head or tag),
and the index file must match the tree of HEAD commit (i.e. the contents of the last commit) when it starts out.
In other words, git diff --cached HEAD must report no changes.

The merged commit is already contained in HEAD. This is the simplest case, called "Already up-to-date."

That should mean the commits in test are already merged in master, but since other commits are done on master, git diff test would still give some differences.

React - Preventing Form Submission

preventDefault is what you're looking for. To just block the button from submitting

<Button onClick={this.onClickButton} ...

code

onClickButton (event) {
  event.preventDefault();
}

If you have a form which you want to handle in a custom way you can capture a higher level event onSubmit which will also stop that button from submitting.

<form onSubmit={this.onSubmit}>

and above in code

onSubmit (event) {
  event.preventDefault();

  // custom form handling here
}

Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 71 bytes)

I changed the memory limit from .htaccess and this problem got resolved.

I was trying to scan my website from one of the antivirus plugin and there I was getting this problem. I increased memory by pasting this in my .htaccess file in Wordpress folder:

php_value memory_limit 512M

After scan was over, I removed this line to make the size as it was before.

How to define dimens.xml for every different screen size in android?

There are nice libraries which will handle everything and reduce your pain. For using it, just add two dependencies in gradle:

 implementation 'com.intuit.ssp:ssp-android:1.0.5'
 implementation 'com.intuit.sdp:sdp-android:1.0.5'

After that, use dimens like this:

        android:layout_marginTop="@dimen/_80sdp"

jQuery Datepicker localization

datepicker in Finnish (Käännös suomeksi)

$.datepicker.regional['fi'] = {
  closeText: "Valmis", // Display text for close link
  prevText: "Edel", // Display text for previous month link
  nextText: "Seur", // Display text for next month link
  currentText: "Tänään", // Display text for current month link
  monthNames: [ "Tammikuu","Helmikuu","Maaliskuu","Huhtikuu","Toukokuu","Kesäkuu",
  "Heinäkuu","Elokuu","Syyskuu","Lokakuu","Marraskuu","Joulukuu" ], // Names of months for drop-down and formatting
  monthNamesShort: [ "Tam", "Hel", "Maa", "Huh", "Tou", "Kes", "Hei", "Elo", "Syy", "Lok", "Mar", "Jou" ], // For formatting
  dayNames: [ "Sunnuntai", "Maanantai", "Tiistai", "Keskiviikko", "Torstai", "Perjantai", "Lauantai" ], // For formatting
  dayNamesShort: [ "Sun", "Maa", "Tii", "Kes", "Tor", "Per", "Lau" ], // For formatting
  dayNamesMin: [ "Su","Ma","Ti","Ke","To","Pe","La" ], // Column headings for days starting at Sunday
  weekHeader: "Vk", // Column header for week of the year
  dateFormat: "mm/dd/yy", // See format options on parseDate
  firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
  isRTL: false, // True if right-to-left language, false if left-to-right
  showMonthAfterYear: false, // True if the year select precedes month, false for month then year
  yearSuffix: "" // Additional text to append to the year in the month headers
  };

How to fix a Div to top of page with CSS only

You can also use flexbox, but you'd have to add a parent div that covers div#top and div#term-defs. So the HTML looks like this:

_x000D_
_x000D_
    #content {_x000D_
        width: 100%;_x000D_
        height: 100%;_x000D_
        display: flex;_x000D_
        flex-direction: column;_x000D_
    }_x000D_
_x000D_
    #term-defs {_x000D_
        flex-grow: 1;_x000D_
        overflow: auto;_x000D_
    } 
_x000D_
    <body>_x000D_
        <div id="content">_x000D_
            <div id="top">_x000D_
                <a href="#A">A</a> |_x000D_
                <a href="#B">B</a> |_x000D_
                <a href="#Z">Z</a>_x000D_
            </div>_x000D_
    _x000D_
            <div id="term-defs">_x000D_
                <dl>_x000D_
                    <span id="A"></span>_x000D_
                    <dt>foo</dt>_x000D_
                    <dd>This is the sound made by a fool</dd>_x000D_
                    <!-- and so on ... -->_x000D_
                </dl>_x000D_
            </div>_x000D_
        </div>_x000D_
    </body>
_x000D_
_x000D_
_x000D_

flex-grow ensures that the div's size is equal to the remaining size.

You could do the same without flexbox, but it would be more complicated to work out the height of #term-defs (you'd have to know the height of #top and use calc(100% - 999px) or set the height of #term-defs directly).
With flexbox dynamic sizes of the divs are possible.

One difference is that the scrollbar only appears on the term-defs div.

Styling of Select2 dropdown select boxes

Thanks for the suggestions in the comments. I made a bit of a dirty hack to get what I want without having to create my own image. With javascript I first hide the default tag that's being used for the down arrow, like so:

$('b[role="presentation"]').hide();

I then included font-awesome in my page and add my own down arrow, again with a line of javascript, to replace the default one:

$('.select2-arrow').append('<i class="fa fa-angle-down"></i>');

Then with CSS I style the select boxes. I set the height, change the background color of the arrow area to a gradient black, change the width, font-size and also the color of the down arrow to white:

.select2-container .select2-choice {
    padding: 5px 10px;
    height: 40px;
    width: 132px; 
    font-size: 1.2em;  
}

.select2-container .select2-choice .select2-arrow {
    background-image: -khtml-gradient(linear, left top, left bottom, from(#424242), to(#030303));
    background-image: -moz-linear-gradient(top, #424242, #030303);
    background-image: -ms-linear-gradient(top, #424242, #030303);
    background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #424242), color-stop(100%, #030303));
    background-image: -webkit-linear-gradient(top, #424242, #030303);
    background-image: -o-linear-gradient(top, #424242, #030303);
    background-image: linear-gradient(#424242, #030303);
    width: 40px;
    color: #fff;
    font-size: 1.3em;
    padding: 4px 12px;
}

The result is the styling the way I want it:

screenshot

Update 5/6/2015 As @Katie Lacy mentioned in the other answer the classnames have been changed in version 4 of Select2. The updated CSS with the new classnames should look like this:

.select2-container--default .select2-selection--single{
    padding:6px;
    height: 37px;
    width: 148px; 
    font-size: 1.2em;  
    position: relative;
}

.select2-container--default .select2-selection--single .select2-selection__arrow {
    background-image: -khtml-gradient(linear, left top, left bottom, from(#424242), to(#030303));
    background-image: -moz-linear-gradient(top, #424242, #030303);
    background-image: -ms-linear-gradient(top, #424242, #030303);
    background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #424242), color-stop(100%, #030303));
    background-image: -webkit-linear-gradient(top, #424242, #030303);
    background-image: -o-linear-gradient(top, #424242, #030303);
    background-image: linear-gradient(#424242, #030303);
    width: 40px;
    color: #fff;
    font-size: 1.3em;
    padding: 4px 12px;
    height: 27px;
    position: absolute;
    top: 0px;
    right: 0px;
    width: 20px;
}

JS:

$('b[role="presentation"]').hide();
$('.select2-selection__arrow').append('<i class="fa fa-angle-down"></i>');

Django DoesNotExist

I have found the solution to this issue using ObjectDoesNotExist on this way

from django.core.exceptions import ObjectDoesNotExist
......

try:
  # try something
except ObjectDoesNotExist:
  # do something

After this, my code works as I need

Thanks any way, your post help me to solve my issue

Open page in new window without popup blocking

PS> I posted this answer on a related question. Here's how I got round the issue of my async ajax request losing the trusted context:

I opened the popup directly on the users click, directed the url to about:blank and got a handle on that window. You could probably direct the popup to a 'loading' url while your ajax request is made

var myWindow = window.open("about:blank",'name','height=500,width=550');

Then, when my request is successful, I open my callback url in the window

function showWindow(win, url) {
     win.open(url,'name','height=500,width=550');
}

Using psql to connect to PostgreSQL in SSL mode

Well, you cloud provide all the information with following command in CLI, if connection requires in SSL mode:

psql "sslmode=verify-ca sslrootcert=server-ca.pem sslcert=client-cert.pem sslkey=client-key.pem hostaddr=your_host port=5432 user=your_user dbname=your_db" 

Implementing two interfaces in a class with same method. Which interface method is overridden?

If a type implements two interfaces, and each interface define a method that has identical signature, then in effect there is only one method, and they are not distinguishable. If, say, the two methods have conflicting return types, then it will be a compilation error. This is the general rule of inheritance, method overriding, hiding, and declarations, and applies also to possible conflicts not only between 2 inherited interface methods, but also an interface and a super class method, or even just conflicts due to type erasure of generics.


Compatibility example

Here's an example where you have an interface Gift, which has a present() method (as in, presenting gifts), and also an interface Guest, which also has a present() method (as in, the guest is present and not absent).

Presentable johnny is both a Gift and a Guest.

public class InterfaceTest {
    interface Gift  { void present(); }
    interface Guest { void present(); }

    interface Presentable extends Gift, Guest { }

    public static void main(String[] args) {
        Presentable johnny = new Presentable() {
            @Override public void present() {
                System.out.println("Heeeereee's Johnny!!!");
            }
        };
        johnny.present();                     // "Heeeereee's Johnny!!!"

        ((Gift) johnny).present();            // "Heeeereee's Johnny!!!"
        ((Guest) johnny).present();           // "Heeeereee's Johnny!!!"

        Gift johnnyAsGift = (Gift) johnny;
        johnnyAsGift.present();               // "Heeeereee's Johnny!!!"

        Guest johnnyAsGuest = (Guest) johnny;
        johnnyAsGuest.present();              // "Heeeereee's Johnny!!!"
    }
}

The above snippet compiles and runs.

Note that there is only one @Override necessary!!!. This is because Gift.present() and Guest.present() are "@Override-equivalent" (JLS 8.4.2).

Thus, johnny only has one implementation of present(), and it doesn't matter how you treat johnny, whether as a Gift or as a Guest, there is only one method to invoke.


Incompatibility example

Here's an example where the two inherited methods are NOT @Override-equivalent:

public class InterfaceTest {
    interface Gift  { void present(); }
    interface Guest { boolean present(); }

    interface Presentable extends Gift, Guest { } // DOES NOT COMPILE!!!
    // "types InterfaceTest.Guest and InterfaceTest.Gift are incompatible;
    //  both define present(), but with unrelated return types"
}

This further reiterates that inheriting members from an interface must obey the general rule of member declarations. Here we have Gift and Guest define present() with incompatible return types: one void the other boolean. For the same reason that you can't an void present() and a boolean present() in one type, this example results in a compilation error.


Summary

You can inherit methods that are @Override-equivalent, subject to the usual requirements of method overriding and hiding. Since they ARE @Override-equivalent, effectively there is only one method to implement, and thus there's nothing to distinguish/select from.

The compiler does not have to identify which method is for which interface, because once they are determined to be @Override-equivalent, they're the same method.

Resolving potential incompatibilities may be a tricky task, but that's another issue altogether.

References

String replace a Backslash

This will replace backslashes with forward slashes in the string:

source = source.replace('\\','/');

Bootstrap: wider input field

In bootstrap 4, they have designed a bigger input file.

A simple solution to increase the size input file is to use font-size:

Add you style, for example:

input[type="file"] {
  font-size:35px
}

Otherwise, you can make one custom class and add to input control.

Why can't I enter a string in Scanner(System.in), when calling nextLine()-method?

This is a common misunderstanding which leads to confusion if you use the same Scanner for nextLine() right after you used nextInt().

You can either fix the cursor jumping to the next Line by yourself or just use a different scanner for your Integers.

OPTION A: use 2 different scanners

import java.util.Scanner;

class string
{

    public static void main(String a[]){
    int a;
    String s;
    Scanner intscan =new Scanner(System.in);


    System.out.println("enter a no");
    a=intscan.nextInt();
    System.out.println("no is ="+a);


     Scanner textscan=new Scanner(System.in);
    System.out.println("enter a string");
    s=textscan.nextLine();
    System.out.println("string is="+s);
        }
}

OPTION B: just jump to the next Line

class string
{
    public static void main(String a[]){
        int a;
        String s;
        Scanner scan =new Scanner(System.in);

        System.out.println("enter a no");
        a = scan.nextInt();
        System.out.println("no is ="+a);
        scan.nextLine();

        System.out.println("enter a string");
        s = scan.nextLine();
        System.out.println("string is="+s);
    }
}

Redirect to new Page in AngularJS using $location

It might help you!

AngularJs Code-sample

var app = angular.module('urlApp', []);
app.controller('urlCtrl', function ($scope, $log, $window) {
    $scope.ClickMeToRedirect = function () {
        var url = "http://" + $window.location.host + "/Account/Login";
        $log.log(url);
        $window.location.href = url;
    };
});

HTML Code-sample

<div ng-app="urlApp">
    <div ng-controller="urlCtrl">
        Redirect to <a href="#" ng-click="ClickMeToRedirect()">Click Me!</a>
    </div>
</div>

Dropping connected users in Oracle database

Basically I believe that killing all sessions should be the solution, but...

I found similar discussion - https://community.oracle.com/thread/1054062 to my problem and that was I had no sessions for that users, but I still received the error. I tried also second the best answer:

sql>Shutdown immediate;

sql>startup restrict;

sql>drop user TEST cascade;

What worked for me at the end was to login as the user, drop all tables manually - select for creating drop statements is

select 'drop table ' || TABLE_NAME || ';'  from user_tables;

(Needs to be re-run several times because of references)

I have no idea how is that related, I dropped also functions and sequences (because that was all I had in schema)

When I did that and I logged off, I had several sessions in v$session table and when I killed those I was able to drop user.

My DB was still started in restricted mode (not sure if important or not).

Might help someone else.

BTW: my Oracle version is Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit Production

How to grep and replace

Another option would be to just use perl with globstar.

Enabling shopt -s globstar in your .bashrc (or wherever) allows the ** glob pattern to match all sub-directories and files recursively.

Thus using perl -pXe 's/SEARCH/REPLACE/g' -i ** will recursively replace SEARCH with REPLACE.

The -X flag tells perl to "disable all warnings" - which means that it won't complain about directories.

The globstar also allows you to do things like sed -i 's/SEARCH/REPLACE/g' **/*.ext if you wanted to replace SEARCH with REPLACE in all child files with the extension .ext.

what is the difference between ajax and jquery and which one is better?

It's really not an 'either/or' situation. AJAX stands for Asynchronous JavaScript and XML, and JQuery is a JavaScript library that takes the pain out of writing common JavaScript routines.

It's the difference between a thing (jQuery) and a process (AJAX). To compare them would be to compare apples and oranges.

Android Studio error: "Environment variable does not point to a valid JVM installation"

The answer to this question can be found here

goto the AndroidStudio installation folder.
goto bin folder and open studio.bat in text editor
add set JAVA_HOME=C:\Program Files\Java2\jdk1.8.0//your java path after the ECHO line.
goto Start -> All Programmes -> Android Studio ->
right click on Android Studio and click on properties.
You will see the Target something like <installation path>android-studio\bin\studio64.exe
change it to <installation path>android-studio\bin\studio.bat

or..... even this might work

Java_Home path set to its parent folder to C:\Program Files\Java\jdk1.8.0_25

Why does GitHub recommend HTTPS over SSH?

Maybe because it's harder to steal a password from your brain then to steal a key file from your computer (at least to my knowledge, maybe some substances exist already or methods but this is an infinite discussion)? And if you password protect the key, then you are using a password again and the same problems arise (but some might argue that you have to do more work, because you need to get the key and then crack the password).

Google Map API v3 ~ Simply Close an infowindow?

Or you can share/reuse the same infoWindow object. See this google demo for reference.

Same code from demo

var Demo = { map: null,  infoWindow: null
};

/**
 * Called when clicking anywhere on the map and closes the info window.
 */
Demo.closeInfoWindow = function() {
  Demo.infoWindow.close();
};

/**
 * Opens the shared info window, anchors it to the specified marker, and
 * displays the marker's position as its content.
 */
Demo.openInfoWindow = function(marker) {
  var markerLatLng = marker.getPosition();
  Demo.infoWindow.setContent([
    '<b>Marker position is:</b><br/>',
    markerLatLng.lat(),
    ', ',
    markerLatLng.lng()
  ].join(''));
  Demo.infoWindow.open(Demo.map, marker);
},

/**
 * Called only once on initial page load to initialize the map.
 */
Demo.init = function() {
  // Create single instance of a Google Map.
  var centerLatLng = new google.maps.LatLng(37.789879, -122.390442);
  Demo.map = new google.maps.Map(document.getElementById('map-canvas'), {
    zoom: 13,
    center: centerLatLng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });

  // Create a single instance of the InfoWindow object which will be shared
  // by all Map objects to display information to the user.
  Demo.infoWindow = new google.maps.InfoWindow();

  // Make the info window close when clicking anywhere on the map.
  google.maps.event.addListener(Demo.map, 'click', Demo.closeInfoWindow);

  // Add multiple markers in a few random locations around San Francisco.
  // First random marker
  var marker1 = new google.maps.Marker({
    map: Demo.map,
    position: centerLatLng
  });

  // Register event listeners to each marker to open a shared info
  // window displaying the marker's position when clicked or dragged.
  google.maps.event.addListener(marker1, 'click', function() {
    Demo.openInfoWindow(marker1);
  });

  // Second random marker
  var marker2 = new google.maps.Marker({
    map: Demo.map,
    position: new google.maps.LatLng(37.787814,-122.40764),
    draggable: true
  });

  // Register event listeners to each marker to open a shared info
  // window displaying the marker's position when clicked or dragged.
  google.maps.event.addListener(marker2, 'click', function() {
    Demo.openInfoWindow(marker2);
  });

  // Third random marker
  var marker3 = new google.maps.Marker({
    map: Demo.map,
    position: new google.maps.LatLng(37.767568,-122.391665),
    draggable: true
  });

  // Register event listeners to each marker to open a shared info
  // window displaying the marker's position when clicked or dragged.
  google.maps.event.addListener(marker3, 'click', function() {
    Demo.openInfoWindow(marker3);
  });
}

How to add property to object in PHP >= 5.3 strict mode without generating error

If you absolutely have to add the property to the object, I believe you could cast it as an array, add your property (as a new array key), then cast it back as an object. The only time you run into stdClass objects (I believe) is when you cast an array as an object or when you create a new stdClass object from scratch (and of course when you json_decode() something - silly me for forgetting!).

Instead of:

$foo = new StdClass();
$foo->bar = '1234';

You'd do:

$foo = array('bar' => '1234');
$foo = (object)$foo;

Or if you already had an existing stdClass object:

$foo = (array)$foo;
$foo['bar'] = '1234';
$foo = (object)$foo;

Also as a 1 liner:

$foo = (object) array_merge( (array)$foo, array( 'bar' => '1234' ) );

Flutter plugin not installed error;. When running flutter doctor

I’ve just had this problem after an update and I solved entering File/Settings/Plugins. Then at the top of the window there are two options: Marketplace and Installed, then I clicked on Installed and on Flutter plugin there’s was message saying that the current version of Flutter does not support the new version of Android Studio, so there was a green button Written “Restart” then I clicked and when It opened again, the problem disappeared. May not be the same for you, but many people will search for it here and may help someone.

How to replace unicode characters in string with something else python?

Funny the answer is hidden in among the answers.

str.replace("•", "something") 

would work if you use the right semantics.

str.replace(u"\u2022","something") 

works wonders ;) , thnx to RParadox for the hint.

How to VueJS router-link active style

As mentioned above by @Ricky vue-router automatically applies two active classes, .router-link-active and .router-link-exact-active, to the component.

So, to change active link css use:

.router-link-exact-active{
 //your desired design when link is clicked
font-weight: 700;
}

How to keep the spaces at the end and/or at the beginning of a String?

This question may be old, but as of now the easiest way to do it is to add quotation marks. For example:

<string name="Toast_Memory_GameWon_part1">"you found ALL PAIRS ! on "</string>
<string name="Toast_Memory_GameWon_part2">" flips !"</string>

How to watch and reload ts-node when TypeScript files change

EDIT: Updated for the latest version of nodemon!

I was struggling with the same thing for my development environment until I noticed that nodemon's API allows us to change its default behaviour in order to execute a custom command. For example:

nodemon --watch 'src/**/*.ts' --ignore 'src/**/*.spec.ts' --exec 'ts-node' src/index.ts

Or even better: externalize nodemon's config to a nodemon.json file with the following content, and then just run nodemon, as Sandokan suggested:

{ "watch": ["src/**/*.ts"], "ignore": ["src/**/*.spec.ts"], "exec": "ts-node ./index.ts" }

By virtue of doing this, you'll be able to live-reload a ts-node process without having to worry about the underlying implementation.

Cheers!

Updated for the most recent version of nodemon:

You can run this, for example:

nodemon --watch "src/**" --ext "ts,json" --ignore "src/**/*.spec.ts" --exec "ts-node src/index.ts"

Or create a nodemon.json file with the following content:

{
  "watch": ["src"],
  "ext": "ts,json",
  "ignore": ["src/**/*.spec.ts"],
  "exec": "ts-node ./src/index.ts"      // or "npx ts-node src/index.ts"
}

and then run nodemon with no arguments.

@selector() in Swift?

Using #selector will check your code at compile time to make sure the method you want to call actually exists. Even better, if the method doesn’t exist, you’ll get a compile error: Xcode will refuse to build your app, thus banishing to oblivion another possible source of bugs.

override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.rightBarButtonItem =
            UIBarButtonItem(barButtonSystemItem: .Add, target: self,
                            action: #selector(addNewFireflyRefernce))
    }

    func addNewFireflyReference() {
        gratuitousReferences.append("Curse your sudden but inevitable betrayal!")
    }

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

You may catch multiple exceptions in single catch block.

try{
  // somecode throwing multiple exceptions;
} catch (Exception1 | Exception2 | Exception3 exception){
  // handle exception.
} 

Java String import

Everything in the java.lang package is implicitly imported (including String) and you do not need to do so yourself. This is simply a feature of the Java language. ArrayList and HashMap are however in the java.util package, which is not implicitly imported.

The package java.lang mostly includes essential features, such a class version of primitives, basic exceptions and the Object class. This being integral to most programs, forcing people to import them is redundant and thus the contents of this package are implicitly imported.

jQuery changing css class to div

An HTML element like div can have more than one classes. Let say div is assigned two styles using addClass method. If style1 has 3 properties like font-size, weight and color, and style2 has 4 properties like font-size, weight, color and background-color, the resultant effective properties set (style), i think, will have 4 properties i.e. union of all style sets. Common properties, in our case, color,font-size, weight, will have one occuerance with latest values. If div is assigned style1 first and style2 second, the common prpoerties will be overwritten by style2 values.

Further, I have written a post at Using JQuery to Apply,Remove and Manage Styles, I hope it will help you

Regards Awais