Programs & Examples On #Rails migrations

Rails migrations are used to track and apply database alterations in a reversible manner.

Add a reference column migration in Rails 4

Just to document if someone has the same problem...

In my situation I've been using :uuid fields, and the above answers does not work to my case, because rails 5 are creating a column using :bigint instead :uuid:

add_reference :uploads, :user, index: true, type: :uuid

Reference: Active Record Postgresql UUID

How to drop columns using Rails migration

In a rails4 app it is possible to use the change method also for removing columns. The third param is the data_type and in the optional forth you can give options. It is a bit hidden in the section 'Available transformations' on the documentation .

class RemoveFieldFromTableName < ActiveRecord::Migration
  def change
    remove_column :table_name, :field_name, :data_type, {}
  end
end

Return JSON with error status code MVC

A simple way to send a error to Json is control Http Status Code of response object and set a custom error message.

Controller

public JsonResult Create(MyObject myObject) 
{
  //AllFine
  return Json(new { IsCreated = True, Content = ViewGenerator(myObject));

  //Use input may be wrong but nothing crashed
  return Json(new { IsCreated = False, Content = ViewGenerator(myObject));  

  //Error
  Response.StatusCode = (int)HttpStatusCode.InternalServerError;
  return Json(new { IsCreated = false, ErrorMessage = 'My error message');
}

JS

$.ajax({
     type: "POST",
     dataType: "json",
     url: "MyController/Create",
     data: JSON.stringify(myObject),
     success: function (result) {
       if(result.IsCreated)
     {
    //... ALL FINE
     }
     else
     {
    //... Use input may be wrong but nothing crashed
     }
   },
    error: function (error) {
            alert("Error:" + erro.responseJSON.ErrorMessage ); //Error
        }
  });

How to add link to flash banner

If you have a flash FLA file that shows the FLV movie you can add a button inside the FLA file. This button can be given an action to load the URL.

on (release) {
  getURL("http://someurl/");
}

To make the button transparent you can place a square inside it that is moved to the hit-area frame of the button.

I think it would go too far to explain into depth with pictures how to go about in stackoverflow.

correct quoting for cmd.exe for multiple arguments

Note the "" at the beginning and at the end!

Run a program and pass a Long Filename

cmd /c write.exe "c:\sample documents\sample.txt"

Spaces in Program Path

cmd /c ""c:\Program Files\Microsoft Office\Office\Winword.exe""

Spaces in Program Path + parameters

cmd /c ""c:\Program Files\demo.cmd"" Parameter1 Param2

Spaces in Program Path + parameters with spaces

cmd /k ""c:\batch files\demo.cmd" "Parameter 1 with space" "Parameter2 with space""

Launch Demo1 and then Launch Demo2

cmd /c ""c:\Program Files\demo1.cmd" & "c:\Program Files\demo2.cmd""

CMD.exe (Command Shell)

Tracing XML request/responses with JAX-WS

with logback.xml configuration files, you can do :

<logger name="com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe" level="trace" additivity="false">
    <appender-ref ref="STDOUT"/>
</logger>

That will log the request and the response like this (depending on your configuration for the log output) :

09:50:23.266 [qtp1068445309-21] DEBUG c.s.x.i.w.t.h.c.HttpTransportPipe - ---[HTTP request - http://xyz:8081/xyz.svc]---
Accept: application/soap+xml, multipart/related
Content-Type: application/soap+xml; charset=utf-8;action="http://xyz.Web.Services/IServiceBase/GetAccessTicket"
User-Agent: JAX-WS RI 2.2.9-b130926.1035 svn-revision#5f6196f2b90e9460065a4c2f4e30e065b245e51e
<?xml version="1.0" ?><S:Envelope xmlns:S="http://www.w3.org/2003/05/soap-envelope">[CONTENT REMOVED]</S:Envelope>--------------------

09:50:23.312 [qtp1068445309-21] DEBUG c.s.x.i.w.t.h.c.HttpTransportPipe - ---[HTTP response - http://xyz:8081/xyz.svc - 200]---
null: HTTP/1.1 200 OK
Content-Length: 792
Content-Type: application/soap+xml; charset=utf-8
Date: Tue, 12 Feb 2019 14:50:23 GMT
Server: Microsoft-IIS/10.0
X-Powered-By: ASP.NET
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing">[CONTENT REMOVED]</s:Envelope>--------------------

git-upload-pack: command not found, when cloning remote Git repo

Like Johan pointed out many times its .bashrc that's needed:

ln -s .bash_profile .bashrc

Is java.sql.Timestamp timezone specific?

You can use the below method to store the timestamp in database specific to your desired zone/zone Id.

ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("Asia/Calcutta")) ;
Timestamp timestamp = Timestamp.valueOf(zdt.toLocalDateTime());

A common mistake people do is use LocaleDateTime to get the timestamp of that instant which discards any information specif to your zone even if you try to convert it later. It does not understand the Zone.

Please note Timestamp is of the class java.sql.Timestamp.

How to initialize var?

Thank you Mr.Snake, Found this helpfull for another trick i was looking for :) (Not enough rep to comment)

Shorthand assignment of nullable types. Like this:

var someDate = !Convert.IsDBNull(dataRow["SomeDate"])
                    ? Convert.ToDateTime(dataRow["SomeDate"])
                    : (DateTime?) null;

How to unlock a file from someone else in Team Foundation Server

If you login into the source control with the admin account, you will be able to force undo checkout, or check in with any file you provide.

mysql Foreign key constraint is incorrectly formed error

The problem is very simple to solve

e.g: you have two table with names users and posts and you want create foreign key in posts table and you use phpMyAdmin

1) in post table add new column (name:use_id | type: like the id in user table | Length:like the id in user table | Default:NULL | Attributes:unsigned | index:INDEX )

2)on Structure tab go to relation view (Constraint name: auto set by phpmyAdmin | column name:select user_id |table:users | key: id ,...)

It was simply solved

javad mosavi iran/urmia

Get root password for Google Cloud Engine VM

I had the same problem. Even after updating the password using sudo passwd it was not working. I had to give "multiple" roles for my user through IAM & Admin Refer Screen Shot on IAM & Admin screen of google cloud

After that i restarted the VM. Then again changed the password and then it worked.

user1@sap-hanaexpress-public-1-vm:~> sudo passwd
New password: 
Retype new password: 
passwd: password updated successfully
user1@sap-hanaexpress-public-1-vm:~> su
Password: 
sap-hanaexpress-public-1-vm:/home/user1 # whoami
root
sap-hanaexpress-public-1-vm:/home/user1 #

use current date as default value for a column

Table creation Syntax can be like:

Create table api_key(api_key_id INT NOT NULL IDENTITY(1,1) 
PRIMARY KEY, date_added date DEFAULT 
GetDate());

Insertion query syntax can be like:

Insert into api_key values(GETDATE());

Check if cookies are enabled

Here is a very useful and lightweight javascript plugin to accomplish this: js-cookie

Cookies.set('cookieName', 'Value');
      setTimeout(function(){
        var cookieValue =  Cookies.get('cookieName');
        if(cookieValue){
           console.log("Test Cookie is set!");
        } else {
           document.write('<p>Sorry, but cookies must be enabled</p>');
        }
        Cookies.remove('cookieName');
      }, 1000);

Works in all browsers, accepts any character.

JSON.Parse,'Uncaught SyntaxError: Unexpected token o

var jsonStringNoQuotes = [{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}];

it will create json object. no need to parse.

jsonStringQuotes = "'" + jsonStringNoQuotes + "'";

will return '[object]'

thats why it(below) is causing error

var myData = JSON.parse(jsonStringQuotes);

Granting DBA privileges to user in Oracle

You need only to write:

GRANT DBA TO NewDBA;

Because this already makes the user a DB Administrator

Splitting on last delimiter in Python string?

I just did this for fun

    >>> s = 'a,b,c,d'
    >>> [item[::-1] for item in s[::-1].split(',', 1)][::-1]
    ['a,b,c', 'd']

Caution: Refer to the first comment in below where this answer can go wrong.

How to access your website through LAN in ASP.NET

You may also need to enable the World Wide Web Service inbound firewall rule.

On Windows 7: Start -> Control Panel -> Windows Firewall -> Advanced Settings -> Inbound Rules

Find World Wide Web Services (HTTP Traffic-In) in the list and select to enable the rule. Change is pretty much immediate.

Checking if a textbox is empty in Javascript

your validation should be occur before your event suppose you are going to submit your form.

anyway if you want this on onchange, so here is code.

function valid(id)
{
    var textVal=document.getElementById(id).value;
    if (!textVal.match(/\S/)) 
    {
        alert("Field is blank");
        return false;
    } 
    else 
    {
        return true;
    }
 }

Convert list to array in Java

Try this:

List list = new ArrayList();
list.add("Apple");
list.add("Banana");

Object[] ol = list.toArray();

How to change text color and console color in code::blocks?

An Easy Approach...

system("Color F0");

Letter Represents Background Color while the number represents the text color.

0 = Black

1 = Blue

2 = Green

3 = Aqua

4 = Red

5 = Purple

6 = Yellow

7 = White

8 = Gray

9 = Light Blue

A = Light Green

B = Light Aqua

C = Light Red

D = Light Purple

E = Light Yellow

F = Bright White

this.getClass().getClassLoader().getResource("...") and NullPointerException

I think I did encounter the same issue as yours. I created a simple mvn project and used "mvn eclipse:eclipse" to setup a eclipse project.

For example, my source file "Router.java" locates in "java/main/org/jhoh/mvc". And Router.java wants to read file "routes" which locates in "java/main/org/jhoh/mvc/resources"

I run "Router.java" in eclipse, and eclipse's console got NullPointerExeption. I set pom.xml with this setting to make all *.class java bytecode files locate in build directory.

<build>
    <defaultGoal>package</defaultGoal>
    <directory>${basedir}/build</directory>
<build>

I went to directory "build/classes/org/jhoh/mvc/resources", and there is no "routes". Eclipse DID NOT copy "routes" to "build/classes/org/jhoh/mvc/resources"

I think you can copy your "install.xml" to your *.class bytecode directory, NOT in your source code directory.

AngularJS dynamic routing

Not sure why this works but dynamic (or wildcard if you prefer) routes are possible in angular 1.2.0-rc.2...

http://code.angularjs.org/1.2.0-rc.2/angular.min.js
http://code.angularjs.org/1.2.0-rc.2/angular-route.min.js

angular.module('yadda', [
  'ngRoute'
]).

config(function ($routeProvider, $locationProvider) {
  $routeProvider.
    when('/:a', {
  template: '<div ng-include="templateUrl">Loading...</div>',
  controller: 'DynamicController'
}).


controller('DynamicController', function ($scope, $routeParams) {
console.log($routeParams);
$scope.templateUrl = 'partials/' + $routeParams.a;
}).

example.com/foo -> loads "foo" partial

example.com/bar-> loads "bar" partial

No need for any adjustments in the ng-view. The '/:a' case is the only variable I have found that will acheive this.. '/:foo' does not work unless your partials are all foo1, foo2, etc... '/:a' works with any partial name.

All values fire the dynamic controller - so there is no "otherwise" but, I think it is what you're looking for in a dynamic or wildcard routing scenario..

jQuery click events firing multiple times

It happens due to the particular event is bound multiple times to the same element.

The solution which worked for me is:

Kill all the events attached using .die() method.

And then attach your method listener.

Thus,

$('.arrow').click(function() {
// FUNCTION BODY HERE
}

should be:

$('.arrow').die("click")
$('.arrow').click(function() {
// FUNCTION BODY HERE
}

Matplotlib-Animation "No MovieWriters Available"

Had the same problem....managed to get it to work after a little while.

Thing to do is follow instructions on installing FFmpeg - which is (at least on windows) a bundle of executables you need to set a path to in your environment variables

http://www.wikihow.com/Install-FFmpeg-on-Windows

Download from ffmpeg.org

Hope this helps someone - even after a while after the question - good luck

How to set viewport meta for iPhone that handles rotation properly?

Was just trying to work this out myself, and the solution I came up with was:

<meta name="viewport" content="initial-scale = 1.0,maximum-scale = 1.0" />

This seems to lock the device into 1.0 scale regardless of it's orientation. As a side effect, it does however completely disable user scaling (pinch zooming, etc).

AngularJS: How to run additional code after AngularJS has rendered a template?

In some scenarios where you update a service and redirect to a new view(page) and then your directive gets loaded before your services are updated then you can use $rootScope.$broadcast if your $watch or $timeout fails

View

<service-history log="log" data-ng-repeat="log in requiedData"></service-history>

Controller

app.controller("MyController",['$scope','$rootScope', function($scope, $rootScope) {

   $scope.$on('$viewContentLoaded', function () {
       SomeSerive.getHistory().then(function(data) {
           $scope.requiedData = data;
           $rootScope.$broadcast("history-updation");
       });
  });

}]);

Directive

app.directive("serviceHistory", function() {
    return {
        restrict: 'E',
        replace: true,
        scope: {
           log: '='
        },
        link: function($scope, element, attrs) {
            function updateHistory() {
               if(log) {
                   //do something
               }
            }
            $rootScope.$on("history-updation", updateHistory);
        }
   };
});

How can I refresh or reload the JFrame?

You should use this code

this.setVisible(false); //this will close frame i.e. NewJFrame

new NewJFrame().setVisible(true); // Now this will open NewJFrame for you again and will also get refreshed 

IllegalMonitorStateException on wait() call

Based on your comments it sounds like you are doing something like this:

Thread thread = new Thread(new Runnable(){
    public void run() { // do stuff }});

thread.start();
...
thread.wait();

There are three problems.

  1. As others have said, obj.wait() can only be called if the current thread holds the primitive lock / mutex for obj. If the current thread does not hold the lock, you get the exception you are seeing.

  2. The thread.wait() call does not do what you seem to be expecting it to do. Specifically, thread.wait() does not cause the nominated thread to wait. Rather it causes the current thread to wait until some other thread calls thread.notify() or thread.notifyAll().

    There is actually no safe way to force a Thread instance to pause if it doesn't want to. (The nearest that Java has to this is the deprecated Thread.suspend() method, but that method is inherently unsafe, as is explained in the Javadoc.)

    If you want the newly started Thread to pause, the best way to do it is to create a CountdownLatch instance and have the thread call await() on the latch to pause itself. The main thread would then call countDown() on the latch to let the paused thread continue.

  3. Orthogonal to the previous points, using a Thread object as a lock / mutex may cause problems. For example, the javadoc for Thread::join says:

    This implementation uses a loop of this.wait calls conditioned on this.isAlive. As a thread terminates the this.notifyAll method is invoked. It is recommended that applications not use wait, notify, or notifyAll on Thread instances.

Send cookies with curl

You can use -b to specify a cookie file to read the cookies from as well.

In many situations using -c and -b to the same file is what you want:

curl -b cookies.txt -c cookies.txt http://example.com

Further

Using only -c will make curl start with no cookies but still parse and understand cookies and if redirects or multiple URLs are used, it will then use the received cookies within the single invoke before it writes them all to the output file in the end.

The -b option feeds a set of initial cookies into curl so that it knows about them at start, and it activates curl's cookie parser so that it'll parse and use incoming cookies as well.

See Also

The cookies chapter in the Everything curl book.

Is it possible to select the last n items with nth-child?

This will select the last two iems of a list:

_x000D_
_x000D_
li:nth-last-child(-n+2) {color:red;}
_x000D_
<ul>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
</ul>
_x000D_
_x000D_
_x000D_

'ng' is not recognized as an internal or external command, operable program or batch file

You don't need to set any path. Follow the below step to resolve the problem-

Step 1- go to

C:\Users\user\AppData\Roaming and delete npm, npm-update and npm-cache folder

Step 2- run

npm install -g @angular/cli@yourangularversion again.

CSS Flex Box Layout: full-width row and columns

This is copied from above, but condensed slightly and re-written in semantic terms. Note: #Container has display: flex; and flex-direction: column;, while the columns have flex: 3; and flex: 2; (where "One value, unitless number" determines the flex-grow property) per MDN flex docs.

_x000D_
_x000D_
#Container {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  height: 600px;_x000D_
  width: 580px;_x000D_
}_x000D_
_x000D_
.Content {_x000D_
  display: flex;_x000D_
  flex: 1;_x000D_
}_x000D_
_x000D_
#Detail {_x000D_
  flex: 3;_x000D_
  background-color: lime;_x000D_
}_x000D_
_x000D_
#ThumbnailContainer {_x000D_
  flex: 2;_x000D_
  background-color: black;_x000D_
}
_x000D_
<div id="Container">_x000D_
  <div class="Content">_x000D_
    <div id="Detail"></div>_x000D_
    <div id="ThumbnailContainer"></div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Property 'value' does not exist on type EventTarget in TypeScript

Try code below:

  console.log(event['target'].value)

it works for me :-)

"npm config set registry https://registry.npmjs.org/" is not working in windows bat file

We can also run npm install with registry options for multiple custom registry URLs.

npm install --registry=https://registry.npmjs.org/ 
npm install --registry=https://custom.npm.registry.com/ 

Select last N rows from MySQL

SELECT * FROM table ORDER BY id DESC,datechat desc LIMIT 50

If you have a date field that is storing the date(and time) on which the chat was sent or any field that is filled with incrementally(order by DESC) or desinscrementally( order by ASC) data per row put it as second column on which the data should be order.

That's what worked for me!!!! hope it will help!!!!

SQL Insert Multiple Rows

You can use UNION All clause to perform multiple insert in a table.

ex:

INSERT INTO dbo.MyTable (ID, Name)
SELECT 123, 'Timmy'
UNION ALL
SELECT 124, 'Jonny'
UNION ALL
SELECT 125, 'Sally'

Check here

How do I add a newline to command output in PowerShell?

Or, just set the output field separator (OFS) to double newlines, and then make sure you get a string when you send it to file:

$OFS = "`r`n`r`n"
"$( gci -path hklm:\software\microsoft\windows\currentversion\uninstall | 
    ForEach-Object -Process { write-output $_.GetValue('DisplayName') } )" | 
 out-file addrem.txt

Beware to use the ` and not the '. On my keyboard (US-English Qwerty layout) it's located left of the 1.
(Moved here from the comments - Thanks Koen Zomers)

Adding additional data to select options using jQuery

I made two examples from what I think your question might be:

http://jsfiddle.net/grdn4/

Check this out for storing additional values. It uses data attributes to store the other value:

http://jsfiddle.net/27qJP/1/

How can I save an image with PIL?

You should be able to simply let PIL get the filetype from extension, i.e. use:

j.save("C:/Users/User/Desktop/mesh_trans.bmp")

How do you make div elements display inline?

An inline div is a freak of the web & should be beaten until it becomes a span (at least 9 times out of 10)...

<span>foo</span>
<span>bar</span>
<span>baz</span>

...answers the original question...

Pandas sort by group aggregate and column

Here's a more concise approach...

df['a_bsum'] = df.groupby('A')['B'].transform(sum)
df.sort(['a_bsum','C'], ascending=[True, False]).drop('a_bsum', axis=1)

The first line adds a column to the data frame with the groupwise sum. The second line performs the sort and then removes the extra column.

Result:

    A       B           C
5   baz     -2.301539   True
2   baz     -0.528172   False
1   bar     -0.611756   True
4   bar      0.865408   False
3   foo     -1.072969   True
0   foo      1.624345   False

NOTE: sort is deprecated, use sort_values instead

AngularJS - Trigger when radio button is selected

There are at least 2 different methods of invoking functions on radio button selection:

1) Using ng-change directive:

<input type="radio" ng-model="value" value="foo" ng-change='newValue(value)'>

and then, in a controller:

$scope.newValue = function(value) {
     console.log(value);
}

Here is the jsFiddle: http://jsfiddle.net/ZPcSe/5/

2) Watching the model for changes. This doesn't require anything special on the input level:

<input type="radio" ng-model="value" value="foo">

but in a controller one would have:

$scope.$watch('value', function(value) {
       console.log(value);
 });

And the jsFiddle: http://jsfiddle.net/vDTRp/2/

Knowing more about your the use case would help to propose an adequate solution.

codes for ADD,EDIT,DELETE,SEARCH in vb2010

Have you googled about it - insert update delete access vb.net, there are lots of reference about this.

Insert Update Delete Navigation & Searching In Access Database Using VB.NET

  • Create Visual Basic 2010 Project: VB-Access
  • Assume that, we have a database file named data.mdb
  • Place the data.mdb file into ..\bin\Debug\ folder (Where the project executable file (.exe) is placed)

what could be the easier way to connect and manipulate the DB?
Use OleDBConnection class to make connection with DB

is it by using MS ACCESS 2003 or MS ACCESS 2007?
you can use any you want to use or your client will use on their machine.

it seems that you want to find some example of opereations fo the database. Here is an example of Access 2010 for your reference:

Example code snippet:

Imports System
Imports System.Data
Imports System.Data.OleDb

Public Class DBUtil

 Private connectionString As String

 Public Sub New()

  Dim con As New OleDb.OleDbConnection
  Dim dbProvider As String = "Provider=Microsoft.ace.oledb.12.0;"
  Dim dbSource = "Data Source=d:\DB\Database11.accdb"

  connectionString = dbProvider & dbSource

 End Sub

 Public Function GetCategories() As DataSet

  Dim query As String = "SELECT * FROM Categories"
  Dim cmd As New OleDbCommand(query)
  Return FillDataSet(cmd, "Categories")

 End Function

 Public SubUpdateCategories(ByVal name As String)
  Dim query As String = "update Categories set name = 'new2' where name = ?"
  Dim cmd As New OleDbCommand(query)
cmd.Parameters.AddWithValue("Name", name)
  Return FillDataSet(cmd, "Categories")

 End Sub

 Public Function GetItems() As DataSet

  Dim query As String = "SELECT * FROM Items"
  Dim cmd As New OleDbCommand(query)
  Return FillDataSet(cmd, "Items")

 End Function

 Public Function GetItems(ByVal categoryID As Integer) As DataSet

  'Create the command.
  Dim query As String = "SELECT * FROM Items WHERE Category_ID=?"
  Dim cmd As New OleDbCommand(query)
  cmd.Parameters.AddWithValue("category_ID", categoryID)

  'Fill the dataset.
  Return FillDataSet(cmd, "Items")

 End Function

 Public Sub AddCategory(ByVal name As String)

  Dim con As New OleDbConnection(connectionString)

  'Create the command.
  Dim insertSQL As String = "INSERT INTO Categories "
  insertSQL &= "VALUES(?)"
  Dim cmd As New OleDbCommand(insertSQL, con)
  cmd.Parameters.AddWithValue("Name", name)

  Try
   con.Open()
   cmd.ExecuteNonQuery()
  Finally
   con.Close()
  End Try

 End Sub

 Public Sub AddItem(ByVal title As String, ByVal description As String, _
    ByVal price As Decimal, ByVal categoryID As Integer)

  Dim con As New OleDbConnection(connectionString)

  'Create the command.
  Dim insertSQL As String = "INSERT INTO Items "
  insertSQL &= "(Title, Description, Price, Category_ID)"
  insertSQL &= "VALUES (?, ?, ?, ?)"
  Dim cmd As New OleDb.OleDbCommand(insertSQL, con)
  cmd.Parameters.AddWithValue("Title", title)
  cmd.Parameters.AddWithValue("Description", description)
  cmd.Parameters.AddWithValue("Price", price)
  cmd.Parameters.AddWithValue("CategoryID", categoryID)

  Try
   con.Open()
   cmd.ExecuteNonQuery()
  Finally
   con.Close()
  End Try

 End Sub

 Private Function FillDataSet(ByVal cmd As OleDbCommand, ByVal tableName As String) As DataSet

  Dim con As New OleDb.OleDbConnection
  Dim dbProvider As String = "Provider=Microsoft.ace.oledb.12.0;"
  Dim dbSource = "Data Source=D:\DB\Database11.accdb"

  connectionString = dbProvider & dbSource
  con.ConnectionString = connectionString
  cmd.Connection = con
  Dim adapter As New OleDbDataAdapter(cmd)
  Dim ds As New DataSet()

  Try
   con.Open()
   adapter.Fill(ds, tableName)
  Finally
   con.Close()
  End Try
  Return ds

 End Function

End Class

Refer these links:
Insert, Update, Delete & Search Values in MS Access 2003 with VB.NET 2005
INSERT, DELETE, UPDATE AND SELECT Data in MS-Access with VB 2008
How Add new record ,Update record,Delete Records using Vb.net Forms when Access as a back

How do I create a HTTP Client Request with a cookie?

The use of http.createClient is now deprecated. You can pass Headers in options collection as below.

var options = { 
    hostname: 'example.com',
    path: '/somePath.php',
    method: 'GET',
    headers: {'Cookie': 'myCookie=myvalue'}
};
var results = ''; 
var req = http.request(options, function(res) {
    res.on('data', function (chunk) {
        results = results + chunk;
        //TODO
    }); 
    res.on('end', function () {
        //TODO
    }); 
});

req.on('error', function(e) {
        //TODO
});

req.end();

Remove large .pack file created by git

Run the following command, replacing PATH-TO-YOUR-FILE-WITH-SENSITIVE-DATA with the path to the file you want to remove, not just its filename. These arguments will:

  1. Force Git to process, but not check out, the entire history of every branch and tag
  2. Remove the specified file, as well as any empty commits generated as a result
  3. Overwrite your existing tags
git filter-branch --force --index-filter "git rm --cached --ignore-unmatch PATH-TO-YOUR-FILE-WITH-SENSITIVE-DATA" --prune-empty --tag-name-filter cat -- --all

This will forcefully remove all references to the files from the active history of the repo.

Next step, to perform a GC cycle to force all references to the file to be expired and purged from the pack file. Nothing needs to be replaced in these commands.

git update-ref -d refs/original/refs/remotes/origin/master
git for-each-ref --format='delete %(refname)' refs/original | git update-ref --stdin
git reflog expire --expire=now --all
git gc --aggressive --prune=now

How to insert a new line in Linux shell script?

Use this echo statement

 echo -e "Hai\nHello\nTesting\n"

The output is

Hai
Hello
Testing

laravel 5.3 new Auth::routes()

This worked for me with Laravel 5.6.

In the file web.php, just replace:

Auth::routes();

By:

//Auth::routes();
// Authentication Routes...
Route::get('admin/login', 'Auth\LoginController@showLoginForm')->name('login');
Route::post('admin/login', 'Auth\LoginController@login');
Route::post('admin/logout', 'Auth\LoginController@logout')->name('logout');
// Password Reset Routes...
Route::get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->name('password.request');
Route::post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')->name('password.email');
Route::get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset');
Route::post('password/reset', 'Auth\ResetPasswordController@reset');

And remove the Register link in the two files below:

welcome.blade.php
layouts/app.blade.php

ComboBox.SelectedText doesn't give me the SelectedText

Here's how I would approach the problem, assuming you want to change the text of say, a label

    private void comboBoxtest_SelectedIndexChanged(object sender, EventArgs e)
    {
        var combotext = comboBoxtest.Text;
        var status = "The status of my combo box is" + combotext;
        label1.Text = status;
    }

WPF Databinding: How do I access the "parent" data context?

This will also work:

<Hyperlink Command="{Binding RelativeSource={RelativeSource AncestorType=ItemsControl},
                             Path=DataContext.AllowItemCommand}" />

ListView will inherit its DataContext from Window, so it's available at this point, too.
And since ListView, just like similar controls (e. g. Gridview, ListBox, etc.), is a subclass of ItemsControl, the Binding for such controls will work perfectly.

Keep only first n characters in a string?

You could use String.slice:

var str = '12345678value';
var strshortened = str.slice(0,8);
alert(strshortened); //=> '12345678'

Using this, a String extension could be:

String.prototype.truncate = String.prototype.truncate ||
  function (n){
    return this.slice(0,n);
  };
var str = '12345678value';
alert(str.truncate(8)); //=> '12345678'

See also

Shortcut to open file in Vim

If you're editing files in a common directory, you can :cd to that directory, then use :e on just the filename.

For example, rather than:

:e /big/long/path/that/takes/a/while/to/type/or/tab/complete/thingy.rb
:sp /big/long/path/that/takes/a/while/to/type/or/tab/complete/other_thingy.c
:vs /big/long/path/that/takes/a/while/to/type/or/tab/complete/one_more_thingy.java

You can do:

:cd /big/long/path/that/takes/a/while/to/type/or/tab/complete/
:e thingy.rb
:sp other_thingy.c
:vs one_more_thingy.java

Or, if you already have a file in the desired directory open, you can use the % shorthand for the current filename, and trim it to the current directory with the :h modifier (:help :_%:) :

:e /big/long/path/that/takes/a/while/to/type/or/tab/complete/thingy.rb
:cd %:h
:sp other_thingy.c
:vs one_more_thingy.java

And, like others have said, you can tab-complete file names on the ex-line (see :help cmdline-completion for more).

VB.NET Connection string (Web.Config, App.Config)

Connection in APPConfig

<connectionStrings>
  <add name="ConnectionString" connectionString="Data Source=192.168.1.25;Initial Catalog=Login;Persist Security Info=True;User ID=sa;Password=example.com"   providerName="System.Data.SqlClient" />
</connectionStrings>

In Class.Cs

public string ConnectionString
{
    get
    {
        return System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
    }
}

Load HTML File Contents to Div [without the use of iframes]

http://www.boutell.com/newfaq/creating/include.html

this would explain how to write your own clientsideinlcude but jQuery is a lot, A LOT easier option ... plus you will gain a lot more by using jQuery anyways

javascript - pass selected value from popup window to parent window input box

(parent window)

<html> 
<script language="javascript"> 
function openWindow() { 
  window.open("target.html","_blank","height=200,width=400, status=yes,toolbar=no,menubar=no,location=no"); 
} 
</script> 
<body> 
<form name=frm> 
<input id=text1 type=text> 
<input type=button onclick="javascript:openWindow()" value="Open window.."> 
</form> 
</body> 
</html>

(child window)

<html> 
<script language="javascript"> 
function changeParent() { 
  window.opener.document.getElementById('text1').value="Value changed..";
  window.close();
} 
</script> 
<body> 
<form> 
<input type=button onclick="javascript:changeParent()" value="Change opener's textbox's value.."> 
</form> 
</body> 
</html>

http://www.codehappiness.com/post/access-parent-window-from-child-window-or-access-child-window-from-parent-window-using-javascript.aspx

How to vertically align text with icon font?

You can use this property : vertical-align:middle;

.selector-class { 
    float:left;
    vertical-align:middle; 
} 

How to use boolean 'and' in Python

In python, use and instead of && like this:

#!/usr/bin/python
foo = True;
bar = True;
if foo and bar:
    print "both are true";

This prints:

both are true

Typescript Type 'string' is not assignable to type

If you're casting to a dropdownvalue[] when mocking data for example, compose it as an array of objects with value and display properties.

example:

[{'value': 'test1', 'display1': 'test display'},{'value': 'test2', 'display': 'test display2'},]

webpack command not working

I had to reinstall webpack to get it working with my local version of webpack, e.g:

$ npm uninstall webpack
$ npm i -D webpack

Convert txt to csv python script

import pandas as pd
df = pd.read_fwf('log.txt')
df.to_csv('log.csv')

SQL Server check case-sensitivity?

Collation can be set at various levels:

  1. Server
  2. Database
  3. Column

So you could have a Case Sensitive Column in a Case Insensitive database. I have not yet come across a situation where a business case could be made for case sensitivity of a single column of data, but I suppose there could be.

Check Server Collation

SELECT SERVERPROPERTY('COLLATION')

Check Database Collation

SELECT DATABASEPROPERTYEX('AdventureWorks', 'Collation') SQLCollation;

Check Column Collation

select table_name, column_name, collation_name
from INFORMATION_SCHEMA.COLUMNS
where table_name = @table_name

Html attributes for EditorFor() in ASP.NET MVC

As of MVC 5.1, you can now do the following:

@Html.EditorFor(model => model, new { htmlAttributes = new { @class = "form-control" }, })

http://www.asp.net/mvc/overview/releases/mvc51-release-notes#new-features

How do you automatically set text box to Uppercase?

I think the most robust solution that will insure that it is posted in uppercase is to use the oninput method inline like:

_x000D_
_x000D_
<input oninput="this.value = this.value.toUpperCase()" />
_x000D_
_x000D_
_x000D_

EDIT

Some people have been complaining that the cursor jumps to the end when editing the value, so this slightly expanded version should resolve that

_x000D_
_x000D_
<input oninput="let p=this.selectionStart;this.value=this.value.toUpperCase();this.setSelectionRange(p, p);" />
_x000D_
_x000D_
_x000D_

Property 'catch' does not exist on type 'Observable<any>'

In angular 8:

//for catch:
import { catchError } from 'rxjs/operators';

//for throw:
import { Observable, throwError } from 'rxjs';

//and code should be written like this.

getEmployees(): Observable<IEmployee[]> {
    return this.http.get<IEmployee[]>(this.url).pipe(catchError(this.erroHandler));
  }

  erroHandler(error: HttpErrorResponse) {
    return throwError(error.message || 'server Error');
  }

Python subprocess/Popen with a modified environment

To temporarily set an environment variable without having to copy the os.envrion object etc, I do this:

process = subprocess.Popen(['env', 'RSYNC_PASSWORD=foobar', 'rsync', \
'rsync://[email protected]::'], stdout=subprocess.PIPE)

Can I open a dropdownlist using jQuery

You can easily simulate a click on an element, but a click on a <select> won’t open up the dropdown.

Using multiple selects can be problematic. Perhaps you should consider radio buttons inside a container element which you can expand and contract as needed.

When does Java's Thread.sleep throw InterruptedException?

A solid and easy way to handle it in single threaded code would be to catch it and retrow it in a RuntimeException, to avoid the need to declare it for every method.

How can I use Google's Roboto font on a website?

Old post, I know.

This is also possible using CSS @import url:

@import url(http://fonts.googleapis.com/css?family=Roboto:400,100,100italic,300,300ita??lic,400italic,500,500italic,700,700italic,900italic,900);
html, body, html * {
  font-family: 'Roboto', sans-serif;
}

Failed binder transaction when putting an bitmap dynamically in a widget

The right approach is to use setImageViewUri() (slower) or the setImageViewBitmap() and recreating RemoteViews every time you update the notification.

error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)' -- Missing /var/run/mysqld/mysqld.sock

my situation is that the mysql in the /etc/ directory is renamed mysql_bk, just copy mysql_bk

sudo cp -r /etc/mysql_bk/ /etc/mysql/

then

service mysql restart

How do I set log4j level on the command line?

These answers actually dissuaded me from trying the simplest possible thing! Simply specify a threshold for an appender (say, "console") in your log4j.configuration like so:

log4j.appender.console.threshold=${my.logging.threshold}

Then, on the command line, include the system property -Dlog4j.info -Dmy.logging.threshold=INFO. I assume that any other property can be parameterized in this way, but this is the easiest way to raise or lower the logging level globally.

How to deal with "data of class uneval" error from ggplot2?

This could also occur if you refer to a variable in the data.frame that doesn't exist. For example, recently I forgot to tell ddply to summarize by one of my variables that I used in geom_line to specify line color. Then, ggplot didn't know where to find the variable I hadn't created in the summary table, and I got this error.

What does "where T : class, new()" mean?

where (C# Reference)

The new() Constraint lets the compiler know that any type argument supplied must have an accessible parameterless--or default-- constructor

So it should be, T must be a class, and have an accessible parameterless--or default constructor.

How to format a java.sql Timestamp for displaying?

Use a DateFormat. In an internationalized application, use the format provide by getInstance. If you want to explicitly control the format, create a new SimpleDateFormat yourself.

MySql Proccesslist filled with "Sleep" Entries leading to "Too many Connections"?

Basically, you get connections in the Sleep state when :

  • a PHP script connects to MySQL
  • some queries are executed
  • then, the PHP script does some stuff that takes time
    • without disconnecting from the DB
  • and, finally, the PHP script ends
    • which means it disconnects from the MySQL server

So, you generally end up with many processes in a Sleep state when you have a lot of PHP processes that stay connected, without actually doing anything on the database-side.

A basic idea, so : make sure you don't have PHP processes that run for too long -- or force them to disconnect as soon as they don't need to access the database anymore.


Another thing, that I often see when there is some load on the server :

  • There are more and more requests coming to Apache
    • which means many pages to generate
  • Each PHP script, in order to generate a page, connects to the DB and does some queries
  • These queries take more and more time, as the load on the DB server increases
  • Which means more processes keep stacking up

A solution that can help is to reduce the time your queries take -- optimizing the longest ones.

Setting timezone in Python

For windows you can use:

Running Windows command prompt commands in python.

import os
os.system('tzutil /s "Central Standard Time"')

In windows command prompt try:

This gives current timezone:

tzutil /g

This gives a list of timezones:

tzutil /l

This will set the timezone:

tzutil /s "Central America Standard Time"

For further reference: http://woshub.com/how-to-set-timezone-from-command-prompt-in-windows/

Share Text on Facebook from Android App via ACTION_SEND

Check this out : By this we can check activity results also....
// Open all sharing option for user
                    Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND); 
                    sharingIntent.setType("text/plain");                    
                    sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, ShortDesc+" from "+BusinessName);
                    sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, ShortDesc+" "+ShareURL);
                    sharingIntent.putExtra(Intent.EXTRA_TITLE, ShortDesc+" "+ShareURL);
                    startActivityForResult(Intent.createChooser(sharingIntent, "Share via"),1000);
/**
     * Get the result when we share any data to another activity 
     * */
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch(requestCode) {
        case 1000:
            if(resultCode == RESULT_OK)
                Toast.makeText(getApplicationContext(), "Activity 1 returned OK", Toast.LENGTH_LONG).show();
            else
                Toast.makeText(getApplicationContext(), "Activity 1 returned NOT OK", Toast.LENGTH_LONG).show();
            break;
        case 1002:
            if(resultCode == RESULT_OK)
                Toast.makeText(getApplicationContext(), "Activity 2 returned OK", Toast.LENGTH_LONG).show();
            break;
        }// end switch



    }// end onActivityResult

Is key-value pair available in Typescript?

If you are trying to use below example

Example: { value1: "value1" }

And add conditionalData dynamically based on some condition, Try

let dataToWrite: any = {value1: "value1"};

if(conditionalData)
   dataToWrite["conditionalData"] = conditionalData

Java: How to read a text file

Use Apache Commons (IO and Lang) for simple/common things like this.

Imports:

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.ArrayUtils;

Code:

String contents = FileUtils.readFileToString(new File("path/to/your/file.txt"));
String[] array = ArrayUtils.toArray(contents.split(" "));

Done.

How can I clear the SQL Server query cache?

EXEC sys.sp_configure N'max server memory (MB)', N'2147483646'
GO
RECONFIGURE WITH OVERRIDE
GO

What value you specify for the server memory is not important, as long as it differs from the current one.

Btw, the thing that causes the speedup is not the query cache, but the data cache.

Can you put two conditions in an xslt test attribute?

Maybe this is a no-brainer for the xslt-professional, but for me at beginner/intermediate level, this got me puzzled. I wanted to do exactly the same thing, but I had to test a responsetime value from an xml instead of a plain number. Following this thread, I tried this:

<xsl:when test="responsetime/@value &gt;= 5000 and responsetime/@value &lt;= 8999"> 

which generated an error. This works:

<xsl:when test="number(responsetime/@value) &gt;= 5000 and number(responsetime/@value) &lt;= 8999">

Don't really understand why it doesn't work without number(), though. Could it be that without number() the value is treated as a string and you can't compare numbers with a string?

Anyway, hope this saves someone a lot of searching...

Can I give a default value to parameters or optional parameters in C# functions?

This is a feature of C# 4.0, but was not possible without using function overload prior to that version.

Check if object exists in JavaScript

Think it's easiest like this

if(myobject_or_myvar)
    alert('it exists');
else
   alert("what the hell you'll talking about");

How to convert const char* to char* in C?

You can cast it by doing (char *)Identifier_Of_Const_char

But as there is probabbly a reason that the api doesn't accept const cahr *, you should do this only, if you are sure, the function doesn't try to assign any value in range of your const char* which you casted to a non const one.

Force drop mysql bypassing foreign key constraint

Simple solution to drop all the table at once from terminal.

This involved few steps inside your mysql shell (not a one step solution though), this worked me and saved my day.

Worked for Server version: 5.6.38 MySQL Community Server (GPL)

Steps I followed:

 1. generate drop query using concat and group_concat.
 2. use database
 3. turn off / disable foreign key constraint check (SET FOREIGN_KEY_CHECKS = 0;), 
 4. copy the query generated from step 1
 5. re enable foreign key constraint check (SET FOREIGN_KEY_CHECKS = 1;)
 6. run show table

MySQL shell

$ mysql -u root -p
Enter password: ****** (your mysql root password)
mysql> SYSTEM CLEAR;
mysql> SELECT CONCAT('DROP TABLE IF EXISTS `', GROUP_CONCAT(table_name SEPARATOR '`, `'), '`;') AS dropquery FROM information_schema.tables WHERE table_schema = 'emall_duplicate';
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| dropquery                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| DROP TABLE IF EXISTS `admin`, `app`, `app_meta_settings`, `commission`, `commission_history`, `coupon`, `email_templates`, `infopages`, `invoice`, `m_pc_xref`, `member`, `merchant`, `message_templates`, `mnotification`, `mshipping_address`, `notification`, `order`, `orderdetail`, `pattributes`, `pbrand`, `pcategory`, `permissions`, `pfeatures`, `pimage`, `preport`, `product`, `product_review`, `pspecification`, `ptechnical_specification`, `pwishlist`, `role_perms`, `roles`, `settings`, `test`, `testanother`, `user_perms`, `user_roles`, `users`, `wishlist`; |
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> USE emall_duplicate;
Database changed
mysql> SET FOREIGN_KEY_CHECKS = 0;                                                                                                                                                   Query OK, 0 rows affected (0.00 sec)

// copy and paste generated query from step 1
mysql> DROP TABLE IF EXISTS `admin`, `app`, `app_meta_settings`, `commission`, `commission_history`, `coupon`, `email_templates`, `infopages`, `invoice`, `m_pc_xref`, `member`, `merchant`, `message_templates`, `mnotification`, `mshipping_address`, `notification`, `order`, `orderdetail`, `pattributes`, `pbrand`, `pcategory`, `permissions`, `pfeatures`, `pimage`, `preport`, `product`, `product_review`, `pspecification`, `ptechnical_specification`, `pwishlist`, `role_perms`, `roles`, `settings`, `test`, `testanother`, `user_perms`, `user_roles`, `users`, `wishlist`;
Query OK, 0 rows affected (0.18 sec)

mysql> SET FOREIGN_KEY_CHECKS = 1;
Query OK, 0 rows affected (0.00 sec)

mysql> SHOW tables;
Empty set (0.01 sec)

mysql> 

org.hibernate.MappingException: Unknown entity: annotations.Users

Problem occurs because of the entry mapping class="annotations.Users" in hibernate.cfg.xml remove that line then it will be work.

I had the same issue. When I removed the above line then it was working fine for me.

How do I get a value of datetime.today() in Python that is "timezone aware"?

Getting a timezone-aware date in utc timezone is enough for date subtraction to work.

But if you want a timezone-aware date in your current time zone, tzlocal is the way to go:

from tzlocal import get_localzone  # pip install tzlocal
from datetime import datetime
datetime.now(get_localzone())

PS dateutil has a similar function (dateutil.tz.tzlocal). But inspite of sharing the name it has a completely different code base, which as noted by J.F. Sebastian can give wrong results.

How can I insert data into a MySQL database?

This way worked for me when adding random data to MySql table using a python script.
First install the following packages using the below commands

pip install mysql-connector-python<br>
pip install random
import mysql.connector
import random

from datetime import date


start_dt = date.today().replace(day=1, month=1).toordinal()
end_dt = date.today().toordinal()

mydb = mysql.connector.connect(
    host="localhost",
    user="root",
    password="root",
    database="your_db_name"
)

mycursor = mydb.cursor()

sql_insertion = "INSERT INTO customer (name,email,address,dateJoined) VALUES (%s, %s,%s, %s)"
#insert 10 records(rows)
for x in range(1,11):
    #generate a random date
    random_day = date.fromordinal(random.randint(start_dt, end_dt))
    value = ("customer" + str(x),"customer_email" + str(x),"customer_address" + str(x),random_day)
    mycursor.execute(sql_insertion , value)

mydb.commit()

print("customer records inserted!")


Following is a sample output of the insertion

cid       |  name      |  email           |    address        |  dateJoined  |

1         | customer1  |  customer_email1 | customer_address1 |  2020-11-15  |
2         | customer2  |  customer_email2 | customer_address2 |  2020-10-11  |
3         | customer3  |  customer_email3 | customer_address3 |  2020-11-17  |
4         | customer4  |  customer_email4 | customer_address4 |  2020-09-20  |
5         | customer5  |  customer_email5 | customer_address5 |  2020-02-18  |
6         | customer6  |  customer_email6 | customer_address6 |  2020-01-11  |
7         | customer7  |  customer_email7 | customer_address7 |  2020-05-30  |
8         | customer8  |  customer_email8 | customer_address8 |  2020-04-22  |
9         | customer9  |  customer_email9 | customer_address9 |  2020-01-05  |
10        | customer10 |  customer_email10| customer_address10|  2020-11-12  |



“Unable to find manifest signing certificate in the certificate store” - even when add new key

Go to your projects "Properties" within visual studio. Then go to signing tab.

Then make sure Sign the Click Once manifests is turned off.

OR

1.Open the .csproj file in Notepad.

2.Delete the following information related to signing certificate in the certificate store xxxxx xxxxxx xxxxxxxx.pfx true false `

Worked for me.

SyntaxError: unexpected EOF while parsing

Here is one of my mistakes that produced this exception: I had a try block without any except or finally blocks. This will not work:

try:
    lets_do_something_beneficial()

To fix this, add an except or finally block:

try:
    lets_do_something_beneficial()
finally:
    lets_go_to_sleep()

How to create a List with a dynamic object type

Just use dynamic as the argument:

var list = new List<dynamic>();

What's the simplest way of detecting keyboard input in a script from the terminal?

I wrote a more easy-to-use implementation for @enrico.bacis's answer. It supports both Linux(python2.7 and python3.5) and Windows(python2.7). It may support Mac OS, but I didn't test it. If you tried it on Mac, please tell me the result.

'''
Author: Yu Lou
Date: 2017-02-23

Based on the answer by @enrico.bacis in http://stackoverflow.com/a/13207724/4398908
and @Phylliida in http://stackoverflow.com/a/31736883/4398908
'''

# Import modules
try:
    try:
        import termios, fcntl, sys, os, curses # Import modules for Linux
    except ImportError:
        import msvcrt # Import module for Windows
except ImportError:
    raise Exception('This platform is not supported.')

class KeyGetterLinux:
    '''
    Implemented kbhit(), getch() and getchar() in Linux.

    Tested on Ubuntu 16.10(Linux 4.8.0), Python 2.7.12 and Python 3.5.2
    '''
    def __init__(self):
        self.buffer = '' # A buffer to store the character read by kbhit
        self.started = False # Whether initialization is complete

    def kbhit(self, echo = False):
        '''
        Return whether a key is hitten.
        '''
        if not self.buffer:
            if echo:
                self.buffer = self.getchar(block = False)
            else:
                self.buffer = self.getch(block = False)

        return bool(self.buffer)

    def getch(self, block = True):
        '''
        Return a single character without echo.
        If block is False and no input is currently available, return an empty string without waiting.
        '''
        try:
            curses.initscr()
            curses.noecho()
            return self.getchar(block)
        finally:
            curses.endwin()

    def getchar(self, block = True):
        '''
        Return a single character and echo.
        If block is False and no input is currently available, return an empty string without waiting.
        '''
        self._start()
        try:
            return self._getchar(block)
        finally:
            self._stop()

    def _getchar(self, block = True):
        '''
        Return a single character and echo.
        If block is False and no input is currently available, return a empty string without waiting.
        Should be called between self._start() and self._end()
        '''
        assert self.started, ('_getchar() is called before _start()')

        # Change the terminal setting
        if block:
            fcntl.fcntl(self.fd, fcntl.F_SETFL, self.old_flags & ~os.O_NONBLOCK)
        else:
            fcntl.fcntl(self.fd, fcntl.F_SETFL, self.old_flags | os.O_NONBLOCK)

        if self.buffer: # Use the character in buffer first
            result = self.buffer
            self.buffer = ''
        else:
            try:
                result = sys.stdin.read(1)
            except IOError: # In python 2.7, using read() when no input is available will result in IOError.
                return ''

        return result

    def _start(self):
        '''
        Initialize the terminal.
        '''
        assert not self.started, '_start() is called twice'

        self.fd = sys.stdin.fileno()

        self.old_attr = termios.tcgetattr(self.fd)

        new_attr = termios.tcgetattr(self.fd)
        new_attr[3] = new_attr[3] & ~termios.ICANON
        termios.tcsetattr(self.fd, termios.TCSANOW, new_attr)

        self.old_flags = fcntl.fcntl(self.fd, fcntl.F_GETFL)

        self.started = True

    def _stop(self):
        '''
        Restore the terminal.
        '''
        assert self.started, '_start() is not called'

        termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old_attr)
        fcntl.fcntl(self.fd, fcntl.F_SETFL, self.old_flags)

        self.started = False

    # Magic functions for context manager
    def __enter__(self):
        self._start()
        self.getchar = self._getchar # No need for self._start() now
        return self

    def __exit__(self, type, value, traceback):
        self._stop()
        return False

class KeyGetterWindows:
    '''
    kbhit() and getchar() in Windows.

    Tested on Windows 7 64 bit, Python 2.7.1
    '''
    def kbhit(self, echo):
        return msvcrt.kbhit()

    def getchar(self, block = True):
        if not block and not msvcrt.kbhit():
            return ''
        return msvcrt.getchar()

    def getch(self, block = True):
        if not block and not msvcrt.kbhit():
            return ''
        return msvcrt.getch()

    _getchar = getchar

    # Magic functions for context manager
    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        return False

try:
    import termios
    KeyGetter = KeyGetterLinux # Use KeyGetterLinux if termios exists
except ImportError:
    KeyGetter = KeyGetterWindows # Use KeyGetterWindows otherwise

This is an example(assume that you saved the codes above in 'key_getter.py'):

from key_getter import KeyGetter
import time

def test1(): # Test with block=False
    print('test1')

    k = KeyGetter()
    try:
        while True:
            if k.kbhit():
                print('Got', repr(k.getch(False)))
                print('Got', repr(k.getch(False)))
            else:
                print('Nothing')

            time.sleep(0.5)
    except KeyboardInterrupt:
        pass
    print(input('Enter something:'))

def test2(): # Test context manager with block=True
    print('test2')

    with KeyGetter() as k:
        try:
            while True:
                if k.kbhit():
                    print('Got', repr(k.getchar(True)))
                    print('Got', repr(k.getchar(True)))
                else:
                    print('Nothing')

                time.sleep(0.5)
        except KeyboardInterrupt:
            pass
    print(input('Enter something:'))

test1()
test2()

How to get parameter value for date/time column from empty MaskedTextBox

You're storing the .Text properties of the textboxes directly into the database, this doesn't work. The .Text properties are Strings (i.e. simple text) and not typed as DateTime instances. Do the conversion first, then it will work.

Do this for each date parameter:

Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) ) 

Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse or DateTime.TryParseExact, but implementing that is an exercise for the reader.

Backup a single table with its data from a database in sql server 2008

You can use the "Generate script for database objects" feature on SSMS.

  1. Right click on the target database
  2. Select Tasks > Generate Scripts
  3. Choose desired table or specific object
  4. Hit the Advanced button
  5. Under General, choose value on the Types of data to script. You can select Data only, Schema only, and Schema and data. Schema and data includes both table creation and actual data on the generated script.
  6. Click Next until wizard is done

This one solved my challenge.
Hope this will help you as well.

How to get a right click mouse event? Changing EventArgs to MouseEventArgs causes an error in Form1Designer?

For me neither the MouseClick or Click event worked, because the events, simply, are not called when you right click. The quick way to do it is:

 private void button1_MouseUp(object sender, MouseEventArgs e)
 {
        if (e.Button == MouseButtons.Right)
        {
            //do something here
        }
        else//left or middle click
        {
            //do something here
        }
 }

You can modify that to do exactly what you want depended on the arguments' values.

WARNING: There is one catch with only using the mouse up event. if you mousedown on the control and then you move the cursor out of the control to release it, you still get the event fired. In order to avoid that, you should also make sure that the mouse up occurs within the control in the event handler. Checking whether the mouse cursor coordinates are within the control's rectangle before you check the buttons will do it properly.

compareTo with primitives -> Integer / int

They're already ints. Why not just use subtraction?

compare = a - b;

Note that Integer.compareTo() doesn't necessarily return only -1, 0 or 1 either.

Partly JSON unmarshal into a map in Go

Here is an elegant way to do similar thing. But why do partly JSON unmarshal? That doesn't make sense.

  1. Create your structs for the Chat.
  2. Decode json to the Struct.
  3. Now you can access everything in Struct/Object easily.

Look below at the working code. Copy and paste it.

import (
   "bytes"
   "encoding/json" // Encoding and Decoding Package
   "fmt"
 )

var messeging = `{
"say":"Hello",
"sendMsg":{
    "user":"ANisus",
    "msg":"Trying to send a message"
   }
}`

type SendMsg struct {
   User string `json:"user"`
   Msg  string `json:"msg"`
}

 type Chat struct {
   Say     string   `json:"say"`
   SendMsg *SendMsg `json:"sendMsg"`
}

func main() {
  /** Clean way to solve Json Decoding in Go */
  /** Excellent solution */

   var chat Chat
   r := bytes.NewReader([]byte(messeging))
   chatErr := json.NewDecoder(r).Decode(&chat)
   errHandler(chatErr)
   fmt.Println(chat.Say)
   fmt.Println(chat.SendMsg.User)
   fmt.Println(chat.SendMsg.Msg)

}

 func errHandler(err error) {
   if err != nil {
     fmt.Println(err)
     return
   }
 }

Go playground

Android splash screen image sizes to fit all devices

Based off this answer from Lucas Cerro I calculated the dimensions using the ratios in the Android docs, using the baseline in the answer. I hope this helps someone else coming to this post!

  • xxxlarge (xxxhdpi): 1280x1920 (4.0x)
  • xxlarge (xxhdpi): 960x1440 (3.0x)
  • xlarge (xhdpi): 640x960 (2.0x)
  • large (hdpi): 480x800 (1.5x)
  • medium (mdpi): 320x480 (1.0x baseline)
  • small (ldpi): 240x320 (0.75x) 

CSS3 Transition - Fade out effect

Since display is not one of the animatable CSS properties. One display:none fadeOut animation replacement with pure CSS3 animations, just set width:0 and height:0 at last frame, and use animation-fill-mode: forwards to keep width:0 and height:0 properties.

@-webkit-keyframes fadeOut {
    0% { opacity: 1;}
    99% { opacity: 0.01;width: 100%; height: 100%;}
    100% { opacity: 0;width: 0; height: 0;}
}  
@keyframes fadeOut {
    0% { opacity: 1;}
    99% { opacity: 0.01;width: 100%; height: 100%;}
    100% { opacity: 0;width: 0; height: 0;}
}

.display-none.on{
    display: block;
    -webkit-animation: fadeOut 1s;
    animation: fadeOut 1s;
    animation-fill-mode: forwards;
}

Close all infowindows in Google Maps API v3

I have something like the following

function initMap()
{
    //...create new map here
    var infowindow;
    $('.business').each(function(el){
        //...get lat/lng
        var position = new google.maps.LatLng(lat, lng);
        var content = "contents go here";
        var title = "titleText";
        var openWindowFn;
        var closure = function(content, position){.
            openWindowFn = function()
            {
                if (infowindow)
                {
                    infowindow.close();
                }
                infowindow = new google.maps.InfoWindow({
                    position:position,
                    content:content
                });
                infowindow.open(map, marker);
            }
        }(content, position);
        var marker = new google.maps.Marker({
            position:position,
            map:map,
            title:title.
        });
        google.maps.event.addListener(marker, 'click', openWindowFn);
    }
}

In my understanding, using a closure like that allows the capturing of variables and their values at the time of function declaration, rather than relying on global variables. So when openWindowFn is called later, on the first marker for example, the content and position variable have the values they did during the first iteration in the each() function.

I'm not really sure how openWindowFn has infowindow in its scope. I'm also not sure I'm doing things right, but it works, even with multiple maps on one page (each map gets one open infowindow).

If anyone has any insights, please comment.

Pandas convert string to int

You need add parameter errors='coerce' to function to_numeric:

ID = pd.to_numeric(ID, errors='coerce')

If ID is column:

df.ID = pd.to_numeric(df.ID, errors='coerce')

but non numeric are converted to NaN, so all values are float.

For int need convert NaN to some value e.g. 0 and then cast to int:

df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)

Sample:

df = pd.DataFrame({'ID':['4806105017087','4806105017087','CN414149']})
print (df)
              ID
0  4806105017087
1  4806105017087
2       CN414149

print (pd.to_numeric(df.ID, errors='coerce'))
0    4.806105e+12
1    4.806105e+12
2             NaN
Name: ID, dtype: float64

df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)
print (df)
              ID
0  4806105017087
1  4806105017087
2              0

EDIT: If use pandas 0.25+ then is possible use integer_na:

df.ID = pd.to_numeric(df.ID, errors='coerce').astype('Int64')
print (df)
              ID
0  4806105017087
1  4806105017087
2            NaN

Convert json to a C# array?

Yes, Json.Net is what you need. You basically want to deserialize a Json string into an array of objects.

See their examples:

string myJsonString = @"{
  "Name": "Apple",
  "Expiry": "\/Date(1230375600000+1300)\/",
  "Price": 3.99,
  "Sizes": [
    "Small",
    "Medium",
    "Large"
  ]
}";

// Deserializes the string into a Product object
Product myProduct = JsonConvert.DeserializeObject<Product>(myJsonString);

How to enable/disable bluetooth programmatically in android

Here is a bit more robust way of doing this, also handling the return values of enable()\disable() methods:

public static boolean setBluetooth(boolean enable) {
    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    boolean isEnabled = bluetoothAdapter.isEnabled();
    if (enable && !isEnabled) {
        return bluetoothAdapter.enable(); 
    }
    else if(!enable && isEnabled) {
        return bluetoothAdapter.disable();
    }
    // No need to change bluetooth state
    return true;
}

And add the following permissions into your manifest file:

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

But remember these important points:

This is an asynchronous call: it will return immediately, and clients should listen for ACTION_STATE_CHANGED to be notified of subsequent adapter state changes. If this call returns true, then the adapter state will immediately transition from STATE_OFF to STATE_TURNING_ON, and some time later transition to either STATE_OFF or STATE_ON. If this call returns false then there was an immediate problem that will prevent the adapter from being turned on - such as Airplane mode, or the adapter is already turned on.

UPDATE:

Ok, so how to implement bluetooth listener?:

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();

        if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
            final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
                                                 BluetoothAdapter.ERROR);
            switch (state) {
            case BluetoothAdapter.STATE_OFF:
                // Bluetooth has been turned off;
                break;
            case BluetoothAdapter.STATE_TURNING_OFF:
                // Bluetooth is turning off;
                break;
            case BluetoothAdapter.STATE_ON:
                // Bluetooth is on
                break;
            case BluetoothAdapter.STATE_TURNING_ON:
                // Bluetooth is turning on
                break;
            }
        }
    }
};

And how to register/unregister the receiver? (In your Activity class)

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // ...

    // Register for broadcasts on BluetoothAdapter state change
    IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    registerReceiver(mReceiver, filter);
}

@Override
public void onStop() {
    super.onStop();

     // ...

    // Unregister broadcast listeners
    unregisterReceiver(mReceiver);
}

PHP Session data not being saved

Check who the group and owner are of the folder where the script runs. If the group id or user id are wrong, for example, set to root, it will cause sessions to not be saved properly.

How to insert a newline in front of a pattern?

In this case, I do not use sed. I use tr.

cat Somefile |tr ',' '\012' 

This takes the comma and replaces it with the carriage return.

Why Visual Studio 2015 can't run exe file (ucrtbased.dll)?

rdtsc solution did not work for me.

Firstly, I use Visual Studio 2015 Express, for which installer "modify" query does not propose any "Common Tools for Visual C++ 2015" option you could uncheck.

Secondly, even after 2 uninstall/reinstall (many hours waiting for them to complete...), the problem still remains.

I finally fixed the issue by reinstalling the whole Windows SDK from a standalone installer (independently from Visual C++ 2015 install): https://developer.microsoft.com/fr-fr/windows/downloads/windows-8-1-sdk or https://developer.microsoft.com/fr-fr/windows/downloads/windows-10-sdk

This fixed the issue for me.

Div width 100% minus fixed amount of pixels

We can achieve this using flex-box very easily.

If we have three elements like Header, MiddleContainer and Footer. And we want to give some fixed height to Header and Footer. then we can write like this:

For React/RN(defaults are 'display' as flex and 'flexDirection' as column), in web css we'll have to specify the body container or container containing these as display: 'flex', flex-direction: 'column' like below:

    container-containing-these-elements: {
     display: flex,
     flex-direction: column
    }
    header: {
     height: 40,
    },
    middle-container: {
     flex: 1, // this will take the rest of the space available.
    },
    footer: {
     height: 100,
    }

Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed

hope this helps someone. this worked for me on Ubuntu 18.10

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument('--no-sandbox')
driver = webdriver.Chrome('/usr/lib/chromium-browser/chromedriver', options=chrome_options)
driver.get('http://www.google.com')
print('test')
driver.close()

Have border wrap around text

Not sure, if that's what you want, but you could make the inner div an inline-element. This way the border should be wrapped only around the text. Even better than that is to use an inline-element for your title.

Solution 1

<div id="page" style="width: 600px;">
    <div id="title" style="display: inline; border...">Title</div>
</div>

Solution 2

<div id="page" style="width: 600px;">
    <span id="title" style="border...">Title</span>
</div>

Edit: Strange, SO doesn't interpret my code-examples correctly as block, so I had to use inline-code-method.

Check if EditText is empty.

with this short code you can delete empty space at start and end of the string. If the string is "" return the message "error" else you ave a string

EditText user = findViewById(R.id.user); 
userString = user.getText().toString().trim(); 
if (userString.matches("")) {
    Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
    return; 
}else{
     Toast.makeText(this, "Ok", Toast.LENGTH_SHORT).show();
}

Split (explode) pandas dataframe string entry to separate rows

My version of the solution to add to this collection! :-)

# Original problem
from pandas import DataFrame
import numpy as np
a = DataFrame([{'var1': 'a,b,c', 'var2': 1},
               {'var1': 'd,e,f', 'var2': 2}])
b = DataFrame([{'var1': 'a', 'var2': 1},
               {'var1': 'b', 'var2': 1},
               {'var1': 'c', 'var2': 1},
               {'var1': 'd', 'var2': 2},
               {'var1': 'e', 'var2': 2},
               {'var1': 'f', 'var2': 2}])
### My solution
import pandas as pd
import functools
def expand_on_cols(df, fuse_cols, delim=","):
    def expand_on_col(df, fuse_col):
        col_order = df.columns
        df_expanded = pd.DataFrame(
            df.set_index([x for x in df.columns if x != fuse_col])[fuse_col]
            .apply(lambda x: x.split(delim))
            .explode()
        ).reset_index()
        return df_expanded[col_order]
    all_expanded = functools.reduce(expand_on_col, fuse_cols, df)
    return all_expanded

assert(b.equals(expand_on_cols(a, ["var1"], delim=",")))

C# "No suitable method found to override." -- but there is one

You're not inheriting from your base class:

public class Ext : Base {
    // constructor

    public override void Draw()
    {
    }
}

How to Get True Size of MySQL Database?

MySQL Utilities by Oracle have a command called mysqldiskusage that displays the disk usage of every database: https://dev.mysql.com/doc/mysql-utilities/1.6/en/mysqldiskusage.html

Convert and format a Date in JSP

<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
 <!DOCTYPE html>
 <html dir="ltr" lang="en-US">
 <head>
 <meta charset="UTF-8" />
  <title>JSP with the current date</title>
  </head>
 <body>
 <%java.text.DateFormat df = new java.text.SimpleDateFormat("dd/MM/yyyy"); %>
<h1>Current Date: <%= df.format(new java.util.Date()) %> </h1>
</body>
</html>

Output: Current Date: 10/03/2010

Declare a dictionary inside a static class

The correct syntax ( as tested in VS 2008 SP1), is this:

public static class ErrorCode
{
    public static IDictionary<string, string> ErrorCodeDic;
     static ErrorCode()
    {
        ErrorCodeDic = new Dictionary<string, string>()
            { {"1", "User name or password problem"} };
    }
}

remove all variables except functions

Here's a one-liner that removes all objects except for functions:

rm(list = setdiff(ls(), lsf.str()))

It uses setdiff to find the subset of objects in the global environment (as returned by ls()) that don't have mode function (as returned by lsf.str())

Add primary key to existing table

There is already an primary key in your table. You can't just add primary key,otherwise will cause error. Because there is one primary key for sql table.

First, you have to drop your old primary key.

MySQL:

ALTER TABLE Persion
DROP PRIMARY KEY;

SQL Server / Oracle / MS Access:

ALTER TABLE Persion
DROP CONSTRAINT 'constraint name';

You have to find the constraint name in your table. If you had given constraint name when you created table,you can easily use the constraint name(ex:PK_Persion).

Second,Add primary key.

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Persion ADD PRIMARY KEY (PersionId,Pname,PMID);

or the better one below

ALTER TABLE Persion ADD CONSTRAINT PK_Persion PRIMARY KEY (PersionId,Pname,PMID);

This can set constraint name by developer. It's more easily to maintain the table.

I got a little confuse when i have looked all answers. So I research some document to find every detail. Hope this answer can help other SQL beginner.

Reference:https://www.w3schools.com/sql/sql_primarykey.asp

refresh both the External data source and pivot tables together within a time schedule

Under the connection properties, uncheck "Enable background refresh". This will make the connection refresh when told to, not in the background as other processes happen.

With background refresh disabled, your VBA procedure will wait for your external data to refresh before moving to the next line of code.

Then you just modify the following code:

ActiveWorkbook.Connections("CONNECTION_NAME").Refresh
Sheets("SHEET_NAME").PivotTables("PIVOT_TABLE_NAME").PivotCache.Refresh

You can also turn off background refresh in VBA:

ActiveWorkbook.Connections("CONNECTION_NAME").ODBCConnection.BackgroundQuery = False

How to format date with hours, minutes and seconds when using jQuery UI Datepicker?

If don't like to add time picker, we can use just javascript for time part.

  var dateObj=new Date();
  var date = $.datepicker.formatDate('dd M yy', dateObj);
  var time  = dateObj.getHours()+":"+dateObj.getMinutes()+":"+dateObj.getSeconds(); 

  console.log(date," ",time);

Event for Handling the Focus of the EditText

  1. Declare object of EditText on top of class:

     EditText myEditText;
    
  2. Find EditText in onCreate Function and setOnFocusChangeListener of EditText:

    myEditText = findViewById(R.id.yourEditTextNameInxml); 
    
    myEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View view, boolean hasFocus) {
                    if (!hasFocus) {
                         Toast.makeText(this, "Focus Lose", Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(this, "Get Focus", Toast.LENGTH_SHORT).show();
                    }
    
                }
            });
    

It works fine.

"Prevent saving changes that require the table to be re-created" negative effects

Reference - Turning off this option can help you avoid re-creating a table, it can also lead to changes being lost. For example, suppose that you enable the Change Tracking feature in SQL Server 2008 to track changes to the table. When you perform an operation that causes the table to be re-created, you receive the error message that is mentioned in the "Symptoms" section. However, if you turn off this option, the existing change tracking information is deleted when the table is re-created. Therefore,Microsoft recommend that you do not work around this problem by turning off the option.

How to parse a JSON string into JsonNode in Jackson?

A third variant:

ObjectMapper mapper = new ObjectMapper();
JsonNode actualObj = mapper.readValue("{\"k1\":\"v1\"}", JsonNode.class);

How do I make background-size work in IE?

There is a good polyfill for that: louisremi/background-size-polyfill

To quote the documentation:

Upload backgroundsize.min.htc to your website, along with the .htaccess that will send the mime-type required by IE (Apache only — it's built in nginx, node and IIS).

Everywhere you use background-size in your CSS, add a reference to this file.

.selector { 
    background-size: cover;
    /* The url is relative to the document, not to the css file! */
    /* Prefer absolute urls to avoid confusion. */
    -ms-behavior: url(/backgroundsize.min.htc);
}

How to pass in a react component into another react component to transclude the first component's content?

You can pass it as a normal prop: foo={<ComponentOne />}

For example:

const ComponentOne = () => <div>Hello world!</div>
const ComponentTwo = () => (
  <div>
    <div>Hola el mundo!</div>
    <ComponentThree foo={<ComponentOne />} />
  </div>
)
const ComponentThree = ({ foo }) => <div>{foo}</div>

How can I render Partial views in asp.net mvc 3?

<%= Html.Partial("PartialName", Model) %>

Maintain image aspect ratio when changing height

No need to add a containing div.

The default for the css "align-items" property is "stretch" which is what is causing your images to be stretched to its full original height. Setting the css "align-items" property to "flex-start" fixes your issue.

.slider {
    display: flex;
    align-items: flex-start;  /* ADD THIS! */
}

Get refresh token google api

Found out by adding this to your url parameters

approval_prompt=force

Update:

Use access_type=offline&prompt=consent instead.

approval_prompt=force no longer works https://github.com/googleapis/oauth2client/issues/453

Your project contains error(s), please fix it before running it

I have had a similar problem.

Under "problems" tab I have found an error saying "Error generating final archive: Debug Certificate expired on 2/22/12 1:49 PM"

So my advice is to look in the problems tab to get some more info.

Bye

CURRENT_TIMESTAMP in milliseconds

I faced the same issue recently and I created a small github project that contains a new mysql function UNIX_TIMESTAMP_MS() that returns the current timestamp in milliseconds.

Also you can do the following :

SELECT UNIX_TIMESTAMP_MS(NOW(3)) or SELECT UNIX_TIMESTAMP_MS(DateTimeField)

The project is located here : https://github.com/silviucpp/unix_timestamp_ms

To compile you need to Just run make compile in the project root.

Then you need to only copy the shared library in the /usr/lib/mysql/plugin/ (or whatever the plugin folder is on your machine.)

After this just open a mysql console and run :

CREATE FUNCTION UNIX_TIMESTAMP_MS RETURNS INT SONAME 'unix_timestamp_ms.so';

I hope this will help, Silviu

MySQL high CPU usage

As this is the top post if you google for MySQL high CPU usage or load, I'll add an additional answer:

On the 1st of July 2012, a leap second was added to the current UTC-time to compensate for the slowing rotation of the earth due to the tides. When running ntp (or ntpd) this second was added to your computer's/server's clock. MySQLd does not seem to like this extra second on some OS'es, and yields a high CPU load. The quick fix is (as root):

$ /etc/init.d/ntpd stop
$ date -s "`date`"
$ /etc/init.d/ntpd start

Pods stuck in Terminating status

You can use following command to delete the POD forcefully.

kubectl delete pod <PODNAME> --grace-period=0 --force --namespace <NAMESPACE>

RegEx pattern any two letters followed by six numbers

Everything you need here can be found in this quickstart guide. A straightforward solution would be [A-Za-z][A-Za-z]\d\d\d\d\d\d or [A-Za-z]{2}\d{6}.

If you want to accept only capital letters then replace [A-Za-z] with [A-Z].

jQuery see if any or no checkboxes are selected

Without using 'length' you can do it like this:

if ($('input[type=checkbox]').is(":checked")) {
      //any one is checked
}
else {
//none is checked
}

How can I generate an apk that can run without server with react-native?

I have another solution:- Generating a signing key You can generate a private signing key using keytool. On Windows keytool must be run from C:\Program Files\Java\jdkx.x.x_x\bin.

$ keytool -genkey -v -keystore my-release-key.keystore -alias my-key-alias -keyalg RSA -keysize 2048 -validity 10000

Place the my-release-key.keystore file under the android/app directory in your project folder.

Edit the file android/app/build.gradle in your project folder and add the signing config,

android {
....
signingConfigs { 
  release { 

      storeFile file('my-release-key.keystore') 
      storePassword 'yourpassword' 
      keyAlias 'my-key-alias' 
      keyPassword 'yourpassword' 

  } 
}}}


buildTypes {release {signingConfig signingConfigs.release}}

and run

gradlew assembleRelease

This will give you two files at android\app\build\outputs\apk app-release.apk and app-release-unsigned.apk now install the app-release.apk in your android device.

C++ where to initialize static const

Since C++17 the inline specifier also applies to variables. You can now define static member variables in the class definition:

#include <string>

class foo {
public:
   foo();
   foo( int );
private:
   inline static const std::string s { "foo" };
};

VERR_VMX_MSR_VMXON_DISABLED when starting an image from Oracle virtual box

I had the same problem. I enabled vtx in bios and it didn't worked. After a doublecheck in the bios I recogniced that the bios said that you have to poweroff (and realy power off) the computer. After that it worked. Heavy Pitfall :)

Gradle Sync failed could not find constraint-layout:1.0.0-alpha2

enter image description here

i'm try constraint layout dependency update available 1,and plugin gradle alpha-6,it worked

Removing page title and date when printing web page (with CSS?)

Historically, it's been impossible to make these things disappear as they are user settings and not considered part of the page you have control over.

However, as of 2017, the @page at-rule has been standardized, which can be used to hide the page title and date in modern browsers:

@page { size: auto;  margin: 0mm; }

Print headers/footers and print margins

When printing Web documents, margins are set in the browser's Page Setup (or Print Setup) dialog box. These margin settings, although set within the browser, are controlled at the operating system/printer driver level and are not controllable at the HTML/CSS/DOM level. (For CSS-controlled printed page headers and footers see Printing Headers .)

The settings must be big enough to encompass the printer's physical non-printing areas. Further, they must be big enough to encompass the header and footer that the browser is usually configured to print (typically the page title, page number, URL and date). Note that these headers and footers, although specified by the browser and usually configurable through user preferences, are not part of the Web page itself and therefore are not controllable by CSS. In CSS terms, they fall outside the Page Box CSS2.1 Section 13.2.

... i.e. setting a margin of 0 hides the page title because the title is printed in the margin.

Credit to Vigneswaran S for this tip.

Is there a <meta> tag to turn off caching in all browsers?

This is a link to a great Case Study on the industry wide misunderstanding of controlling caches.

http://securityevaluators.com/knowledge/case_studies/caching/

In summary, according to this article, only Cache-Control: no-store is recognized by Chrome, Firefox, and IE. IE recognizes other controls, but Chrome and Firefox do not.

How do you receive a url parameter with a spring controller mapping

You should be using @RequestParam instead of @ModelAttribute, e.g.

@RequestMapping("/{someID}")
public @ResponseBody int getAttr(@PathVariable(value="someID") String id, 
                                 @RequestParam String someAttr) {
}

You can even omit @RequestParam altogether if you choose, and Spring will assume that's what it is:

@RequestMapping("/{someID}")
public @ResponseBody int getAttr(@PathVariable(value="someID") String id, 
                                 String someAttr) {
}

INSERT INTO a temp table, and have an IDENTITY field created, without first declaring the temp table?

You commented: not working if oldtable has an identity column.

I think that's your answer. The #newtable gets an identity column from the oldtable automatically. Run the next statements:

create table oldtable (id int not null identity(1,1), v varchar(10) )

select * into #newtable from oldtable

use tempdb
GO
sp_help #newtable

It shows you that #newtable does have the identity column.

If you don't want the identity column, try this at creation of #newtable:

select id + 1 - 1 as nid, v, IDENTITY( int ) as id into #newtable
     from oldtable

How do I assert an Iterable contains elements with a certain property?

Alternatively to hasProperty you can try hamcrest-more-matchers where matcher with extracting function. In your case it will look like:

import static com.github.seregamorph.hamcrest.MoreMatchers.where;

assertThat(myClass.getMyItems(), contains(
    where(MyItem::getName, is("foo")), 
    where(MyItem::getName, is("bar"))
));

The advantages of this approach are:

  • It is not always possible to verify by field if the value is computed in get-method
  • In case of mismatch there should be a failure message with diagnostics (pay attention to resolved method reference MyItem.getName:
Expected: iterable containing [Object that matches is "foo" after call
MyItem.getName, Object that matches is "bar" after call MyItem.getName]
     but: item 0: was "wrong-name"
  • It works in Java 8, Java 11 and Java 14

Python Graph Library

There are two excellent choices:

NetworkX

and

igraph

I like NetworkX, but I read good things about igraph as well. I routinely use NetworkX with graphs with 1 million nodes with no problem (it's about double the overhead of a dict of size V + E)

If you want a feature comparison, see this from the Networkx-discuss list

Feature comparison thread

Python - OpenCV - imread - Displaying Image

This can help you

namedWindow( "Display window", CV_WINDOW_AUTOSIZE );// Create a window for display.
imshow( "Display window", image );                   // Show our image inside it.

How to create a WPF Window without a border that can be resized via a grip only?

While the accepted answer is very true, just want to point out that AllowTransparency has some downfalls. It does not allow child window controls to show up, ie WebBrowser, and it usually forces software rendering which can have negative performance effects.

There is a better work around though.

When you want to create a window with no border that is resizeable and is able to host a WebBrowser control or a Frame control pointed to a URL you simply couldn't, the contents of said control would show empty.

I found a workaround though; in the Window, if you set the WindowStyle to None, ResizeMode to NoResize (bear with me, you will still be able to resize once done) then make sure you have UNCHECKED AllowsTransparency you will have a static sized window with no border and will show the browser control.

Now, you probably still want to be able to resize right? Well we can to that with a interop call:

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

    [DllImportAttribute("user32.dll")]
    public static extern bool ReleaseCapture();

    //Attach this to the MouseDown event of your drag control to move the window in place of the title bar
    private void WindowDrag(object sender, MouseButtonEventArgs e) // MouseDown
    {
        ReleaseCapture();
        SendMessage(new WindowInteropHelper(this).Handle,
            0xA1, (IntPtr)0x2, (IntPtr)0);
    }

    //Attach this to the PreviewMousLeftButtonDown event of the grip control in the lower right corner of the form to resize the window
    private void WindowResize(object sender, MouseButtonEventArgs e) //PreviewMousLeftButtonDown
    {
        HwndSource hwndSource = PresentationSource.FromVisual((Visual)sender) as HwndSource;
        SendMessage(hwndSource.Handle, 0x112, (IntPtr)61448, IntPtr.Zero);
    }

And voila, A WPF window with no border and still movable and resizable without losing compatibility with with controls like WebBrowser

How to set combobox default value?

You can do something like this:

    public myform()
    {
         InitializeComponent(); // this will be called in ComboBox ComboBox = new System.Windows.Forms.ComboBox();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        // TODO: This line of code loads data into the 'myDataSet.someTable' table. You can move, or remove it, as needed.
        this.myTableAdapter.Fill(this.myDataSet.someTable);
        comboBox1.SelectedItem = null;
        comboBox1.SelectedText = "--select--";           
    }

Output data from all columns in a dataframe in pandas

I know this is an old question, but I have just had a similar problem and I think what I did would work for you too.

I used the to_csv() method and wrote to stdout:

import sys

paramdata.to_csv(sys.stdout)

This should dump the whole dataframe whether it's nicely-printable or not, and you can use the to_csv parameters to configure column separators, whether the index is printed, etc.

Edit: It is now possible to use None as the target for .to_csv() with similar effect, which is arguably a lot nicer:

paramdata.to_csv(None)

How do I limit the number of decimals printed for a double?

Check out DecimalFormat: http://docs.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html

You'll do something like:

new DecimalFormat("$#.00").format(shippingCost);

Or since you're working with currency, you could see how NumberFormat.getCurrencyInstance() works for you.

How to reset all checkboxes using jQuery or pure JS?

In some cases the checkbox may be selected by default. If you want to restore default selection rather than set as unselected, compare the defaultChecked property.

$(':checkbox').each(function(i,item){ 
        this.checked = item.defaultChecked; 
}); 

Get current url in Angular

With pure JavaScript:

console.log(window.location.href)

Using Angular:

this.router.url

import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
    template: 'The href is: {{href}}'
    /*
    Other component settings
    */
})
export class Component {
    public href: string = "";

    constructor(private router: Router) {}

    ngOnInit() {
        this.href = this.router.url;
        console.log(this.router.url);
    }
}

The plunkr is here: https://plnkr.co/edit/0x3pCOKwFjAGRxC4hZMy?p=preview

Difference between /res and /assets directories

Ted Hopp answered this quite nicely. I have been using res/raw for my opengl texture and shader files. I was thinking about moving them to an assets directory to provide a hierarchical organization.

This thread convinced me not to. First, because I like the use of a unique resource id. Second because it's very simple to use InputStream/openRawResource or BitmapFactory to read in the file. Third because it's very useful to be able to use in a portable library.

Centering floating divs within another div

With Flexbox you can easily horizontally (and vertically) center floated children inside a div.

So if you have simple markup like so:

<div class="wpr">
    <span></span>
    <span></span>
    <span></span>
    <span></span>
    <span></span>
</div>

with CSS:

.wpr
{
    width: 400px;
    height: 100px;
    background: pink;
    padding: 10px 30px;
}

.wpr span
{
    width: 50px;
    height: 50px;
    background: green;
    float: left; /* **children floated left** */
    margin: 0 5px;
}

(This is the (expected - and undesirable) RESULT)

Now add the following rules to the wrapper:

display: flex;
justify-content: center; /* align horizontal */

and the floated children get aligned center (DEMO)

Just for fun, to get vertical alignment as well just add:

align-items: center; /* align vertical */

DEMO

Is putting a div inside an anchor ever correct?

There's a DTD for HTML 4 at http://www.w3.org/TR/REC-html40/sgml/dtd.html . This DTD is the machine-processable form of the spec, with the limitation that a DTD governs XML and HTML 4, especially the "transient" flavor, permits a lot of things that are not "legal" XML. Still, I consider it comes close to codifying the intent of the specifiers.

<!ELEMENT A - - (%inline;)* -(A)       -- anchor -->

<!ENTITY % inline "#PCDATA | %fontstyle; | %phrase; | %special; | %formctrl;">

<!ENTITY % fontstyle "TT | I | B | BIG | SMALL">

<!ENTITY % phrase "EM | STRONG | DFN | CODE | SAMP | KBD | VAR | CITE | ABBR | ACRONYM" >

<!ENTITY % special "A | IMG | OBJECT | BR | SCRIPT | MAP | Q | SUB | SUP | SPAN | BDO">

<!ENTITY % formctrl "INPUT | SELECT | TEXTAREA | LABEL | BUTTON">

I would interpret the tags listed in this hierarchy to be the total of tags allowed.

While the spec may say "inline elements," I'm pretty sure it's not intended that you can get around the intent by declaring the display type of a block element to be inline. Inline tags have different semantics no matter how you may abuse them.

On the other hand, I find it intriguing that the inclusion of special seems to allow nesting A elements. There's probably some strong wording in the spec that disallows this even if it's XML-syntactically correct but I won't pursue this further as it's not the topic of the question.

window.onload vs document.onload

Add Event Listener

<script type="text/javascript">
  document.addEventListener("DOMContentLoaded", function(event) {
      // - Code to execute when all DOM content is loaded. 
      // - including fonts, images, etc.
  });
</script>


Update March 2017

1 Vanilla JavaScript

window.addEventListener('load', function() {
    console.log('All assets are loaded')
})


2 jQuery

$(window).on('load', function() {
    console.log('All assets are loaded')
})


Good Luck.

how to find host name from IP with out login to the host

If you are specifically looking for a Windows machine, try below command:

nbtstat -a 10.228.42.57

JPG vs. JPEG image formats

They are identical. JPG is simply a holdover from the days of DOS when file extensions were required to be 3 characters long. You can find out more information about the JPEG standard here. A question very similar to this one was asked over at SuperUser, where the accepted answer should give you some more detailed information.

Netbeans - Error: Could not find or load main class

You can :

  • RightClick on project node and go to Set configuration
  • Select the main class for your application.
  • Then clean and build.

Even if the above steps don't work for you then then delete the Netbeans cache by deleting the (index) folder

User\.netbeans\SOME_NUMBER_reflecting_your_version\var\cache\index\

Prevent form submission on Enter key press

A little simple

Don't send the form on keypress "Enter":

<form id="form_cdb" onsubmit="return false">

Execute the function on keypress "Enter":

<input type="text" autocomplete="off" onkeypress="if(event.key === 'Enter') my_event()">

How do you run a .bat file from PHP?

For anyone who needs to run a program in the background "without PHP waiting for it to finish" do this:

 pclose(popen("start /B ".$cmd, "r")); 

where $cmd is the string command for the program that you need to run (e.g. $cmd can equal notepad.exe or node Path\to\server.js).

Source: https://www.php.net/manual/en/function.exec.php (see Arno van den Brink's note in the section titled "User Contributed Notes").

replacing NA's with 0's in R dataframe

dataset <- matrix(sample(c(NA, 1:5), 25, replace = TRUE), 5);
data <- as.data.frame(dataset)
[,1] [,2] [,3] [,4] [,5] 
[1,]    2    3    5    5    4
[2,]    2    4    3    2    4
[3,]    2   NA   NA   NA    2
[4,]    2    3   NA    5    5
[5,]    2    3    2    2    3
data[is.na(data)] <- 0

Correct way to remove plugin from Eclipse

Using the menus, open

  • Help | About Eclipse IDE | Installation details (in newer versions),
  • Help | Installation Details (in older versions), or
  • Help | About Eclipse | Installation details (in even older versions).

In the "Installed software" tab click on the software that you wish to uninstall, then click the "Uninstall..." button below.

If you installed the plug-in by dropping into the dropins folder, then just delete it from the dropins folder and restart Eclipse.

See the answer of @Cogentleman for more recent versions of Eclipse.

How to auto-format code in Eclipse?

CTRL + SHIFT + F will auto format your code(whether it is highlighted or non highlighted).

How do I include negative decimal numbers in this regular expression?

For negative number only, this is perfect.

^-\d*\.?\d+$

Fiddler not capturing traffic from browsers

Another possible issue is related to WCF client (this may also include other clients but i'm not sure). The client can be configured not to use the machine default proxy, which makes the client/application bypass Fiddler capture.

For further reading: What is the purpose of usedefaultwebproxy in WCF.

How to split a delimited string into an array in awk?

I do not like the echo "..." | awk ... solution as it calls unnecessary fork and execsystem calls.

I prefer a Dimitre's solution with a little twist

awk -F\| '{print $3 $2 $1}' <<<'12|23|11'

Or a bit shorter version:

awk -F\| '$0=$3 $2 $1' <<<'12|23|11'

In this case the output record put together which is a true condition, so it gets printed.

In this specific case the stdin redirection can be spared with setting an internal variable:

awk -v T='12|23|11' 'BEGIN{split(T,a,"|");print a[3] a[2] a[1]}'

I used quite a while, but in this could be managed by internal string manipulation. In the first case the original string is split by internal terminator. In the second case it is assumed that the string always contains digit pairs separated by a one character separator.

T='12|23|11';echo -n ${T##*|};T=${T%|*};echo ${T#*|}${T%|*}
T='12|23|11';echo ${T:6}${T:3:2}${T:0:2}

The result in all cases is

112312

CSS Box Shadow - Top and Bottom Only

After some experimentation I found that a fourth value in the line controls the spread (at least in FF 10). I opposed the vertical offsets and gave them a negative spread.

Here's the working pen: http://codepen.io/gillytech/pen/dlbsx

<html>
<head>
<style type="text/css">

#test {
    width: 500px;
    border: 1px  #CCC solid;
    height: 200px;

    box-shadow: 
        inset 0px 11px 8px -10px #CCC,
        inset 0px -11px 8px -10px #CCC; 
}
</style>
</head>
<body>
    <div id="test"></div>
</body>
</html>

This works perfectly for me!

Simple and clean way to convert JSON string to Object in Swift

Use swiftyJson swiftyJson

platform :ios, '8.0'
use_frameworks!

target 'MyApp' do
pod 'SwiftyJSON', '~> 4.0'
end

Usage

import SwiftyJSON

let json = JSON(jsonObject)

let id = json["Id"].intValue
let name = json["Name"].stringValue
let lat = json["Latitude"].stringValue
let long = json["Longitude"].stringValue
let address = json["Address"].stringValue
            
print(id)
print(name)
print(lat)
print(long)
print(address)

Getting the Username from the HKEY_USERS values

You can use the command PSGetSid from Microsoft's SysInternals team.

Download URL: http://technet.microsoft.com/en-gb/sysinternals/bb897417.aspx

Usage:

psgetsid [\\computer[,computer[,...] | @file] [-u username [-p password]]] [account|SID]
-u  Specifies optional user name for login to remote computer.
-p  Specifies optional password for user name. If you omit this you will be prompted to enter a hidden password.
Account PsGetSid will report the SID for the specified user account rather than the computer.
SID PsGetSid will report the account for the specified SID.
Computer    Direct PsGetSid to perform the command on the remote computer or computers specified. If you omit the computer name PsGetSid runs the command on the local system, and if you specify a wildcard (\\*), PsGetSid runs the command on all computers in the current domain.
@file   PsGetSid will execute the command on each of the computers listed in the file.

Example:

psgetsid S-1-5-21-583907252-682003330-839522115-63941

NB:

  • Where the user is a domain/AD(LDAP) user, running this on any computer on the domain should give the same results.
  • Where the user is local to the machine the command should either be run on that machine, or you should specify the computer via the optional parameter.

Update

If you use PowerShell, the following may be useful for resolving any AD users listed:

#create a drive for HKEY USERS:
New-PSDrive -PSProvider Registry -Name HKU -Root HKEY_USERS -ErrorAction SilentlyContinue

#List all immediate subfolders
#where they're a folder (not a key)
#and they's an SID (i.e. exclude .DEFAULT and SID_Classes entries)
#return the SID
#and return the related AD entry (should one exist).
Get-ChildItem -Path 'HKU:\' `
| ?{($_.PSIsContainer -eq $true) `
-and ($_.PSChildName -match '^S-[\d-]+$')} `
| select @{N='SID';E={$_.PSChildName}} `
, @{N='Name';E={Get-ADUser $_.PSChildName | select -expand Name}}

You could also refine the SID filter further to only pull back those SIDs which will resolve to an AD account if you wished; more on the SID structure here: https://technet.microsoft.com/en-us/library/cc962011.aspx

How to zip a file using cmd line?

tar.exe -acf out.zip in.txt

out.zip is an output folder or filename and in.txt is an input folder or filename. To use this command you should be in the file existing folder.

How to list all the files in a commit?

I'll just assume that gitk is not desired for this. In that case, try git show --name-only <sha>.

jQuery: Return data after ajax call success

Note: This answer was written in February 2010.
See updates from 2015, 2016 and 2017 at the bottom.

You can't return anything from a function that is asynchronous. What you can return is a promise. I explained how promises work in jQuery in my answers to those questions:

If you could explain why do you want to return the data and what do you want to do with it later, then I might be able to give you a more specific answer how to do it.

Generally, instead of:

function testAjax() {
  $.ajax({
    url: "getvalue.php",  
    success: function(data) {
      return data; 
    }
  });
}

you can write your testAjax function like this:

function testAjax() {
  return $.ajax({
      url: "getvalue.php"
  });
}

Then you can get your promise like this:

var promise = testAjax();

You can store your promise, you can pass it around, you can use it as an argument in function calls and you can return it from functions, but when you finally want to use your data that is returned by the AJAX call, you have to do it like this:

promise.success(function (data) {
  alert(data);
});

(See updates below for simplified syntax.)

If your data is available at this point then this function will be invoked immediately. If it isn't then it will be invoked as soon as the data is available.

The whole point of doing all of this is that your data is not available immediately after the call to $.ajax because it is asynchronous. Promises is a nice abstraction for functions to say: I can't return you the data because I don't have it yet and I don't want to block and make you wait so here's a promise instead and you'll be able to use it later, or to just give it to someone else and be done with it.

See this DEMO.

UPDATE (2015)

Currently (as of March, 2015) jQuery Promises are not compatible with the Promises/A+ specification which means that they may not cooperate very well with other Promises/A+ conformant implementations.

However jQuery Promises in the upcoming version 3.x will be compatible with the Promises/A+ specification (thanks to Benjamin Gruenbaum for pointing it out). Currently (as of May, 2015) the stable versions of jQuery are 1.x and 2.x.

What I explained above (in March, 2011) is a way to use jQuery Deferred Objects to do something asynchronously that in synchronous code would be achieved by returning a value.

But a synchronous function call can do two things - it can either return a value (if it can) or throw an exception (if it can't return a value). Promises/A+ addresses both of those use cases in a way that is pretty much as powerful as exception handling in synchronous code. The jQuery version handles the equivalent of returning a value just fine but the equivalent of complex exception handling is somewhat problematic.

In particular, the whole point of exception handling in synchronous code is not just giving up with a nice message, but trying to fix the problem and continue the execution, or possibly rethrowing the same or a different exception for some other parts of the program to handle. In synchronous code you have a call stack. In asynchronous call you don't and advanced exception handling inside of your promises as required by the Promises/A+ specification can really help you write code that will handle errors and exceptions in a meaningful way even for complex use cases.

For differences between jQuery and other implementations, and how to convert jQuery promises to Promises/A+ compliant, see Coming from jQuery by Kris Kowal et al. on the Q library wiki and Promises arrive in JavaScript by Jake Archibald on HTML5 Rocks.

How to return a real promise

The function from my example above:

function testAjax() {
  return $.ajax({
      url: "getvalue.php"
  });
}

returns a jqXHR object, which is a jQuery Deferred Object.

To make it return a real promise, you can change it to - using the method from the Q wiki:

function testAjax() {
  return Q($.ajax({
      url: "getvalue.php"
  }));
}

or, using the method from the HTML5 Rocks article:

function testAjax() {
  return Promise.resolve($.ajax({
      url: "getvalue.php"
  }));
}

This Promise.resolve($.ajax(...)) is also what is explained in the promise module documentation and it should work with ES6 Promise.resolve().

To use the ES6 Promises today you can use es6-promise module's polyfill() by Jake Archibald.

To see where you can use the ES6 Promises without the polyfill, see: Can I use: Promises.

For more info see:

Future of jQuery

Future versions of jQuery (starting from 3.x - current stable versions as of May 2015 are 1.x and 2.x) will be compatible with the Promises/A+ specification (thanks to Benjamin Gruenbaum for pointing it out in the comments). "Two changes that we've already decided upon are Promise/A+ compatibility for our Deferred implementation [...]" (jQuery 3.0 and the future of Web development). For more info see: jQuery 3.0: The Next Generations by Dave Methvin and jQuery 3.0: More interoperability, less Internet Explorer by Paul Krill.

Interesting talks

UPDATE (2016)

There is a new syntax in ECMA-262, 6th Edition, Section 14.2 called arrow functions that may be used to further simplify the examples above.

Using the jQuery API, instead of:

promise.success(function (data) {
  alert(data);
});

you can write:

promise.success(data => alert(data));

or using the Promises/A+ API:

promise.then(data => alert(data));

Remember to always use rejection handlers either with:

promise.then(data => alert(data), error => alert(error));

or with:

promise.then(data => alert(data)).catch(error => alert(error));

See this answer to see why you should always use rejection handlers with promises:

Of course in this example you could use just promise.then(alert) because you're just calling alert with the same arguments as your callback, but the arrow syntax is more general and lets you write things like:

promise.then(data => alert("x is " + data.x));

Not every browser supports this syntax yet, but there are certain cases when you're sure what browser your code will run on - e.g. when writing a Chrome extension, a Firefox Add-on, or a desktop application using Electron, NW.js or AppJS (see this answer for details).

For the support of arrow functions, see:

UPDATE (2017)

There is an even newer syntax right now called async functions with a new await keyword that instead of this code:

functionReturningPromise()
    .then(data => console.log('Data:', data))
    .catch(error => console.log('Error:', error));

lets you write:

try {
    let data = await functionReturningPromise();
    console.log('Data:', data);
} catch (error) {
    console.log('Error:', error);
}

You can only use it inside of a function created with the async keyword. For more info, see:

For support in browsers, see:

For support in Node, see:

In places where you don't have native support for async and await you can use Babel:

or with a slightly different syntax a generator based approach like in co or Bluebird coroutines:

More info

Some other questions about promises for more details:

datetimepicker is not a function jquery

Keep in mind, the jQuery UI's datepicker is not initialized with datetimepicker(), there appears to be a plugin/addon here: http://trentrichardson.com/examples/timepicker/.

However, with just jquery-ui it's actually initialized as $("#example").datepicker(). See jQuery's demo site here: http://jqueryui.com/demos/datepicker/

   $(document).ready(function(){
        $("#example1").datepicker();
    });

To use the datetimepicker at the link referenced above, you will want to be certain that your scripts path is correct for the plugin.

git pull displays "fatal: Couldn't find remote ref refs/heads/xxxx" and hangs up

In my case, it happenned for the master branch. Later found that my access to the project was accidentally revoked by the project manager. To cross-check, I visited the review site and couldn't see any commits of the said branch and others for that project.

javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found

Hi same problem i have solved you can try this

java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.NETWORK

 // SET SSL
public static OkClient setSSLFactoryForClient(OkHttpClient client) {
    try {
        // Create a trust manager that does not validate certificate chains
        final TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                    }

                    @Override
                    public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                    }

                    @Override
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }
                }
        };

        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        // Create an ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();


        client.setSslSocketFactory(sslSocketFactory);
        client.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return new OkClient(client);
}

Python convert tuple to string

here is an easy way to use join.

''.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))

Forbidden: You don't have permission to access / on this server, WAMP Error

This could be one solution.

public class RegisterActivity extends AppCompatActivity {

    private static final String TAG = "RegisterActivity";
    private static final String URL_FOR_REGISTRATION = "http://192.168.10.4/android_login_example/register.php";
    ProgressDialog progressDialog;

    private EditText signupInputName, signupInputEmail, signupInputPassword, signupInputAge;
    private Button btnSignUp;
    private Button btnLinkLogin;
    private RadioGroup genderRadioGroup;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        // Progress dialog
        progressDialog = new ProgressDialog(this);
        progressDialog.setCancelable(false);

        signupInputName = (EditText) findViewById(R.id.signup_input_name);
        signupInputEmail = (EditText) findViewById(R.id.signup_input_email);
        signupInputPassword = (EditText) findViewById(R.id.signup_input_password);
        signupInputAge = (EditText) findViewById(R.id.signup_input_age);

        btnSignUp = (Button) findViewById(R.id.btn_signup);
        btnLinkLogin = (Button) findViewById(R.id.btn_link_login);

        genderRadioGroup = (RadioGroup) findViewById(R.id.gender_radio_group);
        btnSignUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                submitForm();
            }
        });
        btnLinkLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent i = new Intent(getApplicationContext(),MainActivity.class);
                startActivity(i);
            }
        });
    }

    private void submitForm() {

        int selectedId = genderRadioGroup.getCheckedRadioButtonId();
        String gender;
        if(selectedId == R.id.female_radio_btn)
            gender = "Female";
        else
            gender = "Male";

        registerUser(signupInputName.getText().toString(),
                signupInputEmail.getText().toString(),
                signupInputPassword.getText().toString(),
                gender,
                signupInputAge.getText().toString());
    }

    private void registerUser(final String name,  final String email, final String password,
                              final String gender, final String dob) {
        // Tag used to cancel the request
        String cancel_req_tag = "register";

        progressDialog.setMessage("Adding you ...");
        showDialog();

        StringRequest strReq = new StringRequest(Request.Method.POST,
                URL_FOR_REGISTRATION, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Register Response: " + response.toString());
                hideDialog();

                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");

                    if (!error) {
                        String user = jObj.getJSONObject("user").getString("name");
                        Toast.makeText(getApplicationContext(), "Hi " + user +", You are successfully Added!", Toast.LENGTH_SHORT).show();

                        // Launch login activity
                        Intent intent = new Intent(
                                RegisterActivity.this,
                                MainActivity.class);
                        startActivity(intent);
                        finish();
                    } else {



                        String errorMsg = jObj.getString("error_msg");
                        Toast.makeText(getApplicationContext(),
                                errorMsg, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Registration Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_LONG).show();
                hideDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                // Posting params to register url
                Map<String, String> params = new HashMap<String, String>();
                params.put("name", name);
                params.put("email", email);
                params.put("password", password);
                params.put("gender", gender);
                params.put("age", dob);
                return params;
            }
        };
        // Adding request to request queue
        AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq, cancel_req_tag);
    }

    private void showDialog() {
        if (!progressDialog.isShowing())
            progressDialog.show();
    }

    private void hideDialog() {
        if (progressDialog.isShowing())
            progressDialog.dismiss();
    }
    }

How do I concatenate two arrays in C#?

For int[] what you've done looks good to me. astander's answer would also work well for List<int>.

How to find index of STRING array in Java from a given value?

Refactoring the above methods and showing with the use:

private String[] languages = {"pt", "en", "es"};
private Integer indexOf(String[] arr, String str){
   for (int i = 0; i < arr.length; i++)
      if(arr[i].equals(str)) return i;
   return -1;
}
indexOf(languages, "en")

Command to get time in milliseconds

When you use GNU AWK since version 4.1, you can load the time library and do:

$ awk '@load "time"; BEGIN{printf "%.6f", gettimeofday()}'

This will print the current time in seconds since 1970-01-01T00:00:00 in sub second accuracy.

the_time = gettimeofday() Return the time in seconds that has elapsed since 1970-01-01 UTC as a floating-point value. If the time is unavailable on this platform, return -1 and set ERRNO. The returned time should have sub-second precision, but the actual precision may vary based on the platform. If the standard C gettimeofday() system call is available on this platform, then it simply returns the value. Otherwise, if on MS-Windows, it tries to use GetSystemTimeAsFileTime().

source: GNU awk manual

On Linux systems, the standard C function getimeofday() returns the time in microsecond accuracy.

Why is January month 0 in Java Calendar?

Probably because C's "struct tm" does the same.

Active Directory LDAP Query by sAMAccountName and Domain

You can use following queries

Users whose Logon Name(Pre-Windows 2000) is equal to John

(&(objectCategory=person)(objectClass=user)(!sAMAccountType=805306370)(sAMAccountName=**John**))

All Users

(&(objectCategory=person)(objectClass=user)(!sAMAccountType=805306370))

Enabled Users

(&(objectCategory=person)(objectClass=user)(!sAMAccountType=805306370)(!userAccountControl:1.2.840.113556.1.4.803:=2))

Disabled Users

(&(objectCategory=person)(objectClass=user)(!sAMAccountType=805306370)(userAccountControl:1.2.840.113556.1.4.803:=2))

LockedOut Users

(&(objectCategory=person)(objectClass=user)(!sAMAccountType=805306370)(lockouttime>=1))

Unable to load AWS credentials from the /AwsCredentials.properties file on the classpath

A java program to set AWS environment vairiable.

Map<String, String> environment = new HashMap<String, String>();
        environment.put("AWS_ACCESS_KEY_ID", "*****************");
        environment.put("AWS_SECRET_KEY", "*************************");

private static void setEnv(Map<String, String> newenv) throws Exception {
        try {
            Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment");
            Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment");
            theEnvironmentField.setAccessible(true);
            Map<String, String> env = (Map<String, String>) theEnvironmentField.get(null);
            env.putAll(newenv);
            Field theCaseInsensitiveEnvironmentField = processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment");
            theCaseInsensitiveEnvironmentField.setAccessible(true);
            Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null);
            cienv.putAll(newenv);
        } catch (NoSuchFieldException e) {
            Class[] classes = Collections.class.getDeclaredClasses();
            Map<String, String> env = System.getenv();
            for (Class cl : classes) {
                if ("java.util.Collections$UnmodifiableMap".equals(cl.getName())) {
                    Field field = cl.getDeclaredField("m");
                    field.setAccessible(true);
                    Object obj = field.get(env);
                    Map<String, String> map = (Map<String, String>) obj;
                    map.clear();
                    map.putAll(newenv);
                }
            }
        }
    }

How to insert an item into an array at a specific index (JavaScript)?

I recommend using pure JavaScript in this case, also there is no insert method in JavaScript, but we have a method which is a built-in Array method which does the job for you, it's called splice...

Let's see what's splice()...

The splice() method changes the contents of an array by removing existing elements and/or adding new elements.

OK, imagine we have this array below:

const arr = [1, 2, 3, 4, 5];

We can remove 3 like this:

arr.splice(arr.indexOf(3), 1);

It will return 3, but if we check the arr now, we have:

[1, 2, 4, 5]

So far, so good, but how we can add a new element to array using splice? Let's put back 3 in the arr...

arr.splice(2, 0, 3);

Let's see what we have done...

We use splice again, but this time for the second argument, we pass 0, means we want to delete no item, but at the same time, we add third argument which is 3 that will be added at second index...

You should be aware, that we can delete and add at the same time, for example now we can do:

arr.splice(2, 2, 3);

Which will delete 2 items at index 2, then add 3 at index 2 and result will be:

[1, 2, 3, 5];

This is showing how each item in splice work:

array.splice(start, deleteCount, item1, item2, item3 ...)

Change column type in pandas

I thought I had the same problem but actually I have a slight difference that makes the problem easier to solve. For others looking at this question it's worth checking the format of your input list. In my case the numbers are initially floats not strings as in the question:

a = [['a', 1.2, 4.2], ['b', 70, 0.03], ['x', 5, 0]]

but by processing the list too much before creating the dataframe I lose the types and everything becomes a string.

Creating the data frame via a numpy array

df = pd.DataFrame(np.array(a))

df
Out[5]: 
   0    1     2
0  a  1.2   4.2
1  b   70  0.03
2  x    5     0

df[1].dtype
Out[7]: dtype('O')

gives the same data frame as in the question, where the entries in columns 1 and 2 are considered as strings. However doing

df = pd.DataFrame(a)

df
Out[10]: 
   0     1     2
0  a   1.2  4.20
1  b  70.0  0.03
2  x   5.0  0.00

df[1].dtype
Out[11]: dtype('float64')

does actually give a data frame with the columns in the correct format

How to sum columns in a dataTable?

You can loop through the DataColumn and DataRow collections in your DataTable:

// Sum rows.
foreach (DataRow row in dt.Rows) {
    int rowTotal = 0;
    foreach (DataColumn col in row.Table.Columns) {
        Console.WriteLine(row[col]);
        rowTotal += Int32.Parse(row[col].ToString());
    }
    Console.WriteLine("row total: {0}", rowTotal);
}
// Sum columns.
foreach (DataColumn col in dt.Columns) {
    int colTotal = 0;
    foreach (DataRow row in col.Table.Rows) {
        Console.WriteLine(row[col]);
        colTotal += Int32.Parse(row[col].ToString());
    }
    Console.WriteLine("column total: {0}", colTotal);
}

Beware: The code above does not do any sort of checking before casting an object to an int.

EDIT: add a DataRow displaying the column sums

Try this to create a new row to display your column sums:

DataRow totalsRow = dt.NewRow();
foreach (DataColumn col in dt.Columns) {
    int colTotal = 0;
    foreach (DataRow row in col.Table.Rows) {
        colTotal += Int32.Parse(row[col].ToString());
    }
    totalsRow[col.ColumnName] = colTotal;
}
dt.Rows.Add(totalsRow);

This approach is fine if the data type of any of your DataTable's DataRows are non-numeric or if you want to inspect the value of each cell as you sum. Otherwise I believe @Tim's response using DataTable.Compute is a better.

Spark difference between reduceByKey vs groupByKey vs aggregateByKey vs combineByKey

Although both of them will fetch the same results, there is a significant difference in the performance of both the functions. reduceByKey() works better with larger datasets when compared to groupByKey().

In reduceByKey(), pairs on the same machine with the same key are combined (by using the function passed into reduceByKey()) before the data is shuffled. Then the function is called again to reduce all the values from each partition to produce one final result.

In groupByKey(), all the key-value pairs are shuffled around. This is a lot of unnecessary data to being transferred over the network.

Reset par to the default values at startup

From Quick-R

par()              # view current settings
opar <- par()      # make a copy of current settings
par(col.lab="red") # red x and y labels 
hist(mtcars$mpg)   # create a plot with these new settings 
par(opar)          # restore original settings

Junit test case for database insert method with DAO and web service

The design of your classes will make it hard to test them. Using hardcoded connection strings or instantiating collaborators in your methods with new can be considered as test-antipatterns. Have a look at the DependencyInjection pattern. Frameworks like Spring might be of help here.

To have your DAO tested you need to have control over your database connection in your unit tests. So the first thing you would want to do is extract it out of your DAO into a class that you can either mock or point to a specific test database, which you can setup and inspect before and after your tests run.

A technical solution for testing db/DAO code might be dbunit. You can define your test data in a schema-less XML and let dbunit populate it in your test database. But you still have to wire everything up yourself. With Spring however you could use something like spring-test-dbunit which gives you lots of leverage and additional tooling.

As you call yourself a total beginner I suspect this is all very daunting. You should ask yourself if you really need to test your database code. If not you should at least refactor your code, so you can easily mock out all database access. For mocking in general, have a look at Mockito.

Joda DateTime to Timestamp conversion

It is a common misconception that time (a measurable 4th dimension) is different over the world. Timestamp as a moment in time is unique. Date however is influenced how we "see" time but actually it is "time of day".

An example: two people look at the clock at the same moment. The timestamp is the same, right? But one of them is in London and sees 12:00 noon (GMT, timezone offset is 0), and the other is in Belgrade and sees 14:00 (CET, Central Europe, daylight saving now, offset is +2).

Their perception is different but the moment is the same.

You can find more details in this answer.

UPDATE

OK, it's not a duplicate of this question but it is pointless since you are confusing the terms "Timestamp = moment in time (objective)" and "Date[Time] = time of day (subjective)".

Let's look at your original question code broken down like this:

// Get the "original" value from database.
Timestamp momentFromDB = rs.getTimestamp("anytimestampcolumn");

// Turn it into a Joda DateTime with time zone.
DateTime dt = new DateTime(momentFromDB, DateTimeZone.forID("anytimezone"));

// And then turn it back into a timestamp but "with time zone".
Timestamp ts = new Timestamp(dt.getMillis());

I haven't run this code but I am certain it will print true and the same number of milliseconds each time:

System.out.println("momentFromDB == dt : " + (momentFromDB.getTime() == dt.getTimeInMillis());
System.out.println("momentFromDB == ts : " + (momentFromDB.getTime() == ts.getTime()));
System.out.println("dt == ts : " + (dt.getTimeInMillis() == ts.getTime()));

System.out.println("momentFromDB [ms] : " + momentFromDB.getTime());
System.out.println("ts [ms] : " + ts.getTime());
System.out.println("dt [ms] : " + dt.getTimeInMillis());

But as you said yourself printing them out as strings will result in "different" time because DateTime applies the time zone. That's why "time" is stored and transferred as Timestamp objects (which basically wraps a long) and displayed or entered as Date[Time].

In your own answer you are artificially adding an offset and creating a "wrong" time. If you use that timestamp to create another DateTime and print it out it will be offset twice.

// Turn it back into a Joda DateTime with time zone.
DateTime dt = new DateTime(ts, DateTimeZone.forID("anytimezone"));

P.S. If you have the time go through the very complex Joda Time source code to see how it holds the time (millis) and how it prints it.

JUnit Test as proof

import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

import org.junit.Before;
import org.junit.Test;


public class WorldTimeTest {
    private static final int MILLIS_IN_HOUR = 1000 * 60 * 60;
    private static final String ISO_FORMAT_NO_TZ = "yyyy-MM-dd'T'HH:mm:ss.SSS";
    private static final String ISO_FORMAT_WITH_TZ = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";

    private TimeZone londonTimeZone;
    private TimeZone newYorkTimeZone;
    private TimeZone sydneyTimeZone;
    private long nowInMillis;
    private Date now;

    public static SimpleDateFormat createDateFormat(String pattern, TimeZone timeZone) throws Exception {
        SimpleDateFormat result = new SimpleDateFormat(pattern);
        // Must explicitly set the time zone with "setCalendar()".
        result.setCalendar(Calendar.getInstance(timeZone));
        return result;
    }

    public static SimpleDateFormat createDateFormat(String pattern) throws Exception {
        return createDateFormat(pattern, TimeZone.getDefault());
    }

    public static SimpleDateFormat createDateFormat() throws Exception {
        return createDateFormat(ISO_FORMAT_WITH_TZ, TimeZone.getDefault());
    }

    public void printSystemInfo() throws Exception {
        final String[] propertyNames = {
                "java.runtime.name", "java.runtime.version", "java.vm.name", "java.vm.version",
                "os.name", "os.version", "os.arch",
                "user.language", "user.country", "user.script", "user.variant",
                "user.language.format", "user.country.format", "user.script.format",
                "user.timezone" };

        System.out.println();
        System.out.println("System Information:");
        for (String name : propertyNames) {
            if (name == null || name.length() == 0) {
                continue;
            }
            String value = System.getProperty(name);
            if (value != null && value.length() > 0) {
                System.out.println("  " + name + " = " + value);
            }
        }

        final TimeZone defaultTZ = TimeZone.getDefault();
        final int defaultOffset = defaultTZ.getOffset(nowInMillis) / MILLIS_IN_HOUR;
        final int userOffset = TimeZone.getTimeZone(System
                .getProperty("user.timezone")).getOffset(nowInMillis) / MILLIS_IN_HOUR;
        final Locale defaultLocale = Locale.getDefault();

        System.out.println("  default.timezone-offset (hours) = " + userOffset);
        System.out.println("  default.timezone = " + defaultTZ.getDisplayName());
        System.out.println("  default.timezone.id = " + defaultTZ.getID());
        System.out.println("  default.timezone-offset (hours) = " + defaultOffset);
        System.out.println("  default.locale = "
                + defaultLocale.getLanguage() + "_" + defaultLocale.getCountry()
                + " (" + defaultLocale.getDisplayLanguage()
                + "," + defaultLocale.getDisplayCountry() + ")");
        System.out.println("  now = " + nowInMillis + " [ms] or "
                + createDateFormat().format(now));
        System.out.println();
    }

    @Before
    public void setUp() throws Exception {
        // Remember this moment.
        now = new Date();
        nowInMillis = now.getTime(); // == System.currentTimeMillis();

        // Print out some system information.
        printSystemInfo();

        // "Europe/London" time zone is DST aware, we'll use fixed offset.
        londonTimeZone = TimeZone.getTimeZone("GMT");
        // The same applies to "America/New York" time zone ...
        newYorkTimeZone = TimeZone.getTimeZone("GMT-5");
        // ... and for the "Australia/Sydney" time zone.
        sydneyTimeZone = TimeZone.getTimeZone("GMT+10");
    }

    @Test
    public void testDateFormatting() throws Exception {
        int londonOffset = londonTimeZone.getOffset(nowInMillis) / MILLIS_IN_HOUR; // in hours
        Calendar londonCalendar = Calendar.getInstance(londonTimeZone);
        londonCalendar.setTime(now);

        int newYorkOffset = newYorkTimeZone.getOffset(nowInMillis) / MILLIS_IN_HOUR;
        Calendar newYorkCalendar = Calendar.getInstance(newYorkTimeZone);
        newYorkCalendar.setTime(now);

        int sydneyOffset = sydneyTimeZone.getOffset(nowInMillis) / MILLIS_IN_HOUR;
        Calendar sydneyCalendar = Calendar.getInstance(sydneyTimeZone);
        sydneyCalendar.setTime(now);

        // Check each time zone offset.
        assertThat(londonOffset, equalTo(0));
        assertThat(newYorkOffset, equalTo(-5));
        assertThat(sydneyOffset, equalTo(10));

        // Check that calendars are not equals (due to time zone difference).
        assertThat(londonCalendar, not(equalTo(newYorkCalendar)));
        assertThat(londonCalendar, not(equalTo(sydneyCalendar)));

        // Check if they all point to the same moment in time, in milliseconds.
        assertThat(londonCalendar.getTimeInMillis(), equalTo(nowInMillis));
        assertThat(newYorkCalendar.getTimeInMillis(), equalTo(nowInMillis));
        assertThat(sydneyCalendar.getTimeInMillis(), equalTo(nowInMillis));

        // Check if they all point to the same moment in time, as Date.
        assertThat(londonCalendar.getTime(), equalTo(now));
        assertThat(newYorkCalendar.getTime(), equalTo(now));
        assertThat(sydneyCalendar.getTime(), equalTo(now));

        // Check if hours are all different (skip local time because
        // this test could be executed in those exact time zones).
        assertThat(newYorkCalendar.get(Calendar.HOUR_OF_DAY),
                not(equalTo(londonCalendar.get(Calendar.HOUR_OF_DAY))));
        assertThat(sydneyCalendar.get(Calendar.HOUR_OF_DAY),
                not(equalTo(londonCalendar.get(Calendar.HOUR_OF_DAY))));


        // Display London time in multiple forms.
        SimpleDateFormat dfLondonNoTZ = createDateFormat(ISO_FORMAT_NO_TZ, londonTimeZone);
        SimpleDateFormat dfLondonWithTZ = createDateFormat(ISO_FORMAT_WITH_TZ, londonTimeZone);
        System.out.println("London (" + londonTimeZone.getDisplayName(false, TimeZone.SHORT)
                + ", " + londonOffset + "):");
        System.out.println("  time (ISO format w/o TZ) = "
                + dfLondonNoTZ.format(londonCalendar.getTime()));
        System.out.println("  time (ISO format w/ TZ)  = "
                + dfLondonWithTZ.format(londonCalendar.getTime()));
        System.out.println("  time (default format)    = "
                + londonCalendar.getTime() + " / " + londonCalendar.toString());
        // Using system default time zone.
        System.out.println("  time (default TZ)        = "
                + createDateFormat(ISO_FORMAT_NO_TZ).format(londonCalendar.getTime())
                + " / " + createDateFormat().format(londonCalendar.getTime()));


        // Display New York time in multiple forms.
        SimpleDateFormat dfNewYorkNoTZ = createDateFormat(ISO_FORMAT_NO_TZ, newYorkTimeZone);
        SimpleDateFormat dfNewYorkWithTZ = createDateFormat(ISO_FORMAT_WITH_TZ, newYorkTimeZone);
        System.out.println("New York (" + newYorkTimeZone.getDisplayName(false, TimeZone.SHORT)
                + ", " + newYorkOffset + "):");
        System.out.println("  time (ISO format w/o TZ) = "
                + dfNewYorkNoTZ.format(newYorkCalendar.getTime()));
        System.out.println("  time (ISO format w/ TZ)  = "
                + dfNewYorkWithTZ.format(newYorkCalendar.getTime()));
        System.out.println("  time (default format)    = "
                + newYorkCalendar.getTime() + " / " + newYorkCalendar.toString());
        // Using system default time zone.
        System.out.println("  time (default TZ)        = "
                + createDateFormat(ISO_FORMAT_NO_TZ).format(newYorkCalendar.getTime())
                + " / " + createDateFormat().format(newYorkCalendar.getTime()));


        // Display Sydney time in multiple forms.
        SimpleDateFormat dfSydneyNoTZ = createDateFormat(ISO_FORMAT_NO_TZ, sydneyTimeZone);
        SimpleDateFormat dfSydneyWithTZ = createDateFormat(ISO_FORMAT_WITH_TZ, sydneyTimeZone);
        System.out.println("Sydney (" + sydneyTimeZone.getDisplayName(false, TimeZone.SHORT)
                + ", " + sydneyOffset + "):");
        System.out.println("  time (ISO format w/o TZ) = "
                + dfSydneyNoTZ.format(sydneyCalendar.getTime()));
        System.out.println("  time (ISO format w/ TZ)  = "
                + dfSydneyWithTZ.format(sydneyCalendar.getTime()));
        System.out.println("  time (default format)    = "
                + sydneyCalendar.getTime() + " / " + sydneyCalendar.toString());
        // Using system default time zone.
        System.out.println("  time (default TZ)        = "
                + createDateFormat(ISO_FORMAT_NO_TZ).format(sydneyCalendar.getTime())
                + " / " + createDateFormat().format(sydneyCalendar.getTime()));
    }

    @Test
    public void testDateParsing() throws Exception {
        // Create date parsers that look for time zone information in a date-time string.
        final SimpleDateFormat londonFormatTZ = createDateFormat(ISO_FORMAT_WITH_TZ, londonTimeZone);
        final SimpleDateFormat newYorkFormatTZ = createDateFormat(ISO_FORMAT_WITH_TZ, newYorkTimeZone);
        final SimpleDateFormat sydneyFormatTZ = createDateFormat(ISO_FORMAT_WITH_TZ, sydneyTimeZone);

        // Create date parsers that ignore time zone information in a date-time string.
        final SimpleDateFormat londonFormatLocal = createDateFormat(ISO_FORMAT_NO_TZ, londonTimeZone);
        final SimpleDateFormat newYorkFormatLocal = createDateFormat(ISO_FORMAT_NO_TZ, newYorkTimeZone);
        final SimpleDateFormat sydneyFormatLocal = createDateFormat(ISO_FORMAT_NO_TZ, sydneyTimeZone);

        // We are looking for the moment this millenium started, the famous Y2K,
        // when at midnight everyone welcomed the New Year 2000, i.e. 2000-01-01 00:00:00.
        // Which of these is the right one?
        // a) "2000-01-01T00:00:00.000-00:00"
        // b) "2000-01-01T00:00:00.000-05:00"
        // c) "2000-01-01T00:00:00.000+10:00"
        // None of them? All of them?
        // For those who guessed it - yes, it is a trick question because we didn't specify
        // the "where" part, or what kind of time (local/global) we are looking for.
        // The first (a) is the local Y2K moment in London, which is at the same time global.
        // The second (b) is the local Y2K moment in New York, but London is already celebrating for 5 hours.
        // The third (c) is the local Y2K moment in Sydney, and they started celebrating 15 hours before New York did.
        // The point here is that each answer is correct because everyone thinks of that moment in terms of "celebration at midnight".
        // The key word here is "midnight"! That moment is actually a "time of day" moment illustrating our perception of time based on the movement of our Sun.

        // These are global Y2K moments, i.e. the same moment all over the world, UTC/GMT midnight.
        final String MIDNIGHT_GLOBAL = "2000-01-01T00:00:00.000-00:00";
        final Date milleniumInLondon = londonFormatTZ.parse(MIDNIGHT_GLOBAL);
        final Date milleniumInNewYork = newYorkFormatTZ.parse(MIDNIGHT_GLOBAL);
        final Date milleniumInSydney = sydneyFormatTZ.parse(MIDNIGHT_GLOBAL);

        // Check if they all point to the same moment in time.
        // And that parser ignores its own configured time zone and uses the information from the date-time string.
        assertThat(milleniumInNewYork, equalTo(milleniumInLondon));
        assertThat(milleniumInSydney, equalTo(milleniumInLondon));


        // These are all local Y2K moments, a.k.a. midnight at each location on Earth, with time zone information.
        final String MIDNIGHT_LONDON = "2000-01-01T00:00:00.000-00:00";
        final String MIDNIGHT_NEW_YORK = "2000-01-01T00:00:00.000-05:00";
        final String MIDNIGHT_SYDNEY = "2000-01-01T00:00:00.000+10:00";
        final Date midnightInLondonTZ = londonFormatLocal.parse(MIDNIGHT_LONDON);
        final Date midnightInNewYorkTZ = newYorkFormatLocal.parse(MIDNIGHT_NEW_YORK);
        final Date midnightInSydneyTZ = sydneyFormatLocal.parse(MIDNIGHT_SYDNEY);

        // Check if they all point to the same moment in time.
        assertThat(midnightInNewYorkTZ, not(equalTo(midnightInLondonTZ)));
        assertThat(midnightInSydneyTZ, not(equalTo(midnightInLondonTZ)));

        // Check if the time zone offset is correct.
        assertThat(midnightInLondonTZ.getTime() - midnightInNewYorkTZ.getTime(),
                equalTo((long) newYorkTimeZone.getOffset(milleniumInLondon.getTime())));
        assertThat(midnightInLondonTZ.getTime() - midnightInSydneyTZ.getTime(),
                equalTo((long) sydneyTimeZone.getOffset(milleniumInLondon.getTime())));


        // These are also local Y2K moments, just withouth the time zone information.
        final String MIDNIGHT_ANYWHERE = "2000-01-01T00:00:00.000";
        final Date midnightInLondon = londonFormatLocal.parse(MIDNIGHT_ANYWHERE);
        final Date midnightInNewYork = newYorkFormatLocal.parse(MIDNIGHT_ANYWHERE);
        final Date midnightInSydney = sydneyFormatLocal.parse(MIDNIGHT_ANYWHERE);

        // Check if these are the same as the local moments with time zone information.
        assertThat(midnightInLondon, equalTo(midnightInLondonTZ));
        assertThat(midnightInNewYork, equalTo(midnightInNewYorkTZ));
        assertThat(midnightInSydney, equalTo(midnightInSydneyTZ));

        // Check if they all point to the same moment in time.
        assertThat(midnightInNewYork, not(equalTo(midnightInLondon)));
        assertThat(midnightInSydney, not(equalTo(midnightInLondon)));

        // Check if the time zone offset is correct.
        assertThat(midnightInLondon.getTime() - midnightInNewYork.getTime(),
                equalTo((long) newYorkTimeZone.getOffset(milleniumInLondon.getTime())));
        assertThat(midnightInLondon.getTime() - midnightInSydney.getTime(),
                equalTo((long) sydneyTimeZone.getOffset(milleniumInLondon.getTime())));


        // Final check - if Y2K moment is in London ..
        final String Y2K_LONDON = "2000-01-01T00:00:00.000Z";
        // .. New York local time would be still 5 hours in 1999 ..
        final String Y2K_NEW_YORK = "1999-12-31T19:00:00.000-05:00";
        // .. and Sydney local time would be 10 hours in 2000.
        final String Y2K_SYDNEY = "2000-01-01T10:00:00.000+10:00";

        final String londonTime = londonFormatTZ.format(milleniumInLondon);
        final String newYorkTime = newYorkFormatTZ.format(milleniumInLondon);
        final String sydneyTime = sydneyFormatTZ.format(milleniumInLondon);

        // WHat do you think, will the test pass?
        assertThat(londonTime, equalTo(Y2K_LONDON));
        assertThat(newYorkTime, equalTo(Y2K_NEW_YORK));
        assertThat(sydneyTime, equalTo(Y2K_SYDNEY));
    }
}

Hashmap with Streams in Java 8 Streams to collect value of Map

What you need to do is create a Stream out of the Map's .entrySet():

// Map<K, V> --> Set<Map.Entry<K, V>> --> Stream<Map.Entry<K, V>>
map.entrySet().stream()

From the on, you can .filter() over these entries. For instance:

// Stream<Map.Entry<K, V>> --> Stream<Map.Entry<K, V>>
.filter(entry -> entry.getKey() == 1)

And to obtain the values from it you .map():

// Stream<Map.Entry<K, V>> --> Stream<V>
.map(Map.Entry::getValue)

Finally, you need to collect into a List:

// Stream<V> --> List<V>
.collect(Collectors.toList())

If you have only one entry, use this instead (NOTE: this code assumes that there is a value; otherwise, use .orElse(); see the javadoc of Optional for more details):

// Stream<V> --> Optional<V> --> V
.findFirst().get()

Missing artifact com.microsoft.sqlserver:sqljdbc4:jar:4.0

For self-containing Maven project I usually installing all external jar dependencies into project's repository. For SQL Server JDBC driver you can do:

  • download JDBC driver from https://www.microsoft.com/en-us/download/confirmation.aspx?id=11774
  • create folder local-repo in your Maven project
  • temporary copy sqljdbc42.jar into local-repo folder
  • in local-repo folder run mvn deploy:deploy-file -Dfile=sqljdbc42.jar -DartifactId=sqljdbc42 -DgroupId=com.microsoft.sqlserver -DgeneratePom=true -Dpackaging=jar -Dversion=6.0.7507.100 -Durl=file://. to deploy JAR into local repository (stored together with your code in SCM)
  • sqljdbc42.jar and downloaded files can be deleted
  • modify your's pom.xml and add reference to project's local repository: xml <repositories> <repository> <id>parent-local-repository</id> <name>Parent Local repository</name> <layout>default</layout> <url>file://${basedir}/local-repo</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>true</enabled> </snapshots> </repository> </repositories> Now you can run your project everywhere without any additional configurations or installations.

Create multiple threads and wait all of them to complete

In .NET 4.0, you can use the Task Parallel Library.

In earlier versions, you can create a list of Thread objects in a loop, calling Start on each one, and then make another loop and call Join on each one.

Measure the time it takes to execute a t-sql query

Another way is using a SQL Server built-in feature named Client Statistics which is accessible through Menu > Query > Include Client Statistics.

You can run each query in separated query window and compare the results which is given in Client Statistics tab just beside the Messages tab.

For example in image below it shows that the average time elapsed to get the server reply for one of my queries is 39 milliseconds.

Result

You can read all 3 ways for acquiring execution time in here. You may even need to display Estimated Execution Plan ctrlL for further investigation about your query.

How can INSERT INTO a table 300 times within a loop in SQL?

In ssms we can use GO to execute same statement

Edit This mean if you put

 some query

 GO n

Some query will be executed n times

Difference between fprintf, printf and sprintf?

printf("format", args) is used to print the data onto the standard output which is often a computer monitor.

sprintf(char *, "format", args) is like printf. Instead of displaying the formated string on the standard output i.e. a monitor, it stores the formated data in a string pointed to by the char pointer (the very first parameter). The string location is the only difference between printf and sprint syntax.

fprintf(FILE *fp, "format", args) is like printf again. Here, instead of displaying the data on the monitor, or saving it in some string, the formatted data is saved on a file which is pointed to by the file pointer which is used as the first parameter to fprintf. The file pointer is the only addition to the syntax of printf.

If stdout file is used as the first parameter in fprintf, its working is then considered equivalent to that of printf.

Windows 7 - Add Path

I think you are editing something in the windows registry but that has no effect on the path.

Try this:

How to Add, Remove or Edit Environment variables in Windows 7

the variable of interest is the PATH

also you can type on the command line:

Set PATH=%PATH%;(your new path);

Disable browsers vertical and horizontal scrollbars

Try CSS

<body style="overflow: hidden">

Migration: Cannot add foreign key constraint

For me, the table column that my child table referenced wasn't indexed.

Schema::create('schools', function (Blueprint $table) {
    $table->integer('dcid')->index()->unque();
    $table->integer('school_number')->index(); // The important thing is that this is indexed
    $table->string('name');
    $table->string('abbreviation');
    $table->integer('high_grade');
    $table->integer('low_grade');
    $table->timestamps();
    $table->primary('dcid');
});

Schema::create('students', function (Blueprint $table) {
      $table->increments('id');
      $table->integer('dcid')->index()->unique()->nullable();
      $table->unsignedInteger('student_number')->nullable();
      $table->integer('schoolid')->nullable();
      $table->foreign('schoolid')->references('school_number')->on('schools')->onDelete('set null');
      // ...
});

Ignore the terrible naming, it's from another terribly designed system.