Programs & Examples On #Constraints

A constraint is a condition that has to be fulfilled in a given context. Constraints are typically used in databases and programming languages to detect errors, ensure data consistency, accuracy, and to enforce business requirements.

How to truncate a foreign key constrained table?

you can do

DELETE FROM `mytable` WHERE `id` > 0

Turn off constraints temporarily (MS SQL)

You can disable FK and CHECK constraints only in SQL 2005+. See ALTER TABLE

ALTER TABLE foo NOCHECK CONSTRAINT ALL

or

ALTER TABLE foo NOCHECK CONSTRAINT CK_foo_column

Primary keys and unique constraints can not be disabled, but this should be OK if I've understood you correctly.

What are database constraints?

Constraints dictate what values are valid for data in the database. For example, you can enforce the a value is not null (a NOT NULL constraint), or that it exists as a unique constraint in another table (a FOREIGN KEY constraint), or that it's unique within this table (a UNIQUE constraint or perhaps PRIMARY KEY constraint depending on your requirements). More general constraints can be implemented using CHECK constraints.

The MSDN documentation for SQL Server 2008 constraints is probably your best starting place.

Oracle find a constraint

select * from all_constraints
where owner = '<NAME>'
and constraint_name = 'SYS_C00381400'
/

Like all data dictionary views, this a USER_CONSTRAINTS view if you just want to check your current schema and a DBA_CONSTRAINTS view for administration users.

The construction of the constraint name indicates a system generated constraint name. For instance, if we specify NOT NULL in a table declaration. Or indeed a primary or unique key. For example:

SQL> create table t23 (id number not null primary key)
  2  /

Table created.

SQL> select constraint_name, constraint_type
  2  from user_constraints
  3  where table_name = 'T23'
  4  /

CONSTRAINT_NAME                C
------------------------------ -
SYS_C00935190                  C
SYS_C00935191                  P

SQL>

'C' for check, 'P' for primary.

Generally it's a good idea to give relational constraints an explicit name. For instance, if the database creates an index for the primary key (which it will do if that column is not already indexed) it will use the constraint name oo name the index. You don't want a database full of indexes named like SYS_C00935191.

To be honest most people don't bother naming NOT NULL constraints.

Creating layout constraints programmatically

Regarding your second question about properties, you can use self.myView only if you declared it as a property in class. Since myView is a local variable, you can not use it that way. For more details on this, I would recommend you to go through the apple documentation on Declared Properties,

How to add not null constraint to existing column in MySQL

Would like to add:

After update, such as

ALTER TABLE table_name modify column_name tinyint(4) NOT NULL;

If you get

ERROR 1138 (22004): Invalid use of NULL value

Make sure you update the table first to have values in the related column (so it's not null)

How to create a unique index on a NULL column?

Using SQL Server 2008, you can create a filtered index: http://msdn.microsoft.com/en-us/library/cc280372.aspx. (I see Simon added this as a comment, but thought it deserved its own answer as the comment is easily missed.)

Another option is a trigger to check uniqueness, but this could affect performance.

Add primary key to existing table

Please try this-

ALTER TABLE TABLE_NAME DROP INDEX `PRIMARY`, ADD PRIMARY KEY (COLUMN1, COLUMN2,..);

How to drop all user tables?

The easiest way would be to drop the tablespace then build the tablespace back up. But I'd rather not have to do that. This is similar to Henry's except that I just do a copy/paste on the resultset in my gui.

SELECT
  'DROP'
  ,object_type
  ,object_name
  ,CASE(object_type)
     WHEN 'TABLE' THEN 'CASCADE CONSTRAINTS;'
     ELSE ';'
   END
 FROM user_objects
 WHERE
   object_type IN ('TABLE','VIEW','PACKAGE','PROCEDURE','FUNCTION','SEQUENCE')

Temporarily disable all foreign key constraints

Truncating the table wont be possible even if you disable the foreign keys.so you can use delete command to remove all the records from the table,but be aware if you are using delete command for a table which consists of millions of records then your package will be slow and your transaction log size will increase and it may fill up your valuable disk space.

If you drop the constraints it may happen that you will fill up your table with unclean data and when you try to recreate the constraints it may not allow you to as it will give errors. so make sure that if you drop the constraints,you are loading data which are correctly related to each other and satisfy the constraint relations which you are going to recreate.

so please carefully think the pros and cons of each method and use it according to your requirements

How can I use interface as a C# generic type constraint?

You cannot do this in any released version of C#, nor in the upcoming C# 4.0. It's not a C# limitation, either - there's no "interface" constraint in the CLR itself.

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1922-1' for key 'IDX_STOCK_PRODUCT'

Many time this error is caused when you update a product in your custom module's observer as shown below.

class [NAMESPACE]_[MODULE NAME]_Model_Observer
{
    /**
     * Flag to stop observer executing more than once
     *
     * @var static bool
     */
    static protected $_singletonFlag = false;

    public function saveProductData(Varien_Event_Observer $observer)
    {
        if (!self::$_singletonFlag) {
            self::$_singletonFlag = true;

            $product = $observer->getEvent()->getProduct();
             //do stuff to the $product object
            // $product->save();  // commenting out this line prevents the error
            $product->getResource()->save($product);
    }
} 

Hence whenever you save your product after updating some properties in your module's observer use $product->getResource()->save($product) instead of $product->save()

MySQL Removing Some Foreign keys

first need to get actual constrain name by this query

SHOW CREATE TABLE TABLE_NAME

This query will result constrain name of the foreign key, now below query will drop it.

ALTER TABLE TABLE_NAME DROP FOREIGN KEY COLUMN_NAME_ibfk_1

last number in above constrain name depends how many foreign keys you have in table

Remove all constraints affecting a UIView

The only solution I have found so far is to remove the view from its superview:

[view removeFromSuperview]

This looks like it removes all constraints affecting its layout and is ready to be added to a superview and have new constraints attached. However, it will incorrectly remove any subviews from the hierarchy as well, and get rid of [C7] incorrectly.

How to trap on UIViewAlertForUnsatisfiableConstraints?

Whenever I attempt to remove the constraints that the system had to break, my constraints are no longer enough to satisfy the IB (ie "missing constraints" shows in the IB, which means they're incomplete and won't be used). I actually got around this by setting the constraint it wants to break to low priority, which (and this is an assumption) allows the system to break the constraint gracefully. It's probably not the best solution, but it solved my problem and the resulting constraints worked perfectly.

Is there a constraint that restricts my generic method to numeric types?

Unfortunately you are only able to specify struct in the where clause in this instance. It does seem strange you can't specify Int16, Int32, etc. specifically but I'm sure there's some deep implementation reason underlying the decision to not permit value types in a where clause.

I guess the only solution is to do a runtime check which unfortunately prevents the problem being picked up at compile time. That'd go something like:-

static bool IntegerFunction<T>(T value) where T : struct {
  if (typeof(T) != typeof(Int16)  &&
      typeof(T) != typeof(Int32)  &&
      typeof(T) != typeof(Int64)  &&
      typeof(T) != typeof(UInt16) &&
      typeof(T) != typeof(UInt32) &&
      typeof(T) != typeof(UInt64)) {
    throw new ArgumentException(
      string.Format("Type '{0}' is not valid.", typeof(T).ToString()));
  }

  // Rest of code...
}

Which is a little bit ugly I know, but at least provides the required constraints.

I'd also look into possible performance implications for this implementation, perhaps there's a faster way out there.

Unique Key constraints for multiple columns in Entity Framework

I found three ways to solve the problem.

Unique indexes in EntityFramework Core:

First approach:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
   modelBuilder.Entity<Entity>()
   .HasIndex(p => new {p.FirstColumn , p.SecondColumn}).IsUnique();
}

The second approach to create Unique Constraints with EF Core by using Alternate Keys.

Examples

One column:

modelBuilder.Entity<Blog>().HasAlternateKey(c => c.SecondColumn).HasName("IX_SingeColumn");

Multiple columns:

modelBuilder.Entity<Entity>().HasAlternateKey(c => new [] {c.FirstColumn, c.SecondColumn}).HasName("IX_MultipleColumns");

EF 6 and below:


First approach:

dbContext.Database.ExecuteSqlCommand(string.Format(
                        @"CREATE UNIQUE INDEX LX_{0} ON {0} ({1})", 
                                 "Entitys", "FirstColumn, SecondColumn"));

This approach is very fast and useful but the main problem is that Entity Framework doesn't know anything about those changes!


Second approach:
I found it in this post but I did not tried by myself.

CreateIndex("Entitys", new string[2] { "FirstColumn", "SecondColumn" },
              true, "IX_Entitys");

The problem of this approach is the following: It needs DbMigration so what do you do if you don't have it?


Third approach:
I think this is the best one but it requires some time to do it. I will just show you the idea behind it: In this link http://code.msdn.microsoft.com/CSASPNETUniqueConstraintInE-d357224a you can find the code for unique key data annotation:

[UniqueKey] // Unique Key 
public int FirstColumn  { get; set;}
[UniqueKey] // Unique Key 
public int SecondColumn  { get; set;}

// The problem hier
1, 1  = OK 
1 ,2  = NO OK 1 IS UNIQUE

The problem for this approach; How can I combine them? I have an idea to extend this Microsoft implementation for example:

[UniqueKey, 1] // Unique Key 
public int FirstColumn  { get; set;}
[UniqueKey ,1] // Unique Key 
public int SecondColumn  { get; set;}

Later in the IDatabaseInitializer as described in the Microsoft example you can combine the keys according to the given integer. One thing has to be noted though: If the unique property is of type string then you have to set the MaxLength.

Annotations from javax.validation.constraints not working

In my case, I was using spring boot version 2.3.0. When I changed my maven dependency to use 2.1.3 it worked.

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.3.RELEASE</version>
    <relativePath /> <!-- lookup parent from repository -->
</parent>
<dependencies>
    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
    </dependency>
</dependencies>

How to add "on delete cascade" constraints?

I'm pretty sure you can't simply add on delete cascade to an existing foreign key constraint. You have to drop the constraint first, then add the correct version. In standard SQL, I believe the easiest way to do this is to

  • start a transaction,
  • drop the foreign key,
  • add a foreign key with on delete cascade, and finally
  • commit the transaction

Repeat for each foreign key you want to change.

But PostgreSQL has a non-standard extension that lets you use multiple constraint clauses in a single SQL statement. For example

alter table public.scores
drop constraint scores_gid_fkey,
add constraint scores_gid_fkey
   foreign key (gid)
   references games(gid)
   on delete cascade;

If you don't know the name of the foreign key constraint you want to drop, you can either look it up in pgAdminIII (just click the table name and look at the DDL, or expand the hierarchy until you see "Constraints"), or you can query the information schema.

select *
from information_schema.key_column_usage
where position_in_unique_constraint is not null

How to remove constraints from my MySQL table?

The simplest way to remove constraint is to use syntax ALTER TABLE tbl_name DROP CONSTRAINT symbol; introduced in MySQL 8.0.19:

As of MySQL 8.0.19, ALTER TABLE permits more general (and SQL standard) syntax for dropping and altering existing constraints of any type, where the constraint type is determined from the constraint name

ALTER TABLE tbl_magazine_issue DROP CONSTRAINT FK_tbl_magazine_issue_mst_users;

db<>fiddle demo

What is the difference between primary, unique and foreign key constraints, and indexes?

Here are some reference for you:

Primary & foreign key Constraint.

Primary Key: A primary key is a field or combination of fields that uniquely identify a record in a table, so that an individual record can be located without confusion.

Foreign Key: A foreign key (sometimes called a referencing key) is a key used to link two tables together. Typically you take the primary key field from one table and insert it into the other table where it becomes a foreign key (it remains a primary key in the original table).

Index, on the other hand, is an attribute that you can apply on some columns so that the data retrieval done on those columns can be speed up.

SQL DROP TABLE foreign key constraint

If it is SQL Server you must drop the constraint before you can drop the table.

SQL Server 2008- Get table constraints

You should use the current sys catalog views (if you're on SQL Server 2005 or newer - the sysobjects views are deprecated and should be avoided) - check out the extensive MSDN SQL Server Books Online documentation on catalog views here.

There are quite a few views you might be interested in:

  • sys.default_constraints for default constraints on columns
  • sys.check_constraints for check constraints on columns
  • sys.key_constraints for key constraints (e.g. primary keys)
  • sys.foreign_keys for foreign key relations

and a lot more - check it out!

You can query and join those views to get the info needed - e.g. this will list the tables, columns and all default constraints defined on them:

SELECT 
    TableName = t.Name,
    ColumnName = c.Name,
    dc.Name,
    dc.definition
FROM sys.tables t
INNER JOIN sys.default_constraints dc ON t.object_id = dc.parent_object_id
INNER JOIN sys.columns c ON dc.parent_object_id = c.object_id AND c.column_id = dc.parent_column_id
ORDER BY t.Name

Foreign key constraint may cause cycles or multiple cascade paths?

SQL Server does simple counting of cascade paths and, rather than trying to work out whether any cycles actually exist, it assumes the worst and refuses to create the referential actions (CASCADE): you can and should still create the constraints without the referential actions. If you can't alter your design (or doing so would compromise things) then you should consider using triggers as a last resort.

FWIW resolving cascade paths is a complex problem. Other SQL products will simply ignore the problem and allow you to create cycles, in which case it will be a race to see which will overwrite the value last, probably to the ignorance of the designer (e.g. ACE/Jet does this). I understand some SQL products will attempt to resolve simple cases. Fact remains, SQL Server doesn't even try, plays it ultra safe by disallowing more than one path and at least it tells you so.

Microsoft themselves advises the use of triggers instead of FK constraints.

Get table name by constraint name

SELECT constraint_name, constraint_type, column_name
from user_constraints natural join user_cons_columns
where table_name = "my_table_name";

will give you what you need

How can foreign key constraints be temporarily disabled using T-SQL?

I have a more useful version if you are interested. I lifted a bit of code from here a website where the link is no longer active. I modifyied it to allow for an array of tables into the stored procedure and it populates the drop, truncate, add statements before executing all of them. This gives you control to decide which tables need truncating.

/****** Object:  UserDefinedTableType [util].[typ_objects_for_managing]    Script Date: 03/04/2016 16:42:55 ******/
CREATE TYPE [util].[typ_objects_for_managing] AS TABLE(
    [schema] [sysname] NOT NULL,
    [object] [sysname] NOT NULL
)
GO

create procedure [util].[truncate_table_with_constraints]
@objects_for_managing util.typ_objects_for_managing readonly

--@schema sysname
--,@table sysname

as 
--select
--    @table = 'TABLE',
--    @schema = 'SCHEMA'

declare @exec_table as table (ordinal int identity (1,1), statement nvarchar(4000), primary key (ordinal));

--print '/*Drop Foreign Key Statements for ['+@schema+'].['+@table+']*/'

insert into @exec_table (statement)
select
          'ALTER TABLE ['+SCHEMA_NAME(o.schema_id)+'].['+ o.name+'] DROP CONSTRAINT ['+fk.name+']'
from sys.foreign_keys fk
inner join sys.objects o
          on fk.parent_object_id = o.object_id
where 
exists ( 
select * from @objects_for_managing chk 
where 
chk.[schema] = SCHEMA_NAME(o.schema_id)  
and 
chk.[object] = o.name
) 
;
          --o.name = @table and
          --SCHEMA_NAME(o.schema_id)  = @schema

insert into @exec_table (statement) 
select
'TRUNCATE TABLE ' + src.[schema] + '.' + src.[object] 
from @objects_for_managing src
; 

--print '/*Create Foreign Key Statements for ['+@schema+'].['+@table+']*/'
insert into @exec_table (statement)
select 'ALTER TABLE ['+SCHEMA_NAME(o.schema_id)+'].['+o.name+'] ADD CONSTRAINT ['+fk.name+'] FOREIGN KEY (['+c.name+']) 
REFERENCES ['+SCHEMA_NAME(refob.schema_id)+'].['+refob.name+'](['+refcol.name+'])'
from sys.foreign_key_columns fkc
inner join sys.foreign_keys fk
          on fkc.constraint_object_id = fk.object_id
inner join sys.objects o
          on fk.parent_object_id = o.object_id
inner join sys.columns c
          on      fkc.parent_column_id = c.column_id and
                   o.object_id = c.object_id
inner join sys.objects refob
          on fkc.referenced_object_id = refob.object_id
inner join sys.columns refcol
          on fkc.referenced_column_id = refcol.column_id and
                   fkc.referenced_object_id = refcol.object_id
where 
exists ( 
select * from @objects_for_managing chk 
where 
chk.[schema] = SCHEMA_NAME(o.schema_id)  
and 
chk.[object] = o.name
) 
;

          --o.name = @table and
          --SCHEMA_NAME(o.schema_id)  = @schema



declare @looper int , @total_records int, @sql_exec nvarchar(4000)

select @looper = 1, @total_records = count(*) from @exec_table; 

while @looper <= @total_records 
begin

select @sql_exec = (select statement from @exec_table where ordinal =@looper)
exec sp_executesql @sql_exec 
print @sql_exec 
set @looper = @looper + 1
end

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.

trying to animate a constraint in swift

In my case, I only updated the custom view.

// DO NOT LIKE THIS
customView.layoutIfNeeded()    // Change to view.layoutIfNeeded()
UIView.animate(withDuration: 0.5) {
   customViewConstraint.constant = 100.0
   customView.layoutIfNeeded() // Change to view.layoutIfNeeded()
}

SQL Server 2005 How Create a Unique Constraint?

I also found you can do this via, the database diagrams.

By right clicking the table and selecting Indexes/Keys...

Click the 'Add' button, and change the columns to the column(s) you wish make unique.

Change Is Unique to Yes.

Click close and save the diagram, and it will add it to the table.

Display names of all constraints for a table in Oracle SQL

select constraint_name,constraint_type 
from user_constraints
where table_name = 'YOUR TABLE NAME';

note: table name should be in caps.

In case you don't know the name of the table then,

select constraint_name,constraint_type,table_name 
from user_constraints;

"Insert if not exists" statement in SQLite

insert into bookmarks (users_id, lessoninfo_id)

select 1, 167
EXCEPT
select user_id, lessoninfo_id
from bookmarks
where user_id=1
and lessoninfo_id=167;

This is the fastest way.

For some other SQL engines, you can use a Dummy table containing 1 record. e.g:

select 1, 167 from ONE_RECORD_DUMMY_TABLE

Check if inputs form are empty jQuery

Define a helper function like this

function checkWhitespace(inputString){

    let stringArray = inputString.split(' ');

    let output = true;

    for (let el of stringArray){
        if (el!=''){
            output=false;
        }
    }

    return output;
}

Then check your input field value by passing through as an argument. If function returns true, that means value is only white space.

As an example

let inputValue = $('#firstName').val();
if(checkWhitespace(inputValue)) {
  // Show Warnings or return warnings
}else {
  // // Block of code-probably store input value into database
}

How to echo JSON in PHP

if you want to encode or decode an array from or to JSON you can use these functions

$myJSONString = json_encode($myArray);
$myArray = json_decode($myString);

json_encode will result in a JSON string, built from an (multi-dimensional) array. json_decode will result in an Array, built from a well formed JSON string

with json_decode you can take the results from the API and only output what you want, for example:

echo $myArray['payload']['ign'];

Create directories using make file

make in, and off itself, handles directory targets just the same as file targets. So, it's easy to write rules like this:

outDir/someTarget: Makefile outDir
    touch outDir/someTarget

outDir:
    mkdir -p outDir

The only problem with that is, that the directories timestamp depends on what is done to the files inside. For the rules above, this leads to the following result:

$ make
mkdir -p outDir
touch outDir/someTarget
$ make
touch outDir/someTarget
$ make
touch outDir/someTarget
$ make
touch outDir/someTarget

This is most definitely not what you want. Whenever you touch the file, you also touch the directory. And since the file depends on the directory, the file consequently appears to be out of date, forcing it to be rebuilt.

However, you can easily break this loop by telling make to ignore the timestamp of the directory. This is done by declaring the directory as an order-only prerequsite:

# The pipe symbol tells make that the following prerequisites are order-only
#                           |
#                           v
outDir/someTarget: Makefile | outDir
    touch outDir/someTarget

outDir:
    mkdir -p outDir

This correctly yields:

$ make
mkdir -p outDir
touch outDir/someTarget
$ make
make: 'outDir/someTarget' is up to date.

TL;DR:

Write a rule to create the directory:

$(OUT_DIR):
    mkdir -p $(OUT_DIR)

And have the targets for the stuff inside depend on the directory order-only:

$(OUT_DIR)/someTarget: ... | $(OUT_DIR)

MySQL "Or" Condition

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

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

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

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

how to delete files from amazon s3 bucket?

you can do it using aws cli : https://aws.amazon.com/cli/ and some unix command.

this aws cli commands should work:

aws s3 rm s3://<your_bucket_name> --exclude "*" --include "<your_regex>" 

if you want to include sub-folders you should add the flag --recursive

or with unix commands:

aws s3 ls s3://<your_bucket_name>/ | awk '{print $4}' | xargs -I%  <your_os_shell>   -c 'aws s3 rm s3:// <your_bucket_name>  /% $1'

explanation:

  1. list all files on the bucket --pipe-->
  2. get the 4th parameter(its the file name) --pipe--> // you can replace it with linux command to match your pattern
  3. run delete script with aws cli

How to mark a method as obsolete or deprecated?

To mark as obsolete with a warning:

[Obsolete]
private static void SomeMethod()

You get a warning when you use it:

Obsolete warning is shown

And with IntelliSense:

Obsolete warning with IntelliSense

If you want a message:

[Obsolete("My message")]
private static void SomeMethod()

Here's the IntelliSense tool tip:

IntelliSense shows the obsolete message

Finally if you want the usage to be flagged as an error:

[Obsolete("My message", true)]
private static void SomeMethod()

When used this is what you get:

Method usage is displayed as an error

Note: Use the message to tell people what they should use instead, not why it is obsolete.

How to convert Nvarchar column to INT

CONVERT takes the column name, not a string containing the column name; your current expression tries to convert the string A.my_NvarcharColumn to an integer instead of the column content.

SELECT convert (int, N'A.my_NvarcharColumn') FROM A;

should instead be

SELECT convert (int, A.my_NvarcharColumn) FROM A;

Simple SQLfiddle here.

Angular 2 router no base href set

https://angular.io/docs/ts/latest/guide/router.html

Add the base element just after the <head> tag. If the app folder is the application root, as it is for our application, set the href value exactly as shown here.

The <base href="/"> tells the Angular router what is the static part of the URL. The router then only modifies the remaining part of the URL.

<head>
  <base href="/">
  ...
</head>

Alternatively add

>= Angular2 RC.6

import {APP_BASE_HREF} from '@angular/common';

@NgModule({
  declarations: [AppComponent],
  imports: [routing /* or RouterModule */], 
  providers: [{provide: APP_BASE_HREF, useValue : '/' }]
]); 

in your bootstrap.

In older versions the imports had to be like

< Angular2 RC.6

import {APP_BASE_HREF} from '@angular/common';
bootstrap(AppComponent, [
  ROUTER_PROVIDERS, 
  {provide: APP_BASE_HREF, useValue : '/' });
]); 

< RC.0

import {provide} from 'angular2/core';
bootstrap(AppComponent, [
  ROUTER_PROVIDERS, 
  provide(APP_BASE_HREF, {useValue : '/' });
]); 

< beta.17

import {APP_BASE_HREF} from 'angular2/router';

>= beta.17

import {APP_BASE_HREF} from 'angular2/platform/common';

See also Location and HashLocationStrategy stopped working in beta.16

How to open generated pdf using jspdf in new window

Javascript code

// IE doesn't allow using a blob object directly as link href
// instead it is necessary to use msSaveOrOpenBlob
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
  window.navigator.msSaveOrOpenBlob(doc.output("blob"), "Name.pdf");
} else {

  // For other browsers:
  // Create a link pointing to the ObjectURL containing the blob.
  doc.autoPrint();
  window.open(
    URL.createObjectURL(doc.output("blob")),
    "_blank",
    "height=650,width=500,scrollbars=yes,location=yes"
  );

  // For Firefox it is necessary to delay revoking the ObjectURL
  setTimeout(() => {    
    window.URL.revokeObjectURL(doc.output("bloburl"));
  }, 100);
}

JTable won't show column headers

    public table2() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 485, 218);
    setTitle("jtable");
    getContentPane().setLayout(null);

    String data[][] = { { "Row1/1", "Row1/2", "Row1/3" },
            { "Row2/1", "Row2/2", "Row2/3" },
            { "Row3/1", "Row3/2", "Row3/3" },
            { "Row4/1", "Row4/2", "Row4/3" }, };

    String header[] = { "Column 1", "Column 2", "Column 3" };

    // Table
    JTable table = new JTable(data,header);


    // ScrollPane
    JScrollPane scrollPane = new JScrollPane(table);
    scrollPane.setBounds(36, 37, 407, 79);
    getContentPane().add(scrollPane);

   }

}

try this!!

How to call a JavaScript function within an HTML body

Try to use createChild() method of DOM or insertRow() and insertCell() method of table object in script tag.

What is web.xml file and what are all things can I do with it?

I am trying to figure out exactly how this works too. This site might be helpful to you. It has all of the possible tags for web.xml along with examples and descriptions of each tag.

http://wiki.metawerx.net/wiki/Web.xml

How to get a specific output iterating a hash in Ruby?

hash.each do |key, array|
  puts "#{key}-----"
  puts array
end

Regarding order I should add, that in 1.8 the items will be iterated in random order (well, actually in an order defined by Fixnum's hashing function), while in 1.9 it will be iterated in the order of the literal.

How to set DOM element as the first child?

var eElement; // some E DOM instance
var newFirstElement; //element which should be first in E

eElement.insertBefore(newFirstElement, eElement.firstChild);

How can I check if a Perl module is installed on my system from the command line?

Bravo for @user80168's solution (I'm still counting \'s !) but to avoid all the escaping involved with aliases and shells:

%~/ cat ~/bin/perlmod
perl -le'eval qq{require $ARGV[0]; } 
    ? print ( "Found $ARGV[0] Version: ", eval "$ARGV[0]->VERSION" ) 
    : print "Not installed" ' $1

works reasonably well.

Here might be the simplest and most "modern" approach, using Module::Runtime:

perl -MModule::Runtime=use_module -E '
     say "$ARGV[0] ", use_module($ARGV[0])->VERSION' DBI

This will give a useful error if the module is not installed.

Using -MModule::Runtime requires it to be installed (it is not a core module).

how does unix handle full path name with space and arguments?

You can quote if you like, or you can escape the spaces with a preceding \, but most UNIX paths (Mac OS X aside) don't have spaces in them.

/Applications/Image\ Capture.app/Contents/MacOS/Image\ Capture

"/Applications/Image Capture.app/Contents/MacOS/Image Capture"

/Applications/"Image Capture.app"/Contents/MacOS/"Image Capture"

All refer to the same executable under Mac OS X.

I'm not sure what you mean about recognizing a path - if any of the above paths are passed as a parameter to a program the shell will put the entire string in one variable - you don't have to parse multiple arguments to get the entire path.

tmux set -g mouse-mode on doesn't work

Paste here in ~/.tmux.conf

set -g mouse on

and run on terminal

tmux source-file ~/.tmux.conf

With Spring can I make an optional path variable?

If you are using Spring 4.1 and Java 8 you can use java.util.Optional which is supported in @RequestParam, @PathVariable, @RequestHeader and @MatrixVariable in Spring MVC -

@RequestMapping(value = {"/json/{type}", "/json" }, method = RequestMethod.GET)
public @ResponseBody TestBean typedTestBean(
    @PathVariable Optional<String> type,
    @RequestParam("track") String track) {      
    if (type.isPresent()) {
        //type.get() will return type value
        //corresponds to path "/json/{type}"
    } else {
        //corresponds to path "/json"
    }       
}

how to convert string to numerical values in mongodb

Collation is what you need:

db.collectionName.find().sort({PartnerID: 1}).collation({locale: "en_US", numericOrdering: true})

How can I make git show a list of the files that are being tracked?

The accepted answer only shows files in the current directory's tree. To show all of the tracked files that have been committed (on the current branch), use

git ls-tree --full-tree --name-only -r HEAD
  • --full-tree makes the command run as if you were in the repo's root directory.
  • -r recurses into subdirectories. Combined with --full-tree, this gives you all committed, tracked files.
  • --name-only removes SHA / permission info for when you just want the file paths.
  • HEAD specifies which branch you want the list of tracked, committed files for. You could change this to master or any other branch name, but HEAD is the commit you have checked out right now.

This is the method from the accepted answer to the ~duplicate question https://stackoverflow.com/a/8533413/4880003.

Is there a way to check which CSS styles are being used or not used on a web page?

Install the CSS Usage add-on for Firebug and run it on that page. It will tell you which styles are being used and not used by that page.

execute shell command from android

Process p;
StringBuffer output = new StringBuffer();
try {
    p = Runtime.getRuntime().exec(params[0]);
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(p.getInputStream()));
    String line = "";
    while ((line = reader.readLine()) != null) {
        output.append(line + "\n");
        p.waitFor();
    }
} 
catch (IOException e) {
    e.printStackTrace();
} catch (InterruptedException e) {
    e.printStackTrace();
}
String response = output.toString();
return response;

Put content in HttpResponseMessage object?

You should create the response using Request.CreateResponse:

HttpResponseMessage response =  Request.CreateResponse(HttpStatusCode.BadRequest, "Error message");

You can pass objects not just strings to CreateResponse and it will serialize them based on the request's Accept header. This saves you from manually choosing a formatter.

How to write "not in ()" sql query using join

This article:

may be if interest to you.

In a couple of words, this query:

SELECT  d1.short_code
FROM    domain1 d1
LEFT JOIN
        domain2 d2
ON      d2.short_code = d1.short_code
WHERE   d2.short_code IS NULL

will work but it is less efficient than a NOT NULL (or NOT EXISTS) construct.

You can also use this:

SELECT  short_code
FROM    domain1
EXCEPT
SELECT  short_code
FROM    domain2

This is using neither NOT IN nor WHERE (and even no joins!), but this will remove all duplicates on domain1.short_code if any.

Set up adb on Mac OS X

If you using zsh then you need do the add the following to your .zshrc

Steps: Step 1: Open your .zshrc profile

open -e .zshrc

Step 2: Add the following to the file

export PATH=$PATH:/Users/${YourUser}/Library/Android/sdk/platform-tools
export ANDROID_HOME=/Users/${YourUser}/Library/Android/sdk

Step 3: Save the file and close. Step 4: Reload the .zshrc

source .zshrc

Step 5: Check the devices connected

adb devices

WordPress Get the Page ID outside the loop

Use this global $post instead:

global $post;
echo $post->ID;

Getting all selected checkboxes in an array

here is my code for the same problem someone can also try this. jquery

<script>
$(document).ready(function(){`
$(".check11").change(function(){
var favorite1 = [];        
$.each($("input[name='check1']:checked"), function(){                    
favorite1.push($(this).val());
document.getElementById("countch1").innerHTML=favorite1;
});
});
});
</script>

SSIS - Text was truncated or one or more characters had no match in the target code page - Special Characters

If you go to the Flat file connection manager under Advanced and Look at the "OutputColumnWidth" description's ToolTip It will tell you that Composit characters may use more spaces. So the "é" in "Société" most likely occupies more than one character.

EDIT: Here's something about it: http://en.wikipedia.org/wiki/Precomposed_character

Get the current date in java.sql.Date format

Since the java.sql.Date has a constructor that takes 'long time' and java.util.Date has a method that returns 'long time', I just pass the returned 'long time' to the java.sql.Date to create the date.

java.util.Date date = new java.util.Date();
java.sql.Date sqlDate = new Date(date.getTime());

Add common prefix to all cells in Excel

Select the cell you want to be like this, Go To Cell Properties (or CTRL 1) under Number tab in custom enter "X"#

did you register the component correctly? For recursive components, make sure to provide the "name" option

In my case, i was calling twice the import...

@click="$router.push({ path: 'searcherresult' })"

import SearcherResult from "../views/SearcherResult"; --- ERROR

Cause i call in other component...

How can I use threading in Python?

Since this question was asked in 2010, there has been real simplification in how to do simple multithreading with Python with map and pool.

The code below comes from an article/blog post that you should definitely check out (no affiliation) - Parallelism in one line: A Better Model for Day to Day Threading Tasks. I'll summarize below - it ends up being just a few lines of code:

from multiprocessing.dummy import Pool as ThreadPool
pool = ThreadPool(4)
results = pool.map(my_function, my_array)

Which is the multithreaded version of:

results = []
for item in my_array:
    results.append(my_function(item))

Description

Map is a cool little function, and the key to easily injecting parallelism into your Python code. For those unfamiliar, map is something lifted from functional languages like Lisp. It is a function which maps another function over a sequence.

Map handles the iteration over the sequence for us, applies the function, and stores all of the results in a handy list at the end.

Enter image description here


Implementation

Parallel versions of the map function are provided by two libraries:multiprocessing, and also its little known, but equally fantastic step child:multiprocessing.dummy.

multiprocessing.dummy is exactly the same as multiprocessing module, but uses threads instead (an important distinction - use multiple processes for CPU-intensive tasks; threads for (and during) I/O):

multiprocessing.dummy replicates the API of multiprocessing, but is no more than a wrapper around the threading module.

import urllib2
from multiprocessing.dummy import Pool as ThreadPool

urls = [
  'http://www.python.org',
  'http://www.python.org/about/',
  'http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html',
  'http://www.python.org/doc/',
  'http://www.python.org/download/',
  'http://www.python.org/getit/',
  'http://www.python.org/community/',
  'https://wiki.python.org/moin/',
]

# Make the Pool of workers
pool = ThreadPool(4)

# Open the URLs in their own threads
# and return the results
results = pool.map(urllib2.urlopen, urls)

# Close the pool and wait for the work to finish
pool.close()
pool.join()

And the timing results:

Single thread:   14.4 seconds
       4 Pool:   3.1 seconds
       8 Pool:   1.4 seconds
      13 Pool:   1.3 seconds

Passing multiple arguments (works like this only in Python 3.3 and later):

To pass multiple arrays:

results = pool.starmap(function, zip(list_a, list_b))

Or to pass a constant and an array:

results = pool.starmap(function, zip(itertools.repeat(constant), list_a))

If you are using an earlier version of Python, you can pass multiple arguments via this workaround).

(Thanks to user136036 for the helpful comment.)

How do I debug Node.js applications?

Use Webstorm! It's perfect for debugging Node.js applications. It has a built-in debugger. Check out the docs here: https://www.jetbrains.com/help/webstorm/2016.1/running-and-debugging-node-js.html

How to convert PDF files to images

I used PDFiumSharp and ImageSharp in a .NET Standard 2.1 class library.

/// <summary>
/// Saves a thumbnail (jpg) to the same folder as the PDF file, using dimensions 300x423,
/// which corresponds to the aspect ratio of 'A' paper sizes like A4 (ratio h/w=sqrt(2))
/// </summary>
/// <param name="pdfPath">Source path of the pdf file.</param>
/// <param name="thumbnailPath">Target path of the thumbnail file.</param>
/// <param name="width"></param>
/// <param name="height"></param>
public static void SaveThumbnail(string pdfPath, string thumbnailPath = "", int width = 300, int height = 423)
{
    using var pdfDocument = new PdfDocument(pdfPath);
    var firstPage = pdfDocument.Pages[0];

    using var pageBitmap = new PDFiumBitmap(width, height, true);

    firstPage.Render(pageBitmap);

    var imageJpgPath = string.IsNullOrWhiteSpace(thumbnailPath)
        ? Path.ChangeExtension(pdfPath, "jpg")
        : thumbnailPath;
    var image = Image.Load(pageBitmap.AsBmpStream());

    // Set the background to white, otherwise it's black. https://github.com/SixLabors/ImageSharp/issues/355#issuecomment-333133991
    image.Mutate(x => x.BackgroundColor(Rgba32.White));

    image.Save(imageJpgPath, new JpegEncoder());
}

Input widths on Bootstrap 3

In Bootstrap 3

You can simply create a custom style:

.form-control-inline {
    min-width: 0;
    width: auto;
    display: inline;
}

Then add it to form controls like so:

<div class="controls">
    <select id="expirymonth" class="form-control form-control-inline">
        <option value="01">01 - January</option>
        <option value="02">02 - February</option>
        <option value="03">03 - March</option>
        <option value="12">12 - December</option>
    </select>
    <select id="expiryyear" class="form-control form-control-inline">
        <option value="2014">2014</option>
        <option value="2015">2015</option>
        <option value="2016">2016</option>
    </select>
</div>

This way you don't have to put extra markup for layout in your HTML.

rsync - mkstemp failed: Permission denied (13)

run in root access ssh chould solve this problem

or chmod 0777 /dir/to/be/backedup/

or chown username:user /dir/to/be/backedup/

What is the 'override' keyword in C++ used for?

override is a C++11 keyword which means that a method is an "override" from a method from a base class. Consider this example:

   class Foo
   {
   public:
        virtual void func1();
   }

   class Bar : public Foo
   {
   public:
        void func1() override;
   }

If B::func1() signature doesn't equal A::func1() signature a compilation error will be generated because B::func1() does not override A::func1(), it will define a new method called func1() instead.

shared global variables in C

In the header file write it with extern. And at the global scope of one of the c files declare it without extern.

Using OR & AND in COUNTIFS

In a more general case:

N( A union B) = N(A) + N(B) - N(A intersect B) 
= COUNTIFS(A1:A196,"Yes",J1:J196,"Agree")+COUNTIFS(A1:A196,"No",J1:J196,"Agree")-A1:A196,"Yes",A1:A196,"No")

Reading value from console, interactively

I recommend using Inquirer, since it provides a collection of common interactive command line user interfaces.

const inquirer = require('inquirer');

const questions = [{
  type: 'input',
  name: 'name',
  message: "What's your name?",
}];

const answers = await inquirer.prompt(questions);
console.log(answers);

SQL Server: How to use UNION with two queries that BOTH have a WHERE clause?

The answer is misleading because it attempts to fix a problem that is not a problem. You actually CAN have a WHERE CLAUSE in each segment of a UNION. You cannot have an ORDER BY except in the last segment. Therefore, this should work...

select top 2 t1.ID, t1.ReceivedDate
from Table t1
where t1.Type = 'TYPE_1'
-----remove this-- order by ReceivedDate desc
union
select top 2 t2.ID,  t2.ReceivedDate --- add second column
  from Table t2
 where t2.Type = 'TYPE_2'
order by ReceivedDate desc

How do I modify the URL without reloading the page?

NOTE: If you are working with an HTML5 browser then you should ignore this answer. This is now possible as can be seen in the other answers.

There is no way to modify the URL in the browser without reloading the page. The URL represents what the last loaded page was. If you change it (document.location) then it will reload the page.

One obvious reason being, you write a site on www.mysite.com that looks like a bank login page. Then you change the browser URL bar to say www.mybank.com. The user will be totally unaware that they are really looking at www.mysite.com.

angularjs ng-style: background-image isn't working

Just for the records you can also define your object in the controller like this:

this.styleDiv = {color: '', backgroundColor:'', backgroundImage : '' };

and then you can define a function to change the property of the object directly:

this.changeBackgroundImage = function (){
        this.styleDiv.backgroundImage = 'url('+this.backgroundImage+')';
    }

Doing it in that way you can modify dinamicaly your style.

Drop all tables command

I don't think you can drop all tables in one hit but you can do the following to get the commands:

select 'drop table ' || name || ';' from sqlite_master
    where type = 'table';

The output of this is a script that will drop the tables for you. For indexes, just replace table with index.

You can use other clauses in the where section to limit which tables or indexes are selected (such as "and name glob 'pax_*'" for those starting with "pax_").

You could combine the creation of this script with the running of it in a simple bash (or cmd.exe) script so there's only one command to run.

If you don't care about any of the information in the DB, I think you can just delete the file it's stored in off the hard disk - that's probably faster. I've never tested this but I can't see why it wouldn't work.

printf() formatting for hex

The "0x" counts towards the eight character count. You need "%#010x".

Note that # does not append the 0x to 0 - the result will be 0000000000 - so you probably actually should just use "0x%08x" anyway.

Setting multiple attributes for an element at once with JavaScript

You might be able to use Object.assign(...) to apply your properties to the created element. See comments for additional details.

Keep in mind that height and width attributes are defined in pixels, not percents. You'll have to use CSS to make it fluid.

_x000D_
_x000D_
var elem = document.createElement('img')_x000D_
Object.assign(elem, {_x000D_
  className: 'my-image-class',_x000D_
  src: 'https://dummyimage.com/320x240/ccc/fff.jpg',_x000D_
  height: 120, // pixels_x000D_
  width: 160, // pixels_x000D_
  onclick: function () {_x000D_
    alert('Clicked!')_x000D_
  }_x000D_
})_x000D_
document.body.appendChild(elem)_x000D_
_x000D_
// One-liner:_x000D_
// document.body.appendChild(Object.assign(document.createElement(...), {...}))
_x000D_
.my-image-class {_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  border: solid 5px transparent;_x000D_
  box-sizing: border-box_x000D_
}_x000D_
_x000D_
.my-image-class:hover {_x000D_
  cursor: pointer;_x000D_
  border-color: red_x000D_
}_x000D_
_x000D_
body { margin:0 }
_x000D_
_x000D_
_x000D_

Java ArrayList Index

Here is how I would write it.

String[] fruit = "apple banana orange".split(" ");
System.out.println(fruit[1]);

JQuery - Get select value

val() returns the value of the <select> element, i.e. the value attribute of the selected <option> element.

Since you actually want the inner text of the selected <option> element, you should match that element and use text() instead:

var nationality = $("#dancerCountry option:selected").text();

Where is SQL Server Management Studio 2012?

After going back into the installer & checking off "Management Tools", ssms.exe was available under "C:\Program Files\Microsoft SQL Server\110\Tools\Binn\ManagementStudio" (thanks to everyone for pointing out where to find it).

sql server setup

What exactly is the meaning of an API?

  1. an API(Application Programming Interface) is a set of defined functions and methods for interfacing with the underlying operating system or another program or service running on the computer.

  2. It is usually used by establishing a reference to a library in your software or importing a function from a dll.

  3. It is used in one form or another in almost all software, being explicitly called in your program or implicitly called by the compiler.

I need a Nodejs scheduler that allows for tasks at different intervals

I would recommend node-cron. It allows to run tasks using Cron patterns e.g.

'* * * * * *' - runs every second
'*/5 * * * * *' - runs every 5 seconds
'10,20,30 * * * * *' - run at 10th, 20th and 30th second of every minute
'0 * * * * *' - runs every minute
'0 0 * * * *' - runs every hour (at 0 minutes and 0 seconds)

But also more complex schedules e.g.

'00 30 11 * * 1-5' - Runs every weekday (Monday through Friday) at 11:30:00 AM. It does not run on Saturday or Sunday.

Sample code: running job every 10 minutes:

var cron = require('cron');
var cronJob = cron.job("0 */10 * * * *", function(){
    // perform operation e.g. GET request http.get() etc.
    console.info('cron job completed');
}); 
cronJob.start();

You can find more examples in node-cron wiki

More on cron configuration can be found on cron wiki

I've been using that library in many projects and it does the job. I hope that will help.

MySQL INNER JOIN Alias

You'll need to join twice:

SELECT home.*, away.*, g.network, g.date_start 
FROM game AS g
INNER JOIN team AS home
  ON home.importid = g.home
INNER JOIN team AS away
  ON away.importid = g.away
ORDER BY g.date_start DESC 
LIMIT 7

Java regex capturing groups indexes

For The Rest Of Us

Here is a simple and clear example of how this works

Regex: ([a-zA-Z0-9]+)([\s]+)([a-zA-Z ]+)([\s]+)([0-9]+)

String: "!* UserName10 John Smith 01123 *!"

group(0): UserName10 John Smith 01123
group(1): UserName10
group(2):  
group(3): John Smith
group(4):  
group(5): 01123

As you can see, I have created FIVE groups which are each enclosed in parentheses.

I included the !* and *! on either side to make it clearer. Note that none of those characters are in the RegEx and therefore will not be produced in the results. Group(0) merely gives you the entire matched string (all of my search criteria in one single line). Group 1 stops right before the first space because the space character was not included in the search criteria. Groups 2 and 4 are simply the white space, which in this case is literally a space character, but could also be a tab or a line feed etc. Group 3 includes the space because I put it in the search criteria ... etc.

Hope this makes sense.

How can I get the IP address from NIC in Python?

try below code, it works for me in Mac10.10.2:

import subprocess

if __name__ == "__main__":
    result = subprocess.check_output('ifconfig en0 |grep -w inet', shell=True) # you may need to use eth0 instead of en0 here!!!
    print 'output = %s' % result.strip()
    # result = None
    ip = ''
    if result:
        strs = result.split('\n')
        for line in strs:
            # remove \t, space...
            line = line.strip()
            if line.startswith('inet '):
                a = line.find(' ')
                ipStart = a+1
                ipEnd = line.find(' ', ipStart)
                if a != -1 and ipEnd != -1:
                    ip = line[ipStart:ipEnd]
                    break
    print 'ip = %s' % ip

bind/unbind service example (android)

First of all, two things that we need to understand,

Client

  • It makes request to a specific server

bindService(new Intent("com.android.vending.billing.InAppBillingService.BIND"), mServiceConn, Context.BIND_AUTO_CREATE);

here mServiceConn is instance of ServiceConnection class(inbuilt) it is actually interface that we need to implement with two (1st for network connected and 2nd network not connected) method to monitor network connection state.

Server

  • It handles the request of the client and makes replica of its own which is private to client only who send request and this raplica of server runs on different thread.

Now at client side, how to access all the methods of server?

  • Server sends response with IBinder Object. So, IBinder object is our handler which accesses all the methods of Service by using (.) operator.

.

MyService myService;
public ServiceConnection myConnection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className, IBinder binder) {
        Log.d("ServiceConnection","connected");
        myService = binder;
    }
    //binder comes from server to communicate with method's of 

    public void onServiceDisconnected(ComponentName className) {
        Log.d("ServiceConnection","disconnected");
        myService = null;
    }
}

Now how to call method which lies in service

myservice.serviceMethod();

Here myService is object and serviceMethod is method in service. and by this way communication is established between client and server.

Anaconda Installed but Cannot Launch Navigator

In my case; it was available in the anaconda folder in "All App" from main menu

Bootstrap 3 .col-xs-offset-* doesn't work?

The bootstrap css used in the jsfiddle link, dont have the css for col-xs-offset-*, thats why the css are not been applied. Refer the latest bootstrap css.

Change button text from Xcode?

[myButton setTitle:@"Play" forState:UIControlStateNormal];

OWIN Startup Class Missing

I tried most of the recommended fixes here, and still couldn't avoid the error message. I finally performed a combination of a few recommended solutions:

  1. Added this entry to the top of the AppSettings section of my web.config:

    <add key="owin:AutomaticAppStartup" value="false"/>

  2. Expanded the References node of my project and deleted everything that contained the string OWIN. (I felt safe doing so since my organization is not (and won't be) an active OWIN provider in the future)

I then clicked Run and my homepage loaded right up.

Copy multiple files in Python

You can use os.listdir() to get the files in the source directory, os.path.isfile() to see if they are regular files (including symbolic links on *nix systems), and shutil.copy to do the copying.

The following code copies only the regular files from the source directory into the destination directory (I'm assuming you don't want any sub-directories copied).

import os
import shutil
src_files = os.listdir(src)
for file_name in src_files:
    full_file_name = os.path.join(src, file_name)
    if os.path.isfile(full_file_name):
        shutil.copy(full_file_name, dest)

Enable ASP.NET ASMX web service for HTTP POST / GET requests

Actually, I found a somewhat quirky way to do this. Add the protocol to your web.config, but inside a location element. Specify the webservice location as the path attribute, like so:

<location path="YourWebservice.asmx">
  <system.web>
    <webServices>
      <protocols>
        <add name="HttpGet"/>
        <add name="HttpPost"/>
      </protocols>
    </webServices>
  </system.web>
</location>

Matplotlib transparent line plots

Plain and simple:

plt.plot(x, y, 'r-', alpha=0.7)

(I know I add nothing new, but the straightforward answer should be visible).

converting string to long in python

longcan only take string convertibles which can end in a base 10 numeral. So, the decimal is causing the harm. What you can do is, float the value before calling the long. If your program is on Python 2.x where int and long difference matters, and you are sure you are not using large integers, you could have just been fine with using int to provide the key as well.

So, the answer is long(float('234.89')) or it could just be int(float('234.89')) if you are not using large integers. Also note that this difference does not arise in Python 3, because int is upgraded to long by default. All integers are long in python3 and call to covert is just int

Using subprocess to run Python script on Windows

Just found sys.executable - the full path to the current Python executable, which can be used to run the script (instead of relying on the shbang, which obviously doesn't work on Windows)

import sys
import subprocess

theproc = subprocess.Popen([sys.executable, "myscript.py"])
theproc.communicate()

How do I remove newlines from a text file?

If the data is in file.txt, then:

echo $(<file.txt) | tr -d ' '

The '$(<file.txt)' reads the file and gives the contents as a series of words which 'echo' then echoes with a space between them. The 'tr' command then deletes any spaces:

22791;14336;22821;34653;21491;25522;33238;

Save file/open file dialog box, using Swing & Netbeans GUI editor

saving in any format is very much possible. Check following- http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html

2ndly , What exactly you are expecting the save dialog to work , it works like that, Opening a doc file is very much possible- http://srikanthtechnologies.com/blog/openworddoc.html

How to read a file into vector in C++?

  //file name must be of the form filename.yourfileExtension
       std::vector<std::string> source;
bool getFileContent(std::string & fileName)
{
    if (fileName.substr(fileName.find_last_of(".") + 1) =="yourfileExtension")
    {

        // Open the File
        std::ifstream in(fileName.c_str());

        // Check if object is valid
        if (!in)
        {
            std::cerr << "Cannot open the File : " << fileName << std::endl;
            return false;
        }
        std::string str;
        // Read the next line from File untill it reaches the end.
        while (std::getline(in, str))
        {
            // Line contains string of length > 0 then save it in vector
            if (str.size() > 0)
                source.push_back(str);
        }
        /*for (size_t i = 0; i < source.size(); i++)
    {
        lexer(source[i], i);
        cout << source[i] << endl;
    }
    */
        //Close The File
        in.close();
        return true;
    }
    else
    {
        std::cerr << ":VIP doe\'s not support this file type" << std::endl;
        std::cerr << "supported extensions is filename.yourfileExtension" << endl;
    }
}

Oracle: is there a tool to trace queries, like Profiler for sql server?

Oracle, along with other databases, analyzes a given query to create an execution plan. This plan is the most efficient way of retrieving the data.

Oracle provides the 'explain plan' statement which analyzes the query but doesn't run it, instead populating a special table that you can query (the plan table).

The syntax (simple version, there are other options such as to mark the rows in the plan table with a special ID, or use a different plan table) is:

explain plan for <sql query>

The analysis of that data is left for another question, or your further research.

How to hide app title in android?

use

<activity android:name=".ActivityName" 
          android:theme="@android:style/Theme.NoTitleBar">

Node.js Error: connect ECONNREFUSED

You need to have a server running on port 8080 when you run the code above that simply returns the request back through the response. Copy the code below to a separate file (say 'server.js') and start this server using the node command (node server.js). You can then separately run your code above (node app.js) from a separate command line.

var http = require('http');

http.createServer(function(request, response){

    //The following code will print out the incoming request text
    request.pipe(response);

}).listen(8080, '127.0.0.1');

console.log('Listening on port 8080...');

JSP : JSTL's <c:out> tag

Older versions of JSP did not support the second syntax.

Google Maps Android API v2 - Interactive InfoWindow (like in original android google maps)

It is really simple.

googleMap.setInfoWindowAdapter(new InfoWindowAdapter() {

            // Use default InfoWindow frame
            @Override
            public View getInfoWindow(Marker marker) {              
                return null;
            }           

            // Defines the contents of the InfoWindow
            @Override
            public View getInfoContents(Marker marker) {

                // Getting view from the layout file info_window_layout
                View v = getLayoutInflater().inflate(R.layout.info_window_layout, null);

                // Getting reference to the TextView to set title
                TextView note = (TextView) v.findViewById(R.id.note);

                note.setText(marker.getTitle() );

                // Returning the view containing InfoWindow contents
                return v;

            }

        });

Just add above code in your class where you are using GoogleMap. R.layout.info_window_layout is our custom layout that is showing the view that will come in place of infowindow. I just added the textview here. You can add additonal view here to make it like the sample snap. My info_window_layout was

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" 
    android:orientation="vertical" 
    >

        <TextView 
        android:id="@+id/note"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

I hope it will help. We can find a working example of custom infowindow at http://wptrafficanalyzer.in/blog/customizing-infowindow-contents-in-google-map-android-api-v2-using-infowindowadapter/#comment-39731

EDITED : This code is shows how we can add custom view on infoWindow. This code did not handle the clicks on Custom View items. So it is close to answer but not exactly the answer that's why It is not accepted as answer.

Force browser to download image files on click

A more modern approach using Promise and async/await :

toDataURL(url) {
    return fetch(url).then((response) => {
            return response.blob();
        }).then(blob => {
            return URL.createObjectURL(blob);
        });
}

then

async download() {
        const a = document.createElement("a");
        a.href = await toDataURL("https://cdn1.iconfinder.com/data/icons/ninja-things-1/1772/ninja-simple-512.png");
        a.download = "myImage.png";
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
}

Find documentation here: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

JMS Topic vs Queues

A JMS topic is the type of destination in a 1-to-many model of distribution. The same published message is received by all consuming subscribers. You can also call this the 'broadcast' model. You can think of a topic as the equivalent of a Subject in an Observer design pattern for distributed computing. Some JMS providers efficiently choose to implement this as UDP instead of TCP. For topic's the message delivery is 'fire-and-forget' - if no one listens, the message just disappears. If that's not what you want, you can use 'durable subscriptions'.

A JMS queue is a 1-to-1 destination of messages. The message is received by only one of the consuming receivers (please note: consistently using subscribers for 'topic client's and receivers for queue client's avoids confusion). Messages sent to a queue are stored on disk or memory until someone picks it up or it expires. So queues (and durable subscriptions) need some active storage management, you need to think about slow consumers.

In most environments, I would argue, topics are the better choice because you can always add additional components without having to change the architecture. Added components could be monitoring, logging, analytics, etc. You never know at the beginning of the project what the requirements will be like in 1 year, 5 years, 10 years. Change is inevitable, embrace it :-)

Convert SVG to PNG in Python

I'm using Wand-py (an implementation of the Wand wrapper around ImageMagick) to import some pretty advanced SVGs and so far have seen great results! This is all the code it takes:

    with wand.image.Image( blob=svg_file.read(), format="svg" ) as image:
        png_image = image.make_blob("png")

I just discovered this today, and felt like it was worth sharing for anyone else who might straggle across this answer as it's been a while since most of these questions were answered.

NOTE: Technically in testing I discovered you don't even actually have to pass in the format parameter for ImageMagick, so with wand.image.Image( blob=svg_file.read() ) as image: was all that was really needed.

EDIT: From an attempted edit by qris, here's some helpful code that lets you use ImageMagick with an SVG that has a transparent background:

from wand.api import library
import wand.color
import wand.image

with wand.image.Image() as image:
    with wand.color.Color('transparent') as background_color:
        library.MagickSetBackgroundColor(image.wand, 
                                         background_color.resource) 
    image.read(blob=svg_file.read(), format="svg")
    png_image = image.make_blob("png32")

with open(output_filename, "wb") as out:
    out.write(png_image)

What is a MIME type?

MIME stands for Multipurpose Internet Mail Extensions. It's a way of identifying files on the Internet according to their nature and format.

For example, using the Content-type header value defined in a HTTP response, the browser can open the file with the proper extension/plugin.

Internet Media Type (also Content-type) is the same as a MIME type. MIME types were originally created for emails sent using the SMTP protocol. Nowadays, this standard is used in a lot of other protocols, hence the new naming convention "Internet Media Type".

A MIME type is a string identifier composed of two parts: a type and a subtype.

  • The "type" refers to a logical grouping of many MIME types that are closely related to each other; it's no more than a high level category.
  • "subtypes" are specific to one file type within the "type".

The x- prefix of a MIME subtype simply means that it's non-standard.
The vnd prefix means that the MIME value is vendor specific.

Source

Pie chart with jQuery

Chart.js is quite useful, supporting numerous other types of charts as well.

It can be used both with jQuery and without.

Pass a PHP variable value through an HTML form

EDIT: After your comments, I understand that you want to pass variable through your form.

You can do this using hidden field:

<input type='hidden' name='var' value='<?php echo "$var";?>'/> 

In PHP action File:

<?php 
   if(isset($_POST['var'])) $var=$_POST['var'];
?>

Or using sessions: In your first page:

 $_SESSION['var']=$var;

start_session(); should be placed at the beginning of your php page.

In PHP action File:

if(isset($_SESSION['var'])) $var=$_SESSION['var'];

First Answer:

You can also use $GLOBALS :

if (isset($_POST['save_exit']))
{

   echo $GLOBALS['var']; 

}

Check this documentation for more informations.

Timestamp with a millisecond precision: How to save them in MySQL

You need to be at MySQL version 5.6.4 or later to declare columns with fractional-second time datatypes. Not sure you have the right version? Try SELECT NOW(3). If you get an error, you don't have the right version.

For example, DATETIME(3) will give you millisecond resolution in your timestamps, and TIMESTAMP(6) will give you microsecond resolution on a *nix-style timestamp.

Read this: https://dev.mysql.com/doc/refman/8.0/en/fractional-seconds.html

NOW(3) will give you the present time from your MySQL server's operating system with millisecond precision.

If you have a number of milliseconds since the Unix epoch, try this to get a DATETIME(3) value

FROM_UNIXTIME(ms * 0.001)

Javascript timestamps, for example, are represented in milliseconds since the Unix epoch.

(Notice that MySQL internal fractional arithmetic, like * 0.001, is always handled as IEEE754 double precision floating point, so it's unlikely you'll lose precision before the Sun becomes a white dwarf star.)

If you're using an older version of MySQL and you need subsecond time precision, your best path is to upgrade. Anything else will force you into doing messy workarounds.

If, for some reason you can't upgrade, you could consider using BIGINT or DOUBLE columns to store Javascript timestamps as if they were numbers. FROM_UNIXTIME(col * 0.001) will still work OK. If you need the current time to store in such a column, you could use UNIX_TIMESTAMP() * 1000

How do I update a formula with Homebrew?

You can't use brew install to upgrade an installed formula. If you want upgrade all of outdated formulas, you can use the command below.

brew outdated | xargs brew upgrade

Generate MD5 hash string with T-SQL

Use HashBytes

SELECT HashBytes('MD5', '[email protected]')

That will give you 0xF53BD08920E5D25809DF2563EF9C52B6

-

SELECT CONVERT(NVARCHAR(32),HashBytes('MD5', '[email protected]'),2)

That will give you F53BD08920E5D25809DF2563EF9C52B6

What is the JavaScript version of sleep()?

In case you really need a sleep() just to test something. But be aware that it'll crash the browser most of the times while debuggin - probably that's why you need it anyway. In production mode I'll comment out this function.

function pauseBrowser(millis) {
    var date = Date.now();
    var curDate = null;
    do {
        curDate = Date.now();
    } while (curDate-date < millis);
}

Don't use new Date() in the loop, unless you want to waste memory, processing power, battery and possibly the lifetime of your device.

Check whether a cell contains a substring

This is an old question but a solution for those using Excel 2016 or newer is you can remove the need for nested if structures by using the new IFS( condition1, return1 [,condition2, return2] ...) conditional.

I have formatted it to make it visually clearer on how to use it for the case of this question:

=IFS(
ISERROR(SEARCH("String1",A1))=FALSE,"Something1",
ISERROR(SEARCH("String2",A1))=FALSE,"Something2",
ISERROR(SEARCH("String3",A1))=FALSE,"Something3"
)

Since SEARCH returns an error if a string is not found I wrapped it with an ISERROR(...)=FALSE to check for truth and then return the value wanted. It would be great if SEARCH returned 0 instead of an error for readability, but thats just how it works unfortunately.

Another note of importance is that IFS will return the match that it finds first and thus ordering is important. For example if my strings were Surf, Surfing, Surfs as String1,String2,String3 above and my cells string was Surfing it would match on the first term instead of the second because of the substring being Surf. Thus common denominators need to be last in the list. My IFS would need to be ordered Surfing, Surfs, Surf to work correctly (swapping Surfing and Surfs would also work in this simple example), but Surf would need to be last.

is the + operator less performant than StringBuffer.append()

Yes it's true but you shouldn't care. Go with the one that's easier to read. If you have to benchmark your app, then focus on the bottlenecks.

I would guess that string concatenation isn't going to be your bottleneck.

Jenkins, specifying JAVA_HOME

Upgrading from Ubuntu 10.0.4 to 12.0.4 we got wrong footed. We had a JDK installation configured (auto-configured?) pointing to /usr/lib/jvm/java-6-openjdk this no longer contained a JDK, Changing to /usr/lib/jvm/default-java fixed, and should make for a seamless java-7 upgrade.

So in answer to the question: do not specify JAVA_HOME on Ubuntu.

Mutex example / tutorial?

SEMAPHORE EXAMPLE ::

sem_t m;
sem_init(&m, 0, 0); // initialize semaphore to 0

sem_wait(&m);
// critical section here
sem_post(&m);

Reference : http://pages.cs.wisc.edu/~remzi/Classes/537/Fall2008/Notes/threads-semaphores.txt

How to make return key on iPhone make keyboard disappear?

Add this instead of the pre-defined class

class ViewController: UIViewController, UITextFieldDelegate {

To remove keyboard when clicked outside the keyboard

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        self.view.endEditing(true)
    }

and to remove keyboard when pressed enter

add this line in viewDidLoad()

inputField is the name of the textField used.

self.inputField.delegate = self

and add this function

func textFieldShouldReturn(textField: UITextField) -> Bool {        
        textField.resignFirstResponder()        
        return true        
    }

JavaScript - cannot set property of undefined

d = {} is an empty object right now.

And d[a] is also an empty object.

It does not have any key values. So you should initialize the key values to this.

d[a] = {
greetings:'',
data:''
}

How many bytes does one Unicode character take?

For UTF-16, the character needs four bytes (two code units) if it starts with 0xD800 or greater; such a character is called a "surrogate pair." More specifically, a surrogate pair has the form:

[0xD800 - 0xDBFF]  [0xDC00 - 0xDFF]

where [...] indicates a two-byte code unit with the given range. Anything <= 0xD7FF is one code unit (two bytes). Anything >= 0xE000 is invalid (except BOM markers, arguably).

See http://unicodebook.readthedocs.io/unicode_encodings.html, section 7.5.

How to update value of a key in dictionary in c#?

Just use the indexer and update directly:

dictionary["cat"] = 3

Convert output of MySQL query to utf8

Addition:

When using the MySQL client library, then you should prevent a conversion back to your connection's default charset. (see mysql_set_character_set()[1])

In this case, use an additional cast to binary:

SELECT column1, CAST(CONVERT(column2 USING utf8) AS binary)
FROM my_table
WHERE my_condition;

Otherwise, the SELECT statement converts to utf-8, but your client library converts it back to a (potentially different) default connection charset.

Angular 2 beta.17: Property 'map' does not exist on type 'Observable<Response>'

If you happen to see this error in VS2015, there's a github issue & workaround mentioned here:

https://github.com/Microsoft/TypeScript/issues/8518#issuecomment-229506507

This did help me resolve the property map does not exist on observable issue. Besides, make sure you have typescript version above 1.8.2

Java Constructor Inheritance

Because constructors are an implementation detail - they're not something that a user of an interface/superclass can actually invoke at all. By the time they get an instance, it's already been constructed; and vice-versa, at the time you construct an object there's by definition no variable it's currently assigned to.

Think about what it would mean to force all subclasses to have an inherited constructor. I argue it's clearer to pass the variables in directly than for the class to "magically" have a constructor with a certain number of arguments just because it's parent does.

Convert list to array in Java

This (Ondrej's answer):

Foo[] array = list.toArray(new Foo[0]);

Is the most common idiom I see. Those who are suggesting that you use the actual list size instead of "0" are misunderstanding what's happening here. The toArray call does not care about the size or contents of the given array - it only needs its type. It would have been better if it took an actual Type in which case "Foo.class" would have been a lot clearer. Yes, this idiom generates a dummy object, but including the list size just means that you generate a larger dummy object. Again, the object is not used in any way; it's only the type that's needed.

DLL and LIB files - what and why?

One important reason for creating a DLL/LIB rather than just compiling the code into an executable is reuse and relocation. The average Java or .NET application (for example) will most likely use several 3rd party (or framework) libraries. It is much easier and faster to just compile against a pre-built library, rather than having to compile all of the 3rd party code into your application. Compiling your code into libraries also encourages good design practices, e.g. designing your classes to be used in different types of applications.

Calculate average in java

 System.out.println(result/count) 

you can't do this because result/count is not a String type, and System.out.println() only takes a String parameter. perhaps try:

double avg = (double)result / (double)args.length

How do I test if a variable is a number in Bash?

Below is a Script written by me and used for a script integration with Nagios and it is working properly till now

#!/bin/bash
# Script to test variable is numeric or not
# Shirish Shukla
# Pass arg1 as number
a1=$1
a=$(echo $a1|awk '{if($1 > 0) print $1; else print $1"*-1"}')
b=$(echo "scale=2;$a/$a + 1" | bc -l 2>/dev/null)
if [[ $b > 1 ]]
then
    echo "$1 is Numeric"
else
    echo "$1 is Non Numeric"
fi

EG:

# sh isnumsks.sh   "-22.22"
-22.22 is Numeric

# sh isnumsks.sh   "22.22"
22.22 is Numeric

# sh isnumsks.sh   "shirish22.22"
shirish22.22 is Non  Numeric

Difference between "Complete binary tree", "strict binary tree","full binary Tree"?

In my limited experience with binary tree, I think:

  1. Strictly Binary Tree:Every node except the leaf nodes have two children or only have a root node.
  2. Full Binary Tree: A binary tree of H strictly(or exactly) containing 2^(H+1) -1 nodes , it's clear that which every level has the most nodes. Or in short a strict binary tree where all leaf nodes are at same level.
  3. Complete Binary Tree: It is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible.

Loop through a date range with JavaScript

Here simple working code, worked for me

_x000D_
_x000D_
var from = new Date(2012,0,1);_x000D_
var to = new Date(2012,1,20);_x000D_
    _x000D_
// loop for every day_x000D_
for (var day = from; day <= to; day.setDate(day.getDate() + 1)) {_x000D_
      _x000D_
   // your day is here_x000D_
_x000D_
}
_x000D_
_x000D_
_x000D_

Display Records From MySQL Database using JTable in Java

Below is a class which will accomplish the very basics of what you want to do when reading data from a MySQL database into a JTable in Java.

import java.awt.*;
import java.sql.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;

public class TableFromMySqlDatabase extends JFrame
{
    public TableFromMySqlDatabase()
    {
        ArrayList columnNames = new ArrayList();
        ArrayList data = new ArrayList();

        //  Connect to an MySQL Database, run query, get result set
        String url = "jdbc:mysql://localhost:3306/yourdb";
        String userid = "root";
        String password = "sesame";
        String sql = "SELECT * FROM animals";

        // Java SE 7 has try-with-resources
        // This will ensure that the sql objects are closed when the program 
        // is finished with them
        try (Connection connection = DriverManager.getConnection( url, userid, password );
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery( sql ))
        {
            ResultSetMetaData md = rs.getMetaData();
            int columns = md.getColumnCount();

            //  Get column names
            for (int i = 1; i <= columns; i++)
            {
                columnNames.add( md.getColumnName(i) );
            }

            //  Get row data
            while (rs.next())
            {
                ArrayList row = new ArrayList(columns);

                for (int i = 1; i <= columns; i++)
                {
                    row.add( rs.getObject(i) );
                }

                data.add( row );
            }
        }
        catch (SQLException e)
        {
            System.out.println( e.getMessage() );
        }

        // Create Vectors and copy over elements from ArrayLists to them
        // Vector is deprecated but I am using them in this example to keep 
        // things simple - the best practice would be to create a custom defined
        // class which inherits from the AbstractTableModel class
        Vector columnNamesVector = new Vector();
        Vector dataVector = new Vector();

        for (int i = 0; i < data.size(); i++)
        {
            ArrayList subArray = (ArrayList)data.get(i);
            Vector subVector = new Vector();
            for (int j = 0; j < subArray.size(); j++)
            {
                subVector.add(subArray.get(j));
            }
            dataVector.add(subVector);
        }

        for (int i = 0; i < columnNames.size(); i++ )
            columnNamesVector.add(columnNames.get(i));

        //  Create table with database data    
        JTable table = new JTable(dataVector, columnNamesVector)
        {
            public Class getColumnClass(int column)
            {
                for (int row = 0; row < getRowCount(); row++)
                {
                    Object o = getValueAt(row, column);

                    if (o != null)
                    {
                        return o.getClass();
                    }
                }

                return Object.class;
            }
        };

        JScrollPane scrollPane = new JScrollPane( table );
        getContentPane().add( scrollPane );

        JPanel buttonPanel = new JPanel();
        getContentPane().add( buttonPanel, BorderLayout.SOUTH );
    }

    public static void main(String[] args)
    {
        TableFromMySqlDatabase frame = new TableFromMySqlDatabase();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setVisible(true);
    }
}

In the NetBeans IDE which you are using - you will need to add the MySQL JDBC Driver in Project Properties as I display here:

enter image description here

Otherwise the code will throw an SQLException stating that the driver cannot be found.

Now in my example, yourdb is the name of the database and animals is the name of the table that I am performing a query against.

Here is what will be output:

enter image description here

Parting note:

You stated that you were a novice and needed some help understanding some of the basic classes and concepts of Java. I will list a few here, but remember you can always browse the docs on Oracle's site.

How to split the screen with two equal LinearLayouts?

Use the layout_weight attribute. The layout will roughly look like this:

<LinearLayout android:orientation="horizontal"
    android:layout_height="fill_parent" 
    android:layout_width="fill_parent">

    <LinearLayout 
        android:layout_weight="1" 
        android:layout_height="fill_parent" 
        android:layout_width="0dp"/>

    <LinearLayout 
        android:layout_weight="1" 
        android:layout_height="fill_parent" 
        android:layout_width="0dp"/>

</LinearLayout>

How to prevent default event handling in an onclick method?

Just place "javascript:void(0)", in place of "#" in href tag

<a href="javascript:void(0);" onclick="callmymethod(24)">Call</a>

Is there a naming convention for MySQL?

I would say that first and foremost: be consistent.

I reckon you are almost there with the conventions that you have outlined in your question. A couple of comments though:

Points 1 and 2 are good I reckon.

Point 3 - sadly this is not always possible. Think about how you would cope with a single table foo_bar that has columns foo_id and another_foo_id both of which reference the foo table foo_id column. You might want to consider how to deal with this. This is a bit of a corner case though!

Point 4 - Similar to Point 3. You may want to introduce a number at the end of the foreign key name to cater for having more than one referencing column.

Point 5 - I would avoid this. It provides you with little and will become a headache when you want to add or remove columns from a table at a later date.

Some other points are:

Index Naming Conventions

You may wish to introduce a naming convention for indexes - this will be a great help for any database metadata work that you might want to carry out. For example you might just want to call an index foo_bar_idx1 or foo_idx1 - totally up to you but worth considering.

Singular vs Plural Column Names

It might be a good idea to address the thorny issue of plural vs single in your column names as well as your table name(s). This subject often causes big debates in the DB community. I would stick with singular forms for both table names and columns. There. I've said it.

The main thing here is of course consistency!

mySQL select IN range

To select data in numerical range you can use BETWEEN which is inclusive.

SELECT JOB FROM MYTABLE WHERE ID BETWEEN 10 AND 15;

How do I list the symbols in a .so file

For shared libraries libNAME.so the -D switch was necessary to see symbols in my Linux

nm -D libNAME.so

and for static library as reported by others

nm -g libNAME.a

Convert string date to timestamp in Python

To convert the string into a date object:

from datetime import date, datetime

date_string = "01/12/2011"
date_object = date(*map(int, reversed(date_string.split("/"))))
assert date_object == datetime.strptime(date_string, "%d/%m/%Y").date()

The way to convert the date object into POSIX timestamp depends on timezone. From Converting datetime.date to UTC timestamp in Python:

  • date object represents midnight in UTC

    import calendar
    
    timestamp1 = calendar.timegm(utc_date.timetuple())
    timestamp2 = (utc_date.toordinal() - date(1970, 1, 1).toordinal()) * 24*60*60
    assert timestamp1 == timestamp2
    
  • date object represents midnight in local time

    import time
    
    timestamp3 = time.mktime(local_date.timetuple())
    assert timestamp3 != timestamp1 or (time.gmtime() == time.localtime())
    

The timestamps are different unless midnight in UTC and in local time is the same time instance.

What's the difference between %s and %d in Python string formatting?

These are all informative answers, but none are quite getting at the core of what the difference is between %s and %d.

%s tells the formatter to call the str() function on the argument and since we are coercing to a string by definition, %s is essentially just performing str(arg).

%d on the other hand, is calling int() on the argument before calling str(), like str(int(arg)), This will cause int coercion as well as str coercion.

For example, I can convert a hex value to decimal,

>>> '%d' % 0x15
'21'

or truncate a float.

>>> '%d' % 34.5
'34'

But the operation will raise an exception if the argument isn't a number.

>>> '%d' % 'thirteen'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: %d format: a number is required, not str

So if the intent is just to call str(arg), then %s is sufficient, but if you need extra formatting (like formatting float decimal places) or other coercion, then the other format symbols are needed.

With the f-string notation, when you leave the formatter out, the default is str.

>>> a = 1
>>> f'{a}'
'1'
>>> f'{a:d}'
'1'
>>> a = '1'
>>> f'{a:d}'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Unknown format code 'd' for object of type 'str'

The same is true with string.format; the default is str.

>>> a = 1
>>> '{}'.format(a)
'1'
>>> '{!s}'.format(a)
'1'
>>> '{:d}'.format(a)
'1'

How to set selected index JComboBox by value

for example

enter image description here

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

public class ComboboxExample {

    private JFrame frame = new JFrame("Test");
    private JComboBox comboBox = new JComboBox();

    public ComboboxExample() {
        createGui();
    }

    private void createGui() {
        comboBox.addItem("One");
        comboBox.addItem("Two");
        comboBox.addItem("Three");
        JButton button = new JButton("Show Selected");
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(frame, "Selected item: " + comboBox.getSelectedItem());
                javax.swing.SwingUtilities.invokeLater(new Runnable() {

                    @Override
                    public void run() {
                        comboBox.requestFocus();
                        comboBox.requestFocusInWindow();
                    }
                });
            }
        });
        JButton button1 = new JButton("Append Items");
        button1.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                appendCbItem();
            }
        });
        JButton button2 = new JButton("Reduce Items");
        button2.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                reduceCbItem();
            }
        });
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new GridLayout(4, 1));
        frame.add(comboBox);
        frame.add(button);
        frame.add(button1);
        frame.add(button2);
        frame.setLocation(200, 200);
        frame.pack();
        frame.setVisible(true);
        selectFirstItem();
    }

    public void appendCbItem() {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                comboBox.addItem("Four");
                comboBox.addItem("Five");
                comboBox.addItem("Six");
                comboBox.setSelectedItem("Six");
                requestCbFocus();
            }
        });
    }

    public void reduceCbItem() {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                comboBox.removeItem("Four");
                comboBox.removeItem("Five");
                comboBox.removeItem("Six");
                selectFirstItem();
            }
        });
    }

    public void selectFirstItem() {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                comboBox.setSelectedIndex(0);
                requestCbFocus();
            }
        });
    }

    public void requestCbFocus() {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                comboBox.requestFocus();
                comboBox.requestFocusInWindow();
            }
        });
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                ComboboxExample comboboxExample = new ComboboxExample();
            }
        });
    }
}

Can you have if-then-else logic in SQL?

Instead of using EXISTS and COUNT just use @@ROWCOUNT:

select product, price from table1 where project = 1

IF @@ROWCOUNT = 0
BEGIN
    select product, price from table1 where customer = 2

    IF @@ROWCOUNT = 0
    select product, price from table1 where company = 3
END

Scroll RecyclerView to show selected item on top

I don't know why I didn't find the best answer but its really simple.

recyclerView.smoothScrollToPosition(position);

No errors

Creates Animations

How do I add an image to a JButton

It looks like a location problem because that code is perfectly fine for adding the icon.

Since I don't know your folder structure, I suggest adding a simple check:

File imageCheck = new File("water.bmp");

if(imageCheck.exists()) 
    System.out.println("Image file found!")
else 
    System.out.println("Image file not found!");

This way if you ever get your path name wrong it will tell you instead of displaying nothing. Exception should be thrown if file would not exist, tho.

Trying to get property of non-object in

Check the manual for mysql_fetch_object(). It returns an object, not an array of objects.

I'm guessing you want something like this

$results = mysql_query("SELECT * FROM sidemenu WHERE `menu_id`='".$menu."' ORDER BY `id` ASC LIMIT 1", $con);

$sidemenus = array();
while ($sidemenu = mysql_fetch_object($results)) {
    $sidemenus[] = $sidemenu;
}

Might I suggest you have a look at PDO. PDOStatement::fetchAll(PDO::FETCH_OBJ) does what you assumed mysql_fetch_object() to do

Attributes / member variables in interfaces?

In Java you can't. Interface has to do with methods and signature, it does not have to do with the internal state of an object -- that is an implementation question. And this makes sense too -- I mean, simply because certain attributes exist, it does not mean that they have to be used by the implementing class. getHeight could actually point to the width variable (assuming that the implementer is a sadist).

(As a note -- this is not true of all languages, ActionScript allows for declaration of pseudo attributes, and I believe C# does too)

In Mongoose, how do I sort by date? (node.js)

ES6 solution with Koa.

  async recent() {
    data = await ReadSchema.find({}, { sort: 'created_at' });
    ctx.body = data;
  }

Git "error: The branch 'x' is not fully merged"

to see changes that are not merged, I did this:

git checkout experiment
git merge --no-commit master

git diff --cached

Note: This shows changes in master that are not in experiment.

Don't forget to:

git merge --abort

When you're done lookin.

Get folder name of the file in Python

I'm using 2 ways to get the same response: one of them use:

   os.path.basename(filename)

due to errors that I found in my script I changed to:

Path = filename[:(len(filename)-len(os.path.basename(filename)))]

it's a workaround due to python's '\\'

DataTable: How to get item value with row name and column name? (VB)

For i = 0 To dt.Rows.Count - 1

    ListV.Items.Add(dt.Rows(i).Item("STU_NUMBER").ToString)
    ListV.Items(i).SubItems.Add(dt.Rows(i).Item("FNAME").ToString & " " & dt.Rows(i).Item("MI").ToString & ". " & dt.Rows(i).Item("LNAME").ToString)
    ListV.Items(i).SubItems.Add(dt.Rows(i).Item("SEX").ToString)

Next

How to sort dates from Oldest to Newest in Excel?

Saw this ages after posting, but if anyone has the same problem I had, my dates were all the format DD.MM.YYYY (SPSS output) even formatting them to date in Excel still only let me sort from A-Z so basically the 1st-31st irrelevant of month.

Doing a find and replace of all "." to "/" fixed this so that they are now in the format of DD/MM/YYYY. Not sure why it didn't work in the other format when the cell type counted as date.

How can I wrap text in a label using WPF?

I used this to retrieve data from MySql Database:

AccessText a = new AccessText();    
a.Text=reader[1].ToString();       // MySql reader
a.Width = 70;
a.TextWrapping = TextWrapping.WrapWithOverflow;
labels[i].Content = a;

How to process images of a video, frame by frame, in video streaming using OpenCV and Python

In openCV's documentation there is an example for getting video frame by frame. It is written in c++ but it is very easy to port the example to python - you can search for each fumction documentation to see how to call them in python.

#include "opencv2/opencv.hpp"

using namespace cv;

int main(int, char**)
{
    VideoCapture cap(0); // open the default camera
    if(!cap.isOpened())  // check if we succeeded
        return -1;

    Mat edges;
    namedWindow("edges",1);
    for(;;)
    {
        Mat frame;
        cap >> frame; // get a new frame from camera
        cvtColor(frame, edges, CV_BGR2GRAY);
        GaussianBlur(edges, edges, Size(7,7), 1.5, 1.5);
        Canny(edges, edges, 0, 30, 3);
        imshow("edges", edges);
        if(waitKey(30) >= 0) break;
    }
    // the camera will be deinitialized automatically in VideoCapture destructor
    return 0;
}

MessageBox Buttons?

This way to check the condition while pressing 'YES' or 'NO' buttons in MessageBox window.

DialogResult d = MessageBox.Show("Are you sure ?", "Remove Panel", MessageBoxButtons.YesNo);
            if (d == DialogResult.Yes)
            {
                //Contents
            }
            else if (d == DialogResult.No)
            {
                //Contents
            }

Load local JSON file into variable

There are two possible problems:

  1. AJAX is asynchronous, so json will be undefined when you return from the outer function. When the file has been loaded, the callback function will set json to some value but at that time, nobody cares anymore.

    I see that you tried to fix this with 'async': false. To check whether this works, add this line to the code and check your browser's console:

    console.log(['json', json]);
    
  2. The path might be wrong. Use the same path that you used to load your script in the HTML document. So if your script is js/script.js, use js/content.json

    Some browsers can show you which URLs they tried to access and how that went (success/error codes, HTML headers, etc). Check your browser's development tools to see what happens.

How do you represent a JSON array of strings?

I'll elaborate a bit more on ChrisR awesome answer and bring images from his awesome reference.

A valid JSON always starts with either curly braces { or square brackets [, nothing else.

{ will start an object:

left brace followed by a key string (a name that can't be repeated, in quotes), colon and a value (valid types shown below), followed by an optional comma to add more pairs of string and value at will and finished with a right brace

{ "key": value, "another key": value }

Hint: although javascript accepts single quotes ', JSON only takes double ones ".

[ will start an array:

left bracket followed by value, optional comma to add more value at will and finished with a right bracket

[value, value]

Hint: spaces among elements are always ignored by any JSON parser.

And value is an object, array, string, number, bool or null:

Image showing the 6 types a JSON value can be: string, number, JSON object, Array/list, boolean, and null

So yeah, ["a", "b"] is a perfectly valid JSON, like you could try on the link Manish pointed.

Here are a few extra valid JSON examples, one per block:

{}

[0]

{"__comment": "json doesn't accept comments and you should not be commenting even in this way", "avoid!": "also, never add more than one key per line, like this"}

[{   "why":null} ]

{
  "not true": [0, false],
  "true": true,
  "not null": [0, 1, false, true, {
    "obj": null
  }, "a string"]
}

How to get the size of a file in MB (Megabytes)?

     String FILE_NAME = "C:\\Ajay\\TEST\\data_996KB.json";
     File file = new File(FILE_NAME);

    if((file.length()) <= (1048576)) {      
        System.out.println("file size is less than 1 mb");
        }else {
            System.out.println("file size is More  than 1 mb");             
        }

Note: 1048576= (1024*1024)=1MB output : file size is less than 1 mb

How to Join to first row

SELECT   Orders.OrderNumber, LineItems.Quantity, LineItems.Description
FROM     Orders
JOIN     LineItems
ON       LineItems.LineItemGUID =
         (
         SELECT  TOP 1 LineItemGUID 
         FROM    LineItems
         WHERE   OrderID = Orders.OrderID
         )

In SQL Server 2005 and above, you could just replace INNER JOIN with CROSS APPLY:

SELECT  Orders.OrderNumber, LineItems2.Quantity, LineItems2.Description
FROM    Orders
CROSS APPLY
        (
        SELECT  TOP 1 LineItems.Quantity, LineItems.Description
        FROM    LineItems
        WHERE   LineItems.OrderID = Orders.OrderID
        ) LineItems2

Please note that TOP 1 without ORDER BY is not deterministic: this query you will get you one line item per order, but it is not defined which one will it be.

Multiple invocations of the query can give you different line items for the same order, even if the underlying did not change.

If you want deterministic order, you should add an ORDER BY clause to the innermost query.

Example sqlfiddle

What does the line "#!/bin/sh" mean in a UNIX shell script?

It's called a shebang, and tells the parent shell which interpreter should be used to execute the script.

#!/bin/sh <--------- bourne shell compatible script
#!/usr/bin/perl  <-- perl script
#!/usr/bin/php  <--- php script
#!/bin/false <------ do-nothing script, because false returns immediately anyways.

Most scripting languages tend to interpret a line starting with # as comment and will ignore the following !/usr/bin/whatever portion, which might otherwise cause a syntax error in the interpreted language.

Stop jQuery .load response from being cached

You have to use a more complex function like $.ajax() if you want to control caching on a per-request basis. Or, if you just want to turn it off for everything, put this at the top of your script:

$.ajaxSetup ({
    // Disable caching of AJAX responses
    cache: false
});

How to add google-play-services.jar project dependency so my project will run and present map

Be Careful, Follow these steps and save your time

  1. Right Click on your Project Explorer.

  2. Select New-> Project -> Android Application Project from Existing Code

  3. Browse upto this path only - "C:\Users**your path**\Local\Android\android-sdk\extras\google\google_play_services"

  4. Be careful brose only upto - google_play_services and not upto google_play_services_lib

  5. And this way you are able to import the google play service lib.

Let me know if you have any queries regarding the same.

Thanks

How to use shell commands in Makefile

Also, in addition to torek's answer: one thing that stands out is that you're using a lazily-evaluated macro assignment.

If you're on GNU Make, use the := assignment instead of =. This assignment causes the right hand side to be expanded immediately, and stored in the left hand variable.

FILES := $(shell ...)  # expand now; FILES is now the result of $(shell ...)

FILES = $(shell ...)   # expand later: FILES holds the syntax $(shell ...)

If you use the = assignment, it means that every single occurrence of $(FILES) will be expanding the $(shell ...) syntax and thus invoking the shell command. This will make your make job run slower, or even have some surprising consequences.

Parsing JSON Array within JSON Object

mainJSON.getJSONArray("source") returns a JSONArray, hence you can remove the new JSONArray.

The JSONArray contructor with an object parameter expects it to be a Collection or Array (not JSONArray)

Try this:

JSONArray jsonMainArr = mainJSON.getJSONArray("source"); 

How can I remove a substring from a given String?

private static void replaceChar() {
    String str = "hello world";
    final String[] res = Arrays.stream(str.split(""))
            .filter(s -> !s.equalsIgnoreCase("o"))
            .toArray(String[]::new);
    System.out.println(String.join("", res));
}

In case you have some complicated logic to filter the char, just another way instead of replace().

How to write header row with csv.DictWriter?

Edit:
In 2.7 / 3.2 there is a new writeheader() method. Also, John Machin's answer provides a simpler method of writing the header row.
Simple example of using the writeheader() method now available in 2.7 / 3.2:

from collections import OrderedDict
ordered_fieldnames = OrderedDict([('field1',None),('field2',None)])
with open(outfile,'wb') as fou:
    dw = csv.DictWriter(fou, delimiter='\t', fieldnames=ordered_fieldnames)
    dw.writeheader()
    # continue on to write data

Instantiating DictWriter requires a fieldnames argument.
From the documentation:

The fieldnames parameter identifies the order in which values in the dictionary passed to the writerow() method are written to the csvfile.

Put another way: The Fieldnames argument is required because Python dicts are inherently unordered.
Below is an example of how you'd write the header and data to a file.
Note: with statement was added in 2.6. If using 2.5: from __future__ import with_statement

with open(infile,'rb') as fin:
    dr = csv.DictReader(fin, delimiter='\t')

# dr.fieldnames contains values from first row of `f`.
with open(outfile,'wb') as fou:
    dw = csv.DictWriter(fou, delimiter='\t', fieldnames=dr.fieldnames)
    headers = {} 
    for n in dw.fieldnames:
        headers[n] = n
    dw.writerow(headers)
    for row in dr:
        dw.writerow(row)

As @FM mentions in a comment, you can condense header-writing to a one-liner, e.g.:

with open(outfile,'wb') as fou:
    dw = csv.DictWriter(fou, delimiter='\t', fieldnames=dr.fieldnames)
    dw.writerow(dict((fn,fn) for fn in dr.fieldnames))
    for row in dr:
        dw.writerow(row)

Find out free space on tablespace

I use this query

column "Tablespace" format a13
column "Used MB"    format 99,999,999
column "Free MB"    format 99,999,999
column "Total MB"   format 99,999,999
select
   fs.tablespace_name                          "Tablespace",
   (df.totalspace - fs.freespace)              "Used MB",
   fs.freespace                                "Free MB",
   df.totalspace                               "Total MB",
   round(100 * (fs.freespace / df.totalspace)) "Pct. Free"
from
   (select
      tablespace_name,
      round(sum(bytes) / 1048576) TotalSpace
   from
      dba_data_files
   group by
      tablespace_name
   ) df,
   (select
      tablespace_name,
      round(sum(bytes) / 1048576) FreeSpace
   from
      dba_free_space
   group by
      tablespace_name
   ) fs
where
   df.tablespace_name = fs.tablespace_name;

UnicodeEncodeError: 'ascii' codec can't encode character u'\xef' in position 0: ordinal not in range(128)

The problem according to your traceback is the print statement on line 136 of parseXML.py. Unfortunately you didn't see fit to post that part of your code, but I'm going to guess it is just there for debugging. If you change it to:

print repr(ch)

then you should at least see what you are trying to print.

Running an outside program (executable) in Python?

Your usage is correct. I bet that your external program, flow.exe, needs to be executed in its directory, because it accesses some external files stored there.

So you might try:

import sys, string, os, arcgisscripting
os.chdir('c:\\documents and settings\\flow_model')
os.system('"C:\\Documents and Settings\\flow_model\\flow.exe"')

(Beware of the double quotes inside the single quotes...)

Delete all data rows from an Excel table (apart from the first)

I'm simply using this:

On Error Resume Next
Worksheets("Sheet1").ListObjects("Table1").DataBodyRange.Rows.Delete

The first line stays in all cases (it is cleared, of course).

Dynamic LINQ OrderBy on IEnumerable<T> / IQueryable<T>

I've stumble this question looking for Linq multiple orderby clauses and maybe this was what the author was looking for

Here's how to do that:

var query = pets.OrderBy(pet => pet.Name).ThenByDescending(pet => pet.Age);    

Detect backspace and del on "input" event?

It's an old question, but if you wanted to catch a backspace event on input, and not keydown, keypress, or keyup—as I've noticed any one of these break certain functions I've written and cause awkward delays with automated text formatting—you can catch a backspace using inputType:

document.getElementsByTagName('input')[0].addEventListener('input', function(e) {
    if (e.inputType == "deleteContentBackward") {
        // your code here
    }
});

How can I combine two HashMap objects containing the same types?

One-liner using Java 8 Stream API:

map3 = Stream.of(map1, map2).flatMap(m -> m.entrySet().stream())
       .collect(Collectors.toMap(Entry::getKey, Entry::getValue))

Among the benefits of this method is ability to pass a merge function, which will deal with values that have the same key, for example:

map3 = Stream.of(map1, map2).flatMap(m -> m.entrySet().stream())
       .collect(Collectors.toMap(Entry::getKey, Entry::getValue, Math::max))

How do I get NuGet to install/update all the packages in the packages.config?

If you Nuget 2.8 install, check the checkbox

Tools >> Nuget Manager >> Package Manager Settings >> Automatically check for missing packages during build

in Visual Studio. If it is checked, then simply rebuild the project will restore all your reference libraries.

How to set the font style to bold, italic and underlined in an Android TextView?

You can achieve it easily by using Kotlin's buildSpannedString{} under its core-ktx dependency.

val formattedString = buildSpannedString {
    append("Regular")
    bold { append("Bold") }
    italic { append("Italic") }
    underline { append("Underline") }
    bold { italic {append("Bold Italic")} }
}

textView.text = formattedString

What's a good way to extend Error in JavaScript?

The only standard field Error object has is the message property. (See MDN, or EcmaScript Language Specification, section 15.11) Everything else is platform specific.

Mosts environments set the stack property, but fileName and lineNumber are practically useless to be used in inheritance.

So, the minimalistic approach is:

function MyError(message) {
    this.name = 'MyError';
    this.message = message;
    this.stack = (new Error()).stack;
}
MyError.prototype = new Error;  // <-- remove this if you do not 
                                //     want MyError to be instanceof Error

You could sniff the stack, unshift unwanted elements from it and extract information like fileName and lineNumber, but doing so requires information about the platform JavaScript is currently running upon. Most cases that is unnecessary -- and you can do it in post-mortem if you really want.

Safari is a notable exception. There is no stack property, but the throw keyword sets sourceURL and line properties of the object that is being thrown. Those things are guaranteed to be correct.

Test cases I used can be found here: JavaScript self-made Error object comparison.

How to read until end of file (EOF) using BufferedReader in Java?

You are consuming a line at, which is discarded

while((str=input.readLine())!=null && str.length()!=0)

and reading a bigint at

BigInteger n = new BigInteger(input.readLine());

so try getting the bigint from string which is read as

BigInteger n = new BigInteger(str);

   Constructor used: BigInteger(String val)

Aslo change while((str=input.readLine())!=null && str.length()!=0) to

while((str=input.readLine())!=null)

see related post string to bigint

readLine()
Returns:
    A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached 

see javadocs

List comprehension with if statement

You got the order wrong. The if should be after the for (unless it is in an if-else ternary operator)

[y for y in a if y not in b]

This would work however:

[y if y not in b else other_value for y in a]

Change icon on click (toggle)

Here is a very easy way of doing that

 $(function () {
    $(".glyphicon").unbind('click');
    $(".glyphicon").click(function (e) {
        $(this).toggleClass("glyphicon glyphicon-chevron-up glyphicon glyphicon-chevron-down");
});

Hope this helps :D

select certain columns of a data table

You can create a method that looks like this:

  public static DataTable SelectedColumns(DataTable RecordDT_, string col1, string col2)
    {
        DataTable TempTable = RecordDT_;

        System.Data.DataView view = new System.Data.DataView(TempTable);
        System.Data.DataTable selected = view.ToTable("Selected", false, col1, col2);
        return selected;
    }

You can return as many columns as possible.. just add the columns as call parameters as shown below:

public DataTable SelectedColumns(DataTable RecordDT_, string col1, string col2,string col3,...)

and also add the parameters to this line:

System.Data.DataTable selected = view.ToTable("Selected", false,col1, col2,col3,...);

Then simply implement the function as:

 DataTable myselectedColumnTable=SelectedColumns(OriginalTable,"Col1","Col2",...);

Thanks...

Use Invoke-WebRequest with a username and password for basic authentication on the GitHub API

Use this:

$root = 'REST_SERVICE_URL'
$user = "user"
$pass= "password"
$secpasswd = ConvertTo-SecureString $pass -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($user, $secpasswd)

$result = Invoke-RestMethod $root -Credential $credential

How does Python's super() work with multiple inheritance?

Maybe there's still something that can be added, a small example with Django rest_framework, and decorators. This provides an answer to the implicit question: "why would I want this anyway?"

As said: we're with Django rest_framework, and we're using generic views, and for each type of objects in our database we find ourselves with one view class providing GET and POST for lists of objects, and an other view class providing GET, PUT, and DELETE for individual objects.

Now the POST, PUT, and DELETE we want to decorate with Django's login_required. Notice how this touches both classes, but not all methods in either class.

A solution could go through multiple inheritance.

from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required

class LoginToPost:
    @method_decorator(login_required)
    def post(self, arg, *args, **kwargs):
        super().post(arg, *args, **kwargs)

Likewise for the other methods.

In the inheritance list of my concrete classes, I would add my LoginToPost before ListCreateAPIView and LoginToPutOrDelete before RetrieveUpdateDestroyAPIView. My concrete classes' get would stay undecorated.

How to push elements in JSON from javascript array

var arr = [ 'a', 'b', 'c'];
arr.push('d'); // insert as last item

How do I use the lines of a file as arguments of a command?

You do that using backticks:

echo World > file.txt
echo Hello `cat file.txt`

How to grey out a button?

You could Also make it appear as disabled by setting the alpha (making it semi-transparent). This is especially useful if your button background is an image, and you don't want to create states for it.

button.setAlpha(.5f);
button.setClickable(false);

update: I wrote the above solution pre Kotlin and when I was a rookie. It's more of a "quick'n'dirty" solution, but I don't recommend it in a professional environment.

Today, if I wanted a generic solution that works on any button/view without having to create a state list, I would create a Kotlin extension.

fun View.disable() {
    getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY)
    setClickable(false)
}

In Java you can do something is similar with a static util function and you would just have to pass in the view as variable. It's not as clean but it works.

Convert string to nullable type (int, double, etc...)

I like Joel's answer, but I've modified it slightly as I'm not a fan of eating exceptions.

    /// <summary>
    /// Converts a string to the specified nullable type.
    /// </summary>
    /// <typeparam name="T">The type to convert to</typeparam>
    /// <param name="s">The string to convert</param>
    /// <returns>The nullable output</returns>
    public static T? ToNullable<T>(this string s) where T : struct
    {
        if (string.IsNullOrWhiteSpace(s))
            return null;

        TypeConverter conv = TypeDescriptor.GetConverter(typeof (T));
        return (T) conv.ConvertFrom(s);
    }

    /// <summary>
    /// Attempts to convert a string to the specified nullable primative.
    /// </summary>
    /// <typeparam name="T">The primitive type to convert to</typeparam>
    /// <param name="data">The string to convert</param>
    /// <param name="output">The nullable output</param>
    /// <returns>
    /// True if conversion is successfull, false otherwise.  Null and whitespace will
    /// be converted to null and return true.
    /// </returns>
    public static bool TryParseNullable<T>(this string data, out T? output) where T : struct
    {
        try
        {
            output = data.ToNullable<T>();
            return true;
        }
        catch
        {
            output = null;
            return false;
        }
    }

What's the syntax for mod in java

Java actually has no modulo operator the way C does. % in Java is a remainder operator. On positive integers, it works exactly like modulo, but it works differently on negative integers and, unlike modulo, can work with floating point numbers as well. Still, it's rare to use % on anything but positive integers, so if you want to call it a modulo, then feel free!

How to use delimiter for csv in python

Your code is blanking out your file:

import csv
workingdir = "C:\Mer\Ven\sample"
csvfile = workingdir+"\test3.csv"
f=open(csvfile,'wb') # opens file for writing (erases contents)
csv.writer(f, delimiter =' ',quotechar =',',quoting=csv.QUOTE_MINIMAL)

if you want to read the file in, you will need to use csv.reader and open the file for reading.

import csv
workingdir = "C:\Mer\Ven\sample"
csvfile = workingdir+"\test3.csv"
f=open(csvfile,'rb') # opens file for reading
reader = csv.reader(f)
for line in reader:
    print line

If you want to write that back out to a new file with different delimiters, you can create a new file and specify those delimiters and write out each line (instead of printing the tuple).

Difference between spring @Controller and @RestController annotation

@RestController is composition of @Controller and @ResponseBody, if we are not using the @ResponseBody in Method signature then we need to use the @Restcontroller.

Where is the kibana error log? Is there a kibana error log?

It seems that you need to pass a flag "-l, --log-file"

https://github.com/elastic/kibana/issues/3407

Usage: kibana [options]

Kibana is an open source (Apache Licensed), browser based analytics and search dashboard for Elasticsearch.

Options:

    -h, --help                 output usage information
    -V, --version              output the version number
    -e, --elasticsearch <uri>  Elasticsearch instance
    -c, --config <path>        Path to the config file
    -p, --port <port>          The port to bind to
    -q, --quiet                Turns off logging
    -H, --host <host>          The host to bind to
    -l, --log-file <path>      The file to log to
    --plugins <path>           Path to scan for plugins

If you use the init script to run as a service, maybe you will need to customize it.

'const string' vs. 'static readonly string' in C#

Here is a good breakdown of the pros and cons:

So, it appears that constants should be used when it is very unlikely that the value will ever change, or if no external apps/libs will be using the constant. Static readonly fields should be used when run-time calculation is required, or if external consumers are a factor.

Spring Boot application as a Service

If you want to use Spring Boot 1.2.5 with Spring Boot Maven Plugin 1.3.0.M2, here's out solution:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.2.5.RELEASE</version>
</parent>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <version>1.3.0.M2</version>
            <configuration>
                <executable>true</executable>
            </configuration>
        </plugin>
    </plugins>
</build>

<pluginRepositories>
    <pluginRepository>
        <id>spring-libs-milestones</id>
        <url>http://repo.spring.io/libs-milestone</url>
    </pluginRepository> 
</pluginRepositories>

Then compile as ususal: mvn clean package, make a symlink ln -s /.../myapp.jar /etc/init.d/myapp, make it executable chmod +x /etc/init.d/myapp and start it service myapp start (with Ubuntu Server)

Using the "animated circle" in an ImageView while loading stuff

If you would like to not inflate another view just to indicate progress then do the following:

  1. Create ProgressBar in the same XML layout of the list view.
  2. Make it centered
  3. Give it an id
  4. Attach it to your listview instance variable by calling setEmptyView

Android will take care the progress bar's visibility.

For example, in activity_main.xml:

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.fcchyd.linkletandroid.MainActivity">

    <ListView
        android:id="@+id/list_view_xml"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:divider="@color/colorDivider"
        android:dividerHeight="1dp" />

   <ProgressBar
        android:id="@+id/loading_progress_xml"
        style="?android:attr/progress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" />

</RelativeLayout>

And in MainActivity.java:

package com.fcchyd.linkletandroid;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {

final String debugLogHeader = "Linklet Debug Message";
Call<Links> call;
List<Link> arraylistLink;
ListView linksListV;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    linksListV = (ListView) findViewById(R.id.list_view_xml);
    linksListV.setEmptyView(findViewById(R.id.loading_progress_xml));
    arraylistLink = new ArrayList<>();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://api.links.linklet.ml")
            .addConverterFactory(GsonConverterFactory
                    .create())
            .build();

    HttpsInterface HttpsInterface = retrofit
            .create(HttpsInterface.class);

    call = HttpsInterface.httpGETpageNumber(1);

    call.enqueue(new Callback<Links>() {
        @Override
        public void onResponse(Call<Links> call, Response<Links> response) {
            try {
                arraylistLink = response.body().getLinks();

                String[] simpletTitlesArray = new String[arraylistLink.size()];
                for (int i = 0; i < simpletTitlesArray.length; i++) {
                    simpletTitlesArray[i] = arraylistLink.get(i).getTitle();
                }
                ArrayAdapter<String> simpleAdapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, simpletTitlesArray);
                linksListV.setAdapter(simpleAdapter);
            } catch (Exception e) {
                Log.e("erro", "" + e);
            }
        }

        @Override
        public void onFailure(Call<Links> call, Throwable t) {

        }
    });


}

}

PHP Warning: PHP Startup: Unable to load dynamic library

Note that you can also get this error if your PHP library doesn't have the "other" directory opening permission. In my particular case, I noticed this when using php -l to syntax check a script in my text editor. This meant that since my account was called "volomike", that account didn't have permission to run the libraries that the php command relied upon.

For instance, on Ubuntu 14.04, I had PHP5 installed automatically into the path /usr/lib/php5/20121212+lfs. However, because I was working in C++ in building some shared objects, I messed around with the directory permissions and screwed things up such that non-root accounts did not have the directory execute (directory open) permissions to view /usr/lib/php5/20121212+lfs. So, I typed the following command to rectify that problem:

sudo chmod o+x /usr/lib/php5/20121212+lfs.

Now when I do php -l example.php as a non-root user, it never gives me this "Unabled to load dynamic library" problem anymore.

How can I get a Dialog style activity window to fill the screen?

I just want to fill only 80% of the screen for that I did like this below

        DisplayMetrics metrics = getResources().getDisplayMetrics();
        int screenWidth = (int) (metrics.widthPixels * 0.80);

        setContentView(R.layout.mylayout);

        getWindow().setLayout(screenWidth, LayoutParams.WRAP_CONTENT); //set below the setContentview

it works only when I put the getwindow().setLayout... line below the setContentView(..)

thanks @Matthias

Insert the same fixed value into multiple rows

You're looking for UPDATE not insert.

UPDATE mytable
SET    table_column = 'test';

UPDATE will change the values of existing rows (and can include a WHERE to make it only affect specific rows), whereas INSERT is adding a new row (which makes it look like it changed only the last row, but in effect is adding a new row with that value).

Get image dimensions

You can use the getimagesize function like this:

list($width, $height) = getimagesize('path to image');
echo "width: " . $width . "<br />";
echo "height: " .  $height;

How to set default values in Rails?

The suggestion to override new/initialize is probably incomplete. Rails will (frequently) call allocate for ActiveRecord objects, and calls to allocate won't result in calls to initialize.

If you're talking about ActiveRecord objects, take a look at overriding after_initialize.

These blog posts (not mine) are useful:

Default values Default constructors not called

[Edit: SFEley points out that Rails actually does look at the default in the database when it instantiates a new object in memory - I hadn't realized that.]

Why can't I have abstract static methods in C#?

Another respondent (McDowell) said that polymorphism only works for object instances. That should be qualified; there are languages that do treat classes as instances of a "Class" or "Metaclass" type. These languages do support polymorphism for both instance and class (static) methods.

C#, like Java and C++ before it, is not such a language; the static keyword is used explicitly to denote that the method is statically-bound rather than dynamic/virtual.

JAXB: How to ignore namespace during unmarshalling XML document?

This is just a modification of lunicon's answer (https://stackoverflow.com/a/24387115/3519572) if you want to replace one namespace for another during parsing. And if you want to see what exactly is going on, just uncomment the output lines and set a breakpoint.

public class XMLReaderWithNamespaceCorrection extends StreamReaderDelegate {

    private final String wrongNamespace;
    private final String correctNamespace;

    public XMLReaderWithNamespaceCorrection(XMLStreamReader reader, String wrongNamespace, String correctNamespace) {
        super(reader);

        this.wrongNamespace = wrongNamespace;
        this.correctNamespace = correctNamespace;
    }

    @Override
    public String getAttributeNamespace(int arg0) {
//        System.out.println("--------------------------\n");
//        System.out.println("arg0: " + arg0);
//        System.out.println("getAttributeName: " + getAttributeName(arg0));
//        System.out.println("super.getAttributeNamespace: " + super.getAttributeNamespace(arg0));
//        System.out.println("getAttributeLocalName: " + getAttributeLocalName(arg0));
//        System.out.println("getAttributeType: " + getAttributeType(arg0));
//        System.out.println("getAttributeValue: " + getAttributeValue(arg0));
//        System.out.println("getAttributeValue(correctNamespace, LN):"
//                + getAttributeValue(correctNamespace, getAttributeLocalName(arg0)));
//        System.out.println("getAttributeValue(wrongNamespace, LN):"
//                + getAttributeValue(wrongNamespace, getAttributeLocalName(arg0)));

        String origNamespace = super.getAttributeNamespace(arg0);

        boolean replace = (((wrongNamespace == null) && (origNamespace == null))
                || ((wrongNamespace != null) && wrongNamespace.equals(origNamespace)));
        return replace ? correctNamespace : origNamespace;
    }

    @Override
    public String getNamespaceURI() {
//        System.out.println("getNamespaceCount(): " + getNamespaceCount());
//        for (int i = 0; i < getNamespaceCount(); i++) {
//            System.out.println(i + ": " + getNamespacePrefix(i));
//        }
//
//        System.out.println("super.getNamespaceURI: " + super.getNamespaceURI());

        String origNamespace = super.getNamespaceURI();

        boolean replace = (((wrongNamespace == null) && (origNamespace == null))
                || ((wrongNamespace != null) && wrongNamespace.equals(origNamespace)));
        return replace ? correctNamespace : origNamespace;
    }
}

usage:

InputStream is = new FileInputStream(xmlFile);
XMLStreamReader xsr = XMLInputFactory.newFactory().createXMLStreamReader(is);
XMLReaderWithNamespaceCorrection xr =
    new XMLReaderWithNamespaceCorrection(xsr, "http://wrong.namespace.uri", "http://correct.namespace.uri");
rootJaxbElem = (JAXBElement<SqgRootType>) um.unmarshal(xr);
handleSchemaError(rootJaxbElem, pmRes);

Find the line number where a specific word appears with "grep"

Or You can use

   grep -n . file1 |tail -LineNumberToStartWith|grep regEx

This will take care of numbering the lines in the file

   grep -n . file1 

This will print the last-LineNumberToStartWith

   tail -LineNumberToStartWith

And finally it will grep your desired lines(which will include line number as in orignal file)

grep regEX

How can I debug what is causing a connection refused or a connection time out?

Use a packet analyzer to intercept the packets to/from somewhere.com. Studying those packets should tell you what is going on.

Time-outs or connections refused could mean that the remote host is too busy.

Download multiple files as a zip-file using php

This is a working example of making ZIPs in PHP:

$zip = new ZipArchive();
$zip_name = time().".zip"; // Zip name
$zip->open($zip_name,  ZipArchive::CREATE);
foreach ($files as $file) {
  echo $path = "uploadpdf/".$file;
  if(file_exists($path)){
  $zip->addFromString(basename($path),  file_get_contents($path));  
  }
  else{
   echo"file does not exist";
  }
}
$zip->close();

How to get access to raw resources that I put in res folder?

InputStream in = getResources().openRawResource(resourceName);

This will work correctly. Before that you have to create the xml file / text file in raw resource. Then it will be accessible.

Edit
Some times com.andriod.R will be imported if there is any error in layout file or image names. So You have to import package correctly, then only the raw file will be accessible.

how to change text box value with jQuery?

Use like this on dropdown change
$("#assetgroupSelect").change(function(){
    $("#idValue").val($this.val());
})

Ping site and return result in PHP

this is php code I used, reply is usually like this:

    2 packets transmitted, 2 received, 0% packet loss, time 1089ms

So I used code like this:

  

    $ping_how_many = 2;
    $ping_result = shell_exec('ping -c '.$ping_how_many.' bing.com');
    if( !preg_match('/'.$ping_how_many.' received/',$ping_result) ){
       echo 'Bad ping result'. PHP_EOL;
        // goto next1;
    } 


call javascript function on hyperlink click

Ideally I would avoid generating links in you code behind altogether as your code will need recompiling every time you want to make a change to the 'markup' of each of those links. If you have to do it I would not embed your javascript 'calls' inside your HTML, it's a bad practice altogether, your markup should describe your document not what it does, thats the job of your javascript.

Use an approach where you have a specific id for each element (or class if its common functionality) and then use Progressive Enhancement to add the event handler(s), something like:

[c# example only probably not the way you're writing out your js]
Response.Write("<a href=\"/link/for/javascriptDisabled/Browsers.aspx\" id=\"uxAncMyLink\">My Link</a>");

[Javascript]  
document.getElementById('uxAncMyLink').onclick = function(e){

// do some stuff here

    return false;
    }

That way your code won't break for users with JS disabled and it will have a clear seperation of concerns.

Hope that is of use.

Java: random long number in 0 <= x < n range

The methods above work great. If you're using apache commons (org.apache.commons.math.random) check out RandomData. It has a method: nextLong(long lower, long upper)

http://commons.apache.org/math/userguide/random.html

http://commons.apache.org/math/api-1.1/org/apache/commons/math/random/RandomData.html#nextLong(long,%20long)

How big can a MySQL database get before performance starts to degrade

2GB and about 15M records is a very small database - I've run much bigger ones on a pentium III(!) and everything has still run pretty fast.. If yours is slow it is a database/application design problem, not a mysql one.

Google Gson - deserialize list<class> object? (generic type)

Wep, another way to achieve the same result. We use it for its readability.

Instead of doing this hard-to-read sentence:

Type listType = new TypeToken<ArrayList<YourClass>>(){}.getType();
List<YourClass> list = new Gson().fromJson(jsonArray, listType);

Create a empty class that extends a List of your object:

public class YourClassList extends ArrayList<YourClass> {}

And use it when parsing the JSON:

List<YourClass> list = new Gson().fromJson(jsonArray, YourClassList.class);

How to use a calculated column to calculate another column in the same view

In SQL Server

You can do this using With CTE

WITH common_table_expression (Transact-SQL)

CREATE TABLE tab(ColumnA DECIMAL(10,2), ColumnB DECIMAL(10,2), ColumnC DECIMAL(10,2))

INSERT INTO tab(ColumnA, ColumnB, ColumnC) VALUES (2, 10, 2),(3, 15, 6),(7, 14, 3)

WITH tab_CTE (ColumnA, ColumnB, ColumnC,calccolumn1)  
AS  
(  
Select
    ColumnA,
    ColumnB,
    ColumnC,
    ColumnA + ColumnB As calccolumn1
  from tab
)  

SELECT
  ColumnA,
  ColumnB,
  calccolumn1,
  calccolumn1 / ColumnC AS calccolumn2
FROM  tab_CTE

DBFiddle Demo

Verify object attribute value with mockito

A simplified solution, without creating a new Matcher implementation class and using lambda expression:

verify(mockObject).someMockMethod(
        argThat((SomeArgument arg) -> arg.fieldToMatch.equals(expectedFieldValue));

How to set the range of y-axis for a seaborn boxplot?

It is standard matplotlib.pyplot:

...
import matplotlib.pyplot as plt
plt.ylim(10, 40)

Or simpler, as mwaskom comments below:

ax.set(ylim=(10, 40))

enter image description here

Invalid http_host header

In your project settings.py file,set ALLOWED_HOSTS like this :

ALLOWED_HOSTS = ['62.63.141.41', 'namjoosadr.com']

and then restart your apache. in ubuntu:

/etc/init.d/apache2 restart

How can I download HTML source in C#

You can get it with:

var html = new System.Net.WebClient().DownloadString(siteUrl)

What are the rules for calling the superclass constructor?

The only way to pass values to a parent constructor is through an initialization list. The initilization list is implemented with a : and then a list of classes and the values to be passed to that classes constructor.

Class2::Class2(string id) : Class1(id) {
....
}

Also remember that if you have a constructor that takes no parameters on the parent class, it will be called automatically prior to the child constructor executing.

How can I generate an ObjectId with mongoose?

You can create a new MongoDB ObjectId like this using mongoose:

var mongoose = require('mongoose');
var newId = new mongoose.mongo.ObjectId('56cb91bdc3464f14678934ca');
// or leave the id string blank to generate an id with a new hex identifier
var newId2 = new mongoose.mongo.ObjectId();

Unsafe JavaScript attempt to access frame with URL

From a child document of different origin you are not allowed access to the top window's location.hash property, but you are allowed to set the location property itself.

This means that given that the top windows location is http://example.com/page/, instead of doing

parent.location.hash = "#foobar";

you do need to know the parents location and do

parent.location = "http://example.com/page/#foobar";

Since the resource is not navigated this will work as expected, only changing the hash part of the url.

If you are using this for cross-domain communication, then I would recommend using easyXDM instead.

How to print current date on python3?

This function allows you to get the date and time in lots of formats (see the bottom of this post).

# Get the current date or time
def getdatetime(timedateformat='complete'):
    from datetime import datetime
    timedateformat = timedateformat.lower()
    if timedateformat == 'day':
        return ((str(datetime.now())).split(' ')[0]).split('-')[2]
    elif timedateformat == 'month':
        return ((str(datetime.now())).split(' ')[0]).split('-')[1]
    elif timedateformat == 'year':
        return ((str(datetime.now())).split(' ')[0]).split('-')[0]
    elif timedateformat == 'hour':
        return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[0]
    elif timedateformat == 'minute':
        return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[1]
    elif timedateformat == 'second':
        return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[2]
    elif timedateformat == 'millisecond':
        return (str(datetime.now())).split('.')[1]
    elif timedateformat == 'yearmonthday':
        return (str(datetime.now())).split(' ')[0]
    elif timedateformat == 'daymonthyear':
        return ((str(datetime.now())).split(' ')[0]).split('-')[2] + '-' + ((str(datetime.now())).split(' ')[0]).split('-')[1] + '-' + ((str(datetime.now())).split(' ')[0]).split('-')[0]
    elif timedateformat == 'hourminutesecond':
        return ((str(datetime.now())).split(' ')[1]).split('.')[0]
    elif timedateformat == 'secondminutehour':
        return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[2] + ':' + (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[1] + ':' + (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[0]
    elif timedateformat == 'complete':
        return str(datetime.now())
    elif timedateformat == 'datetime':
        return (str(datetime.now())).split('.')[0]
    elif timedateformat == 'timedate':
        return ((str(datetime.now())).split('.')[0]).split(' ')[1] + ' ' + ((str(datetime.now())).split('.')[0]).split(' ')[0]

To obtain the time or date, just use getdatetime("<TYPE>"), replacing <TYPE> with one of the following arguments:

All example outputs use this model information: 25-11-2017 03:23:56.477017

Argument Meaning Example output
day Get the current day 25
month Get the current month 11
year Get the current year 2017
hour Get the current hour 03
minute Get the current minute 23
second Get the current second 56
millisecond Get the current millisecond 477017
yearmonthday Get the year, month and day 2017-11-25
daymonthyear Get the day, month and year 25-11-2017
hourminutesecond Get the hour, minute and second 03:23:56
secondminutehour Get the second, minute and hour 56:23:03
complete Get the complete date and time 2017-11-25 03:23:56.477017
datetime Get the date and time 2017-11-25 03:23:56
timedate Get the time and date 03:23:56 2017-11-25

What is the &#xA; character?

&#xA; is the HTML representation in hex of a line feed character. It represents a new line on Unix and Unix-like (for example) operating systems.

You can find a list of such characters at (for example) http://la.remifa.so/unicode/latin1.html

BadValue Invalid or no user locale set. Please ensure LANG and/or LC_* environment variables are set correctly

Amazon Linux AMI

Permanent solution for ohmyzsh:

$ vim ~/.zshrc

Write there below:

export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
export LANGUAGE=en_US.UTF-8

Update changes in current shell by: $ source ~/.zshrc

How can I create and style a div using JavaScript?

_x000D_
_x000D_
var div = document.createElement("div");_x000D_
div.style.width = "100px";_x000D_
div.style.height = "100px";_x000D_
div.style.background = "red";_x000D_
div.style.color = "white";_x000D_
div.innerHTML = "Hello";_x000D_
_x000D_
document.getElementById("main").appendChild(div);
_x000D_
<body>_x000D_
<div id="main"></div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

var div = document.createElement("div");
div.style.width = "100px";
div.style.height = "100px";
div.style.background = "red";
div.style.color = "white";
div.innerHTML = "Hello";

document.getElementById("main").appendChild(div);
OR
document.body.appendChild(div);

Use parent reference instead of document.body.

How to set up googleTest as a shared library on Linux

Just in case somebody else gets in the same situation like me yesterday (2016-06-22) and also does not succeed with the already posted approaches - on Lubuntu 14.04 it worked for me using the following chain of commands:

git clone https://github.com/google/googletest
cd googletest
cmake -DBUILD_SHARED_LIBS=ON .
make
cd googlemock
sudo cp ./libgmock_main.so ./gtest/libgtest.so gtest/libgtest_main.so ./libgmock.so /usr/lib/
sudo ldconfig

How to use PowerShell select-string to find more than one pattern in a file?

You can specify multiple patterns in an array.

select-string VendorEnquiry,Failed C:\Logs

This works with -notmatch as well:

select-string -notmatch VendorEnquiry,Failed C:\Logs

Android design support library for API 28 (P) not working

Adding androidTestImplementation 'androidx.test:runner:1.2.0-alpha05' works for me.

Can I change the Android startActivity() transition animation?

Starting from API level 5 you can call overridePendingTransition immediately to specify an explicit transition animation:

startActivity();
overridePendingTransition(R.anim.hold, R.anim.fade_in);

or

finish();
overridePendingTransition(R.anim.hold, R.anim.fade_out);

Tuple unpacking in for loops

Short answer, unpacking tuples from a list in a for loop works. enumerate() creates a tuple using the current index and the entire current item, such as (0, ('bob', 3))

I created some test code to demonstrate this:

    list = [('bob', 3), ('alice', 0), ('john', 5), ('chris', 4), ('alex', 2)]

    print("Displaying Enumerated List")
    for name, num in enumerate(list):
        print("{0}: {1}".format(name, num))

    print("Display Normal Iteration though List")
    for name, num in list:
        print("{0}: {1}".format(name, num))

The simplicity of Tuple unpacking is probably one of my favourite things about Python :D

Does adding a duplicate value to a HashSet/HashMap replace the previous value

In the case of HashMap, it replaces the old value with the new one.

In the case of HashSet, the item isn't inserted.

Python: OSError: [Errno 2] No such file or directory: ''

Use os.path.abspath():

os.chdir(os.path.dirname(os.path.abspath(sys.argv[0])))

sys.argv[0] in your case is just a script name, no directory, so os.path.dirname() returns an empty string.

os.path.abspath() turns that into a proper absolute path with directory name.

Overriding !important style

Below is a snippet of code to set the important parameter for the style attribute using jquery.

$.fn.setFixedStyle = function(styles){
    var s = $(this).attr("style");
    s = "{"+s.replace(/;/g,",").replace(/'|"/g,"");
    s = s.substring(0,s.length-1)+"}";
    s = s.replace(/,/g,"\",\"").replace(/{/g,"{\"").replace(/}/g,"\"}").replace(/:/g,"\":\"");
    var stOb = JSON.parse(s),st;
    if(!styles){
     $.each(stOb,function(k,v){
      stOb[k] +=" !important";
     });
    }
    else{
     $.each(styles,function(k,v){
      if(v.length>0){
        stOb[k] = v+" !important";
      }else{
        stOb[k] += " !important";  
      }
     });
    }
    var ns = JSON.stringify(stOb);
    $(this).attr("style",ns.replace(/"|{|}/g,"").replace(/,/g,";"));
};

Usage is pretty simple.Just pass an object containing all the attributes you want to set as important.

$("#i1").setFixedStyle({"width":"50px","height":""});

There are two additional options.

1.To just add important parameter to already present style attribute pass empty string.

2.To add important param for all attributes present dont pass anything. It will set all attributes as important.

Here is it live in action. http://codepen.io/agaase/pen/nkvjr

Parse XML document in C#

Try this:

XmlDocument doc = new XmlDocument();
doc.Load(@"C:\Path\To\Xml\File.xml");

Or alternatively if you have the XML in a string use the LoadXml method.

Once you have it loaded, you can use SelectNodes and SelectSingleNode to query specific values, for example:

XmlNode node = doc.SelectSingleNode("//Company/Email/text()");
// node.Value contains "[email protected]"

Finally, note that your XML is invalid as it doesn't contain a single root node. It must be something like this:

<Data>
    <Employee>
        <Name>Test</Name>
        <ID>123</ID>
    </Employee>
    <Company>
        <Name>ABC</Name>
        <Email>[email protected]</Email>
    </Company>
</Data>

Get custom product attributes in Woocommerce

You can get the single value for the attribute with below code:

$pa_koostis_value = get_post_meta($product->id, 'pa_koostis', true);