Programs & Examples On #Migration

An action of moving between major version of any framework, product or language, or, just as commonly, alteration to the data schema of an application. This might involve modifying existing data to make it work with the new version.

How to implement LIMIT with SQL Server?

SELECT TOP 10 * FROM table;

Is the same as

SELECT * FROM table LIMIT 0,10;

Here's an article about implementing Limit in MsSQL Its a nice read, specially the comments.

Warning about `$HTTP_RAW_POST_DATA` being deprecated

Unfortunately, this answer here by @EatOng is not correct. After reading his answer I added a dummy variable to every AJAX request I was firing (even if some of them already had some fields) just to be sure the error never appears.

But just now I came across the same damn error from PHP. I double-confirmed that I had sent some POST data (some other fields too along with the dummy variable). PHP version 5.6.25, always_populate_raw_post_data value is set to 0.

Also, as I am sending a application/json request, PHP is not populating it to $_POST, rather I have to json_decode() the raw POST request body, accessible by php://input.

As the answer by @rr- cites,

0/off/whatever: BC behavior (populate if content-type is not registered or request method is other than POST).

Because the request method is for sure POST, I guess PHP didn't recognize/like my Content-Type: application/json request (again, why??).

OPTION 1:

Edit the php.ini file manually and set the culprit variable to -1, as many of the answers here suggest.

OPTION 2:

This is a PHP 5.6 bug. Upgrade PHP.

OPTION 3:

As @user9541305 answered here, changing the Content-Type of AJAX request to application/x-www-form-urlencoded or multipart/form-data will make PHP populate the $_POST from the POSTed body (because PHP likes/recognizes those content-type headers!?).

OPTION 4: LAST RESORT

Well, I did not want to change the Content-Type of AJAX, it would cause a lot of trouble for debugging. (Chrome DevTools nicely views the POSTed variables of JSON requests.)

I am developing this thing for a client and cannot ask them to use latest PHP, nor to edit the php.ini file. As a last resort, I will just check if it is set to 0 and if so, edit the php.ini file in my PHP script itself. Of course I will have to ask the user to restart apache. What a shame!

Here is a sample code:

<?php

if(ini_get('always_populate_raw_post_data') != '-1')
{
    // Get the path to php.ini file
    $iniFilePath = php_ini_loaded_file();

    // Get the php.ini file content
    $iniContent = file_get_contents($iniFilePath);

    // Un-comment (if commented) always_populate_raw_post_data line, and set its value to -1
    $iniContent = preg_replace('~^\s*;?\s*always_populate_raw_post_data\s*=\s*.*$~im', 'always_populate_raw_post_data = -1', $iniContent);

    // Write the content back to the php.ini file
    file_put_contents($iniFilePath, $iniContent);

    // Exit the php script here
    // Also, write some response here to notify the user and ask to restart Apache / WAMP / Whatever.
    exit;
}

How to change a nullable column to not nullable in a Rails migration?

In Rails 4, this is a better (DRYer) solution:

change_column_null :my_models, :date_column, false

To ensure no records exist with NULL values in that column, you can pass a fourth parameter, which is the default value to use for records with NULL values:

change_column_null :my_models, :date_column, false, Time.now

Rails: Adding an index after adding column

You can use this, just think Job is the name of the model to which you are adding index cader_id:

class AddCaderIdToJob < ActiveRecord::Migration[5.2]
  def change
    change_table :jobs do |t|
      t.integer :cader_id
      t.index :cader_id
    end
  end
end

Add a default value to a column through a migration

This is what you can do:

class Profile < ActiveRecord::Base
  before_save :set_default_val

  def set_default_val
    self.send_updates = 'val' unless self.send_updates
  end
end

EDIT: ...but apparently this is a Rookie mistake!

Change a column type from Date to DateTime during ROR migration

First in your terminal:

rails g migration change_date_format_in_my_table

Then in your migration file:

For Rails >= 3.2:

class ChangeDateFormatInMyTable < ActiveRecord::Migration
  def up
    change_column :my_table, :my_column, :datetime
  end

  def down
    change_column :my_table, :my_column, :date
  end
end

How to import a SQL Server .bak file into MySQL?

SQL Server databases are very Microsoft proprietary. Two options I can think of are:

  1. Dump the database in CSV, XML or similar format that you'd then load into MySQL.

  2. Setup ODBC connection to MySQL and then using DTS transport the data. As Charles Graham has suggested, you may need to build the tables before doing this. But that's as easy as a cut and paste from SQL Enterprise Manager windows to the corresponding MySQL window.

How to declare local variables in postgresql?

Postgresql historically doesn't support procedural code at the command level - only within functions. However, in Postgresql 9, support has been added to execute an inline code block that effectively supports something like this, although the syntax is perhaps a bit odd, and there are many restrictions compared to what you can do with SQL Server. Notably, the inline code block can't return a result set, so can't be used for what you outline above.

In general, if you want to write some procedural code and have it return a result, you need to put it inside a function. For example:

CREATE OR REPLACE FUNCTION somefuncname() RETURNS int LANGUAGE plpgsql AS $$
DECLARE
  one int;
  two int;
BEGIN
  one := 1;
  two := 2;
  RETURN one + two;
END
$$;
SELECT somefuncname();

The PostgreSQL wire protocol doesn't, as far as I know, allow for things like a command returning multiple result sets. So you can't simply map T-SQL batches or stored procedures to PostgreSQL functions.

Rails DB Migration - How To Drop a Table?

You won't always be able to simply generate the migration to already have the code you want. You can create an empty migration and then populate it with the code you need.

You can find information about how to accomplish different tasks in a migration here:

http://api.rubyonrails.org/classes/ActiveRecord/Migration.html

More specifically, you can see how to drop a table using the following approach:

drop_table :table_name

Laravel migration table field's type change

For me the solution was just replace unsigned with index

This is the full code:

    Schema::create('champions_overview',function (Blueprint $table){
        $table->engine = 'InnoDB';
        $table->increments('id');
        $table->integer('cid')->index();
        $table->longText('name');
    });


    Schema::create('champions_stats',function (Blueprint $table){
        $table->engine = 'InnoDB';
        $table->increments('id');
        $table->integer('championd_id')->index();
        $table->foreign('championd_id', 'ch_id')->references('cid')->on('champions_overview');
    });

Rails 3 migrations: Adding reference column?

You can add references to your model through command line in the following manner:

rails g migration add_column_to_tester user_id:integer

This will generate a migration file like :

class AddColumnToTesters < ActiveRecord::Migration
  def change
    add_column :testers, :user_id, :integer
  end
end

This works fine every time i use it..

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

Generate a Ruby on Rails migration:

$:> rails g migration Fixcolumnname

Insert code in the migration file (XXXXXfixcolumnname.rb):

class Fixcolumnname < ActiveRecord::Migration
  def change
    rename_column :table_name, :old_column, :new_column
  end
end

Assigning default value while creating migration file

I tried t.boolean :active, :default => 1 in migration file for creating entire table. After ran that migration when i checked in db it made as null. Even though i told default as "1". After that slightly i changed migration file like this then it worked for me for setting default value on create table migration file.

t.boolean :active, :null => false,:default =>1. Worked for me.

My Rails framework version is 4.0.0

Package Manager Console Enable-Migrations CommandNotFoundException only in a specific VS project

downgrade to 6.2 helped me.
.NET Framework version 4.6.1
Project in old format(non .NET Standard)
Visual Studio should be open with Admin rights for initial migration.
I guess EF with version above 6.2 require latest .NET Framework.

Rails migration for change column

I'm not aware if you can create a migration from the command line to do all this, but you can create a new migration, then edit the migration to perform this taks.

If tablename is the name of your table, fieldname is the name of your field and you want to change from a datetime to date, you can write a migration to do this.

You can create a new migration with:

rails g migration change_data_type_for_fieldname

Then edit the migration to use change_table:

class ChangeDataTypeForFieldname < ActiveRecord::Migration
  def self.up
    change_table :tablename do |t|
      t.change :fieldname, :date
    end
  end
  def self.down
    change_table :tablename do |t|
      t.change :fieldname, :datetime
    end
  end
end

Then run the migration:

rake db:migrate

Removing a model in rails (reverse of "rails g model Title...")

  1. To remove migration (if you already migrated the migration)

    rake db:migrate:down VERSION="20130417185845" #Your migration version
    
  2. To remove Model

    rails d model name  #name => Your model name
    

Quick easy way to migrate SQLite3 to MySQL?

Everyone seems to starts off with a few greps and perl expressions and you sorta kinda get something that works for your particular dataset but you have no idea if it's imported the data correctly or not. I'm seriously surprised nobody's built a solid library that can convert between the two.

Here a list of ALL the differences in SQL syntax that I know about between the two file formats: The lines starting with:

  • BEGIN TRANSACTION
  • COMMIT
  • sqlite_sequence
  • CREATE UNIQUE INDEX

are not used in MySQL

  • SQLite uses CREATE TABLE/INSERT INTO "table_name" and MySQL uses CREATE TABLE/INSERT INTO table_name
  • MySQL doesn't use quotes inside the schema definition
  • MySQL uses single quotes for strings inside the INSERT INTO clauses
  • SQLite and MySQL have different ways of escaping strings inside INSERT INTO clauses
  • SQLite uses 't' and 'f' for booleans, MySQL uses 1 and 0 (a simple regex for this can fail when you have a string like: 'I do, you don't' inside your INSERT INTO)
  • SQLLite uses AUTOINCREMENT, MySQL uses AUTO_INCREMENT

Here is a very basic hacked up perl script which works for my dataset and checks for many more of these conditions that other perl scripts I found on the web. Nu guarantees that it will work for your data but feel free to modify and post back here.

#! /usr/bin/perl

while ($line = <>){
    if (($line !~  /BEGIN TRANSACTION/) && ($line !~ /COMMIT/) && ($line !~ /sqlite_sequence/) && ($line !~ /CREATE UNIQUE INDEX/)){
        
        if ($line =~ /CREATE TABLE \"([a-z_]*)\"(.*)/i){
            $name = $1;
            $sub = $2;
            $sub =~ s/\"//g;
            $line = "DROP TABLE IF EXISTS $name;\nCREATE TABLE IF NOT EXISTS $name$sub\n";
        }
        elsif ($line =~ /INSERT INTO \"([a-z_]*)\"(.*)/i){
            $line = "INSERT INTO $1$2\n";
            $line =~ s/\"/\\\"/g;
            $line =~ s/\"/\'/g;
        }else{
            $line =~ s/\'\'/\\\'/g;
        }
        $line =~ s/([^\\'])\'t\'(.)/$1THIS_IS_TRUE$2/g;
        $line =~ s/THIS_IS_TRUE/1/g;
        $line =~ s/([^\\'])\'f\'(.)/$1THIS_IS_FALSE$2/g;
        $line =~ s/THIS_IS_FALSE/0/g;
        $line =~ s/AUTOINCREMENT/AUTO_INCREMENT/g;
        print $line;
    }
}

Migration: Cannot add foreign key constraint

Chiming in here a few years after the original question, using laravel 5.1, I had the same error as my migrations were computer generated with all the same date code. I went through all the proposed solutions, then refactored to find the error source.

In following laracasts, and in reading these posts, I believe the correct answer is similar to Vickies answer, with the exception that you don't need to add a separate schema call. You don't need to set the table to Innodb, I am assuming laravel is now doing that.

The migrations simply need to be timed correctly, which means you will modify the date code up (later) in the filename for tables that you need foreign keys on. Alternatively or in addition, Lower the datecode for tables that don't need foreign keys.

The advantage in modifying the datecode is your migration code will be easier to read and maintain.

So far my code is working by adjusting the time code up to push back migrations that need foreign keys.

However I do have hundreds of tables, so at the very end I have one last table for just foreign keys. Just to get things flowing. I am assuming I will pull those into the correct file and modify the datecode as i test them.

So an example: file 2016_01_18_999999_create_product_options_table. This one needs the products table to be created. Look at the file names.

 public function up()
{
    Schema::create('product_options', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('product_attribute_id')->unsigned()->index();
        $table->integer('product_id')->unsigned()->index();
        $table->string('value', 40)->default('');
        $table->timestamps();
        //$table->foreign('product_id')->references('id')->on('products');
        $table->foreign('product_attribute_id')->references('id')->on('product_attributes');
        $table->foreign('product_id')->references('id')->on('products');


    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::drop('product_options');
}

the products table: this needs to migrate first. 2015_01_18_000000_create_products_table

public function up()
{
    Schema::create('products', function (Blueprint $table) {
        $table->increments('id');

        $table->string('style_number', 64)->default('');
        $table->string('title')->default('');
        $table->text('overview')->nullable();
        $table->text('description')->nullable();


        $table->timestamps();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::drop('products');
}

And finally at the very end the file that I am temporarily using to resolve issues, which I will refactor as I write tests for the models which I named 9999_99_99_999999_create_foreign_keys.php. These keys are commented as I pulled them out, but you get the point.

    public function up()
    {
//        Schema::table('product_skus', function ($table) {
//            $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
//    });

    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
//        Schema::table('product_skus', function ($table)
//        {
//            $table->dropForeign('product_skus_product_id_foreign');
//        });

How do I handle too long index names in a Ruby on Rails ActiveRecord migration?

In PostgreSQL, the default limit is 63 characters. Because index names must be unique it's nice to have a little convention. I use (I tweaked the example to explain more complex constructions):

def change
  add_index :studies, [:professor_id, :user_id], name: :idx_study_professor_user
end

The normal index would have been:

:index_studies_on_professor_id_and_user_id

The logic would be:

  • index becomes idx
  • Singular table name
  • No joining words
  • No _id
  • Alphabetical order

Which usually does the job.

SQLSTATE[HY000] [2002] Connection refused within Laravel homestead

If you are using Homestead like I do, do not forget to ssh into it before running artisan test for example.

List all sequences in a Postgres db 8.1 with SQL

Here is another one which has the schema name beside the sequence name

select nspname,relname from pg_class c join pg_namespace n on c.relnamespace=n.oid where relkind = 'S' order by nspname

SQL Server String or binary data would be truncated

One other potential reason for this is if you have a default value setup for a column that exceeds the length of the column. It appears someone fat fingered a column that had a length of 5 but the default value exceeded the length of 5. This drove me nuts as I was trying to understand why it wasn't working on any insert, even if all i was inserting was a single column with an integer of 1. Because the default value on the table schema had that violating default value it messed it all up - which I guess brings us to the lesson learned - avoid having tables with default value's in the schema. :)

Populating a database in a Laravel migration file

Don't put the DB::insert() inside of the Schema::create(), because the create method has to finish making the table before you can insert stuff. Try this instead:

public function up()
{
    // Create the table
    Schema::create('users', function($table){
        $table->increments('id');
        $table->string('email', 255);
        $table->string('password', 64);
        $table->boolean('verified');
        $table->string('token', 255);
        $table->timestamps();
    });

    // Insert some stuff
    DB::table('users')->insert(
        array(
            'email' => '[email protected]',
            'verified' => true
        )
    );
}

Java error: Comparison method violates its general contract

I had the same symptom. For me it turned out that another thread was modifying the compared objects while the sorting was happening in a Stream. To resolve the issue, I mapped the objects to immutable temporary objects, collected the Stream to a temporary Collection and did the sorting on that.

Adding :default => true to boolean in existing Rails column

As a variation on the accepted answer you could also use the change_column_default method in your migrations:

def up
  change_column_default :profiles, :show_attribute, true
end

def down
  change_column_default :profiles, :show_attribute, nil
end

Rails API-docs

Maven is not working in Java 8 when Javadoc tags are incomplete

I would like to add some insight into other answers

In my case

-Xdoclint:none

Didn't work.

Let start with that, in my project, I didn't really need javadoc at all. Only some necessary plugins had got a build time dependency on it.

So, the most simple way solve my problem was:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-javadoc-plugin</artifactId>
    <configuration>
        <skip>true</skip>
    </configuration>
</plugin>

Run a single migration file

You can just run the code directly out of the ruby file:

rails console
>> require "db/migrate/20090408054532_add_foos.rb"
>> AddFoos.new.up

Note: Very old versions of rails may require AddFoos.up rather than AddFoos.new.up.

An alternative way (without IRB) which relies on the fact that require returns an array of class names:

script/runner 'require("db/migrate/20090408054532_add_foos.rb").first.constantize.up'

Note that if you do this, it won't update the schema_migrations table, but it seems like that's what you want anyway.

Additionally, if it can't find the file you may need to use require("./db/..." or try require_relative depending on your working directory

How can I rename column in laravel using migration?

You need to create another migration file - and place it in there:

Run

Laravel 4:    php artisan migrate:make rename_stnk_column
Laravel 5:    php artisan make:migration rename_stnk_column

Then inside the new migration file place:

class RenameStnkColumn extends Migration
{

    public function up()
    {
        Schema::table('stnk', function(Blueprint $table) {
            $table->renameColumn('id', 'id_stnk');
        });
    }


    public function down()
    {
        Schema::table('stnk', function(Blueprint $table) {
            $table->renameColumn('id_stnk', 'id');
        });
    }

}

Laravel 5.4 Specific Table Migration

php artisan migrate --path=database/migrations/2020_04_10_130703_create_test_table.php

note: after --path no / before

How do you write a migration to rename an ActiveRecord model and its table in Rails?

Here's an example:

class RenameOldTableToNewTable < ActiveRecord::Migration
  def self.up
    rename_table :old_table_name, :new_table_name
  end

  def self.down
    rename_table :new_table_name, :old_table_name
  end
end

I had to go and rename the model declaration file manually.

Edit:

In Rails 3.1 & 4, ActiveRecord::Migration::CommandRecorder knows how to reverse rename_table migrations, so you can do this:

class RenameOldTableToNewTable < ActiveRecord::Migration
  def change
    rename_table :old_table_name, :new_table_name
  end 
end

(You still have to go through and manually rename your files.)

Want to upgrade project from Angular v5 to Angular v6

There are few steps to upgrade 2/4/5 to Angular 6.

npm uninstall --save-dev angular-cli
npm install --save-dev @angular/cli@latest
npm install

To fix the issue related to "angular.json" :-

ng update @angular/cli --migrate-only --from=1.7.4

Store MIGRATION
https://github.com/ngrx/platform/blob/master/MIGRATION.md#ngrxstore

RXJS MIGRATION
https://www.academind.com/learn/javascript/rxjs-6-what-changed/

Hoping this will help you :)

Entity Framework rollback and remove bad migration

You can also use

Remove-Migration -Force

This will revert and remove the last applied migration

Wordpress keeps redirecting to install-php after migration

As I was trying to install server setup to localhost, I have configured the config file as well as DB in local host- I was redirected to the install.php.

wp

Check:1 Go to yourTableName_options Move to 'option_id'- '1' Change 'yousite url' to 'localhost/youLocalSiteFolderName'

Move to 'option_id' - '37' Change homw value to 'localhost/youLocalSiteFolderName'

Check:2 Move to 'wp_config' file check : $table_prefix = 'yourNew_Prefix_';

Hope it will help

JAXB: how to marshall map into <key>value</key>

(Sorry, can't add comments)

In Blaise's answer above, if you change:

@XmlJavaTypeAdapter(MapAdapter.class)
public Map<String, String> getMapProperty() {
    return mapProperty;
}

to:

@XmlJavaTypeAdapter(MapAdapter.class)
@XmlPath(".") // <<-- add this
public Map<String, String> getMapProperty() {
    return mapProperty;
}

then this should get rid of the <mapProperty> tag, and so give you:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <map>
        <key>value</key>
        <key2>value2</key2>
    </map>
</root>

ALTERNATIVELY:

You can also change it to:

@XmlJavaTypeAdapter(MapAdapter.class)
@XmlAnyElement // <<-- add this
public Map<String, String> getMapProperty() {
    return mapProperty;
}

and then you can get rid of AdaptedMap altogether, and just change MapAdapter to marshall to a Document object directly. I've only tested this with marshalling, so there may be unmarshalling issues.

I'll try and find the time to knock up a full example of this, and edit this post accordingly.

Should a RESTful 'PUT' operation return something

There's a difference between the header and body of a HTTP response. PUT should never return a body, but must return a response code in the header. Just choose 200 if it was successful, and 4xx if not. There is no such thing as a null return code. Why do you want to do this?

No Main class found in NetBeans

I also experienced Netbeans complaining to me about "No main classes found". The issue was on a project I knew worked in the past, but failed when I tried it on another pc.

My specific failure reasons probably differ from the OP, but I'll still share what I learnt on the debugging journey, in-case these insights help anybody figure out their own unique issues relating to this topic.

What I learnt is that upon starting NetBeans, it should perform a step called "Scanning projects..." Scanning projects...

Prior to this phase, you should notice that any .java file you have with a main() method within it will show up in the 'Projects' pane with its icon looking like this (no arrow):

icon before scanning

After this scanning phase finishes, if a main() method was discovered within the file, that file's icon will change to this (with arrow):

icon after scanning

So on my system, it appeared this "Scanning projects..." step was failing, and instead would be stuck on an "Opening Projects" step.

I also noticed a little red icon in the bottom-right corner which hinted at the issue ailing me:

Unexpected exception

Unexpected Exception
java.lang.ExceptionInInitializerError

Clicking on that link showed me more details of the error:

java.security.NoSuchAlgorithmException: MD5 MessageDigest not available
    at sun.security.jca.GetInstance.getInstance(GetInstance.java:159)
    at java.security.Security.getImpl(Security.java:695)
    at java.security.MessageDigest.getInstance(MessageDigest.java:167)
    at org.apache.lucene.store.FSDirectory.<clinit>(FSDirectory.java:113)
Caused: java.lang.RuntimeException
    at org.apache.lucene.store.FSDirectory.<clinit>(FSDirectory.java:115)
Caused: java.lang.ExceptionInInitializerError
    at org.netbeans.modules.parsing.lucene.LuceneIndex$DirCache.createFSDirectory(LuceneIndex.java:839)

That mention of "java.security" reminded me that I had fiddled with this machine's "java.security" file (to be specific, I was performing Salvador Valencia's steps from this thread, but did it incorrectly and broke "java.security" in the process :))

Once I repaired the damage I caused to my "java.security" file, NetBeans' "Scanning projects..." step started to work again, the little green arrows appeared on my files once more and I no longer got that "No main classes found" issue.

AngularJs: Reload page

I would suggest to refer the page. Official suggestion

https://docs.angularjs.org/guide/$location

enter image description here

A non well formed numeric value encountered

This helped me a lot -

$new_date = date_format(date_create($old_date), 'Y-m-d');

Here, date_create() provides you a date object for a given date & date_format() will set it in a given format.

for example,

<?php
    $date = date_create("13-02-2013");  // DateTime Object ( [date] => 2013-02-13 00:00:00.000000 [timezone_type] => 3 [timezone] => America/New_York )
    echo date_format($date,"Y-m-d");    // 2013-02-13
?>

Change language of Visual Studio 2017 RC

You need reinstall VS.

Language Pack Support in Visual Studio 2017 RC

Issue:

This release of Visual Studio supports only a single language pack for the user interface. You cannot install two languages for the user interface in the same instance of Visual Studio. In addition, you must select the language of Visual Studio during the initial install, and cannot change it during Modify.

Workaround:

These are known issues that will be fixed in an upcoming release. To change the language in this release, you can uninstall and reinstall Visual Studio.

Reference: https://www.visualstudio.com/en-us/news/releasenotes/vs2017-relnotes#november-16-2016

How do I push amended commit to the remote Git repository?

Short answer: Don't push amended commits to a public repo.

Long answer: A few Git commands, like git commit --amend and git rebase, actually rewrite the history graph. This is fine as long as you haven't published your changes, but once you do, you really shouldn't be mucking around with the history, because if someone already got your changes, then when they try to pull again, it might fail. Instead of amending a commit, you should just make a new commit with the changes.

However, if you really, really want to push an amended commit, you can do so like this:

$ git push origin +master:master

The leading + sign will force the push to occur, even if it doesn't result in a "fast-forward" commit. (A fast-forward commit occurs when the changes you are pushing are a direct descendant of the changes already in the public repo.)

Floating elements within a div, floats outside of div. Why?

The easiest is to put overflow:hidden on the parent div and don't specify a height:

#parent { overflow: hidden }

Another way is to also float the parent div:

#parent { float: left; width: 100% }

Another way uses a clear element:

<div class="parent">
   <img class="floated_child" src="..." />
   <span class="clear"></span>
</div>

CSS

span.clear { clear: left; display: block; }

SQL Server 100% CPU Utilization - One database shows high CPU usage than others

According to this article on sqlserverstudymaterial;

Remember that "%Privileged time" is not based on 100%.It is based on number of processors.If you see 200 for sqlserver.exe and the system has 8 CPU then CPU consumed by sqlserver.exe is 200 out of 800 (only 25%).

If "% Privileged Time" value is more than 30% then it's generally caused by faulty drivers or anti-virus software. In such situations make sure the BIOS and filter drives are up to date and then try disabling the anti-virus software temporarily to see the change.

If "% User Time" is high then there is something consuming of SQL Server. There are several known patterns which can be caused high CPU for processes running in SQL Server including

exceeds the list view threshold 5000 items in Sharepoint 2010

The setting for the list throttle

  • Open the SharePoint Central Administration,
  • go to Application Management --> Manage Web Applications
  • Click to select the web application that hosts your list (eg. SharePoint - 80)
  • At the Ribbon, select the General Settings and select Resource Throttling
  • Then, you can see the 5000 List View Threshold limit and you can edit the value you want.
  • Click OK to save it.

For addtional reading: http://blogs.msdn.com/b/dinaayoub/archive/2010/04/22/sharepoint-2010-how-to-change-the-list-view-threshold.aspx

How to ignore a particular directory or file for tslint?

Currently using Visual Studio Code and the command to disable tslint is

/* tslint:disable */

Something to note. The disable above disables ALL tslint rules on that page. If you want to disable a specific rule you can specify one/multiple rules.

/* tslint:disable comment-format */
/* tslint:disable:rule1 rule2 rule3 etc.. */

Or enable a rule

/* tslint:enable comment-format */

More in depth on TSLint rule flags

Reactjs - Form input validation

Try powerform-react . It is based upon powerform which is a super portable Javascript form library. Once learnt, it can be used in any framework. It works even with vanilla Javascript.

Checkout this simple form that uses powerform-react

There is also a complex example.

How to remove all the occurrences of a char in c++ string

Using copy_if:

#include <string>
#include <iostream>
#include <algorithm>
int main() {
    std::string s1 = "a1a2b3c4a5";
    char s2[256];
    std::copy_if(s1.begin(), s1.end(), s2, [](char c){return c!='a';});
    std::cout << s2 << std::endl;
    return 0;
}

GitHub Error Message - Permission denied (publickey)

This Worked for me

There are 2 options in github - HTTPS/SSH

I had selected SSH by mistake due to which the error was occuring -_-

Switch it to HTTPS and then copy the url again and try :)

How can I print out just the index of a pandas dataframe?

You can use lamba function:

index = df.index[lambda x : for x in df.index() ]
print(index)

Number of rows affected by an UPDATE in PL/SQL

You use the sql%rowcount variable.

You need to call it straight after the statement which you need to find the affected row count for.

For example:

set serveroutput ON; 
DECLARE 
    i NUMBER; 
BEGIN 
    UPDATE employees 
    SET    status = 'fired' 
    WHERE  name LIKE '%Bloggs'; 
    i := SQL%rowcount; 
    --note that assignment has to precede COMMIT
    COMMIT; 
    dbms_output.Put_line(i); 
END; 

Passing arguments to AsyncTask, and returning results

You can receive returning results like that: AsyncTask class

@Override
protected Boolean doInBackground(Void... params) {
    if (host.isEmpty() || dbName.isEmpty() || user.isEmpty() || pass.isEmpty() || port.isEmpty()) {
        try {
            throw new SQLException("Database credentials missing");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    try {
        Class.forName("org.postgresql.Driver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

    try {
        this.conn = DriverManager.getConnection(this.host + ':' + this.port + '/' + this.dbName, this.user, this.pass);
    } catch (SQLException e) {
        e.printStackTrace();
    }

    return true;
}

receiving class:

_store.execute();
boolean result =_store.get();

Hoping it will help.

How do I return a proper success/error message for JQuery .ajax() using PHP?

...you may also want to check for cross site scripting issues...if your html pages comes from a different domain/port combi then your rest service, your browser may block the call.

Typically, right mouse->inspect on your html page. Then look in the error console for errors like

Access to XMLHttpRequest at '...:8080' from origin '...:8383' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

How to select the first row of each group?

A nice way of doing this with the dataframe api is using the argmax logic like so

  val df = Seq(
    (0,"cat26",30.9), (0,"cat13",22.1), (0,"cat95",19.6), (0,"cat105",1.3),
    (1,"cat67",28.5), (1,"cat4",26.8), (1,"cat13",12.6), (1,"cat23",5.3),
    (2,"cat56",39.6), (2,"cat40",29.7), (2,"cat187",27.9), (2,"cat68",9.8),
    (3,"cat8",35.6)).toDF("Hour", "Category", "TotalValue")

  df.groupBy($"Hour")
    .agg(max(struct($"TotalValue", $"Category")).as("argmax"))
    .select($"Hour", $"argmax.*").show

 +----+----------+--------+
 |Hour|TotalValue|Category|
 +----+----------+--------+
 |   1|      28.5|   cat67|
 |   3|      35.6|    cat8|
 |   2|      39.6|   cat56|
 |   0|      30.9|   cat26|
 +----+----------+--------+

Combining a class selector and an attribute selector with jQuery

This will also work:

$(".myclass[reference='12345']").css('border', '#000 solid 1px');

Environment variable substitution in sed

Your two examples look identical, which makes problems hard to diagnose. Potential problems:

  1. You may need double quotes, as in sed 's/xxx/'"$PWD"'/'

  2. $PWD may contain a slash, in which case you need to find a character not contained in $PWD to use as a delimiter.

To nail both issues at once, perhaps

sed 's@xxx@'"$PWD"'@'

How to allow only numeric (0-9) in HTML inputbox using jQuery?

This is what I use to validate number inputs for integer or float values (unobtrusive style with jQuery):

_x000D_
_x000D_
$('input[name="number"]').keyup(function(e) {_x000D_
    var float = parseFloat($(this).attr('data-float'));_x000D_
_x000D_
    /* 2 regexp for validating integer and float inputs *****_x000D_
        > integer_regexp : allow numbers, but do not allow leading zeros_x000D_
        > float_regexp : allow numbers + only one dot sign (and only in the middle of the string), but do not allow leading zeros in the integer part_x000D_
    *************************************************************************/_x000D_
    var integer_regexp = (/[^0-9]|^0+(?!$)/g);_x000D_
    var float_regexp = (/[^0-9\.]|^\.+(?!$)|^0+(?=[0-9]+)|\.(?=\.|.+\.)/g);_x000D_
_x000D_
    var regexp = (float % 1 === 0) ? integer_regexp : float_regexp;_x000D_
    if (regexp.test(this.value)) {_x000D_
        this.value = this.value.replace(regexp, '');_x000D_
    }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="text" data-float="1" id="number" name="number" placeholder="integer">_x000D_
<input type="text" data-float="0.1" id="number" name="number" placeholder="float">
_x000D_
_x000D_
_x000D_

How to get resources directory path programmatically

import org.springframework.core.io.ClassPathResource;

...

File folder = new ClassPathResource("sql").getFile();
File[] listOfFiles = folder.listFiles();

It is worth noting that this will limit your deployment options, ClassPathResource.getFile() only works if the container has exploded (unzipped) your war file.

Directing print output to a .txt file

Use the logging module

def init_logging():
    rootLogger = logging.getLogger('my_logger')

    LOG_DIR = os.getcwd() + '/' + 'logs'
    if not os.path.exists(LOG_DIR):
        os.makedirs(LOG_DIR)
    fileHandler = logging.FileHandler("{0}/{1}.log".format(LOG_DIR, "g2"))
    rootLogger.addHandler(fileHandler)

    rootLogger.setLevel(logging.DEBUG)

    consoleHandler = logging.StreamHandler()
    rootLogger.addHandler(consoleHandler)

    return rootLogger

Get the logger:

logger = init_logging()

And start logging/output(ing):

logger.debug('Hi! :)')

How to load/reference a file as a File instance from the classpath

Or use directly the InputStream of the resource using the absolute CLASSPATH path (starting with the / slash character):


getClass().getResourceAsStream("/com/path/to/file.txt");

Or relative CLASSPATH path (when the class you are writing is in the same Java package as the resource file itself, i.e. com.path.to):


getClass().getResourceAsStream("file.txt");

How do I load an org.w3c.dom.Document from XML in a string?

This works for me in Java 1.5 - I stripped out specific exceptions for readability.

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import java.io.ByteArrayInputStream;

public Document loadXMLFromString(String xml) throws Exception
{
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();

    return builder.parse(new ByteArrayInputStream(xml.getBytes()));
}

how to use XPath with XDocument?

XPath 1.0, which is what MS implements, does not have the idea of a default namespace. So try this:

XDocument xdoc = XDocument.Load(@"C:\SampleXML.xml");
XmlNamespaceManager xnm = new XmlNamespaceManager(new NameTable()); 
xnm.AddNamespace("x", "http://demo.com/2011/demo-schema");
Console.WriteLine(xdoc.XPathSelectElement("/x:Report/x:ReportInfo/x:Name", xnm) == null);

How to use Session attributes in Spring-mvc

Use @SessionAttributes

See the docs: Using @SessionAttributes to store model attributes in the HTTP session between requests

"Understanding Spring MVC Model And Session Attributes" also gives a very good overview of Spring MVC sessions and explains how/when @ModelAttributes are transferred into the session (if the controller is @SessionAttributes annotated).

That article also explains that it is better to use @SessionAttributes on the model instead of setting attributes directly on the HttpSession because that helps Spring MVC to be view-agnostic.

How can I create an array/list of dictionaries in python?

I assume that motifWidth contains an integer.

In Python, lists do not change size unless you tell them to. Hence, Python throws an exception when you try to change an element that isn't there. I believe you want:

weightMatrix = []
for k in range(motifWidth):
    weightMatrix.append({'A':0,'C':0,'G':0,'T':0})

For what it's worth, when asking questions in the future, it would help if you included the stack trace showing the error that you're getting rather than just saying "it isn't working". That would help us directly figure out the cause of the problem, rather than trying to puzzle it out from your code.

Hope that helps!

How to terminate a window in tmux?

For me solution looks like:

  1. ctrl+b q to show pane numbers.
  2. ctrl+b x to kill pane.

Killing last pane will kill window.

How to delete Certain Characters in a excel 2010 cell

Replace [ with nothing, then ] with nothing.

Difference between OData and REST web services

REST stands for REpresentational State Transfer which is a resource based architectural style. Resource based means that data and functionalities are considered as resources.

OData is a web based protocol that defines a set of best practices for building and consuming RESTful web services. OData is a way to create RESTful web services thus an implementation of REST.

Use python requests to download CSV

To simplify these answers, and increase performance when downloading a large file, the below may work a bit more efficiently.

import requests
from contextlib import closing
import csv

url = "http://download-and-process-csv-efficiently/python.csv"

with closing(requests.get(url, stream=True)) as r:
    reader = csv.reader(r.iter_lines(), delimiter=',', quotechar='"')
    for row in reader:
        print row   

By setting stream=True in the GET request, when we pass r.iter_lines() to csv.reader(), we are passing a generator to csv.reader(). By doing so, we enable csv.reader() to lazily iterate over each line in the response with for row in reader.

This avoids loading the entire file into memory before we start processing it, drastically reducing memory overhead for large files.

Difference between signed / unsigned char

There are three char types: (plain) char, signed char and unsigned char. Any char is usually an 8-bit integer* and in that sense, a signed and unsigned char have a useful meaning (generally equivalent to uint8_t and int8_t). When used as a character in the sense of text, use a char (also referred to as a plain char). This is typically a signed char but can be implemented either way by the compiler.

* Technically, a char can be any size as long as sizeof(char) is 1, but it is usually an 8-bit integer.

How do I drag and drop files into an application?

Yet another gotcha:

The framework code that calls the Drag-events swallow all exceptions. You might think your event code is running smoothly, while it is gushing exceptions all over the place. You can't see them because the framework steals them.

That's why I always put a try/catch in these event handlers, just so I know if they throw any exceptions. I usually put a Debugger.Break(); in the catch part.

Before release, after testing, if everything seems to behave, I remove or replace these with real exception handling.

Generic Property in C#

You would need to create a generic class named MyProp. Then, you will need to add implicit or explicit cast operators so you can get and set the value as if it were the type specified in the generic type parameter. These cast operators can do the extra work that you need.

Sort a single String in Java

Question: sort a string in java

public class SortAStringInJava {
    public static void main(String[] args) {

        String str = "Protijayi";
// Method 1
        str = str.chars() // IntStream
                .sorted().collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString();

        System.out.println(str);
        // Method 2
        str = Stream.of(str.split(" ")).sorted().collect(Collectors.joining());
        System.out.println(str);
    }
}

MySql Inner Join with WHERE clause


1. Change the INNER JOIN before the WHERE clause.
2. You have two WHEREs which is not allowed.

Try this:

SELECT table1.f_id FROM table1
  INNER JOIN table2 
     ON (table2.f_id = table1.f_id AND table2.f_type = 'InProcess') 
   WHERE table1.f_com_id = '430' AND table1.f_status = 'Submitted'

Blurry text after using CSS transform: scale(); in Chrome

My solution was:

display: initial;

Then it was crispy sharp

Is ASCII code 7-bit or 8-bit?

ASCII encoding is 7-bit, but in practice, characters encoded in ASCII are not stored in groups of 7 bits. Instead, one ASCII is stored in a byte, with the MSB usually set to 0 (yes, it's wasted in ASCII).

You can verify this by inputting a string in the ASCII character set in a text editor, setting the encoding to ASCII, and viewing the binary/hex:
enter image description here

Aside: the use of (strictly) ASCII encoding is now uncommon, in favor of UTF-8 (which does not waste the MSB mentioned above - in fact, an MSB of 1 indicates the code point is encoded with more than 1 byte).

Laravel Eloquent LEFT JOIN WHERE NULL

I would dump your query so you can take a look at the SQL that was actually executed and see how that differs from what you wrote.

You should be able to do that with the following code:

$queries = DB::getQueryLog();
$last_query = end($queries);
var_dump($last_query);
die();

Hopefully that should give you enough information to allow you to figure out what's gone wrong.

How to remove focus around buttons on click

If you dont want the outline for button with all the status, you can override the css with below code

.btn.active.focus, .btn.active:focus, 
.btn.focus, .btn:active.focus, 
.btn:active:focus, .btn:focus{
  outline: none;
}

How to write a link like <a href="#id"> which link to the same page in PHP?

Edit:

Are you trying to do sth like this? See: http://twitter.github.com/bootstrap/javascript.html#tabs


See the working example: http://jsfiddle.net/U6aKT/

<a href="#id">go to id</a>
<div style="margin-top:2000px;"></div>
<a id="id">id</a>

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

Try following code:

File file = new File("infilename");

// Get the number of bytes in the file
long sizeInBytes = file.length();
//transform in MB
long sizeInMb = sizeInBytes / (1024 * 1024);

Git copy changes from one branch to another

This is 2 step process

  • git checkout BranchB ( destination branch is BranchB, so we need the head on this branch)
  • git merge BranchA (it will merge BranchB with BranchA. Here you have merged code in branch B)

If you want to push your branch code to remote repo then do

  • git push origin master (it will push your BranchB code to remote repo)

Should I set max pool size in database connection string? What happens if I don't?

We can define maximum pool size in following way:

                <pool> 
               <min-pool-size>5</min-pool-size>
                <max-pool-size>200</max-pool-size>
                <prefill>true</prefill>
                <use-strict-min>true</use-strict-min>
                <flush-strategy>IdleConnections</flush-strategy>
                </pool>

SyntaxError: Cannot use import statement outside a module

My solution was to include babel-node path while running nodemon as follows:

nodemon node_modules/.bin/babel-node index.js

you can add in your package.json script as :

debug: nodemon node_modules/.bin/babel-node index.js

NOTE: My entry file is index.js replace it with your entry file (many have app.js/server.js).

How to set JAVA_HOME in Linux for all users

This is a very simple script to solve the problem

export JAVA_HOME_BIN=`which java`
export JAVA_HOME_DIR=`dirname $JAVA_HOME_BIN`
export JAVA_HOME=`dirname $JAVA_HOME_DIR`

And for testing:

echo $JAVA_HOME

Email and phone Number Validation in android

I am always using this methode for Email Validation:

public boolean checkForEmail(Context c, EditText edit) {
    String str = edit.getText().toString();
    if (android.util.Patterns.EMAIL_ADDRESS.matcher(str).matches()) {
        return true;
    }
    Toast.makeText(c, "Email is not valid...", Toast.LENGTH_LONG).show();
    return false;
}

How to render an array of objects in React?

Try this:

_x000D_
_x000D_
class First extends React.Component {
  constructor (props){
    super(props);

  }

  render() {
     const data =[{"name":"test1"},{"name":"test2"}];
    const listItems = data.map((d) => <li key={d.name}>{d.name}</li>;
    
    return (
      <div>
      {listItems}
      </div>
    );
  }
} 
_x000D_
_x000D_
_x000D_

Powershell get ipv4 address into a variable

Here is another solution:

$env:HostIP = (
    Get-NetIPConfiguration |
    Where-Object {
        $_.IPv4DefaultGateway -ne $null -and
        $_.NetAdapter.Status -ne "Disconnected"
    }
).IPv4Address.IPAddress

how to change default python version?

Check the location of python 3

$ which python3
/usr/local/bin/python3

Write alias in bash_profile

vi ~/.bash_profile  
alias python='/usr/local/bin/python3'

Reload bash_profile

source ~/.bash_profile

Confirm python command

$ python --version
Python 3.6.5

How is "mvn clean install" different from "mvn install"?

To stick with the Maven terms:

  • "clean" is a phase of the clean lifecycle
  • "install" is a phase of the default lifecycle

http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html#Lifecycle_Reference

Does WGET timeout?

Prior to version 1.14, wget timeout arguments were not adhered to if downloading over https due to a bug.

twitter bootstrap text-center when in xs mode

There is nothing built into bootstrap for this, but some simple css could fix it. Something like this should work. Not tested though

 @media (max-width: 768px) {
      .col-xs-12.text-right, .col-xs-12.text-left {
              text-align: center;
       } 
    }

Does WhatsApp offer an open API?

1) It looks possible. This info on Github describes how to create a java program to send a message using the whatsapp encryption protocol from WhisperSystems.

2) No. See the whatsapp security white paper.

3) See #1.

Side-by-side list items as icons within a div (css)

This can be a pure CSS solution. Given:

<ul class="tileMe">
    <li>item 1<li>
    <li>item 2<li>
    <li>item 3<li>
</ul>

The CSS would be:

.tileMe li {
    display: inline;
    float: left;
}

Now, since you've changed the display mode from 'block' (implied) to 'inline', any padding, margin, width, or height styles you applied to li elements will not work. You need to nest a block-level element inside the li:

<li><a class="tile" href="home">item 1</a></li>

and add the following CSS:

.tile a {
    display: block;
    padding: 10px;
    border: 1px solid red;
    margin-right: 5px;
}

The key concept behind this solution is that you are changing the display style of the li to 'inline', and nesting a block-level element inside to achieve the consistent tiling effect.

"Cannot send session cache limiter - headers already sent"

"Headers already sent" means that your PHP script already sent the HTTP headers, and as such it can't make modifications to them now.

Check that you don't send ANY content before calling session_start. Better yet, just make session_start the first thing you do in your PHP file (so put it at the absolute beginning, before all HTML etc).

Fatal error: Call to undefined function sqlsrv_connect()

i have same this because in httpd.conf in apache PHPIniDir D:/wamp/bin/php/php5.5.12 that was incorrect

Function for Factorial in Python

def fact(n):
    f = 1
    for i in range(1, n + 1):
        f *= i
    return f

Why does IE9 switch to compatibility mode on my website?

I put

<meta http-equiv="X-UA-Compatible" content="IE=Edge"/>

first thing after

<head>

(I read it somewhere, I can't recall)

I could not believe it did work!!

What is secret key for JWT based authentication and how to generate it?

A Json Web Token made up of three parts. The header, the payload and the signature Now the header is just some metadata about the token itself and the payload is the data that we can encode into the token, any data really that we want. So the more data we want to encode here the bigger the JWT. Anyway, these two parts are just plain text that will get encoded, but not encrypted.

So anyone will be able to decode them and to read them, we cannot store any sensitive data in here. But that's not a problem at all because in the third part, so in the signature, is where things really get interesting. The signature is created using the header, the payload, and the secret that is saved on the server.

And this whole process is then called signing the Json Web Token. The signing algorithm takes the header, the payload, and the secret to create a unique signature. So only this data plus the secret can create this signature, all right? Then together with the header and the payload, these signature forms the JWT, which then gets sent to the client. enter image description here

Once the server receives a JWT to grant access to a protected route, it needs to verify it in order to determine if the user really is who he claims to be. In other words, it will verify if no one changed the header and the payload data of the token. So again, this verification step will check if no third party actually altered either the header or the payload of the Json Web Token.

So, how does this verification actually work? Well, it is actually quite straightforward. Once the JWT is received, the verification will take its header and payload, and together with the secret that is still saved on the server, basically create a test signature.

But the original signature that was generated when the JWT was first created is still in the token, right? And that's the key to this verification. Because now all we have to do is to compare the test signature with the original signature. And if the test signature is the same as the original signature, then it means that the payload and the header have not been modified. enter image description here

Because if they had been modified, then the test signature would have to be different. Therefore in this case where there has been no alteration of the data, we can then authenticate the user. And of course, if the two signatures are actually different, well, then it means that someone tampered with the data. Usually by trying to change the payload. But that third party manipulating the payload does of course not have access to the secret, so they cannot sign the JWT. So the original signature will never correspond to the manipulated data. And therefore, the verification will always fail in this case. And that's the key to making this whole system work. It's the magic that makes JWT so simple, but also extremely powerful.

Now let's do some practices with nodejs:

Configuration file is perfect for storing JWT SECRET data. Using the standard HSA 256 encryption for the signature, the secret should at least be 32 characters long, but the longer the better.

config.env:

JWT_SECRET = my-32-character-ultra-secure-and-ultra-long-secret
//after 90days JWT will no longer be valid, even the signuter is correct and everything is matched.
JWT_EXPIRES_IN=90

now install JWT using command

npm i jsonwebtoken

Example after user signup passing him JWT token so he can stay logged in and get access of resources.

exports.signup = catchAsync(async (req, res, next) => {
  const newUser = await User.create({
    name: req.body.name,
    email: req.body.email,
    password: req.body.password,
    passwordConfirm: req.body.passwordConfirm,
  });
  const token = jwt.sign({ id: newUser._id }, process.env.JWT_SECRET, {
    expiresIn: process.env.JWT_EXPIRES_IN,
  });

  res.status(201).json({
    status: 'success',
    token,
    data: {
      newUser,
    },
  });
});

output: enter image description here

In my opinion, do not take help from a third-party to generate your super-secret key, because you can't say it's secret anymore. Just use your keyboard.

Int to Decimal Conversion - Insert decimal point at specified location

int i = 7122960;
decimal d = (decimal)i / 100;

CodeIgniter - How to return Json response from controller

return $this->output
            ->set_content_type('application/json')
            ->set_status_header(500)
            ->set_output(json_encode(array(
                    'text' => 'Error 500',
                    'type' => 'danger'
            )));

what happens when you type in a URL in browser

Attention: this is an extremely rough and oversimplified sketch, assuming the simplest possible HTTP request (no HTTPS, no HTTP2, no extras), simplest possible DNS, no proxies, single-stack IPv4, one HTTP request only, a simple HTTP server on the other end, and no problems in any step. This is, for most contemporary intents and purposes, an unrealistic scenario; all of these are far more complex in actual use, and the tech stack has become an order of magnitude more complicated since this was written. With this in mind, the following timeline is still somewhat valid:

  1. browser checks cache; if requested object is in cache and is fresh, skip to #9
  2. browser asks OS for server's IP address
  3. OS makes a DNS lookup and replies the IP address to the browser
  4. browser opens a TCP connection to server (this step is much more complex with HTTPS)
  5. browser sends the HTTP request through TCP connection
  6. browser receives HTTP response and may close the TCP connection, or reuse it for another request
  7. browser checks if the response is a redirect or a conditional response (3xx result status codes), authorization request (401), error (4xx and 5xx), etc.; these are handled differently from normal responses (2xx)
  8. if cacheable, response is stored in cache
  9. browser decodes response (e.g. if it's gzipped)
  10. browser determines what to do with response (e.g. is it a HTML page, is it an image, is it a sound clip?)
  11. browser renders response, or offers a download dialog for unrecognized types

Again, discussion of each of these points have filled countless pages; take this only as a summary, abridged for the sake of clarity. Also, there are many other things happening in parallel to this (processing typed-in address, speculative prefetching, adding page to browser history, displaying progress to user, notifying plugins and extensions, rendering the page while it's downloading, pipelining, connection tracking for keep-alive, cookie management, checking for malicious content etc.) - and the whole operation gets an order of magnitude more complex with HTTPS (certificates and ciphers and pinning, oh my!).

Convert java.util.Date to java.time.LocalDate

Short answer

Date input = new Date();
LocalDate date = input.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

Explanation

Despite its name, java.util.Date represents an instant on the time-line, not a "date". The actual data stored within the object is a long count of milliseconds since 1970-01-01T00:00Z (midnight at the start of 1970 GMT/UTC).

The equivalent class to java.util.Date in JSR-310 is Instant, thus there is a convenient method toInstant() to provide the conversion:

Date input = new Date();
Instant instant = input.toInstant();

A java.util.Date instance has no concept of time-zone. This might seem strange if you call toString() on a java.util.Date, because the toString is relative to a time-zone. However that method actually uses Java's default time-zone on the fly to provide the string. The time-zone is not part of the actual state of java.util.Date.

An Instant also does not contain any information about the time-zone. Thus, to convert from an Instant to a local date it is necessary to specify a time-zone. This might be the default zone - ZoneId.systemDefault() - or it might be a time-zone that your application controls, such as a time-zone from user preferences. Use the atZone() method to apply the time-zone:

Date input = new Date();
Instant instant = input.toInstant();
ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());

A ZonedDateTime contains state consisting of the local date and time, time-zone and the offset from GMT/UTC. As such the date - LocalDate - can be easily extracted using toLocalDate():

Date input = new Date();
Instant instant = input.toInstant();
ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
LocalDate date = zdt.toLocalDate();

Java 9 answer

In Java SE 9, a new method has been added that slightly simplifies this task:

Date input = new Date();
LocalDate date = LocalDate.ofInstant(input.toInstant(), ZoneId.systemDefault());

This new alternative is more direct, creating less garbage, and thus should perform better.

How to change the output color of echo in Linux

My riff on Tobias' answer:

# Color
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m' # No Color

function red {
    printf "${RED}$@${NC}\n"
}

function green {
    printf "${GREEN}$@${NC}\n"
}

function yellow {
    printf "${YELLOW}$@${NC}\n"
}

$ echo $(red apple) $(yellow banana) $(green kiwi)
apple banana kiwi

Reading from file using read() function

I am reading some data from a file using read. Here I am reading data in a 2d char pointer but the method is the same for the 1d also. Just read character by character and do not worry about the exceptions because the condition in the while loop is handling the exceptions :D

  while ( (n = read(fd, buffer,1)) > 0 )
{   

if(buffer[0] == '\n')
{
  r++;
  char**tempData=(char**)malloc(sizeof(char*)*r);

  for(int a=0;a<r;a++)
  {
    tempData[a]=(char*)malloc(sizeof(char)*BUF_SIZE);
    memset(tempData[a],0,BUF_SIZE);
  }

  for(int a=0;a<r-1;a++)
  {
    strcpy(tempData[a],data[a]);
  }

   data=tempData;

   c=0;
}

else
{
  data[r-1][c]=buffer[0];
  c++;
  buffer[1]='\0';
}

   }

On Windows, running "import tensorflow" generates No module named "_pywrap_tensorflow" error

One may be tempted to keep the Powershell/cmd open on Windows. I've spent reasonable time till I decided to close and reopen my Powershell only to realize that I've done everything right.

Changing tab bar item image and text color iOS

I know here are lots of answers but I can't find an easy and valid copy/paste answer for Swift 4.2/ Swift 5.1

tabBarController?.tabBar.tintColor = UIColor.red
tabBarController?.tabBar.unselectedItemTintColor = UIColor.green

Or use UITabBar.appearances() instead of tabBarController?.tabBar like this:

UITabBar.appearances().tintColor = UIColor.red
UITabBar.appearances().unselectedItemTintColor = UIColor.green

Images have to be UIImageRenderingModeAlwaysTemplate

Disable Auto Zoom in Input "Text" tag - Safari on iPhone

@media screen and (-webkit-min-device-pixel-ratio:0) { 
  select:focus,
  textarea:focus,
  input:focus {
    font-size: 16px;
    background: #eee;
  }
}

New: IOS will still zoom, unless you use 16px on the input without the focus.

@media screen and (-webkit-min-device-pixel-ratio:0) { 
  select,
  textarea,
  input {
    font-size: 16px;
  }
}

I added a background since IOS adds no background on the select.

How to call javascript function from code-behind

If the order of the execution is not important and you need both some javascript AND some codebehind to be fired on an asp element, heres what you can do.

What you can take away from my example: I have a div covering the ASP control that I want both javascript and codebehind to be ran from. The div's onClick method AND the calendar's OnSelectionChanged event both get fired this way.

In this example, i am using an ASP Calendar control, and im controlling it from both javascript and codebehind:

Front end code:

        <div onclick="showHideModal();">
            <asp:Calendar 
                OnSelectionChanged="DatepickerDateChange" ID="DatepickerCalendar" runat="server" 
                BorderWidth="1px" DayNameFormat="Shortest" Font-Names="Verdana" 
                Font-Size="8pt" ShowGridLines="true" BackColor="#B8C9E1" BorderColor="#003E51" Width="100%"> 
                <OtherMonthDayStyle ForeColor="#6C5D34"> </OtherMonthDayStyle> 
                <DayHeaderStyle  ForeColor="black" BackColor="#D19000"> </DayHeaderStyle>
                <TitleStyle BackColor="#B8C9E1" ForeColor="Black"> </TitleStyle> 
                <DayStyle BackColor="White"> </DayStyle> 
                <SelectedDayStyle BackColor="#003E51" Font-Bold="True"> </SelectedDayStyle> 
            </asp:Calendar>
        </div>

Codebehind:

        protected void DatepickerDateChange(object sender, EventArgs e)
        {
            if (toFromPicked.Value == "MainContent_fromDate")
            {
                fromDate.Text = DatepickerCalendar.SelectedDate.ToShortDateString();
            }
            else
            {
                toDate.Text = DatepickerCalendar.SelectedDate.ToShortDateString();
            }
        }

Python: Continuing to next iteration in outer loop

Another way to deal with this kind of problem is to use Exception().

for ii in range(200):
    try:
        for jj in range(200, 400):
            ...block0...
            if something:
                raise Exception()
    except Exception:
        continue
    ...block1...

For example:

for n in range(1,4):
    for m in range(1,4):
        print n,'-',m

result:

    1-1
    1-2
    1-3
    2-1
    2-2
    2-3
    3-1
    3-2
    3-3

Assuming we want to jump to the outer n loop from m loop if m =3:

for n in range(1,4):
    try:
        for m in range(1,4):
            if m == 3:
                raise Exception()            
            print n,'-',m
    except Exception:
        continue

result:

    1-1
    1-2
    2-1
    2-2
    3-1
    3-2

Reference link:http://www.programming-idioms.org/idiom/42/continue-outer-loop/1264/python

how to compare the Java Byte[] array?

There's a faster way to do that:

Arrays.hashCode(arr1) == Arrays.hashCode(arr2)

How can I get the current user's username in Bash?

The current user's username can be gotten in pure Bash with the ${parameter@operator} parameter expansion (introduced in Bash 4.4):

$ : \\u
$ printf '%s\n' "${_@P}"

The : built-in (synonym of true) is used instead of a temporary variable by setting the last argument, which is stored in $_. We then expand it (\u) as if it were a prompt string with the P operator.

This is better than using $USER, as $USER is just a regular environmental variable; it can be modified, unset, etc. Even if it isn't intentionally tampered with, a common case where it's still incorrect is when the user is switched without starting a login shell (su's default).

Is there a way to use PhantomJS in Python?

this is what I do, python3.3. I was processing huge lists of sites, so failing on the timeout was vital for the job to run through the entire list.

command = "phantomjs --ignore-ssl-errors=true "+<your js file for phantom>
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)

# make sure phantomjs has time to download/process the page
# but if we get nothing after 30 sec, just move on
try:
    output, errors = process.communicate(timeout=30)
except Exception as e:
    print("\t\tException: %s" % e)
    process.kill()

# output will be weird, decode to utf-8 to save heartache
phantom_output = ''
for out_line in output.splitlines():
    phantom_output += out_line.decode('utf-8')

How to use PHP's password_hash to hash and verify passwords

I’ve built a function I use all the time for password validation and to create passwords, e.g. to store them in a MySQL database. It uses a randomly generated salt which is way more secure than using a static salt.

function secure_password($user_pwd, $multi) {

/*
    secure_password ( string $user_pwd, boolean/string $multi ) 

    *** Description: 
        This function verifies a password against a (database-) stored password's hash or
        returns $hash for a given password if $multi is set to either true or false

    *** Examples:
        // To check a password against its hash
        if(secure_password($user_password, $row['user_password'])) {
            login_function();
        } 
        // To create a password-hash
        $my_password = 'uber_sEcUrE_pass';
        $hash = secure_password($my_password, true);
        echo $hash;
*/

// Set options for encryption and build unique random hash
$crypt_options = ['cost' => 11, 'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM)];
$hash = password_hash($user_pwd, PASSWORD_BCRYPT, $crypt_options);

// If $multi is not boolean check password and return validation state true/false
if($multi!==true && $multi!==false) {
    if (password_verify($user_pwd, $table_pwd = $multi)) {
        return true; // valid password
    } else {
        return false; // invalid password
    }
// If $multi is boolean return $hash
} else return $hash;

}

Evenly distributing n points on a sphere

This works and it's deadly simple. As many points as you want:

    private function moveTweets():void {


        var newScale:Number=Scale(meshes.length,50,500,6,2);
        trace("new scale:"+newScale);


        var l:Number=this.meshes.length;
        var tweetMeshInstance:TweetMesh;
        var destx:Number;
        var desty:Number;
        var destz:Number;
        for (var i:Number=0;i<this.meshes.length;i++){

            tweetMeshInstance=meshes[i];

            var phi:Number = Math.acos( -1 + ( 2 * i ) / l );
            var theta:Number = Math.sqrt( l * Math.PI ) * phi;

            tweetMeshInstance.origX = (sphereRadius+5) * Math.cos( theta ) * Math.sin( phi );
            tweetMeshInstance.origY= (sphereRadius+5) * Math.sin( theta ) * Math.sin( phi );
            tweetMeshInstance.origZ = (sphereRadius+5) * Math.cos( phi );

            destx=sphereRadius * Math.cos( theta ) * Math.sin( phi );
            desty=sphereRadius * Math.sin( theta ) * Math.sin( phi );
            destz=sphereRadius * Math.cos( phi );

            tweetMeshInstance.lookAt(new Vector3D());


            TweenMax.to(tweetMeshInstance, 1, {scaleX:newScale,scaleY:newScale,x:destx,y:desty,z:destz,onUpdate:onLookAtTween, onUpdateParams:[tweetMeshInstance]});

        }

    }
    private function onLookAtTween(theMesh:TweetMesh):void {
        theMesh.lookAt(new Vector3D());
    }

jQuery plugin returning "Cannot read property of undefined"

I had same problem with 'parallax' plugin. I changed jQuery librery version to *jquery-1.6.4* from *jquery-1.10.2*. And error cleared.

What is the best JavaScript code to create an img element

var img = document.createElement('img');
img.src = 'my_image.jpg';
document.getElementById('container').appendChild(img);

Can an abstract class have a constructor?

Yes, Abstract Classes can have constructors !

Here is an example using constructor in abstract class:

abstract class Figure { 

    double dim1;        
    double dim2; 

    Figure(double a, double b) {         
        dim1 = a;         
        dim2 = b;         
    }

    // area is now an abstract method 

   abstract double area(); 

}


class Rectangle extends Figure { 
    Rectangle(double a, double b) { 
        super(a, b); 
    } 
    // override area for rectangle 
    double area() { 
        System.out.println("Inside Area for Rectangle."); 
        return dim1 * dim2; 
    } 
}

class Triangle extends Figure { 
    Triangle(double a, double b) { 
        super(a, b); 
    } 
    // override area for right triangle 
    double area() { 
        System.out.println("Inside Area for Triangle."); 
        return dim1 * dim2 / 2; 
    } 
}

class AbstractAreas { 
    public static void main(String args[]) { 
        // Figure f = new Figure(10, 10); // illegal now 
        Rectangle r = new Rectangle(9, 5); 
        Triangle t = new Triangle(10, 8); 
        Figure figref; // this is OK, no object is created 
        figref = r; 
        System.out.println("Area is " + figref.area()); 
        figref = t; 
        System.out.println("Area is " + figref.area()); 
    } 
}

So I think you got the answer.

Get decimal portion of a number with JavaScript

Here's how I do it, which I think is the most straightforward way to do it:

var x = 3.2;
int_part = Math.trunc(x); // returns 3
float_part = Number((x-int_part).toFixed(2)); // return 0.2

Responding with a JSON object in Node.js (converting object/array to JSON string)

var objToJson = { };
objToJson.response = response;
response.write(JSON.stringify(objToJson));

If you alert(JSON.stringify(objToJson)) you will get {"response":"value"}

PostgreSQL - fetch the row which has the Max value for a column

I would propose a clean version based on DISTINCT ON (see docs):

SELECT DISTINCT ON (usr_id)
    time_stamp,
    lives_remaining,
    usr_id,
    trans_id
FROM lives
ORDER BY usr_id, time_stamp DESC, trans_id DESC;

C# string does not contain possible?

You should put all your words into some kind of Collection or List and then call it like this:

var searchFor = new List<string>();
searchFor.Add("pineapple");
searchFor.Add("mango");

bool containsAnySearchString = searchFor.Any(word => compareString.Contains(word));

If you need to make a case or culture independent search you should call it like this:

bool containsAnySearchString = 
   searchFor.Any(word => compareString.IndexOf
     (word, StringComparison.InvariantCultureIgnoreCase >= 0);

How to pass an object into a state using UI-router?

Btw you can also use the ui-sref attribute in your templates to pass objects

ui-sref="myState({ myParam: myObject })"

Differences between action and actionListener

ActionListener gets fired first, with an option to modify the response, before Action gets called and determines the location of the next page.

If you have multiple buttons on the same page which should go to the same place but do slightly different things, you can use the same Action for each button, but use a different ActionListener to handle slightly different functionality.

Here is a link that describes the relationship:

http://www.java-samples.com/showtutorial.php?tutorialid=605

Making an API call in Python with an API that requires a bearer token

If you are using requests module, an alternative option is to write an auth class, as discussed in "New Forms of Authentication":

import requests

class BearerAuth(requests.auth.AuthBase):
    def __init__(self, token):
        self.token = token
    def __call__(self, r):
        r.headers["authorization"] = "Bearer " + self.token
        return r

and then can you send requests like this

response = requests.get('https://www.example.com/', auth=BearerAuth('3pVzwec1Gs1m'))

which allows you to use the same auth argument just like basic auth, and may help you in certain situations.

How to control border height?

A border will always be at the full length of the containing box (the height of the element plus its padding), it can't be controlled except for adjusting the height of the element to which it applies. If all you need is a vertical divider, you could use:

<div id="left">
  content
</div>
<span class="divider"></span>
<div id="right">
  content
</div>

With css:

span {
 display: inline-block;
 width: 0;
 height: 1em;
 border-left: 1px solid #ccc;
 border-right: 1px solid #ccc;
}

Demo at JS Fiddle, adjust the height of the span.container to adjust the border 'height'.

Or, to use pseudo-elements (::before or ::after), given the following HTML:

<div id="left">content</div>
<div id="right">content</div>

The following CSS adds a pseudo-element before any div element that's the adjacent sibling of another div element:

div {
    display: inline-block;
    position: relative;
}

div + div {
    padding-left: 0.3em;
}

div + div::before {
    content: '';
    border-left: 2px solid #000;
    position: absolute;
    height: 50%;
    left: 0;
    top: 25%;
}

JS Fiddle demo.

What's the difference between "&nbsp;" and " "?

&nbsp; is stackable, meaning you can create multiple spaces all together.

HTML will only parse one space '' and it drops the rest...

If you want five spaces, you would place 5 x &nbsp;

python max function using 'key' and lambda expression

max function is used to get the maximum out of an iterable.

The iterators may be lists, tuples, dict objects, etc. Or even custom objects as in the example you provided.

max(iterable[, key=func]) -> value
max(a, b, c, ...[, key=func]) -> value

With a single iterable argument, return its largest item.
With two or more arguments, return the largest argument.

So, the key=func basically allows us to pass an optional argument key to the function on whose basis is the given iterator/arguments are sorted & the maximum is returned.

lambda is a python keyword that acts as a pseudo function. So, when you pass player object to it, it will return player.totalScore. Thus, the iterable passed over to function max will sort according to the key totalScore of the player objects given to it & will return the player who has maximum totalScore.

If no key argument is provided, the maximum is returned according to default Python orderings.

Examples -

max(1, 3, 5, 7)
>>>7
max([1, 3, 5, 7])
>>>7

people = [('Barack', 'Obama'), ('Oprah', 'Winfrey'), ('Mahatma', 'Gandhi')]
max(people, key=lambda x: x[1])
>>>('Oprah', 'Winfrey')

LaTex left arrow over letter in math mode

Use \overleftarrow to create a long arrow to the left.

\overleftarrow{blahblahblah}

LaTeX output

How to create EditText with rounded corners?

Just to add to the other answers, I found that the simplest solution to achieve the rounded corners was to set the following as a background to your Edittext.

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

    <solid android:color="@android:color/white"/>
    <corners android:radius="8dp"/>

</shape>

Git - Won't add files?

If the file is excluded by .gitignore and you want to add it anyway, you can force it with:

git add -f path/to/file.ext

How to skip the OPTIONS preflight request?

setting the content-type to undefined would make javascript pass the header data As it is , and over writing the default angular $httpProvider header configurations. Angular $http Documentation

$http({url:url,method:"POST", headers:{'Content-Type':undefined}).then(success,failure);

Remove duplicate values from JS array

Nested loop method for removing duplicates in array and preserving original order of elements.

var array = [1, 3, 2, 1, [5], 2, [4]]; // INPUT

var element = 0;
var decrement = array.length - 1;
while(element < array.length) {
  while(element < decrement) {
    if (array[element] === array[decrement]) {
      array.splice(decrement, 1);
      decrement--;
    } else {
      decrement--;
    }
  }
  decrement = array.length - 1;
  element++;
}

console.log(array);// [1, 3, 2, [5], [4]]

Explanation: Inner loop compares first element of array with all other elements starting with element at highest index. Decrementing towards the first element a duplicate is spliced from the array.

When inner loop is finished the outer loop increments to the next element for comparison and resets the new length of the array.

Unable to Install Any Package in Visual Studio 2015

I was able to resolve this issue by reinstalling Nuget Package Manager via Tools -> Extensions and Updates

Tomcat manager/html is not available?

In my case, the folder was _Manager. After I renamed it to Manager it worked.

Now, I see login popup and I enter credentials from conf/tomcat-users.xml, It all works fine.

How can I use the apply() function for a single column?

If you are really concerned about the execution speed of your apply function and you have a huge dataset to work on, you could use swifter to make faster execution, here is an example for swifter on pandas dataframe:

import pandas as pd
import swifter

def fnc(m):
    return m*3+4

df = pd.DataFrame({"m": [1,2,3,4,5,6], "c": [1,1,1,1,1,1], "x":[5,3,6,2,6,1]})

# apply a self created function to a single column in pandas
df["y"] = df.m.swifter.apply(fnc)

This will enable your all CPU cores to compute the result hence it will be much faster than normal apply functions. Try and let me know if it become useful for you.

Application not picking up .css file (flask/python)

One more point to add.Along with above upvoted answers, please make sure the below line is added to app.py file:

app = Flask(__name__, static_folder="your path to static")

Otherwise flask will not be able to detect static folder.

How to turn on WCF tracing?

In your web.config (on the server) add

<system.diagnostics>
 <sources>
  <source name="System.ServiceModel" switchValue="Information, ActivityTracing" propagateActivity="true">
   <listeners>
    <add name="traceListener" type="System.Diagnostics.XmlWriterTraceListener" initializeData="C:\logs\Traces.svclog"/>
   </listeners>
  </source>
 </sources>
</system.diagnostics>

Convert HttpPostedFileBase to byte[]

As Darin says, you can read from the input stream - but I'd avoid relying on all the data being available in a single go. If you're using .NET 4 this is simple:

MemoryStream target = new MemoryStream();
model.File.InputStream.CopyTo(target);
byte[] data = target.ToArray();

It's easy enough to write the equivalent of CopyTo in .NET 3.5 if you want. The important part is that you read from HttpPostedFileBase.InputStream.

For efficient purposes you could check whether the stream returned is already a MemoryStream:

byte[] data;
using (Stream inputStream = model.File.InputStream)
{
    MemoryStream memoryStream = inputStream as MemoryStream;
    if (memoryStream == null)
    {
        memoryStream = new MemoryStream();
        inputStream.CopyTo(memoryStream);
    }
    data = memoryStream.ToArray();
}

How to pass data using NotificationCenter in swift 3.0 and NSNotificationCenter in swift 2.0?

Hello @sahil I update your answer for swift 3

let imageDataDict:[String: UIImage] = ["image": image]

  // post a notification
  NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict) 
  // `default` is now a property, not a method call

 // Register to receive notification in your class
 NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)

 // handle notification
 func showSpinningWheel(_ notification: NSNotification) {
        print(notification.userInfo ?? "")
        if let dict = notification.userInfo as NSDictionary? {
            if let id = dict["image"] as? UIImage{
                // do something with your image
            }
        }
 }

Hope it's helpful. Thanks

pg_config executable not found

Installing python-psycopg2 solved it for me on Arch Linux:

pacman -S python-psycopg2

how to open a page in new tab on button click in asp.net?

You shuld do it by client side. you can place a html hyperlink with target="_blank" and style="display:none". after that create a javascript function like following

function openwindow(){
$("#hyperlinkid").click();
return false;
}

use this function as onclientclick event handler of the button like onclientclick="return openwindow()" You need to include a jquery in the page.

You have not accepted the license agreements of the following SDK components

Go to your $ANDROID_HOME/tools/bin and fire the cmd

./sdkmanager --licenses

Accept All licenses listed there.

After this just go to the licenses folder in sdk and check that it's having these five files:

android-sdk-license, android-googletv-license, android-sdk-preview-license, google-gdk-license, mips-android-sysimage-license

Give a retry and build again, still jenkins giving 'licenses not accepted' then you have to give full permission to your 'sdk' directory and all it's parent directories. Here is the command:

sudo chmod -R 777 /opt/

If you having sdk in /opt/ directory.

postgreSQL - psql \i : how to execute script in a given path

Postgres started on Linux/Unix. I suspect that reversing the slash with fix it.

\i somedir/script2.sql 

If you need to fully qualify something

\i c:/somedir/script2.sql

If that doesn't fix it, my next guess would be you need to escape the backslash.

\i somedir\\script2.sql

How can I explicitly free memory in Python?

Unfortunately (depending on your version and release of Python) some types of objects use "free lists" which are a neat local optimization but may cause memory fragmentation, specifically by making more and more memory "earmarked" for only objects of a certain type and thereby unavailable to the "general fund".

The only really reliable way to ensure that a large but temporary use of memory DOES return all resources to the system when it's done, is to have that use happen in a subprocess, which does the memory-hungry work then terminates. Under such conditions, the operating system WILL do its job, and gladly recycle all the resources the subprocess may have gobbled up. Fortunately, the multiprocessing module makes this kind of operation (which used to be rather a pain) not too bad in modern versions of Python.

In your use case, it seems that the best way for the subprocesses to accumulate some results and yet ensure those results are available to the main process is to use semi-temporary files (by semi-temporary I mean, NOT the kind of files that automatically go away when closed, just ordinary files that you explicitly delete when you're all done with them).

Bootstrap 3 jquery event for active tab change

$(function () {
    $('#myTab a:last').tab('show');
});

$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
    var target = $(e.target).attr("href");
    if ((target == '#messages')) {
        alert('ok');
    } else {
        alert('not ok');
    }
});

the problem is that attr('href') is never empty.

Or to compare the #id = "#some value" and then call the ajax.

What's the purpose of SQL keyword "AS"?

The AS in this case is an optional keyword defined in ANSI SQL 92 to define a <<correlation name> ,commonly known as alias for a table.

<table reference> ::=
            <table name> [ [ AS ] <correlation name>
                [ <left paren> <derived column list> <right paren> ] ]
          | <derived table> [ AS ] <correlation name>
                [ <left paren> <derived column list> <right paren> ]
          | <joined table>

     <derived table> ::= <table subquery>

     <derived column list> ::= <column name list>

     <column name list> ::=
          <column name> [ { <comma> <column name> }... ]


     Syntax Rules

     1) A <correlation name> immediately contained in a <table refer-
        ence> TR is exposed by TR. A <table name> immediately contained
        in a <table reference> TR is exposed by TR if and only if TR
        does not specify a <correlation name>.

It seems a best practice NOT to use the AS keyword for table aliases as it is not supported by a number of commonly used databases.

Why is my toFixed() function not working?

document.getElementById("EDTVALOR").addEventListener("change", function() {
  this.value = this.value.replace(",", ".");
  this.value = parseFloat(this.value).toFixed(2);
  if (this.value < 0) {
    this.value = 0;
  }
  this.value = this.value.replace(".", ",");
  this.value = this.value.replace("NaN", "0");
});

How to trim white spaces of array values in php

If the array is multidimensional, this will work great:

//trims empty spaces in array elements (recursively trim multidimesional arrays)
function trimData($data){
   if($data == null)
       return null;

   if(is_array($data)){
       return array_map('trimData', $data);
   }else return trim($data);
}

one sample test is like this:

$arr=[" aaa ", " b  ", "m    ", ["  .e  ", "    12 3", "9 0    0 0   "]];
print_r(trimData($arr));
//RESULT
//Array ( [0] => aaa [1] => b [2] => m [3] => Array ( [0] => .e [1] => 12 3 [2] => 9 0 0 0 ) )

Detect if Android device has Internet connection

A nice solution to check if the active network have internet connection:

public boolean isNetworkAvailable(Context context) {
    ConnectivityManager connectivityManager
            = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivityManager != null) {
        Network network = connectivityManager.getActiveNetwork();
        NetworkCapabilities networkCapabilities = connectivityManager.getNetworkCapabilities(network);
        return networkCapabilities != null && networkCapabilities
                .hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
    }
    return false;
}

How to insert an item into a key/value pair object?

I would use the Dictionary<TKey, TValue> (so long as each key is unique).

EDIT: Sorry, realised you wanted to add it to a specific position. My bad. You could use a SortedDictionary but this still won't let you insert.

html/css buttons that scroll down to different div sections on a webpage

try this:

<input type="button" onClick="document.getElementById('middle').scrollIntoView();" />

What is the right way to check for a null string in Objective-C?

As others have pointed out, there are many kinds of "null" under Cocoa/Objective C. But one further thing to note is that [title isKindOfClass:[NSNull class]] is pointlessly complex since [NSNull null] is documented to be a singleton so you can just check for pointer equality. See Topics for Cocoa: Using Null.

So a good test might be:

if (title == (id)[NSNull null] || title.length == 0 ) title = @"Something";

Note how you can use the fact that even if title is nil, title.length will return 0/nil/false, ie 0 in this case, so you do not have to special case it. This is something that people who are new to Objective C have trouble getting used to, especially coming form other languages where messages/method calls to nil crash.

Determine if Python is running inside virtualenv

In windows OS you see something like this:

C:\Users\yourusername\virtualEnvName\Scripts>activate
(virtualEnvName) C:\Users\yourusername\virtualEnvName\Scripts>

Parentheses mean that you are actually in the virtual environment called "virtualEnvName".

Why can't radio buttons be "readonly"?

This is the trick you can go with.

<input type="radio" name="name" onclick="this.checked = false;" />

Spool Command: Do not output SQL statement to file

You can directly export the query result with export option in the result grig. This export has various options to export. I think this will work.

How do I unload (reload) a Python module?

In Python 3.0–3.3 you would use: imp.reload(module)

The BDFL has answered this question.

However, imp was deprecated in 3.4, in favour of importlib (thanks @Stefan!).

I think, therefore, you’d now use importlib.reload(module), although I’m not sure.

Java Set retain order?

The Set interface does not provide any ordering guarantees.

Its sub-interface SortedSet represents a set that is sorted according to some criterion. In Java 6, there are two standard containers that implement SortedSet. They are TreeSet and ConcurrentSkipListSet.

In addition to the SortedSet interface, there is also the LinkedHashSet class. It remembers the order in which the elements were inserted into the set, and returns its elements in that order.

Calling stored procedure with return value

You need to add return parameter to the command:

using (SqlConnection conn = new SqlConnection(getConnectionString()))
using (SqlCommand cmd = conn.CreateCommand())
{
    cmd.CommandText = parameterStatement.getQuery();
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("SeqName", "SeqNameValue");

    var returnParameter = cmd.Parameters.Add("@ReturnVal", SqlDbType.Int);
    returnParameter.Direction = ParameterDirection.ReturnValue;

    conn.Open();
    cmd.ExecuteNonQuery();
    var result = returnParameter.Value;
}

NLTK and Stopwords Fail #lookuperror

import nltk
nltk.download('stopwords')
from nltk.corpus import stopwords
STOPWORDS = set(stopwords.words('english'))

I want to convert std::string into a const wchar_t *

If you are on Linux/Unix have a look at mbstowcs() and wcstombs() defined in GNU C (from ISO C 90).

  • mbs stand for "Multi Bytes String" and is basically the usual zero terminated C string.

  • wcs stand for Wide Char String and is an array of wchar_t.

For more background details on wide chars have a look at glibc documentation here.

SSIS Excel Connection Manager failed to Connect to the Source

The workaround is, I I save the excel file as excel 97-2003 then it works fine

Location of ini/config files in linux/unix?

For user configuration I've noticed a tendency towards moving away from individual ~/.myprogramrc to a structure below ~/.config. For example, Qt 4 uses ~/.config/<vendor>/<programname> with the default settings of QSettings. The major desktop environments KDE and Gnome use a file structure below a specific folder too (not sure if KDE 4 uses ~/.config, XFCE does use ~/.config).

Generating HTML email body in C#

Use the System.Web.UI.HtmlTextWriter class.

StringWriter writer = new StringWriter();
HtmlTextWriter html = new HtmlTextWriter(writer);

html.RenderBeginTag(HtmlTextWriterTag.H1);
html.WriteEncodedText("Heading Here");
html.RenderEndTag();
html.WriteEncodedText(String.Format("Dear {0}", userName));
html.WriteBreak();
html.RenderBeginTag(HtmlTextWriterTag.P);
html.WriteEncodedText("First part of the email body goes here");
html.RenderEndTag();
html.Flush();

string htmlString = writer.ToString();

For extensive HTML that includes the creation of style attributes HtmlTextWriter is probably the best way to go. However it can be a bit clunky to use and some developers like the markup itself to be easily read but perversly HtmlTextWriter's choices with regard indentation is a bit wierd.

In this example you can also use XmlTextWriter quite effectively:-

writer = new StringWriter();
XmlTextWriter xml = new XmlTextWriter(writer);
xml.Formatting = Formatting.Indented;
xml.WriteElementString("h1", "Heading Here");
xml.WriteString(String.Format("Dear {0}", userName));
xml.WriteStartElement("br");
xml.WriteEndElement();
xml.WriteElementString("p", "First part of the email body goes here");
xml.Flush();

Running Windows batch file commands asynchronously

Create a batch file with the following lines:

start foo.exe
start bar.exe
start baz.exe 

The start command runs your command in a new window, so all 3 commands would run asynchronously.

What is ROWS UNBOUNDED PRECEDING used for in Teradata?

It's the "frame" or "range" clause of window functions, which are part of the SQL standard and implemented in many databases, including Teradata.

A simple example would be to calculate the average amount in a frame of three days. I'm using PostgreSQL syntax for the example, but it will be the same for Teradata:

WITH data (t, a) AS (
  VALUES(1, 1),
        (2, 5),
        (3, 3),
        (4, 5),
        (5, 4),
        (6, 11)
)
SELECT t, a, avg(a) OVER (ORDER BY t ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING)
FROM data
ORDER BY t

... which yields:

t  a  avg
----------
1  1  3.00
2  5  3.00
3  3  4.33
4  5  4.00
5  4  6.67
6 11  7.50

As you can see, each average is calculated "over" an ordered frame consisting of the range between the previous row (1 preceding) and the subsequent row (1 following).

When you write ROWS UNBOUNDED PRECEDING, then the frame's lower bound is simply infinite. This is useful when calculating sums (i.e. "running totals"), for instance:

WITH data (t, a) AS (
  VALUES(1, 1),
        (2, 5),
        (3, 3),
        (4, 5),
        (5, 4),
        (6, 11)
)
SELECT t, a, sum(a) OVER (ORDER BY t ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
FROM data
ORDER BY t

yielding...

t  a  sum
---------
1  1    1
2  5    6
3  3    9
4  5   14
5  4   18
6 11   29

Here's another very good explanations of SQL window functions.

Scrollbar without fixed height/Dynamic height with scrollbar

A quick, clean approach using very little JS and CSS padding: http://jsfiddle.net/benjamincharity/ZcTsT/14/

var headerHeight = $('#header').height(),
    footerHeight = $('#footer').height();

$('#content').css({
  'padding-top': headerHeight,
  'padding-bottom': footerHeight
});

Java Swing revalidate() vs repaint()

Any time you do a remove() or a removeAll(), you should call

  validate();
  repaint();

after you have completed add()'ing the new components.

Calling validate() or revalidate() is mandatory when you do a remove() - see the relevant javadocs.

My own testing indicates that repaint() is also necessary. I'm not sure exactly why.

Regex that matches integers in between whitespace or start/end of string only

This just allow positive integers.

^[0-9]*[1-9][0-9]*$

How to format dateTime in django template?

This is exactly what you want. Try this:

{{ wpis.entry.lastChangeDate|date:'Y-m-d H:i' }}

Leave menu bar fixed on top when scrolled

try with sticky jquery plugin

https://github.com/garand/sticky

_x000D_
_x000D_
<script src="jquery.js"></script>_x000D_
<script src="jquery.sticky.js"></script>_x000D_
<script>_x000D_
  $(document).ready(function(){_x000D_
    $("#sticker").sticky({topSpacing:0});_x000D_
  });_x000D_
</script>
_x000D_
_x000D_
_x000D_

How to center the text in a JLabel?

String text = "In early March, the city of Topeka, Kansas," + "<br>" +
              "temporarily changed its name to Google..." + "<br>" + "<br>" +
              "...in an attempt to capture a spot" + "<br>" +
              "in Google's new broadband/fiber-optics project." + "<br>" + "<br>" +"<br>" +
              "source: http://en.wikipedia.org/wiki/Google_server#Oil_Tanker_Data_Center";
JLabel label = new JLabel("<html><div style='text-align: center;'>" + text + "</div></html>");

How to concatenate two strings to build a complete path

The following script catenates several (relative/absolute) paths (BASEPATH) with a relative path (SUBDIR):

shopt -s extglob
SUBDIR="subdir"
for BASEPATH in '' / base base/ base// /base /base/ /base//; do
  echo "BASEPATH = \"$BASEPATH\" --> ${BASEPATH%%+(/)}${BASEPATH:+/}$SUBDIR"
done

The output of which is:

BASEPATH = "" --> subdir
BASEPATH = "/" --> /subdir
BASEPATH = "base" --> base/subdir
BASEPATH = "base/" --> base/subdir
BASEPATH = "base//" --> base/subdir
BASEPATH = "/base" --> /base/subdir
BASEPATH = "/base/" --> /base/subdir
BASEPATH = "/base//" --> /base/subdir

The shopt -s extglob is only necessary to allow BASEPATH to end on multiple slashes (which is probably nonsense). Without extended globing you can just use:

echo ${BASEPATH%%/}${BASEPATH:+/}$SUBDIR

which would result in the less neat but still working:

BASEPATH = "" --> subdir
BASEPATH = "/" --> /subdir
BASEPATH = "base" --> base/subdir
BASEPATH = "base/" --> base/subdir
BASEPATH = "base//" --> base//subdir
BASEPATH = "/base" --> /base/subdir
BASEPATH = "/base/" --> /base/subdir
BASEPATH = "/base//" --> /base//subdir

Converting Java file:// URL to File(...) path, platform independent, including UNC paths

I hope (not exactly verified) that newer java brought nio package and Path. Hopefully it have it fixed: String s="C:\\some\\ile.txt"; System.out.println(new File(s).toPath().toUri());

R: Print list to a text file

I saw in the comments for Nico's answer that some people were running into issues with saving lists that had lists within them. I also ran into this problem with some of my work and was hoping that someone found a better answer than what I found however no one responded to their issue.

So: @ali, @FMKerckhof, and @Kerry the only way that I found to save a nested list is to use sink() like user6585653 suggested (I tried to up vote his answer but could not). It is not the best way to do it since you link the text file which means it can be easily over written or other results may be saved within that file if you do not cancel the sink. See below for the code.

sink("mylist.txt")
print(mylist)
sink()

Make sure to have the sink() at the end your code so that you cancel the sink.

Declaring array of objects

var ArrayofObjects = [{}]; //An empty array of objects.

Delete newline in Vim

<CURSOR>Evaluator<T>():
    _bestPos(){
}

cursor in first line

NOW, in NORMAL MODE do

shift+v
2j
shift+j

or

V2jJ

:normal V2jJ

Insert ellipsis (...) into HTML tag if content too wide

There is a simple jQuery solution by Devon Govett:

https://gist.github.com/digulla/5796047

To use, just call ellipsis() on a jQuery object. For example:

$("span").ellipsis();

Auto select file in Solution Explorer from its open tab

If you're using the ReSharper plugin, you can do that using the Shift + Alt + L shortcut or navigate via menu as shown.

Enter image description here

Practical uses of different data structures

Any ranking of various data structures will be at least partially tied to problem context. It would help to learn how to analyze time and space performance of algorithms. Typically, "big O notation" is used, e.g. binary search is in O(log n) time, which means that the time to search for an element is the log (in base 2, implicitly) of the number of elements. Intuitively, since every step discards half of the remaining data as irrelevant, doubling the number of elements will increases the time by 1 step. (Binary search scales rather well.) Space performance concerns how the amount of memory grows for larger data sets. Also, note that big-O notation ignores constant factors - for smaller data sets, an O(n^2) algorithm may still be faster than an O(n * log n) algorithm that has a higher constant factor. Complex algorithms often have more work to do on startup.

Besides time and space, other characteristics include whether a data structure is sorted (trees and skiplists are sorted, hash tables are not), persistence (binary trees can reuse pointers from older versions, while hash tables are modified in place), etc.

While you'll need to learn the behavior of several data structures to be able to compare them, one way to develop a sense for why they differ in performance is to closely study a few. I'd suggest comparing singly-linked lists, binary search trees, and skip lists, all of which are relatively simple, but have very different characteristics. Think about how much work it takes to find a value, add a new value, find all values in order, etc.

There are various texts on analyzing algorithms / data structure performance that people recommend, but what really made them make sense to me was learning OCaml. Dealing with complex data structures is ML's strong suit, and their behavior is much clearer when you can avoid pointers and memory management as in C. (Learning OCaml just to understand data structures is almost certainly the long way around, though. :) )

How to get the exact local time of client?

new Date(Date.now() + (-1*new Date().getTimezoneOffset()*60000)).toISOString()

How to remove all numbers from string?

For Western Arabic numbers (0-9):

$words = preg_replace('/[0-9]+/', '', $words);

For all numerals including Western Arabic (e.g. Indian):

$words = '????';
$words = preg_replace('/\d+/u', '', $words);
var_dump($words); // string(0) ""
  • \d+ matches multiple numerals.
  • The modifier /u enables unicode string treatment. This modifier is important, otherwise the numerals would not match.

Can Selenium WebDriver open browser windows silently in the background?

For running without any browser, you can run it in headless mode.

I show you one example in Python that is working for me right now

from selenium import webdriver


options = webdriver.ChromeOptions()
options.add_argument("headless")
self.driver = webdriver.Chrome(executable_path='/Users/${userName}/Drivers/chromedriver', chrome_options=options)

I also add you a bit more of info about this in the official Google website https://developers.google.com/web/updates/2017/04/headless-chrome

Initializing a dictionary in python with a key value and no corresponding values

You can initialize the values as empty strings and fill them in later as they are found.

dictionary = {'one':'','two':''}
dictionary['one']=1
dictionary['two']=2

Detect If Browser Tab Has Focus

Surprising to see nobody mentioned document.hasFocus

if (document.hasFocus()) console.log('Tab is active')

MDN has more information.

Try-catch-finally-return clarification

Here is some code that show how it works.

class Test
{
    public static void main(String args[]) 
    { 
        System.out.println(Test.test()); 
    }

    public static String test()
    {
        try {
            System.out.println("try");
            throw new Exception();
        } catch(Exception e) {
            System.out.println("catch");
            return "return"; 
        } finally {  
            System.out.println("finally");
            return "return in finally"; 
        }
    }
}

The results is:

try
catch
finally
return in finally

Enabling/installing GD extension? --without-gd

For php7.1 do:

sudo apt-get install php7.1-gd

and restart webserver. For apache do

sudo service apache2 restart

Could not find method android() for arguments

This error appear because the compiler could not found "my-upload-key.keystore" file in your project

After you have generated the file you need to paste it into project's andorid/app folder

this worked for me!

How to create a numpy array of all True or all False?

numpy already allows the creation of arrays of all ones or all zeros very easily:

e.g. numpy.ones((2, 2)) or numpy.zeros((2, 2))

Since True and False are represented in Python as 1 and 0, respectively, we have only to specify this array should be boolean using the optional dtype parameter and we are done.

numpy.ones((2, 2), dtype=bool)

returns:

array([[ True,  True],
       [ True,  True]], dtype=bool)

UPDATE: 30 October 2013

Since numpy version 1.8, we can use full to achieve the same result with syntax that more clearly shows our intent (as fmonegaglia points out):

numpy.full((2, 2), True, dtype=bool)

UPDATE: 16 January 2017

Since at least numpy version 1.12, full automatically casts results to the dtype of the second parameter, so we can just write:

numpy.full((2, 2), True)

HTML -- two tables side by side

Depending on your content and space, you can use floats or inline display:

<table style="display: inline-block;">

<table style="float: left;">

Check it out here: http://jsfiddle.net/SM769/

Documentation

angular ng-repeat in reverse

This is what i used:

<alert ng-repeat="alert in alerts.slice().reverse()" type="alert.type" close="alerts.splice(index, 1)">{{$index + 1}}: {{alert.msg}}</alert>

Update:

My answer was OK for old version of Angular. Now, you should be using

ng-repeat="friend in friends | orderBy:'-'"

or

ng-repeat="friend in friends | orderBy:'+':true"

from https://stackoverflow.com/a/26635708/1782470

Update int column in table with unique incrementing values

You can try :

DECLARE @counter int
SET @counter = 0
UPDATE [table]
SET [column] = @counter, @counter = @counter + 1```

Add values to app.config and retrieve them

sorry for late answer but may be my code may help u.

I placed 3 buttons on the winform surface. button1 & 2 will set different value and button3 will retrieve current value. so when run my code first add the reference System.configuration

and click on first button and then click on 3rd button to see what value has been set. next time again click on second & 3rd button to see again what value has been set after change.

so here is the code.

using System.Configuration;

 private void button1_Click(object sender, EventArgs e)
{
    Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
    config.AppSettings.Settings.Remove("DBServerName");
    config.AppSettings.Settings.Add("DBServerName", "FirstAddedValue1");
    config.Save(ConfigurationSaveMode.Modified);
}

private void button2_Click(object sender, EventArgs e)
{
    Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
    config.AppSettings.Settings.Remove("DBServerName");
    config.AppSettings.Settings.Add("DBServerName", "SecondAddedValue1");
    config.Save(ConfigurationSaveMode.Modified);
}

private void button3_Click(object sender, EventArgs e)
{
    Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
          MessageBox.Show(config.AppSettings.Settings["DBServerName"].Value);
}

hide/show a image in jquery

If you're trying to hide upload img and show bandwidth img on bandwidth click and viceversa this would work

<script>

    function show_img(id)
    {
        if(id=='bandwidth')
        {
           $("#upload").hide();
           $("#bandwith").show();
        }
        else if(id=='upload')
        {
            $("#upload").show();
            $("#bandwith").hide();
        }
    return false;
     } 
    </script>
    <a href="#" onclick="javascript:show_img('bandwidth');">Bandwidth</a>
    <a href="#" onclick="javascript:show_img('upload');">Upload</a>
    <p align="center"> 
      <img src="/media/img/close.png" style="visibility: hidden;" id="bandwidth"/>
      <img src="/media/img/close.png" style="visibility: hidden;" id="upload"/>
    </p>

How to check programmatically if an application is installed or not in Android?

If you know the package name, then this works without using a try-catch block or iterating through a bunch of packages:

public static boolean isPackageInstalled(Context context, String packageName) {
    final PackageManager packageManager = context.getPackageManager();
    Intent intent = packageManager.getLaunchIntentForPackage(packageName);
    if (intent == null) {
        return false;
    }
    List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
    return !list.isEmpty();
}

Adding an onclick event to a table row

Something like this.

function addRowHandlers() {
  var table = document.getElementById("tableId");
  var rows = table.getElementsByTagName("tr");
  for (i = 0; i < rows.length; i++) {
    var currentRow = table.rows[i];
    var createClickHandler = function(row) {
      return function() {
        var cell = row.getElementsByTagName("td")[0];
        var id = cell.innerHTML;
        alert("id:" + id);
      };
    };
    currentRow.onclick = createClickHandler(currentRow);
  }
}

EDIT

Working demo.

Node.js server that accepts POST requests

The following code shows how to read values from an HTML form. As @pimvdb said you need to use the request.on('data'...) to capture the contents of the body.

const http = require('http')

const server = http.createServer(function(request, response) {
  console.dir(request.param)

  if (request.method == 'POST') {
    console.log('POST')
    var body = ''
    request.on('data', function(data) {
      body += data
      console.log('Partial body: ' + body)
    })
    request.on('end', function() {
      console.log('Body: ' + body)
      response.writeHead(200, {'Content-Type': 'text/html'})
      response.end('post received')
    })
  } else {
    console.log('GET')
    var html = `
            <html>
                <body>
                    <form method="post" action="http://localhost:3000">Name: 
                        <input type="text" name="name" />
                        <input type="submit" value="Submit" />
                    </form>
                </body>
            </html>`
    response.writeHead(200, {'Content-Type': 'text/html'})
    response.end(html)
  }
})

const port = 3000
const host = '127.0.0.1'
server.listen(port, host)
console.log(`Listening at http://${host}:${port}`)


If you use something like Express.js and Bodyparser then it would look like this since Express will handle the request.body concatenation

var express = require('express')
var fs = require('fs')
var app = express()

app.use(express.bodyParser())

app.get('/', function(request, response) {
  console.log('GET /')
  var html = `
    <html>
        <body>
            <form method="post" action="http://localhost:3000">Name: 
                <input type="text" name="name" />
                <input type="submit" value="Submit" />
            </form>
        </body>
    </html>`
  response.writeHead(200, {'Content-Type': 'text/html'})
  response.end(html)
})

app.post('/', function(request, response) {
  console.log('POST /')
  console.dir(request.body)
  response.writeHead(200, {'Content-Type': 'text/html'})
  response.end('thanks')
})

port = 3000
app.listen(port)
console.log(`Listening at http://localhost:${port}`)

Change the class from factor to numeric of many columns in a data frame

I found this function on a couple other duplicate threads and have found it an elegant and general way to solve this problem. This thread shows up first on most searches on this topic, so I am sharing it here to save folks some time. I take no credit for this just so see the original posts here and here for details.

df <- data.frame(x = 1:10,
                 y = rep(1:2, 5),
                 k = rnorm(10, 5,2),
                 z = rep(c(2010, 2012, 2011, 2010, 1999), 2),
                 j = c(rep(c("a", "b", "c"), 3), "d"))

convert.magic <- function(obj, type){
  FUN1 <- switch(type,
                 character = as.character,
                 numeric = as.numeric,
                 factor = as.factor)
  out <- lapply(obj, FUN1)
  as.data.frame(out)
}

str(df)
str(convert.magic(df, "character"))
str(convert.magic(df, "factor"))
df[, c("x", "y")] <- convert.magic(df[, c("x", "y")], "factor")

Submit button not working in Bootstrap form

  • If you put type=submit it is a Submit Button
  • if you put type=button it is just a button, It does not submit your form inputs.

and also you don't want to use both of these

Which programming language for cloud computing?

"Cloud computing" is more of an operating-system-level concept than a language concept.

Let's say you want to host an application on Amazon's EC2 cloud computing service -- you can develop it in any language you like, on any operating system supported by EC2 (several flavors of Linux, Solaris, and Windows), then install and run it "in the cloud" on one or more virtual machines, much as you would do on a dedicated physical server.

How can I remove an element from a list?

You can use which.

x<-c(1:5)
x
#[1] 1 2 3 4 5
x<-x[-which(x==4)]
x
#[1] 1 2 3 5

npm install hangs

This method is working for me when npm blocks in installation Package for IONIC installation and ReactNative and another package npm.

You can change temporary:

npm config set prefix C:\Users\[username]\AppData\Roaming\npm\node_modules2

  • Change the path in environment variables. Set:

    C:\Users[username]\AppData\Roaming\npm\node_modules2

  • Run the command to install your package.

  • Open file explorer, copy the link:

    C:\Users[username]\AppData\Roaming\npm\node_modules

    ok file yourpackage.CMD created another folder Created "node_modules2" in node_modules and contain your package folder.

  • Copy your package file CMD to parent folder "npm".

  • Copy your package folder to parent folder "node_modules".

  • Now run:

    npm config set prefix C:\Users\[username]\AppData\Roaming\npm

  • Change the path in environment variables. Set:

    C:\Users[username]\AppData\Roaming\npm

Now the package is working correctly with the command line.

PHP: How to get current time in hour:minute:second?

You can have both formats as an argument to the function date():

date("d-m-Y H:i:s")

Check the manual for more info : http://php.net/manual/en/function.date.php

As pointed out by @ThomasVdBerge to display minutes you need the 'i' character

XPath - Difference between node() and text()

Select the text of all items under produce:

//produce/item/text()

Select all the manager nodes in all departments:

//department/*

show distinct column values in pyspark dataframe: python

If you want to see the distinct values of a specific column in your dataframe , you would just need to write -

    df.select('colname').distinct().show(100,False)

This would show the 100 distinct values (if 100 values are available) for the colname column in the df dataframe.

If you want to do something fancy on the distinct values, you can save the distinct values in a vector

    a = df.select('colname').distinct()

Here, a would have all the distinct values of the column colname

How do I exit a foreach loop in C#?

Just use the statement:

break;

HTML Script tag: type or language (or omit both)?

The language attribute has been deprecated for a long time, and should not be used.

When W3C was working on HTML5, they discovered all browsers have "text/javascript" as the default script type, so they standardized it to be the default value. Hence, you don't need type either.

For pages in XHTML 1.0 or HTML 4.01 omitting type is considered invalid. Try validating the following:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script src="http://example.com/test.js"></script>
</head>
<body/>
</html>

You will be informed of the following error:

Line 4, Column 41: required attribute "type" not specified

So if you're a fan of standards, use it. It should have no practical effect, but, when in doubt, may as well go by the spec.

Changing the default title of confirm() in JavaScript?

Don't use the confirm() dialog then... easy to use a custom dialog from prototype/scriptaculous, YUI, jQuery ... there's plenty out there.

document .click function for touch device

can you use jqTouch or jquery mobile ? there it's much easier to handle touch events. If not then you need to simulate click on touch device, follow this articles:

iphone-touch-events-in-javascript

A touch demo

More in this thread

Finding the length of a Character Array in C

You can use this function:

int arraySize(char array[])
{
    int cont = 0;
    for (int i = 0; array[i] != 0; i++)
            cont++;
    return cont;
}

Internal vs. Private Access Modifiers

Internal will allow you to reference, say, a Data Access static class (for thread safety) between multiple business logic classes, while not subscribing them to inherit that class/trip over each other in connection pools, and to ultimately avoid allowing a DAL class to promote access at the public level. This has countless backings in design and best practices.

Entity Framework makes good use of this type of access

How to return rows from left table not found in right table?

This page gives a decent breakdown of the different join types, as well as venn diagram visualizations to help... well... visualize the difference in the joins.

As the comments said this is a quite basic query from the sounds of it, so you should try to understand the differences between the joins and what they actually mean.

Check out http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/

You're looking for a query such as:

DECLARE @table1 TABLE (test int)
DECLARE @table2 TABLE (test int)

INSERT INTO @table1
(
    test
)
SELECT 1
UNION ALL SELECT 2

INSERT INTO @table2
(
    test
)
SELECT 1
UNION ALL SELECT 3

-- Here's the important part
SELECT  a.*
FROM    @table1 a
LEFT    join @table2 b on a.test = b.test -- this will return all rows from a
WHERE   b.test IS null -- this then excludes that which exist in both a and b

-- Returned results:

2

Using PowerShell to remove lines from a text file if it contains a string

Escape the | character using a backtick

get-content c:\new\temp_*.txt | select-string -pattern 'H`|159' -notmatch | Out-File c:\new\newfile.txt

How to connect Bitbucket to Jenkins properly

I was just able to successfully trigger builds on commit using the Hooks option in Bitbucket to a Jenkins instance with the following steps (similar as link):

  1. Generate a custom UUID or string sequence, save for later
  2. Jenkins -> Configure Project -> Build Triggers -> "Trigger builds remotely (e.g., from scripts)"
  3. (Paste UUID/string Here) for "Authentication Token"
  4. Save
  5. Edit Bitbucket repository settings
  6. Hooks -> Edit: Endpoint: http://jenkins.something.co:9009/ Module Name: Project Name: Project Name Token: (Paste UUID/string Here)

The endpoint did not require inserting the basic HTTP auth in the URL despite using authentication, I did not use the Module Name field and the Project Name was entered case sensitive including a space in my test case. The build did not always trigger immediately but relatively fast. One other thing you may consider is disabling the "Prevent Cross Site Request Forgery exploits" option in "Configure Global Security" for testing as I've experienced all sorts of API difficulties from existing integrations when this option was enabled.

c# datatable insert column at position 0

    //Example to define how to do :

    DataTable dt = new DataTable();   

    dt.Columns.Add("ID");
    dt.Columns.Add("FirstName");
    dt.Columns.Add("LastName");
    dt.Columns.Add("Address");
    dt.Columns.Add("City");
           //  The table structure is:
            //ID    FirstName   LastName    Address     City

       //Now we want to add a PhoneNo column after the LastName column. For this we use the                               
             //SetOrdinal function, as iin:
        dt.Columns.Add("PhoneNo").SetOrdinal(3);

            //3 is the position number and positions start from 0.`enter code here`

               //Now the table structure will be:
              // ID      FirstName   LastName    PhoneNo    Address     City

Delete from two tables in one query

The OP is just missing the table aliases after the delete

DELETE t1, t2 
FROM table1 t1 LEFT JOIN table2 t2 ON t1.id = t2.id 
WHERE t1.id = some_id

Android findViewById() in Custom View

Try this in your constructor

MainActivity maniActivity = (MainActivity)context;
EditText firstName = (EditText) maniActivity.findViewById(R.id.display_name);

jQuery: using a variable as a selector

You're thinking too complicated. It's actually just $('#'+openaddress).

How to fix "The ConnectionString property has not been initialized"

The connection string is not in AppSettings.

What you're looking for is in:

System.Configuration.ConfigurationManager.ConnectionStrings["MyDB"]...

How to make a phone call programmatically?

Here I will show you that how you can make a phone call from your activity. To make a call you have to put down this code in your app.

try {
    Intent my_callIntent = new Intent(Intent.ACTION_CALL);
    my_callIntent.setData(Uri.parse("tel:"+phn_no));
    //here the word 'tel' is important for making a call...
    startActivity(my_callIntent);
} catch (ActivityNotFoundException e) {
    Toast.makeText(getApplicationContext(), "Error in your phone call"+e.getMessage(), Toast.LENGTH_LONG).show();
}

php.ini: which one?

It really depends on the situation, for me its in fpm as I'm using PHP5-FPM. A solution to your problem could be a universal php.ini and then using a symbolic link created like:

ln -s /etc/php5/php.ini php.ini

Then any modifications you make will be in one general .ini file. This is probably not really the best solution though, you might want to look into modifying some configuration so that you literally use one file, on one location. Not multiple locations hacked together.

Get remote registry value

For remote registry you have to use .NET with powershell 2.0

$w32reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine',$computer1)
$keypath = 'SOFTWARE\Veritas\NetBackup\CurrentVersion'
$netbackup = $w32reg.OpenSubKey($keypath)
$NetbackupVersion1 = $netbackup.GetValue('PackageVersion')

Regex not operator

You could capture the (2001) part and replace the rest with nothing.

public static string extractYearString(string input) {
    return input.replaceAll(".*\(([0-9]{4})\).*", "$1");
}

var subject = "(2001) (asdf) (dasd1123_asd 21.01.2011 zqge)(dzqge) name (20019)";
var result = extractYearString(subject);
System.out.println(result); // <-- "2001"

.*\(([0-9]{4})\).* means

  • .* match anything
  • \( match a ( character
  • ( begin capture
  • [0-9]{4} any single digit four times
  • ) end capture
  • \) match a ) character
  • .* anything (rest of string)

How can I create and style a div using JavaScript?

Here's one solution that I'd use:

var div = '<div id="yourId" class="yourClass" yourAttribute="yourAttributeValue">blah</div>';

If you wanted the attribute and/or attribute values to be based on variables:

var id = "hello";
var classAttr = "class";
var div = '<div id='+id+' '+classAttr+'="world" >Blah</div>';

Then, to append to the body:

document.getElementsByTagName("body").innerHTML = div;

Easy as pie.

How can I get customer details from an order in WooCommerce?

WooCommerce is using this function to show billing and shipping addresses in the customer profile. So this will might help.

The user needs to be logged in to get address using this function.

wc_get_account_formatted_address( 'billing' );

or

wc_get_account_formatted_address( 'shipping' );

HTML5 tag for horizontal line break

Instead of using <hr>, you can one of the border of the enclosing block and display it as a horizontal line.

Here is a sample code:

The HTML:

<div class="title_block">
    <h3>This is a header.</h3>
</div>
<p>Here is some sample paragraph text.<br>
This demonstrates that a horizontal line goes between the title and the paragraph.</p>

The CSS:

.title_block {
    border-bottom: 1px solid #ddd;
    padding-bottom: 5px;
    margin-bottom: 5px;
}

How to prevent XSS with HTML/PHP?

One of the most important steps is to sanitize any user input before it is processed and/or rendered back to the browser. PHP has some "filter" functions that can be used.

The form that XSS attacks usually have is to insert a link to some off-site javascript that contains malicious intent for the user. Read more about it here.

You'll also want to test your site - I can recommend the Firefox add-on XSS Me.

Why would an Enum implement an Interface?

Here's one example (a similar/better one is found in Effective Java 2nd Edition):

public interface Operator {
    int apply (int a, int b);
}

public enum SimpleOperators implements Operator {
    PLUS { 
        int apply(int a, int b) { return a + b; }
    },
    MINUS { 
        int apply(int a, int b) { return a - b; }
    };
}

public enum ComplexOperators implements Operator {
    // can't think of an example right now :-/
}

Now to get a list of both the Simple + Complex Operators:

List<Operator> operators = new ArrayList<Operator>();

operators.addAll(Arrays.asList(SimpleOperators.values()));
operators.addAll(Arrays.asList(ComplexOperators.values()));

So here you use an interface to simulate extensible enums (which wouldn't be possible without using an interface).

CSS horizontal centering of a fixed div?

left: 50%;
margin-left: -400px; /* Half of the width */

Lumen: get URL parameter in a Blade view

As per official 5.8 docs:

The request() function returns the current request instance or obtains an input item:

$request = request();

$value = request('key', $default);

Docs

How do I add 1 day to an NSDate?

Updated for Swift 5

let today = Date()
let nextDate = Calendar.current.date(byAdding: .day, value: 1, to: today)

Objective C

 NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
 // now build a NSDate object for the next day
 NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
 [offsetComponents setDay:1];
 NSDate *nextDate = [gregorian dateByAddingComponents:offsetComponents toDate: [NSDate date] options:0];

Send JavaScript variable to PHP variable

It depends on the way your page behaves. If you want this to happens asynchronously, you have to use AJAX. Try out "jQuery post()" on Google to find some tuts.

In other case, if this will happen when a user submits a form, you can send the variable in an hidden field or append ?variableName=someValue" to then end of the URL you are opening. :

http://www.somesite.com/send.php?variableName=someValue

or

http://www.somesite.com/send.php?variableName=someValue&anotherVariable=anotherValue

This way, from PHP you can access this value as:

$phpVariableName = $_POST["variableName"];

for forms using POST method or:

$phpVariableName = $_GET["variableName"];

for forms using GET method or the append to url method I've mentioned above (querystring).

Preventing an image from being draggable or selectable without using JS

I've been forgetting to share my solution, I couldn't find a way to do this without using JS. There are some corner cases where @Jeffery A Wooden's suggested CSS just wont cover.

This is what I apply to all of my UI containers, no need to apply to each element since it recuses on all the child elements.

CSS:

.unselectable {
    /* For Opera and <= IE9, we need to add unselectable="on" attribute onto each element */
    /* Check this site for more details: http://help.dottoro.com/lhwdpnva.php */
    -moz-user-select: none; /* These user-select properties are inheritable, used to prevent text selection */
    -webkit-user-select: none;
    -ms-user-select: none; /* From IE10 only */
    user-select: none; /* Not valid CSS yet, as of July 2012 */

    -webkit-user-drag: none; /* Prevents dragging of images/divs etc */
    user-drag: none;
}

JS:

var makeUnselectable = function( $target ) {
    $target
        .addClass( 'unselectable' ) // All these attributes are inheritable
        .attr( 'unselectable', 'on' ) // For IE9 - This property is not inherited, needs to be placed onto everything
        .attr( 'draggable', 'false' ) // For moz and webkit, although Firefox 16 ignores this when -moz-user-select: none; is set, it's like these properties are mutually exclusive, seems to be a bug.
        .on( 'dragstart', function() { return false; } );  // Needed since Firefox 16 seems to ingore the 'draggable' attribute we just applied above when '-moz-user-select: none' is applied to the CSS 

    $target // Apply non-inheritable properties to the child elements
        .find( '*' )
        .attr( 'draggable', 'false' )
        .attr( 'unselectable', 'on' ); 
};

This was way more complicated than it needed to be.

Where do I find old versions of Android NDK?

Here are the links for Windows, Mac and Linux. Latest revision of 18.x, 17.x, 16.x, 15.x, 14.x, 13.x, 12.x, 11.x, 10.x, 9.x, 8.x and 7.x versions.

Update: Download Latest and Old NDK releases from Android official site.


Android NDK, Revision 18b (January 2019)

Windows 32-bit | Windows 64-bit | Mac OS X 64-bit | Linux 64-bit

Android NDK, Revision 17c (June 2018)

Windows 32-bit | Windows 64-bit | Mac OS X 64-bit | Linux 64-bit

Android NDK, Revision 16b (December 2017)

Windows 32-bit | Windows 64-bit | Mac OS X 64-bit | Linux 64-bit

Android NDK, Revision 15c (July 2017)

Windows 32-bit | Windows 64-bit | Mac OS X 64-bit | Linux 64-bit

Android NDK, Revision 14b (March 2017)

Windows 32-bit | Windows 64-bit | Mac OS X 64-bit | Linux 64-bit

Android NDK, Revision 13b (October 2016)

Windows 32-bit | Windows 64-bit | Mac OS X 64-bit | Linux 64-bit

Android NDK, Revision 12b (June 2016)

Windows 32-bit | Windows 64-bit | Mac OS X 64-bit | Linux 64-bit

Android NDK, Revision 11c (March 2016)

Windows 32-bit | Windows 64-bit | Mac OS X 64-bit | Linux 64-bit

Android NDK, Revision 10e (May 2015)

Windows 32-bit | Windows 64-bit | Mac OS X 64-bit | Linux 64-bit

Android NDK r9d

Windows 32-bit | Windows 64-bit | Mac OS X 64-bit | Linux 64-bit

Android NDK r8e

Windows 32-bit | Windows 64-bit | Mac OS X 64-bit | Linux 64-bit

Android NDK r7c

Windows 32-bit | Mac OS X 64-bit | Linux 64-bit

How to kill/stop a long SQL query immediately?

First execute the below command:

sp_who2

After that execute the below command with SPID, which you got from above command:

KILL {SPID value}