Programs & Examples On #Rightscale

Rightscale is a cloud management service that allows users to deploy and manage applications across public, private and hybrid clouds.

Scraping html tables into R data frames using the XML package

library(RCurl)
library(XML)

# Download page using RCurl
# You may need to set proxy details, etc.,  in the call to getURL
theurl <- "http://en.wikipedia.org/wiki/Brazil_national_football_team"
webpage <- getURL(theurl)
# Process escape characters
webpage <- readLines(tc <- textConnection(webpage)); close(tc)

# Parse the html tree, ignoring errors on the page
pagetree <- htmlTreeParse(webpage, error=function(...){})

# Navigate your way through the tree. It may be possible to do this more efficiently using getNodeSet
body <- pagetree$children$html$children$body 
divbodyContent <- body$children$div$children[[1]]$children$div$children[[4]]
tables <- divbodyContent$children[names(divbodyContent)=="table"]

#In this case, the required table is the only one with class "wikitable sortable"  
tableclasses <- sapply(tables, function(x) x$attributes["class"])
thetable  <- tables[which(tableclasses=="wikitable sortable")]$table

#Get columns headers
headers <- thetable$children[[1]]$children
columnnames <- unname(sapply(headers, function(x) x$children$text$value))

# Get rows from table
content <- c()
for(i in 2:length(thetable$children))
{
   tablerow <- thetable$children[[i]]$children
   opponent <- tablerow[[1]]$children[[2]]$children$text$value
   others <- unname(sapply(tablerow[-1], function(x) x$children$text$value)) 
   content <- rbind(content, c(opponent, others))
}

# Convert to data frame
colnames(content) <- columnnames
as.data.frame(content)

Edited to add:

Sample output

                     Opponent Played Won Drawn Lost Goals for Goals against  % Won
    1               Argentina     94  36    24   34       148           150  38.3%
    2                Paraguay     72  44    17   11       160            61  61.1%
    3                 Uruguay     72  33    19   20       127            93  45.8%
    ...

jQuery AJAX submit form

This code works even with file input

$(document).on("submit", "form", function(event)
{
    event.preventDefault();        
    $.ajax({
        url: $(this).attr("action"),
        type: $(this).attr("method"),
        dataType: "JSON",
        data: new FormData(this),
        processData: false,
        contentType: false,
        success: function (data, status)
        {

        },
        error: function (xhr, desc, err)
        {


        }
    });        
});

Where do I put my php files to have Xampp parse them?

Look into the httpd.conf and/or httpd-vhosts.conf files and search for the DocumentRoot entry. If you configure multiple virtual hosts, there may be more than one of those, separated in <VirtualHost> tags.

How to read existing text files without defining path

You could use Directory.GetCurrentDirectory:

var path = Path.Combine(Directory.GetCurrentDirectory(), "\\fileName.txt");

Which will look for the file fileName.txt in the current directory of the application.

Readably print out a python dict() sorted by key

An easy way to print the sorted contents of the dictionary, in Python 3:

>>> dict_example = {'c': 1, 'b': 2, 'a': 3}
>>> for key, value in sorted(dict_example.items()):
...   print("{} : {}".format(key, value))
... 
a : 3
b : 2
c : 1

The expression dict_example.items() returns tuples, which can then be sorted by sorted():

>>> dict_example.items()
dict_items([('c', 1), ('b', 2), ('a', 3)])
>>> sorted(dict_example.items())
[('a', 3), ('b', 2), ('c', 1)]

Below is an example to pretty print the sorted contents of a Python dictionary's values.

for key, value in sorted(dict_example.items(), key=lambda d_values: d_values[1]): 
    print("{} : {}".format(key, value))

Deleting DataFrame row in Pandas based on column value

The best way to do this is with boolean masking:

In [56]: df
Out[56]:
     line_date  daysago  line_race  rating    raw  wrating
0   2007-03-31       62         11      56  1.000   56.000
1   2007-03-10       83         11      67  1.000   67.000
2   2007-02-10      111          9      66  1.000   66.000
3   2007-01-13      139         10      83  0.881   73.096
4   2006-12-23      160         10      88  0.793   69.787
5   2006-11-09      204          9      52  0.637   33.106
6   2006-10-22      222          8      66  0.582   38.408
7   2006-09-29      245          9      70  0.519   36.318
8   2006-09-16      258         11      68  0.486   33.063
9   2006-08-30      275          8      72  0.447   32.160
10  2006-02-11      475          5      65  0.165   10.698
11  2006-01-13      504          0      70  0.142    9.969
12  2006-01-02      515          0      64  0.135    8.627
13  2005-12-06      542          0      70  0.118    8.246
14  2005-11-29      549          0      70  0.114    7.963
15  2005-11-22      556          0      -1  0.110   -0.110
16  2005-11-01      577          0      -1  0.099   -0.099
17  2005-10-20      589          0      -1  0.093   -0.093
18  2005-09-27      612          0      -1  0.083   -0.083
19  2005-09-07      632          0      -1  0.075   -0.075
20  2005-06-12      719          0      69  0.049    3.360
21  2005-05-29      733          0      -1  0.045   -0.045
22  2005-05-02      760          0      -1  0.040   -0.040
23  2005-04-02      790          0      -1  0.034   -0.034
24  2005-03-13      810          0      -1  0.031   -0.031
25  2004-11-09      934          0      -1  0.017   -0.017

In [57]: df[df.line_race != 0]
Out[57]:
     line_date  daysago  line_race  rating    raw  wrating
0   2007-03-31       62         11      56  1.000   56.000
1   2007-03-10       83         11      67  1.000   67.000
2   2007-02-10      111          9      66  1.000   66.000
3   2007-01-13      139         10      83  0.881   73.096
4   2006-12-23      160         10      88  0.793   69.787
5   2006-11-09      204          9      52  0.637   33.106
6   2006-10-22      222          8      66  0.582   38.408
7   2006-09-29      245          9      70  0.519   36.318
8   2006-09-16      258         11      68  0.486   33.063
9   2006-08-30      275          8      72  0.447   32.160
10  2006-02-11      475          5      65  0.165   10.698

UPDATE: Now that pandas 0.13 is out, another way to do this is df.query('line_race != 0').

Difference between $.ajax() and $.get() and $.load()

http://api.jquery.com/jQuery.ajax/

jQuery.ajax()

Description: Perform an asynchronous HTTP (Ajax) request.

The full monty, lets you make any kind of Ajax request.


http://api.jquery.com/jQuery.get/

jQuery.get()

Description: Load data from the server using a HTTP GET request.

Only lets you make HTTP GET requests, requires a little less configuration.


http://api.jquery.com/load/

.load()

Description: Load data from the server and place the returned HTML into the matched element.

Specialized to get data and inject it into an element.

Should a RESTful 'PUT' operation return something

Just as an empty Request body is in keeping with the original purpose of a GET request and empty response body is in keeping with the original purpose of a PUT request.

How to create multidimensional array

Quote taken from Data Structures and Algorithms with JavaScript

The Good Parts (O’Reilly, p. 64). Crockford extends the JavaScript array object with a function that sets the number of rows and columns and sets each value to a value passed to the function. Here is his definition:

Array.matrix = function(numrows, numcols, initial) {
    var arr = [];
    for (var i = 0; i < numrows; ++i) {
        var columns = [];
        for (var j = 0; j < numcols; ++j) {
            columns[j] = initial;
        }
        arr[i] = columns;
    }
    return arr;
}

Here is some code to test the definition:

var nums = Array.matrix(5,5,0);
print(nums[1][1]); // displays 0
var names = Array.matrix(3,3,"");
names[1][2] = "Joe";
print(names[1][2]); // display "Joe"

We can also create a two-dimensional array and initialize it to a set of values in one line:

var grades = [[89, 77, 78],[76, 82, 81],[91, 94, 89]];
print(grades[2][2]); // displays 89

Create multiple threads and wait all of them to complete

If you don't want to use the Task class (for instance, in .NET 3.5) you can just start all your threads, and then add them to the list and join them in a foreach loop.

Example:

List<Thread> threads = new List<Thread>();


// Start threads
for(int i = 0; i<10; i++)
{
    int tmp = i; // Copy value for closure
    Thread t = new Thread(() => Console.WriteLine(tmp));
    t.Start;
    threads.Add(t);
}

// Await threads
foreach(Thread thread in threads)
{
    thread.Join();
}

Why do we use __init__ in Python classes?

The __init__ function is setting up all the member variables in the class. So once your bicluster is created you can access the member and get a value back:

mycluster = bicluster(...actual values go here...)
mycluster.left # returns the value passed in as 'left'

Check out the Python Docs for some info. You'll want to pick up an book on OO concepts to continue learning.

How can I use NSError in my iPhone App?

Another design pattern that I have seen involves using blocks, which is especially useful when a method is being run asynchronously.

Say we have the following error codes defined:

typedef NS_ENUM(NSInteger, MyErrorCodes) {
    MyErrorCodesEmptyString = 500,
    MyErrorCodesInvalidURL,
    MyErrorCodesUnableToReachHost,
};

You would define your method that can raise an error like so:

- (void)getContentsOfURL:(NSString *)path success:(void(^)(NSString *html))success failure:(void(^)(NSError *error))failure {
    if (path.length == 0) {
        if (failure) {
            failure([NSError errorWithDomain:@"com.example" code:MyErrorCodesEmptyString userInfo:nil]);
        }
        return;
    }

    NSString *htmlContents = @"";

    // Exercise for the reader: get the contents at that URL or raise another error.

    if (success) {
        success(htmlContents);
    }
}

And then when you call it, you don't need to worry about declaring the NSError object (code completion will do it for you), or checking the returning value. You can just supply two blocks: one that will get called when there is an exception, and one that gets called when it succeeds:

[self getContentsOfURL:@"http://google.com" success:^(NSString *html) {
    NSLog(@"Contents: %@", html);
} failure:^(NSError *error) {
    NSLog(@"Failed to get contents: %@", error);
    if (error.code == MyErrorCodesEmptyString) { // make sure to check the domain too
        NSLog(@"You must provide a non-empty string");
    }
}];

form action with javascript

It has been almost 8 years since the question was asked, but I will venture an answer not previously given. The OP said this doesn't work:

action="javascript:simpleCart.checkout()"

And the OP said that this code continued to fail despite trying all the good advice he got. So I will venture a guess. The action is calling checkout() as a static method of the simpleCart class; but maybe checkout() is actually an instance member, and not static. It depends how he defined checkout().

By the way, simpleCart is presumably a class name, and by convention class names have an initial capital letter, so let's use that convention, here. Let's use the name SimpleCart.

Here is some sample code that illustrates defining checkout() as an instance member. This was the correct way to do it, prior to ECMA-6:

function SimpleCart() {
    ...
}
SimpleCart.prototype.checkout = function() { ... };

Many people have used a different technique, as illustrated in the following. This was popular, and it worked, but I advocate against it, because instances are supposed to be defined on the prototype, just once, while the following technique defines the member on this and does so repeatedly, with every instantiation.

function SimpleCart() {
    ...
    this.checkout = function() { ... };
}

And here is an instance definition in ECMA-6, using an official class:

class SimpleCart {
    constructor() { ... }
    ...
    checkout()    { ... }
}

Compare to a static definition in ECMA-6. The difference is just one word:

class SimpleCart {
    constructor() { ... }
    ...
    static checkout()    { ... }
}

And here is a static definition the old way, pre-ECMA-6. Note that the checkout() method is defined outside of the function. It is a member of the function object, not the prototype object, and that's what makes it static.

function SimpleCart() {
    ...
}
SimpleCart.checkout = function() { ... };

Because of the way it is defined, a static function will have a different concept of what the keyword this references. Note that instance member functions are called using the this keyword:

this.checkout();

Static member functions are called using the class name:

SimpleCart.checkout();

The problem is that the OP wants to put the call into HTML, where it will be in global scope. He can't use the keyword this because this would refer to the global scope (which is window).

action="javascript:this.checkout()" // not as intended
action="javascript:window.checkout()" // same thing

There is no easy way to use an instance member function in HTML. You can do stuff in combination with JavaScript, creating a registry in the static scope of the Class, and then calling a surrogate static method, while passing an argument to that surrogate that gives the index into the registry of your instance, and then having the surrogate call the actual instance member function. Something like this:

// In Javascript:
SimpleCart.registry[1234] = new SimpleCart();

// In HTML
action="javascript:SimpleCart.checkout(1234);"

// In Javascript
SimpleCart.checkout = function(myIndex) {
    var myThis = SimpleCart.registry[myIndex];
    myThis.checkout();
}

You could also store the index as an attribute on the element.

But usually it is easier to just do nothing in HTML and do everything in JavaScript with .addEventListener() and use the .bind() capability.

Creating and throwing new exception

You can throw your own custom errors by extending the Exception class.

class CustomException : Exception {
    [string] $additionalData

    CustomException($Message, $additionalData) : base($Message) {
        $this.additionalData = $additionalData
    }
}

try {
    throw [CustomException]::new('Error message', 'Extra data')
} catch [CustomException] {
    # NOTE: To access your custom exception you must use $_.Exception
    Write-Output $_.Exception.additionalData

    # This will produce the error message: Didn't catch it the second time
    throw [CustomException]::new("Didn't catch it the second time", 'Extra data')
}

How to remove all click event handlers using jQuery?

$('#saveBtn').off('click').click(function(){saveQuestion(id)});

Angular 2 two way binding using ngModel is not working

As per Angular2 final, you do not even have to import FORM_DIRECTIVES as suggested above by many. However, the syntax has been changed as kebab-case was dropped for the betterment.

Just replace ng-model with ngModel and wrap it in a box of bananas. But you have spilt the code into two files now:

app.ts:

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

@Component({
  selector: 'ng-app',
  template: `
    <input id="name" type="text" [(ngModel)]="name"  />
    {{ name }}
  `
})
export class DataBindingComponent {
  name: string;

  constructor() {
    this.name = 'Jose';
  }
}

app.module.ts:

import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { DataBindingComponent } from './app'; //app.ts above

@NgModule({
  declarations: [DataBindingComponent],
  imports:      [BrowserModule, FormsModule],
  bootstrap:    [DataBindingComponent]
})
export default class MyAppModule {}

platformBrowserDynamic().bootstrapModule(MyAppModule);

creating charts with angularjs

I've created an angular directive for xCharts which is a nice js chart library http://tenxer.github.io/xcharts/. You can install it using bower, quite easy: https://github.com/radu-cigmaian/ng-xCharts

Highcharts is also a solution, but it is not free for comercial use.

How do I get a plist as a Dictionary in Swift?

Since this answer isn't here yet, just wanted to point out you can also use the infoDictionary property to get the info plist as a dictionary, Bundle.main.infoDictionary.

Although something like Bundle.main.object(forInfoDictionaryKey: kCFBundleNameKey as String) may be faster if you're only interested in a specific item in the info plist.

// Swift 4

// Getting info plist as a dictionary
let dictionary = Bundle.main.infoDictionary

// Getting the app display name from the info plist
Bundle.main.infoDictionary?[kCFBundleNameKey as String]

// Getting the app display name from the info plist (another way)
Bundle.main.object(forInfoDictionaryKey: kCFBundleNameKey as String)

How to get Django and ReactJS to work together?

The first approach is building separate Django and React apps. Django will be responsible for serving the API built using Django REST framework and React will consume these APIs using the Axios client or the browser's fetch API. You'll need to have two servers, both in development and production, one for Django(REST API) and the other for React (to serve static files).

The second approach is different the frontend and backend apps will be coupled. Basically you'll use Django to both serve the React frontend and to expose the REST API. So you'll need to integrate React and Webpack with Django, these are the steps that you can follow to do that

First generate your Django project then inside this project directory generate your React application using the React CLI

For Django project install django-webpack-loader with pip:

pip install django-webpack-loader

Next add the app to installed apps and configure it in settings.py by adding the following object

WEBPACK_LOADER = {
    'DEFAULT': {
            'BUNDLE_DIR_NAME': '',
            'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'),
        }
}

Then add a Django template that will be used to mount the React application and will be served by Django

{ % load render_bundle from webpack_loader % }

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width" />
    <title>Django + React </title>
  </head>
  <body>
    <div id="root">
     This is where React will be mounted
    </div>
    { % render_bundle 'main' % }
  </body>
</html>

Then add an URL in urls.py to serve this template

from django.conf.urls import url
from django.contrib import admin
from django.views.generic import TemplateView

urlpatterns = [

    url(r'^', TemplateView.as_view(template_name="main.html")),

]

If you start both the Django and React servers at this point you'll get a Django error saying the webpack-stats.json doesn't exist. So next you need to make your React application able to generate the stats file.

Go ahead and navigate inside your React app then install webpack-bundle-tracker

npm install webpack-bundle-tracker --save

Then eject your Webpack configuration and go to config/webpack.config.dev.js then add

var BundleTracker  = require('webpack-bundle-tracker');
//...

module.exports = {

    plugins: [
          new BundleTracker({path: "../", filename: 'webpack-stats.json'}),
    ]
}

This add BundleTracker plugin to Webpack and instruct it to generate webpack-stats.json in the parent folder.

Make sure also to do the same in config/webpack.config.prod.js for production.

Now if you re-run your React server the webpack-stats.json will be generated and Django will be able to consume it to find information about the Webpack bundles generated by React dev server.

There are some other things to. You can find more information from this tutorial.

Get all LI elements in array

After some years have passed, you can do that now with ES6 Array.from (or spread syntax):

_x000D_
_x000D_
const navbar = Array.from(document.querySelectorAll('#navbar>ul>li'));_x000D_
console.log('Get first: ', navbar[0].textContent);_x000D_
_x000D_
// If you need to iterate once over all these nodes, you can use the callback function:_x000D_
console.log('Iterate with Array.from callback argument:');_x000D_
Array.from(document.querySelectorAll('#navbar>ul>li'),li => console.log(li.textContent))_x000D_
_x000D_
// ... or a for...of loop:_x000D_
console.log('Iterate with for...of:');_x000D_
for (const li of document.querySelectorAll('#navbar>ul>li')) {_x000D_
    console.log(li.textContent);_x000D_
}
_x000D_
.as-console-wrapper { max-height: 100% !important; top: 0; }
_x000D_
<div id="navbar">_x000D_
  <ul>_x000D_
    <li id="navbar-One">One</li>_x000D_
    <li id="navbar-Two">Two</li>_x000D_
    <li id="navbar-Three">Three</li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Create a sample login page using servlet and JSP?

As I can see, you are comparing the message with the empty string using ==.

Its very hard to write the full code, but I can tell the flow of code - first, create db class & method inide that which will return the connection. second, create a servelet(ex-login.java) & import that db class onto that servlet. third, create instance of imported db class with the help of new operator & call the connection method of that db class. fourth, creaet prepared statement & execute statement & put this code in try catch block for exception handling.Use if-else condition in the try block to navigate your login page based on success or failure.

I hope, it will help you. If any problem, then please revert.

Nikhil Pahariya

Disabling swap files creation in vim

here are my personal ~/.vimrc backup settings

" backup to ~/.tmp 
set backup 
set backupdir=~/.vim-tmp,~/.tmp,~/tmp,/var/tmp,/tmp 
set backupskip=/tmp/*,/private/tmp/* 
set directory=~/.vim-tmp,~/.tmp,~/tmp,/var/tmp,/tmp 
set writebackup

How to convert from int to string in objective c: example code

== shouldn't be used to compare objects in your if. For NSString use isEqualToString: to compare them.

How to prevent Browser cache for php site

Here, if you want to control it through HTML: do like below Option 1:

<meta http-equiv="expires" content="Sun, 01 Jan 2014 00:00:00 GMT"/>
<meta http-equiv="pragma" content="no-cache" />

And if you want to control it through PHP: do it like below Option 2:

header('Expires: Sun, 01 Jan 2014 00:00:00 GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', FALSE);
header('Pragma: no-cache');

AND Option 2 IS ALWAYS BETTER in order to avoid proxy based caching issue.

Converting double to string

The exception probably comes from the parseDouble() calls. Check that the values given to that function really reflect a double.

SecurityError: The operation is insecure - window.history.pushState()

In my case I was missing 'www.' from the url I was pushing. It must be exact match, if you're working on www.test.com, you must push to www.test.com and not test.com

sqlalchemy: how to join several tables by one query?

Try this

q = Session.query(
         User, Document, DocumentPermissions,
    ).filter(
         User.email == Document.author,
    ).filter(
         Document.name == DocumentPermissions.document,
    ).filter(
        User.email == 'someemail',
    ).all()

ImportError: No module named google.protobuf

if protobuf is installed then import it like this

pip install protobuf

import google.protobuf

Where are SQL Server connection attempts logged?

Another way to check on connection attempts is to look at the server's event log. On my Windows 2008 R2 Enterprise machine I opened the server manager (right-click on Computer and select Manage. Then choose Diagnostics -> Event Viewer -> Windows Logs -> Applcation. You can filter the log to isolate the MSSQLSERVER events. I found a number that looked like this

Login failed for user 'bogus'. The user is not associated with a trusted SQL Server connection. [CLIENT: 10.12.3.126]

Centering elements in jQuery Mobile

To have them centered correctly and only for the items inside the wrapper .center-wrapper use this. ( all options combined should work cross browser ) if not please post a reply here!

.center-wrapper .ui-btn-text {
    overflow: hidden;
    text-align: center;
    text-overflow: ellipsis;
    white-space: nowrap;
    text-align: center;
    margin: 0 auto;
}

How to make a .jar out from an Android Studio project

Simply add this to your java module's build.gradle. It will include dependent libraries in archive.

mainClassName = "com.company.application.Main"

jar {
  manifest { 
    attributes "Main-Class": "$mainClassName"
  }  

  from {
    configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
  }
}

This will result in [module_name]/build/libs/[module_name].jar file.

Converting double to string with N decimals, dot as decimal separator, and no thousand separator

It's really easy to specify your own decimal separator. Just took me about 2 hours to figure it out :D. You see that you were using the current ou other culture that you specify right? Well, the only thing the parser needs is an IFormatProvider. If you give it the CultureInfo.CurrentCulture.NumberFormat as a formatter, it will format the double according to your current culture's NumberDecimalSeparator. What I did was just to create a new instance of the NumberFormatInfo class and set it's NumberDecimalSeparator property to whichever separator string I wanted. Complete code below:

double value = 2.3d;
NumberFormatInfo nfi = new NumberFormatInfo();
nfi.NumberDecimalSeparator = "-";
string x = value.ToString(nfi);

The result? "2-3"

Java: How to get input from System.console()

It will depend on your environment. If you're running a Swing UI via javaw for example, then there isn't a console to display. If you're running within an IDE, it will very much depend on the specific IDE's handling of console IO.

From the command line, it should be fine though. Sample:

import java.io.Console;

public class Test {

    public static void main(String[] args) throws Exception {
        Console console = System.console();
        if (console == null) {
            System.out.println("Unable to fetch console");
            return;
        }
        String line = console.readLine();
        console.printf("I saw this line: %s", line);
    }
}

Run this just with java:

> javac Test.java
> java Test
Foo  <---- entered by the user
I saw this line: Foo    <---- program output

Another option is to use System.in, which you may want to wrap in a BufferedReader to read lines, or use Scanner (again wrapping System.in).

Best /Fastest way to read an Excel Sheet into a DataTable?

''' <summary>
''' ReadToDataTable reads the given Excel file to a datatable.
''' </summary>
''' <param name="table">The table to be populated.</param>
''' <param name="incomingFileName">The file to attempt to read to.</param>
''' <returns>TRUE if success, FALSE otherwise.</returns>
''' <remarks></remarks>
Public Function ReadToDataTable(ByRef table As DataTable,
                                incomingFileName As String) As Boolean
    Dim returnValue As Boolean = False
    Try

        Dim sheetName As String = ""
        Dim connectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & incomingFileName & ";Extended Properties=""Excel 12.0;HDR=No;IMEX=1"""
        Dim tablesInFile As DataTable
        Dim oleExcelCommand As OleDbCommand
        Dim oleExcelReader As OleDbDataReader
        Dim oleExcelConnection As OleDbConnection

        oleExcelConnection = New OleDbConnection(connectionString)
        oleExcelConnection.Open()

        tablesInFile = oleExcelConnection.GetSchema("Tables")

        If tablesInFile.Rows.Count > 0 Then
            sheetName = tablesInFile.Rows(0)("TABLE_NAME").ToString
        End If

        If sheetName <> "" Then

            oleExcelCommand = oleExcelConnection.CreateCommand()
            oleExcelCommand.CommandText = "Select * From [" & sheetName & "]"
            oleExcelCommand.CommandType = CommandType.Text

            oleExcelReader = oleExcelCommand.ExecuteReader

            'Determine what row of the Excel file we are on
            Dim currentRowIndex As Integer = 0

            While oleExcelReader.Read
                'If we are on the First Row, then add the item as Columns in the DataTable
                If currentRowIndex = 0 Then
                    For currentFieldIndex As Integer = 0 To (oleExcelReader.VisibleFieldCount - 1)
                        Dim currentColumnName As String = oleExcelReader.Item(currentFieldIndex).ToString
                        table.Columns.Add(currentColumnName, GetType(String))
                        table.AcceptChanges()
                    Next
                End If
                'If we are on a Row with Data, add the data to the SheetTable
                If currentRowIndex > 0 Then
                    Dim newRow As DataRow = table.NewRow
                    For currentFieldIndex As Integer = 0 To (oleExcelReader.VisibleFieldCount - 1)
                        Dim currentColumnName As String = table.Columns(currentFieldIndex).ColumnName
                        newRow(currentColumnName) = oleExcelReader.Item(currentFieldIndex)
                        If IsDBNull(newRow(currentFieldIndex)) Then
                            newRow(currentFieldIndex) = ""
                        End If
                    Next
                    table.Rows.Add(newRow)
                    table.AcceptChanges()
                End If

                'Increment the CurrentRowIndex
                currentRowIndex += 1
            End While

            oleExcelReader.Close()

        End If

        oleExcelConnection.Close()
        returnValue = True
    Catch ex As Exception
        'LastError = ex.ToString
        Return False
    End Try


    Return returnValue
End Function

How can I time a code segment for testing performance with Pythons timeit?

Here's a simple wrapper for steven's answer. This function doesn't do repeated runs/averaging, just saves you from having to repeat the timing code everywhere :)

'''function which prints the wall time it takes to execute the given command'''
def time_func(func, *args): #*args can take 0 or more 
  import time
  start_time = time.time()
  func(*args)
  end_time = time.time()
  print("it took this long to run: {}".format(end_time-start_time))

How to get the full URL of a Drupal page?

For Drupal 8 you can do this :

$url = 'YOUR_URL';
$url = \Drupal\Core\Url::fromUserInput('/' . $url,  array('absolute' => 'true'))->toString();

In Oracle, is it possible to INSERT or UPDATE a record through a view?

There are two times when you can update a record through a view:

  1. If the view has no joins or procedure calls and selects data from a single underlying table.
  2. If the view has an INSTEAD OF INSERT trigger associated with the view.

Generally, you should not rely on being able to perform an insert to a view unless you have specifically written an INSTEAD OF trigger for it. Be aware, there are also INSTEAD OF UPDATE triggers that can be written as well to help perform updates.

How to submit an HTML form without redirection

One-liner solution as of 2020, if your data is not meant to be sent as multipart/form-data or application/x-www-form-urlencoded:

<form onsubmit='return false'>
    <!-- ... -->           
</form>

How do I post button value to PHP?

Give them all a name that is the same

For example

<input type="button" value="a" name="btn" onclick="a" />
<input type="button" value="b" name="btn" onclick="b" />

Then in your php use:

$val = $_POST['btn']

Edit, as BalusC said; If you're not going to use onclick for doing any javascript (for example, sending the form) then get rid of it and use type="submit"

Jenkins, specifying JAVA_HOME

Using Jenkins 2 (2.3.2 in my case), the right way seems to insert the following into your pipeline file:

env.JAVA_HOME="${tool 'jdk1.8.0_111'}"
env.PATH="${env.JAVA_HOME}/bin:${env.PATH}"

"jdk1.8.0_111" beeing the name of the java configuration initially registered into Jenkins

How do I iterate through lines in an external file with shell?

This might work for you:

cat <<\! >names.txt
> alison
> barb
> charlie
> david
> !
OIFS=$IFS; IFS=$'\n'; NAMES=($(<names.txt)); IFS=$OIFS
echo "${NAMES[@]}"
alison barb charlie david
echo "${NAMES[0]}"
alison
for NAME in "${NAMES[@]}";do echo $NAME;done
alison
barb
charlie
david

Test if string is URL encoded in PHP

I think there's no foolproof way to do it. For example, consider the following:

$t = "A+B";

Is that an URL encoded "A B" or does it need to be encoded to "A%2BB"?

How to var_dump variables in twig templates?

As most good PHP programmers like to use XDebug to actually step through running code and watch variables change in real-time, using dump() feels like a step back to the bad old days.

That's why I made a Twig Debug extension and put it on Github.

https://github.com/delboy1978uk/twig-debug

composer require delboy1978uk/twig-debug

Then add the extension. If you aren't using Symfony, like this:

<?php

use Del\Twig\DebugExtension;

/** @var $twig Twig_Environment */
$twig->addExtension(new DebugExtension());

If you are, like this in your services YAML config:

twig_debugger:
    class: Del\Twig\DebugExtension
    tags:
        - { name: twig.extension }

Once registered, you can now do this anywhere in a twig template:

{{ breakpoint() }}

Now, you can use XDebug, execution will pause, and you can see all the properties of both the Context and the Environment.

Have fun! :-D

MongoDB: How to find out if an array field contains an element?

I am trying to explain by putting problem statement and solution to it. I hope it will help

Problem Statement:

Find all the published products, whose name like ABC Product or PQR Product, and price should be less than 15/-

Solution:

Below are the conditions that need to be taken care of

  1. Product price should be less than 15
  2. Product name should be either ABC Product or PQR Product
  3. Product should be in published state.

Below is the statement that applies above criterion to create query and fetch data.

$elements = $collection->find(
             Array(
                [price] => Array( [$lt] => 15 ),
                [$or] => Array(
                            [0]=>Array(
                                    [product_name]=>Array(
                                       [$in]=>Array(
                                            [0] => ABC Product,
                                            [1]=> PQR Product
                                            )
                                        )
                                    )
                                ),
                [state]=>Published
                )
            );

Switching users inside Docker image to a non-root user

You should not use su in a dockerfile, however you should use the USER instruction in the Dockerfile.

At each stage of the Dockerfile build, a new container is created so any change you make to the user will not persist on the next build stage.

For example:

RUN whoami
RUN su test
RUN whoami

This would never say the user would be test as a new container is spawned on the 2nd whoami. The output would be root on both (unless of course you run USER beforehand).

If however you do:

RUN whoami
USER test
RUN whoami

You should see root then test.

Alternatively you can run a command as a different user with sudo with something like

sudo -u test whoami

But it seems better to use the official supported instruction.

How to display Oracle schema size with SQL query?

SELECT table_name as Table_Name, row_cnt as Row_Count, SUM(mb) as Size_MB
FROM
  (SELECT in_tbl.table_name,   to_number(extractvalue(xmltype(dbms_xmlgen.getxml('select count(*) c from ' ||ut.table_name)),'/ROWSET/ROW/C')) AS row_cnt , mb
FROM
(SELECT CASE WHEN lob_tables IS NULL THEN table_name WHEN lob_tables IS NOT NULL THEN lob_tables END AS table_name , mb
FROM (SELECT ul.table_name AS lob_tables, us.segment_name AS table_name , us.bytes/1024/1024 MB FROM user_segments us
LEFT JOIN user_lobs ul ON us.segment_name = ul.segment_name ) ) in_tbl INNER JOIN user_tables ut ON in_tbl.table_name = ut.table_name ) GROUP BY table_name, row_cnt ORDER BY 3 DESC;``

Above query will give, Table_name, Row_count, Size_in_MB(includes lob column size) of specific user.

How do I get the path of the assembly the code is in?

Here is a VB.NET port of John Sibly's code. Visual Basic is not case sensitive, so a couple of his variable names were colliding with type names.

Public Shared ReadOnly Property AssemblyDirectory() As String
    Get
        Dim codeBase As String = Assembly.GetExecutingAssembly().CodeBase
        Dim uriBuilder As New UriBuilder(codeBase)
        Dim assemblyPath As String = Uri.UnescapeDataString(uriBuilder.Path)
        Return Path.GetDirectoryName(assemblyPath)
    End Get
End Property

How to wrap text around an image using HTML/CSS

If the image size is variable or the design is responsive, in addition to wrapping the text, you can set a min width for the paragraph to avoid it to become too narrow.
Give an invisible CSS pseudo-element with the desired minimum paragraph width. If there isn't enough space to fit this pseudo-element, then it will be pushed down underneath the image, taking the paragraph with it.

#container:before {
  content: ' ';
  display: table;
  width: 10em;    /* Min width required */
}
#floated{
    float: left;
    width: 150px;
    background: red;
}

How to use Sublime over SSH

A solution that worked great for me - edit locally on Mac, and have the file automatically synchronized to a remote machine

  1. Make sure you have passwordless login to the remote machine. If not, follow these steps http://osxdaily.com/2012/05/25/how-to-set-up-a-password-less-ssh-login/

  2. create a file in ~/Library/LaunchAgents/filesynchronizer.plist, with the following content:

    <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>filesynchronizer</string> <key>ProgramArguments</key> <array> <string>/usr/bin/rsync</string> <string>-avz</string> <string>/Users/USERNAME/SyncDirectory</string> <string>USERNAME@REMOTEMACHINE:~</string> </array> <key>WatchPaths</key> <array> <string>/Users/USERNAME/SyncDirectory</string> </array> </dict> </plist>

  3. In a terminal window run

    launchctl load ~/Library/LaunchAgents/filesynchronizer.plist

  4. That's it. Any changes to any files in ~/SyncDirectory will be synchronized to ~/SyncDirectory on the remote machine. Local changes will override any remote changes.

This creates a launchd job that monitors SyncDirectory, and whenever anything changes there runs rsync to synchronize the directory to the remote machine.

ValueError: unconverted data remains: 02:05

You have to parse all of the input string, you cannot just ignore parts.

from datetime import date, datetime

for item in j:
    st = datetime.strptime(item['start'], '%A %d %B %H:%M')

    if st.date() == date.today():
        item['start'] = st.time()

Here, we compare the date to today's date by using more datetime objects instead of trying to use strings.

The alternative is to only pass in part of the item['start'] string (splitting out just the time), but there really is no point here, not when you could just parse everything in one step first.

Windows Explorer "Command Prompt Here"

As a very quick solution I can give you this. I tested this on Windows 8.1

1- Find File and Right Click on Command Prompt on File Explorer and then add command prompt to your Quick Access Toolbar:

Instruction 1

2- After adding it you can access the folder from here:

Instruction 2

That will open a command prompt in there for you.

How can I use "e" (Euler's number) and power operation in python 2.7

Power is ** and e^ is math.exp:

x.append(1 - math.exp(-0.5 * (value1*value2)**2))

onchange event on input type=range is not triggering in firefox while dragging

Apparently Chrome and Safari are wrong: onchange should only be triggered when the user releases the mouse. To get continuous updates, you should use the oninput event, which will capture live updates in Firefox, Safari and Chrome, both from the mouse and the keyboard.

However, oninput is not supported in IE10, so your best bet is to combine the two event handlers, like this:

<span id="valBox"></span>
<input type="range" min="5" max="10" step="1" 
   oninput="showVal(this.value)" onchange="showVal(this.value)">

Check out this Bugzilla thread for more information.

How to detect IE11?

This appears to be a better method. "indexOf" returns -1 if nothing is matched. It doesn't overwrite existing classes on the body, just adds them.

// add a class on the body ie IE 10/11
var uA = navigator.userAgent;
if(uA.indexOf('Trident') != -1 && uA.indexOf('rv:11') != -1){
    document.body.className = document.body.className+' ie11';
}
if(uA.indexOf('Trident') != -1 && uA.indexOf('MSIE 10.0') != -1){
    document.body.className = document.body.className+' ie10';
}

How to parse a string to an int in C++?

I like Dan's answer, esp because of the avoidance of exceptions. For embedded systems development and other low level system development, there may not be a proper Exception framework available.

Added a check for white-space after a valid string...these three lines

    while (isspace(*end)) {
        end++;
    }


Added a check for parsing errors too.

    if ((errno != 0) || (s == end)) {
        return INCONVERTIBLE;
    }


Here is the complete function..

#include <cstdlib>
#include <cerrno>
#include <climits>
#include <stdexcept>

enum STR2INT_ERROR { SUCCESS, OVERFLOW, UNDERFLOW, INCONVERTIBLE };

STR2INT_ERROR str2long (long &l, char const *s, int base = 0)
{
    char *end = (char *)s;
    errno = 0;

    l = strtol(s, &end, base);

    if ((errno == ERANGE) && (l == LONG_MAX)) {
        return OVERFLOW;
    }
    if ((errno == ERANGE) && (l == LONG_MIN)) {
        return UNDERFLOW;
    }
    if ((errno != 0) || (s == end)) {
        return INCONVERTIBLE;
    }    
    while (isspace((unsigned char)*end)) {
        end++;
    }

    if (*s == '\0' || *end != '\0') {
        return INCONVERTIBLE;
    }

    return SUCCESS;
}

How are SSL certificate server names resolved/Can I add alternative names using keytool?

How host name verification should be done is defined in RFC 6125, which is quite recent and generalises the practice to all protocols, and replaces RFC 2818, which was specific to HTTPS. (I'm not even sure Java 7 uses RFC 6125, which might be too recent for this.)

From RFC 2818 (Section 3.1):

If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead.

[...]

In some cases, the URI is specified as an IP address rather than a hostname. In this case, the iPAddress subjectAltName must be present in the certificate and must exactly match the IP in the URI.

Essentially, the specific problem you have comes from the fact that you're using IP addresses in your CN and not a host name. Some browsers might work because not all tools follow this specification strictly, in particular because "most specific" in RFC 2818 isn't clearly defined (see discussions in RFC 6215).

If you're using keytool, as of Java 7, keytool has an option to include a Subject Alternative Name (see the table in the documentation for -ext): you could use -ext san=dns:www.example.com or -ext san=ip:10.0.0.1.

EDIT:

You can request a SAN in OpenSSL by changing openssl.cnf (it will pick the copy in the current directory if you don't want to edit the global configuration, as far as I remember, or you can choose an explicit location using the OPENSSL_CONF environment variable).

Set the following options (find the appropriate sections within brackets first):

[req]
req_extensions = v3_req

[ v3_req ]
subjectAltName=IP:10.0.0.1
# or subjectAltName=DNS:www.example.com

There's also a nice trick to use an environment variable for this (rather in than fixing it in a configuration file) here: http://www.crsr.net/Notes/SSL.html

Using braces with dynamic variable names in PHP

I was in a position where I had 6 identical arrays and I needed to pick the right one depending on another variable and then assign values to it. In the case shown here $comp_cat was 'a' so I needed to pick my 'a' array ( I also of course had 'b' to 'f' arrays)

Note that the values for the position of the variable in the array go after the closing brace.

${'comp_cat_'.$comp_cat.'_arr'}[1][0] = "FRED BLOGGS";

${'comp_cat_'.$comp_cat.'_arr'}[1][1] = $file_tidy;

echo 'First array value is '.$comp_cat_a_arr[1][0].' and the second value is .$comp_cat_a_arr[1][1];

How to calculate a Mod b in Casio fx-991ES calculator

You can calculate A mod B (for positive numbers) using this:

Pol( -Rec( 1/r , 2πr × A/B ) , Y ) ( πr - Y ) B

Then press [CALC], and enter your values for A and B, and any value for Y.

/ indicates using the fraction key, and r means radians ( [SHIFT] [Ans] [2] )

How to set corner radius of imageView?

I created an UIView extension which allows to round specific corners :

import UIKit

enum RoundType {
    case top
    case none
    case bottom
    case both
}

extension UIView {

    func round(with type: RoundType, radius: CGFloat = 3.0) {
        var corners: UIRectCorner

        switch type {
        case .top:
            corners = [.topLeft, .topRight]
        case .none:
            corners = []
        case .bottom:
            corners = [.bottomLeft, .bottomRight]
        case .both:
            corners = [.allCorners]
        }

        DispatchQueue.main.async {
            let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
            let mask = CAShapeLayer()
            mask.path = path.cgPath
            self.layer.mask = mask
        }
    }

}

How to use addTarget method in swift 3

Yes, don't add "()" if there is no param

button.addTarget(self, action:#selector(handleRegister), for: .touchUpInside). 

and if you want to get the sender

button.addTarget(self, action:#selector(handleRegister(_:)), for: .touchUpInside). 

func handleRegister(sender: UIButton){
   //...
}

Edit:

button.addTarget(self, action:#selector(handleRegister(_:)), for: .touchUpInside)

no longer works, you need to replace _ in the selector with a variable name you used in the function header, in this case it would be sender, so the working code becomes:

button.addTarget(self, action:#selector(handleRegister(sender:)), for: .touchUpInside)

How can I install a local gem?

You can download gems from https://rubygems.org/gems/ or build you local gem via bundle and rack.

eg:

  • bundle gem yourGemName
  • rake install

Take care of installing dependencies before installing actual gems.

  • gem install --local /pathToFolder/xxx-2.6.1.gem

Note: If using fluentd td-agent and ruby on same machine. Please make sure to use td-agent's td-agent-gem command. td-agent has own Ruby.

Sleep for milliseconds

The way to sleep your program in C++ is the Sleep(int) method. The header file for it is #include "windows.h."

For example:

#include "stdafx.h"
#include "windows.h"
#include "iostream"
using namespace std;

int main()
{
    int x = 6000;
    Sleep(x);
    cout << "6 seconds have passed" << endl;
    return 0;
}

The time it sleeps is measured in milliseconds and has no limit.

Second = 1000 milliseconds
Minute = 60000 milliseconds
Hour = 3600000 milliseconds

SELECT list is not in GROUP BY clause and contains nonaggregated column

As @Brian Riley already said you should either remove 1 column in your select

select countrylanguage.language ,sum(country.population*countrylanguage.percentage/100)
from countrylanguage
join country on countrylanguage.countrycode = country.code
group by countrylanguage.language
order by sum(country.population*countrylanguage.percentage) desc ;

or add it to your grouping

select countrylanguage.language, country.code, sum(country.population*countrylanguage.percentage/100)
from countrylanguage
join country on countrylanguage.countrycode = country.code
group by countrylanguage.language, country.code
order by sum(country.population*countrylanguage.percentage) desc ;

close vs shutdown socket?

None of the existing answers tell people how shutdown and close works at the TCP protocol level, so it is worth to add this.

A standard TCP connection gets terminated by 4-way finalization:

  1. Once a participant has no more data to send, it sends a FIN packet to the other
  2. The other party returns an ACK for the FIN.
  3. When the other party also finished data transfer, it sends another FIN packet
  4. The initial participant returns an ACK and finalizes transfer.

However, there is another "emergent" way to close a TCP connection:

  1. A participant sends an RST packet and abandons the connection
  2. The other side receives an RST and then abandon the connection as well

In my test with Wireshark, with default socket options, shutdown sends a FIN packet to the other end but it is all it does. Until the other party send you the FIN packet you are still able to receive data. Once this happened, your Receive will get an 0 size result. So if you are the first one to shut down "send", you should close the socket once you finished receiving data.

On the other hand, if you call close whilst the connection is still active (the other side is still active and you may have unsent data in the system buffer as well), an RST packet will be sent to the other side. This is good for errors. For example, if you think the other party provided wrong data or it refused to provide data (DOS attack?), you can close the socket straight away.

My opinion of rules would be:

  1. Consider shutdown before close when possible
  2. If you finished receiving (0 size data received) before you decided to shutdown, close the connection after the last send (if any) finished.
  3. If you want to close the connection normally, shutdown the connection (with SHUT_WR, and if you don't care about receiving data after this point, with SHUT_RD as well), and wait until you receive a 0 size data, and then close the socket.
  4. In any case, if any other error occurred (timeout for example), simply close the socket.

Ideal implementations for SHUT_RD and SHUT_WR

The following haven't been tested, trust at your own risk. However, I believe this is a reasonable and practical way of doing things.

If the TCP stack receives a shutdown with SHUT_RD only, it shall mark this connection as no more data expected. Any pending and subsequent read requests (regardless whichever thread they are in) will then returned with zero sized result. However, the connection is still active and usable -- you can still receive OOB data, for example. Also, the OS will drop any data it receives for this connection. But that is all, no packages will be sent to the other side.

If the TCP stack receives a shutdown with SHUT_WR only, it shall mark this connection as no more data can be sent. All pending write requests will be finished, but subsequent write requests will fail. Furthermore, a FIN packet will be sent to another side to inform them we don't have more data to send.

How to set x axis values in matplotlib python?

The scaling on your example figure is a bit strange but you can force it by plotting the index of each x-value and then setting the ticks to the data points:

import matplotlib.pyplot as plt
x = [0.00001,0.001,0.01,0.1,0.5,1,5]
# create an index for each tick position
xi = list(range(len(x)))
y = [0.945,0.885,0.893,0.9,0.996,1.25,1.19]
plt.ylim(0.8,1.4)
# plot the index for the x-values
plt.plot(xi, y, marker='o', linestyle='--', color='r', label='Square') 
plt.xlabel('x')
plt.ylabel('y') 
plt.xticks(xi, x)
plt.title('compare')
plt.legend() 
plt.show()

Matching exact string with JavaScript

Here's what is (IMO) by far the best solution in one line, per modern javascript standards:

const str1 = 'abc';
const str2 = 'abc';
return (str1 === str2); // true


const str1 = 'abcd';
const str2 = 'abc';
return (str1 === str2); // false

const str1 = 'abc';
const str2 = 'abcd';
return (str1 === str2); // false

Emulate ggplot2 default color palette

This is the result from

library(scales)
show_col(hue_pal()(4))

Four color ggplot

show_col(hue_pal()(3))

Three color ggplot

jQuery form input select by id

If you have more than one element with the same ID, then you have invalid HTML.

But you can acheive the same result using classes instead. That's what they're designed for.

<input class='b' ... >

You can give it an ID as well if you need to, but it should be unique.

Once you've got the class in there, you can reference it with a dot instead of the hash, like so:

var value = $('#a .b').val();

or

var value = $('#a input.b').val();

which will limit it to 'b' class elements that are inputs within the form (which seems to be close to what you're asking for).

Detect Safari browser

I observed that only one word distinguishes Safari - "Version". So this regex will work perfect:

/.*Version.*Safari.*/.test(navigator.userAgent)

Cannot uninstall angular-cli

The following approach worked for me:

npm uninstall -g @angular/cli

and

npm cache verify

Find and replace in file and overwrite file doesn't work, it empties the file

You can use Vim in Ex mode:

ex -sc '%s/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g|x' index.html
  1. % select all lines

  2. x save and close

How to execute IN() SQL queries with Spring's JDBCTemplate effectively?

I do the "in clause" query with spring jdbc like this:

String sql = "SELECT bg.goodsid FROM beiker_goods bg WHERE bg.goodsid IN (:goodsid)";

List ids = Arrays.asList(new Integer[]{12496,12497,12498,12499});
Map<String, List> paramMap = Collections.singletonMap("goodsid", ids);
NamedParameterJdbcTemplate template = 
    new NamedParameterJdbcTemplate(getJdbcTemplate().getDataSource());

List<Long> list = template.queryForList(sql, paramMap, Long.class);

Forcing anti-aliasing using css: Is this a myth?

No, there's not really any way to control this as a web developer.

Small exceptions are that you can do some fake forcing of anti-aliasing by using Flash through sIFR, and some browsers won't anti-alias bitmap/pixel fonts (as they shouldn't, more info: Anti-Aliasing / Anti-Anti-Aliasing).

Also, as Daniel mentioned, it's ideal to be using em units for all fonts, see The Incredible Em & Elastic Layouts with CSS for more information about this.

Inline <style> tags vs. inline css properties

Whenever is possible is preferable to use class .myclass{} and identifier #myclass{}, so use a dedicated css file or tag <style></style> within an html. Inline style is good to change css option dynamically with javascript.

How to preSelect an html dropdown list with php?

I suppose that you are using an array to create your select form input. In that case, use an array:

<?php
    $selected = array( $_REQUEST['yesnofine'] => 'selected="selected"' );
    $fields = array(1 => 'Yes', 2 => 'No', 3 => 'Fine');
 ?>
  <select name=‘yesnofine'>
 <?php foreach ($fields as $k => $v): ?>
  <option value="<?php echo $k;?>" <?php @print($selected[$k]);?>><?php echo $v;?></options>
 <?php endforeach; ?>
 </select>

If not, you may just unroll the above loop, and still use an array.

 <option value="1" <?php @print($selected[$k]);?>>Yes</options>
 <option value="2" <?php @print($selected[$k]);?>>No</options>
 <option value="3" <?php @print($selected[$k]);?>>Fine</options>

Notes that I don't know:

  • how you are naming your input, so I made up a name for it.
  • which way you are handling your form input on server side, I used $_REQUEST,

You will have to adapt the code to match requirements of the framework you are using, if any.

Also, it is customary in many frameworks to use the alternative syntax in view dedicated scripts.

Dividing two integers to produce a float result

Cast the operands to floats:

float ans = (float)a / (float)b;

How to create a JQuery Clock / Timer

How about the best of both worlds? I combined the answer with the OP's format.

function pretty_time_string(num) {
    return ( num < 10 ? "0" : "" ) + num;
  }

var start = new Date;    

setInterval(function() {
  var total_seconds = (new Date - start) / 1000;   

  var hours = Math.floor(total_seconds / 3600);
  total_seconds = total_seconds % 3600;

  var minutes = Math.floor(total_seconds / 60);
  total_seconds = total_seconds % 60;

  var seconds = Math.floor(total_seconds);

  hours = pretty_time_string(hours);
  minutes = pretty_time_string(minutes);
  seconds = pretty_time_string(seconds);

  var currentTimeString = hours + ":" + minutes + ":" + seconds;

  $('.timer').text(currentTimeString);
}, 1000);

Error: getaddrinfo ENOTFOUND in nodejs for get call

for me it was because in /etc/hosts file the hostname is not added

-XX:MaxPermSize with or without -XX:PermSize

By playing with parameters as -XX:PermSize and -Xms you can tune the performance of - for example - the startup of your application. I haven't looked at it recently, but a few years back the default value of -Xms was something like 32MB (I think), if your application required a lot more than that it would trigger a number of cycles of fill memory - full garbage collect - increase memory etc until it had loaded everything it needed. This cycle can be detrimental for startup performance, so immediately assigning the number required could improve startup.

A similar cycle is applied to the permanent generation. So tuning these parameters can improve startup (amongst others).

WARNING The JVM has a lot of optimization and intelligence when it comes to allocating memory, dividing eden space and older generations etc, so don't do things like making -Xms equal to -Xmx or -XX:PermSize equal to -XX:MaxPermSize as it will remove some of the optimizations the JVM can apply to its allocation strategies and therefor reduce your application performance instead of improving it.

As always: make non-trivial measurements to prove your changes actually improve performance overall (for example improving startup time could be disastrous for performance during use of the application)

Swift - how to make custom header for UITableView?

If you are willing to use custom table header as table header, try the followings....

Updated for swift 3.0

Step 1

Create UITableViewHeaderFooterView for custom header..

import UIKit

class MapTableHeaderView: UITableViewHeaderFooterView {

    @IBOutlet weak var testView: UIView!

}

Step 2

Add custom header to UITableView

    override func viewDidLoad() {
            super.viewDidLoad()

            tableView.delegate = self
            tableView.dataSource = self

            //register the header view

            let nibName = UINib(nibName: "CustomHeaderView", bundle: nil)
            self.tableView.register(nibName, forHeaderFooterViewReuseIdentifier: "CustomHeaderView")


    }

    extension BranchViewController : UITableViewDelegate{

    }

    extension BranchViewController : UITableViewDataSource{

        func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
            return 200
        }

        func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
            let headerView = self.tableView.dequeueReusableHeaderFooterView(withIdentifier: "CustomHeaderView" ) as! MapTableHeaderView

            return headerView
        }

        func tableView(_ tableView: UITableView, numberOfRowsInSection section: 

    Int) -> Int {
            // retuen no of rows in sections
        }

        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
            // retuen your custom cells    
        }

        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        }

        func numberOfSections(in tableView: UITableView) -> Int {
            // retuen no of sections
        }

        func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
            // retuen height of row
        }


    }

Bash script prints "Command Not Found" on empty lines

for executing that you must provide full path of that for example

/home/Manuel/mywrittenscript

How to start MySQL with --skip-grant-tables?

I'm in windows 10, using WAMP64 server. Searched for my.cnf and my.ini. Found my.ini in C:\wamp64\bin\mariadb\mariadb10.2.14.

Following the instructions from the colleagues:

  1. Opened the quick start menu from Wampserver, selected 'Stop All Services'
  2. Opened my.ini in a text editor, searched for [mysqld]
  3. Added 'skip-grant-tables' at the end of the [mysqld] section (but within it)
  4. Save the file, leave the editor open
  5. In the Wampserver menu, select "Restart Services'. There will be a warning about the skip-grant-tables option
  6. In the Wampserver menu select MySQL to open the prompt
  7. It asked for a password, just press enter
  8. Paste the command ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'newpassword';
  9. It must report that the operation was successful (no tables affected)
  10. In the my.ini file, erase the 'skip-grant-tables' line, save the file
  11. In the WampServer menu, select once more Restart Service

Now you can enter with the new password. Thanks to all answers here.

How to check if the docker engine and a docker container are running?

If you are looking for a specific container, you can run:

if [ "$( docker container inspect -f '{{.State.Running}}' $container_name )" == "true" ]; then ...

To avoid issues with a container that is in a crash loop and constantly restarting from showing that it's up, the above can be improved by checking the Status field:

if [ "$( docker container inspect -f '{{.State.Status}}' $container_name )" == "running" ]; then ...

If you want to know if dockerd is running itself on the local machine and you have systemd installed, you can run:

systemctl show --property ActiveState docker

You can also connect to docker with docker info or docker version and they will error out if the daemon is unavailable.

How do I implement __getattribute__ without an infinite recursion error?

Python language reference:

In order to avoid infinite recursion in this method, its implementation should always call the base class method with the same name to access any attributes it needs, for example, object.__getattribute__(self, name).

Meaning:

def __getattribute__(self,name):
    ...
        return self.__dict__[name]

You're calling for an attribute called __dict__. Because it's an attribute, __getattribute__ gets called in search for __dict__ which calls __getattribute__ which calls ... yada yada yada

return  object.__getattribute__(self, name)

Using the base classes __getattribute__ helps finding the real attribute.

jQuery Mobile: document ready vs. page events

The simple difference between document ready and page event in jQuery-mobile is that:

  1. The document ready event is used for the whole HTML page,

    $(document).ready(function(e) {
        // Your code
    });
    
  2. When there is a page event, use for handling particular page event:

    <div data-role="page" id="second">
        <div data-role="header">
            <h3>
                Page header
            </h3>
        </div>
        <div data-role="content">
            Page content
        </div> <!--content-->
        <div data-role="footer">
            Page footer
        </div> <!--footer-->
    </div><!--page-->
    

You can also use document for handling the pageinit event:

$(document).on('pageinit', "#mypage", function() {

});

How to validate phone numbers using regex

I was struggling with the same issue, trying to make my application future proof, but these guys got me going in the right direction. I'm not actually checking the number itself to see if it works or not, I'm just trying to make sure that a series of numbers was entered that may or may not have an extension.

Worst case scenario if the user had to pull an unformatted number from the XML file, they would still just type the numbers into the phone's numberpad 012345678x5, no real reason to keep it pretty. That kind of RegEx would come out something like this for me:

\d+ ?\w{0,9} ?\d+
  • 01234467 extension 123456
  • 01234567x123456
  • 01234567890

How to update column value in laravel

I tried to update a field with

$table->update(['field' => 'val']);

But it wasn't working, i had to modify my table Model to authorize this field to be edited : add 'field' in the array "protected $fillable"

Hope it will help someone :)

PLS-00201 - identifier must be declared

you should give permission on your db

grant execute on (packageName or tableName) to user;

How to get HttpClient returning status code and response body?

BasicResponseHandler throws if the status is not 2xx. See its javadoc.

Here is how I would do it:

HttpResponse response = client.execute( get );
int code = response.getStatusLine().getStatusCode();
InputStream body = response.getEntity().getContent();
// Read the body stream

Or you can also write a ResponseHandler starting from BasicResponseHandler source that don't throw when the status is not 2xx.

Angular - Set headers for every request

To answer, you question you could provide a service that wraps the original Http object from Angular. Something like described below.

import {Injectable} from '@angular/core';
import {Http, Headers} from '@angular/http';

@Injectable()
export class HttpClient {

  constructor(private http: Http) {}

  createAuthorizationHeader(headers: Headers) {
    headers.append('Authorization', 'Basic ' +
      btoa('username:password')); 
  }

  get(url) {
    let headers = new Headers();
    this.createAuthorizationHeader(headers);
    return this.http.get(url, {
      headers: headers
    });
  }

  post(url, data) {
    let headers = new Headers();
    this.createAuthorizationHeader(headers);
    return this.http.post(url, data, {
      headers: headers
    });
  }
}

And instead of injecting the Http object you could inject this one (HttpClient).

import { HttpClient } from './http-client';

export class MyComponent {
  // Notice we inject "our" HttpClient here, naming it Http so it's easier
  constructor(http: HttpClient) {
    this.http = httpClient;
  }

  handleSomething() {
    this.http.post(url, data).subscribe(result => {
        // console.log( result );
    });
  }
}

I also think that something could be done using multi providers for the Http class by providing your own class extending the Http one... See this link: http://blog.thoughtram.io/angular2/2015/11/23/multi-providers-in-angular-2.html.

could not extract ResultSet in hibernate

I had similar issue. Try use the HQL editor. It will display you the SQL (as you have a SQL grammar exception). Copy your SQL and execute it separately. In my case the problem was in schema definition. I defined the schema, but I should leave it empty. This raised the same exception as you got. And the error description reflected the actual state, as the schema name was included in SQL statement.

How to sort with a lambda?

Got it.

sort(mMyClassVector.begin(), mMyClassVector.end(), 
    [](const MyClass & a, const MyClass & b) -> bool
{ 
    return a.mProperty > b.mProperty; 
});

I assumed it'd figure out that the > operator returned a bool (per documentation). But apparently it is not so.

jQuery duplicate DIV into another DIV

_x000D_
_x000D_
$(document).ready(function(){  _x000D_
    $("#btn_clone").click(function(){  _x000D_
        $("#a_clone").clone().appendTo("#b_clone");  _x000D_
    });  _x000D_
});  
_x000D_
.container{_x000D_
    padding: 15px;_x000D_
    border: 12px solid #23384E;_x000D_
    background: #28BAA2;_x000D_
    margin-top: 10px;_x000D_
}
_x000D_
<!DOCTYPE html>  _x000D_
<html>  _x000D_
<head>  _x000D_
<title>jQuery Clone Method</title> _x000D_
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> _x000D_
_x000D_
_x000D_
</head>  _x000D_
<body> _x000D_
<div class="container">_x000D_
<p id="a_clone"><b> This is simple example of clone method.</b></p>  _x000D_
<p id="b_clone"><b>Note:</b>Click The Below button Click Me</p>  _x000D_
<button id="btn_clone">Click Me!</button>  _x000D_
</div> _x000D_
</body>  _x000D_
</html>  
_x000D_
_x000D_
_x000D_

For more detail and demo

Java int to String - Integer.toString(i) vs new Integer(i).toString()

new Integer(i).toString() first creates a (redundant) wrapper object around i (which itself may be a wrapper object Integer).

Integer.toString(i) is preferred because it doesn't create any unnecessary objects.

Oracle SQL escape character (for a '&')

Set the define character to something other than &

SET DEFINE ~
create table blah (x varchar(20));
insert into blah (x) values ('blah&amp');
select * from blah;

X                    
-------------------- 
blah&amp 

How to add files/folders to .gitignore in IntelliJ IDEA?

right click on the project create a file with name .ignore, then you can see that file opened.

at the right top of the file you can see install plugins or else you can install using plugins(plugin name - .ignore).

Now when ever you give a right click on the file or project you can see the option call add to .ignore

Ruby: How to convert a string to boolean

if value.to_s == 'true'
  true
elsif value.to_s == 'false'
  false
end

How to check the value given is a positive or negative integer?

I thought here you wanted to do the action if it is positive.

Then would suggest:

if (Math.sign(number_to_test) === 1) {
     function_to_run_when_positive();
}

How to minify php page html output?

Create a PHP file outside your document root. If your document root is

/var/www/html/

create the a file named minify.php one level above it

/var/www/minify.php

Copy paste the following PHP code into it

<?php
function minify_output($buffer){
    $search = array('/\>[^\S ]+/s','/[^\S ]+\</s','/(\s)+/s');
    $replace = array('>','<','\\1');
    if (preg_match("/\<html/i",$buffer) == 1 && preg_match("/\<\/html\>/i",$buffer) == 1) {
        $buffer = preg_replace($search, $replace, $buffer);
    }
    return $buffer;
}
ob_start("minify_output");?>

Save the minify.php file and open the php.ini file. If it is a dedicated server/VPS search for the following option, on shared hosting with custom php.ini add it.

auto_prepend_file = /var/www/minify.php

Reference: http://websistent.com/how-to-use-php-to-minify-html-output/

Make iframe automatically adjust height according to the contents without using scrollbar?

Add this to your <head> section:

<script>
  function resizeIframe(obj) {
    obj.style.height = obj.contentWindow.document.documentElement.scrollHeight + 'px';
  }
</script>

And change your iframe to this:

<iframe src="..." frameborder="0" scrolling="no" onload="resizeIframe(this)" />

As found on sitepoint discussion.

Android Layout Weight

In the linearLayout set the WeightSum=2;

And distribute the weight to its childs as you want them to display.. I have given weight ="1" to the child .So both will distribute half of the total.

 <LinearLayout
    android:id="@+id/linear1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:weightSum="2"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/ring_oss"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:src="@drawable/ring_oss" />

    <ImageView
        android:id="@+id/maila_oss"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:src="@drawable/maila_oss" />
</LinearLayout>

How to know what the 'errno' means?

Instead of running perror on any error code you get, you can retrieve a complete listing of errno values on your system with the following one-liner:

cpp -dM /usr/include/errno.h | grep 'define E' | sort -n -k 3

Altering column size in SQL Server

Running ALTER COLUMN without mentioning attribute NOT NULL will result in the column being changed to nullable, if it is already not. Therefore, you need to first check if the column is nullable and if not, specify attribute NOT NULL. Alternatively, you can use the following statement which checks the nullability of column beforehand and runs the command with the right attribute.

IF COLUMNPROPERTY(OBJECT_ID('Employee', 'U'), 'Salary', 'AllowsNull')=0
    ALTER TABLE [Employee]
        ALTER COLUMN [Salary] NUMERIC(22,5) NOT NULL
ELSE        
    ALTER TABLE [Employee]
        ALTER COLUMN [Salary] NUMERIC(22,5) NULL

Print to standard printer from Python?

To print to any printer on the network you can send a PJL/PCL print job directly to a network printer on port 9100.

Please have a look at the below link that should give a good start:

http://frank.zinepal.com/printing-directly-to-a-network-printer

Also, If there is a way to call Windows cmd you can use FTP put to print your page on 9100. Below link should give you details, I have used this method for HP printers but I believe it will work for other printers.

http://h20000.www2.hp.com/bizsupport/TechSupport/Document.jsp?objectID=bpj06165

How to Create a real one-to-one relationship in SQL Server

The easiest way to achieve this is to create only 1 table with both Table A and B fields NOT NULL. This way it is impossible to have one without the other.

How to set bootstrap navbar active class with Angular JS?

Use an object as a switch variable.
You can do this inline quite simply with:

<ul class="nav navbar-nav">
   <li ng-class="{'active':switch.linkOne}" ng-click="switch = {linkOne: true}"><a href="/">Link One</a></li>
   <li ng-class="{'active':switch.linkTwo}" ng-click="switch = {link-two: true}"><a href="/link-two">Link Two</a></li>
</ul>

Each time you click on a link the switch object is replaced by a new object where only the correct switch object property is true. The undefined properties will evaluate as false and so the elements which depend on them will not have the active class assigned.

Certificate has either expired or has been revoked

Xcode 11.1 requires generating ?ertificate from Xcode directly

So you will have smth like this on https://developer.apple.com after

enter image description here

Resize on div element

I've created jquery plugin jquery.resize it use resizeObserver if supported or solution based on marcj/css-element-queries scroll event, no setTimeout/setInterval.

You use just

 jQuery('div').on('resize', function() { /* What ever */ });

or as resizer plugin

jQuery('div').resizer(function() { /* What ever */ });

I've created this for jQuery Terminal and extracted into separated repo and npm package, but in a mean time I switched to hidden iframe because I had problems with resize if element was inside iframe. I may update the plugin accordingly. You can look at iframe based resizer plugin in jQuery Terminal source code.

EDIT: new version use iframe and resize on it's window object because the previous solutions was not working when page was inside iframe.

EDIT2: Because the fallback use iframe you can't use it with form controls or images, you need to add it to the wrapper element.

EDIT3:: there is better solution using resizeObserver polyfill that use mutation observer (if resizeObserver is not supported) and work even in IE. It also have TypeScript typings.

jQuery checkbox event handling

There are several useful answers, but none seem to cover all the latest options. To that end all my examples also cater for the presence of matching label elements and also allow you to dynamically add checkboxes and see the results in a side-panel (by redirecting console.log).

  • Listening for click events on checkboxes is not a good idea as that will not allow for keyboard toggling or for changes made where a matching label element was clicked. Always listen for the change event.

  • Use the jQuery :checkbox pseudo-selector, rather than input[type=checkbox]. :checkbox is shorter and more readable.

  • Use is() with the jQuery :checked pseudo-selector to test for whether a checkbox is checked. This is guaranteed to work across all browsers.

Basic event handler attached to existing elements:

$('#myform :checkbox').change(function () {
    if ($(this).is(':checked')) {
        console.log($(this).val() + ' is now checked');
    } else {
        console.log($(this).val() + ' is now unchecked');
    }
});

JSFiddle: http://jsfiddle.net/TrueBlueAussie/u8bcggfL/2/

Notes:

  • Uses the :checkbox selector, which is preferable to using input[type=checkbox]
  • This connects only to matching elements that exist at the time the event was registered.

Delegated event handler attached to ancestor element:

Delegated event handlers are designed for situations where the elements may not yet exist (dynamically loaded or created) and is very useful. They delegate responsibility to an ancestor element (hence the term).

$('#myform').on('change', ':checkbox', function () {
    if ($(this).is(':checked')) {
        console.log($(this).val() + ' is now checked');
    } else {
        console.log($(this).val() + ' is now unchecked');
    }
});

JSFiddle: http://jsfiddle.net/TrueBlueAussie/u8bcggfL/4/

Notes:

  • This works by listening for events (in this case change) to bubble up to a non-changing ancestor element (in this case #myform).
  • It then applies the jQuery selector (':checkbox' in this case) to only the elements in the bubble chain.
  • It then applies the event handler function to only those matching elements that caused the event.
  • Use document as the default to connect the delegated event handler, if nothing else is closer/convenient.
  • Do not use body to attach delegated events as it has a bug (to do with styling) that can stop it getting mouse events.

The upshot of delegated handlers is that the matching elements only need to exist at event time and not when the event handler was registered. This allows for dynamically added content to generate the events.

Q: Is it slower?

A: So long as the events are at user-interaction speeds, you do not need to worry about the negligible difference in speed between a delegated event handler and a directly connected handler. The benefits of delegation far outweigh any minor downside. Delegated event handlers are actually faster to register as they typically connect to a single matching element.


Why doesn't prop('checked', true) fire the change event?

This is actually by design. If it did fire the event you would easily get into a situation of endless updates. Instead, after changing the checked property, send a change event to the same element using trigger (not triggerHandler):

e.g. without trigger no event occurs

$cb.prop('checked', !$cb.prop('checked'));

JSFiddle: http://jsfiddle.net/TrueBlueAussie/u8bcggfL/5/

e.g. with trigger the normal change event is caught

$cb.prop('checked', !$cb.prop('checked')).trigger('change');

JSFiddle: http://jsfiddle.net/TrueBlueAussie/u8bcggfL/6/

Notes:

  • Do not use triggerHandler as was suggested by one user, as it will not bubble events to a delegated event handler.

JSFiddle: http://jsfiddle.net/TrueBlueAussie/u8bcggfL/8/

although it will work for an event handler directly connected to the element:

JSFiddle: http://jsfiddle.net/TrueBlueAussie/u8bcggfL/9/

Events triggered with .triggerHandler() do not bubble up the DOM hierarchy; if they are not handled by the target element directly, they do nothing.

Reference: http://api.jquery.com/triggerhandler/

If anyone has additional features they feel are not covered by this, please do suggest additions.

Bootstrap 3 Horizontal Divider (not in a dropdown)

Currently it only works for the .dropdown-menu:

.dropdown-menu .divider {
  height: 1px;
  margin: 9px 0;
  overflow: hidden;
  background-color: #e5e5e5;
}

If you want it for other use, in your own css, following the bootstrap.css create another one:

.divider {
  height: 1px;
  width:100%;
  display:block; /* for use on default inline elements like span */
  margin: 9px 0;
  overflow: hidden;
  background-color: #e5e5e5;
}

How do I POST JSON data with cURL?

Using CURL Windows, try this:

curl -X POST -H "Content-Type:application/json" -d "{\"firstName\": \"blablabla\",\"lastName\": \"dummy\",\"id\": \"123456\"}" http-host/_ah/api/employeeendpoint/v1/employee

Forwarding port 80 to 8080 using NGINX

This is how you can achieve this.

upstream {
    nodeapp 127.0.0.1:8080;
}

server {
    listen 80;

    # The host name to respond to
    server_name cdn.domain.com;

    location /(.*) {
        proxy_pass http://nodeapp/$1$is_args$args;
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header Host $host;
        proxy_set_header X-Real-Port $server_port;
        proxy_set_header X-Real-Scheme $scheme;
    }
}

You can also use this configuration to load balance amongst multiple Node processes like so:

upstream {
    nodeapp 127.0.0.1:8081;
    nodeapp 127.0.0.1:8082;
    nodeapp 127.0.0.1:8083;
}

Where you are running your node server on ports 8081, 8082 and 8083 in separate processes. Nginx will easily load balance your traffic amongst these server processes.

custom facebook share button

Given that we are in a php code context and the variable $url contains the link the user wants to share, you can try this to use a custom image :

<a class="facebook-share-button" href="https://www.facebook.com/sharer/sharer.php?u=<?php echo urlencode($url); ?>" target="_blank"><img src="/img/facebook-share-button.png" /></a>

or this for just plain text :

<a class="facebook-share-button" href="https://www.facebook.com/sharer/sharer.php?u=<?php echo urlencode($url); ?>" target="_blank">share</a>

You can also style the link purely with css.

The html code :

<a class="facebook-share-button" href="https://www.facebook.com/sharer/sharer.php?u=<?php echo urlencode($url); ?>" target="_blank"></a>

The css code :

.facebook-share-button {
    background-image: url("/img/facebook-share-button.png");
    display: inline-block;
    height: 32px;
    width: 32px;
}

.facebook-share-button:active,
.facebook-share-button:focus,
.facebook-share-button:hover {
    background-image: url("/img/facebook-share-button-hover.png");
}

How can I get the current network interface throughput statistics on Linux/UNIX?

I wrote this dumb script a long time ago, it depends on nothing but Perl and Linux≥2.6:

#!/usr/bin/perl

use strict;
use warnings;

use POSIX qw(strftime);
use Time::HiRes qw(gettimeofday usleep);

my $dev = @ARGV ? shift : 'eth0';
my $dir = "/sys/class/net/$dev/statistics";
my %stats = do {
    opendir +(my $dh), $dir;
    local @_ = readdir $dh;
    closedir $dh;
    map +($_, []), grep !/^\.\.?$/, @_;
};

if (-t STDOUT) {
    while (1) {
        print "\033[H\033[J", run();
        my ($time, $us) = gettimeofday();
        my ($sec, $min, $hour) = localtime $time;
        {
            local $| = 1;
            printf '%-31.31s: %02d:%02d:%02d.%06d%8s%8s%8s%8s',
            $dev, $hour, $min, $sec, $us, qw(1s 5s 15s 60s)
        }
        usleep($us ? 1000000 - $us : 1000000);
    }
}
else {print run()}

sub run {
    map {
        chomp (my ($stat) = slurp("$dir/$_"));
        my $line = sprintf '%-31.31s:%16.16s', $_, $stat;
        $line .= sprintf '%8.8s', int (($stat - $stats{$_}->[0]) / 1)
            if @{$stats{$_}} > 0;
        $line .= sprintf '%8.8s', int (($stat - $stats{$_}->[4]) / 5)
            if @{$stats{$_}} > 4;
        $line .= sprintf '%8.8s', int (($stat - $stats{$_}->[14]) / 15)
            if @{$stats{$_}} > 14;
        $line .= sprintf '%8.8s', int (($stat - $stats{$_}->[59]) / 60)
            if @{$stats{$_}} > 59;
        unshift @{$stats{$_}}, $stat;
        pop @{$stats{$_}} if @{$stats{$_}} > 60;
        "$line\n";
    } sort keys %stats;
}

sub slurp {
    local @ARGV = @_;
    local @_ = <>;
    @_;
}

It just reads from /sys/class/net/$dev/statistics every second, and prints out the current numbers and the average rate of change:

$ ./net_stats.pl eth0
rx_bytes                       :  74457040115259 4369093 4797875 4206554 364088
rx_packets                     :     91215713193   23120   23502   23234  17616
...
tx_bytes                       :  90798990376725 8117924 7047762 7472650 319330
tx_packets                     :     93139479736   23401   22953   23216  23171
...
eth0                           : 15:22:09.002216      1s      5s     15s     60s

                                ^ current reading  ^-------- averages ---------^

ASP.NET MVC controller actions that return JSON or partial html

For folks who have upgraded to MVC 3 here is a neat way Using MVC3 and Json

An implementation of the fast Fourier transform (FFT) in C#

Math.NET's Iridium library provides a fast, regularly updated collection of math-related functions, including the FFT. It's licensed under the LGPL so you are free to use it in commercial products.

Running interactive commands in Paramiko

I'm not familiar with paramiko, but this may work:

ssh_stdin.write('input value')
ssh_stdin.flush()

For information on stdin:

http://docs.python.org/library/sys.html?highlight=stdin#sys.stdin

Which version of MVC am I using?

Select the System.Web.Mvc assembly in the "References" folder in the solution explorer. Bring up the properties window (F4) and check the Version

Reference Properties

How can I import Swift code to Objective-C?

#import <TargetName-Swift.h>

you will see when you enter from keyboard #import < and after automaticly Xcode will advice to you.

What is the difference between readonly="true" & readonly="readonly"?

readonly="true" is invalid HTML5, readonly="readonly" is valid.

HTML5 spec:

http://www.w3.org/TR/html5/forms.html#attr-input-readonly :

The readonly attribute is a boolean attribute

http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes :

The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.

If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.

Conclusion:

The following are valid, equivalent and true:

<input type="text" readonly />
<input type="text" readonly="" />
<input type="text" readonly="readonly" />
<input type="text" readonly="ReAdOnLy" />

The following are invalid:

<input type="text" readonly="0" />
<input type="text" readonly="1" />
<input type="text" readonly="false" />
<input type="text" readonly="true" />

The absence of the attribute is the only valid syntax for false:

<input type="text"/>

Recommendation

If you care about writing valid XHTML, use readonly="readonly", since <input readonly> is invalid and other alternatives are less readable. Else, just use <input readonly> as it is shorter.

Best Regular Expression for Email Validation in C#

This C# function uses a regular expression to evaluate whether the passed email address is syntactically valid or not.

public static bool isValidEmail(string inputEmail)
{
   string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
         @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" + 
         @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
   Regex re = new Regex(strRegex);
   if (re.IsMatch(inputEmail))
    return (true);
   else
    return (false);
}

Get AVG ignoring Null or Zero values

You already attempt to filter out NULL values with NOT NULL. I have changed this to IS NOT NULL in the WHERE clause so it will execute. We can refactor this by removing the ISNULL function in the AVG method. Also, I doubt you'll actually need bigint so we can remove the cast.

SELECT distinct
     AVG(a.SecurityW) as Average1
     ,AVG(a.TransferW) as Average2
     ,AVG(a.StaffW) as Average3
FROM Table1 a,  Table2 b
WHERE a.SecurityW <> 0 AND a.SecurityW IS NOT NULL
AND a.TransferW<> 0 AND a.TransferWIS IS NOT NULL
AND a.StaffW<> 0 AND a.StaffWIS IS NOT NULL
AND MONTH(a.ActualTime) = 4
AND YEAR(a.ActualTime) = 2013

Check if checkbox is checked with jQuery

jQuery code to check whether the checkbox is checked or not:

if($('input[name="checkBoxName"]').is(':checked'))
{
  // checked
}else
{
 // unchecked
}

Alternatively:

if($('input[name="checkBoxName"]:checked'))
{
    // checked
}else{
  // unchecked
}

How to hide a navigation bar from first ViewController in Swift?

I use a variant of the above, and isolate sections of my app to be embedded in differing NavControllers. This way, i don't have to reset visibility. Very useful in startup sequences, for example.

jQuery DataTables: control table width

The issue is caused because dataTable must calculate its width - but when used inside a tab, it's not visible, hence can't calculate the widths. The solution is to call 'fnAdjustColumnSizing' when the tab shows.

Preamble

This example shows how DataTables with scrolling can be used together with jQuery UI tabs (or indeed any other method whereby the table is in a hidden (display:none) element when it is initialised). The reason this requires special consideration, is that when DataTables is initialised and it is in a hidden element, the browser doesn't have any measurements with which to give DataTables, and this will require in the misalignment of columns when scrolling is enabled.

The method to get around this is to call the fnAdjustColumnSizing API function. This function will calculate the column widths that are needed based on the current data and then redraw the table - which is exactly what is needed when the table becomes visible for the first time. For this we use the 'show' method provided by jQuery UI tables. We check to see if the DataTable has been created or not (note the extra selector for 'div.dataTables_scrollBody', this is added when the DataTable is initialised). If the table has been initialised, we re-size it. An optimisation could be added to re-size only of the first showing of the table.

Initialisation code

$(document).ready(function() {
    $("#tabs").tabs( {
        "show": function(event, ui) {
            var oTable = $('div.dataTables_scrollBody>table.display', ui.panel).dataTable();
            if ( oTable.length > 0 ) {
                oTable.fnAdjustColumnSizing();
            }
        }
    } );

    $('table.display').dataTable( {
        "sScrollY": "200px",
        "bScrollCollapse": true,
        "bPaginate": false,
        "bJQueryUI": true,
        "aoColumnDefs": [
            { "sWidth": "10%", "aTargets": [ -1 ] }
        ]
    } );
} );

See this for more info.

Chrome, Javascript, window.open in new tab

You can use this code to open in new tab..

function openWindow( url )
{
  window.open(url, '_blank');
  window.focus();
}

I got it from stackoverflow..

Algorithm to generate all possible permutations of a list?

the simplest way I can think to explain this is by using some pseudo code

so

list of 1, 2 ,3
for each item in list
    templist.Add(item)
    for each item2 in list
        if item2 is Not item
            templist.add(item)
               for each item3 in list
                   if item2 is Not item
                      templist.add(item)

                   end if
               Next
            end if

    Next
    permanentListofPermutaitons,add(templist)
    tempList.Clear()
Next

Now obviously this is not the most flexible way to do this, and doing it recursively would be a lot more functional by my tired sunday night brain doesn't want to think about that at this moment. If no ones put up a recursive version by the morning I'll do one.

Collision resolution in Java HashMap

Your case is not talking about collision resolution, it is simply replacement of older value with a new value for the same key because Java's HashMap can't contain duplicates (i.e., multiple values) for the same key.

In your example, the value 17 will be simply replaced with 20 for the same key 10 inside the HashMap.

If you are trying to put a different/new value for the same key, it is not the concept of collision resolution, rather it is simply replacing the old value with a new value for the same key. It is how HashMap has been designed and you can have a look at the below API (emphasis is mine) taken from here.

public V put(K key, V value)

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


On the other hand, collision resolution techniques comes into play only when multiple keys end up with the same hashcode (i.e., they fall in the same bucket location) where an entry is already stored. HashMap handles the collision resolution by using the concept of chaining i.e., it stores the values in a linked list (or a balanced tree since Java8, depends on the number of entries).

How to install pip for Python 3 on Mac OS X?

On Mac OS X Mojave python stands for python of version 2.7 and python3 for python of version 3. The same is pip and pip3. So, to upgrade pip for python 3 do this:

~$ sudo pip3 install --upgrade pip

Does .NET provide an easy way convert bytes to KB, MB, GB, etc.?

I know this is old thread already. but maybe someone will look for solution. And here's what I use and the easiest way

public static string FormatFileSize(long bytes)
{
    var unit = 1024;
    if (bytes < unit) { return $"{bytes} B"; }

    var exp = (int)(Math.Log(bytes) / Math.Log(unit));
    return $"{bytes / Math.Pow(unit, exp):F2} {("KMGTPE")[exp - 1]}B";
}

Get folder size (for example usage)

public static long GetFolderSize(string path, string ext, bool AllDir)
{
    var option = AllDir ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
    return new DirectoryInfo(path).EnumerateFiles("*" + ext, option).Sum(file => file.Length);
}

EXAMPLE USAGE:

public static void TEST()
{
    string folder = @"C:\Users\User\Videos";

    var bytes = GetFolderSize(folder, "mp4", true); //or GetFolderSize(folder, "mp4", false) to get all single folder only
    var totalFileSize = FormatFileSize(bytes);
    Console.WriteLine(totalFileSize);
}

php convert datetime to UTC

General purpose normalisation function to format any timestamp from any timezone to other. Very useful for storing datetimestamps of users from different timezones in a relational database. For database comparisons store timestamp as UTC and use with gmdate('Y-m-d H:i:s')

/**
 * Convert Datetime from any given olsonzone to other.
 * @return datetime in user specified format
 */

function datetimeconv($datetime, $from, $to)
{
    try {
        if ($from['localeFormat'] != 'Y-m-d H:i:s') {
            $datetime = DateTime::createFromFormat($from['localeFormat'], $datetime)->format('Y-m-d H:i:s');
        }
        $datetime = new DateTime($datetime, new DateTimeZone($from['olsonZone']));
        $datetime->setTimeZone(new DateTimeZone($to['olsonZone']));
        return $datetime->format($to['localeFormat']);
    } catch (\Exception $e) {
        return null;
    }
}

Usage:

$from = ['localeFormat' => "d/m/Y H:i A", 'olsonZone' => 'Asia/Calcutta'];

$to = ['localeFormat' => "Y-m-d H:i:s", 'olsonZone' => 'UTC'];

datetimeconv("14/05/1986 10:45 PM", $from, $to); // returns "1986-05-14 17:15:00"

Adding n hours to a date in Java?

Date argDate = new Date(); //set your date.
String argTime = "09:00"; //9 AM - 24 hour format :- Set your time.
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm");
String dateTime = sdf.format(argDate) + " " + argTime;
Date requiredDate = dateFormat.parse(dateTime);

ReferenceError: Invalid left-hand side in assignment

Common reasons for the error:

  • use of assignment (=) instead of equality (==/===)
  • assigning to result of function foo() = 42 instead of passing arguments (foo(42))
  • simply missing member names (i.e. assuming some default selection) : getFoo() = 42 instead of getFoo().theAnswer = 42 or array indexing getArray() = 42 instead of getArray()[0]= 42

In this particular case you want to use == (or better === - What exactly is Type Coercion in Javascript?) to check for equality (like if(one === "rock" && two === "rock"), but it the actual reason you are getting the error is trickier.

The reason for the error is Operator precedence. In particular we are looking for && (precedence 6) and = (precedence 3).

Let's put braces in the expression according to priority - && is higher than = so it is executed first similar how one would do 3+4*5+6 as 3+(4*5)+6:

 if(one= ("rock" && two) = "rock"){...

Now we have expression similar to multiple assignments like a = b = 42 which due to right-to-left associativity executed as a = (b = 42). So adding more braces:

 if(one= (  ("rock" && two) = "rock" )  ){...

Finally we arrived to actual problem: ("rock" && two) can't be evaluated to l-value that can be assigned to (in this particular case it will be value of two as truthy).

Note that if you'd use braces to match perceived priority surrounding each "equality" with braces you get no errors. Obviously that also producing different result than you'd expect - changes value of both variables and than do && on two strings "rock" && "rock" resulting in "rock" (which in turn is truthy) all the time due to behavior of logial &&:

if((one = "rock") && (two = "rock"))
{
   // always executed, both one and two are set to "rock"
   ...
}

For even more details on the error and other cases when it can happen - see specification:

Assignment

LeftHandSideExpression = AssignmentExpression
...
Throw a SyntaxError exception if the following conditions are all true:
...
IsStrictReference(lref) is true

Left-Hand-Side Expressions

and The Reference Specification Type explaining IsStrictReference:

... function calls are permitted to return references. This possibility is admitted purely for the sake of host objects. No built-in ECMAScript function defined by this specification returns a reference and there is no provision for a user-defined function to return a reference...

How do you run multiple programs in parallel from a bash script?

xargs -P <n> allows you to run <n> commands in parallel.

While -P is a nonstandard option, both the GNU (Linux) and macOS/BSD implementations support it.

The following example:

  • runs at most 3 commands in parallel at a time,
  • with additional commands starting only when a previously launched process terminates.
time xargs -P 3 -I {} sh -c 'eval "$1"' - {} <<'EOF'
sleep 1; echo 1
sleep 2; echo 2
sleep 3; echo 3
echo 4
EOF

The output looks something like:

1   # output from 1st command 
4   # output from *last* command, which started as soon as the count dropped below 3
2   # output from 2nd command
3   # output from 3rd command

real    0m3.012s
user    0m0.011s
sys 0m0.008s

The timing shows that the commands were run in parallel (the last command was launched only after the first of the original 3 terminated, but executed very quickly).

The xargs command itself won't return until all commands have finished, but you can execute it in the background by terminating it with control operator & and then using the wait builtin to wait for the entire xargs command to finish.

{
  xargs -P 3 -I {} sh -c 'eval "$1"' - {} <<'EOF'
sleep 1; echo 1
sleep 2; echo 2
sleep 3; echo 3
echo 4
EOF
} &

# Script execution continues here while `xargs` is running 
# in the background.
echo "Waiting for commands to finish..."

# Wait for `xargs` to finish, via special variable $!, which contains
# the PID of the most recently started background process.
wait $!

Note:

  • BSD/macOS xargs requires you to specify the count of commands to run in parallel explicitly, whereas GNU xargs allows you to specify -P 0 to run as many as possible in parallel.

  • Output from the processes run in parallel arrives as it is being generated, so it will be unpredictably interleaved.

    • GNU parallel, as mentioned in Ole's answer (does not come standard with most platforms), conveniently serializes (groups) the output on a per-process basis and offers many more advanced features.

Get Substring between two characters using javascript

var str = '[basic_salary]+100/[basic_salary]';
var arr = str.split('');
var myArr = [];
for(var i=0;i<arr.length;i++){
    if(arr[i] == '['){
        var a = '';
        for(var j=i+1;j<arr.length;j++){
            if(arr[j] == ']'){
                var i = j-1;
                break;
            }else{
                a += arr[j];
            }
        }
        myArr.push(a);
    }
    var operatorsArr = ['+','-','*','/','%'];
    if(operatorsArr.includes(arr[i])){
        myArr.push(arr[i]);
    }
    var numbArr = ['0','1','2','3','4','5','6','7','8','9'];
    if(numbArr.includes(arr[i])){
        var a = '';
        for(var j=i;j<arr.length;j++){
            if(numbArr.includes(arr[j])){
                a += arr[j];
            }else{
                var i = j-1;
                break;
            }
        }
        myArr.push(a);
    }
}
myArr = ["basic_salary", "+", "100", "/", "basic_salary"]

Get Folder Size from Windows Command Line

I recommend using https://github.com/aleksaan/diskusage utility which I wrote. Very simple and helpful. And very fast.

Just type in a command shell

diskusage.exe -path 'd:/go; d:/Books'

and get list of folders arranged by size

  1.| DIR: d:/go      | SIZE: 325.72 Mb   | DEPTH: 1 
  2.| DIR: d:/Books   | SIZE:  14.01 Mb   | DEPTH: 1 

This example was executed at 272ms on HDD.

You can increase depth of subfolders to analyze, for example:

diskusage.exe -path 'd:/go; d:/Books' -depth 2

and get sizes not only for selected folders but also for its subfolders

  1.| DIR: d:/go            | SIZE: 325.72 Mb   | DEPTH: 1 
  2.| DIR: d:/go/pkg        | SIZE: 212.88 Mb   | DEPTH: 2 
  3.| DIR: d:/go/src        | SIZE:  62.57 Mb   | DEPTH: 2 
  4.| DIR: d:/go/bin        | SIZE:  30.44 Mb   | DEPTH: 2 
  5.| DIR: d:/Books/Chess   | SIZE:  14.01 Mb   | DEPTH: 2 
  6.| DIR: d:/Books         | SIZE:  14.01 Mb   | DEPTH: 1 
  7.| DIR: d:/go/api        | SIZE:   6.41 Mb   | DEPTH: 2 
  8.| DIR: d:/go/test       | SIZE:   5.11 Mb   | DEPTH: 2 
  9.| DIR: d:/go/doc        | SIZE:   4.00 Mb   | DEPTH: 2 
 10.| DIR: d:/go/misc       | SIZE:   3.82 Mb   | DEPTH: 2 
 11.| DIR: d:/go/lib        | SIZE: 358.25 Kb   | DEPTH: 2 

*** 3.5Tb on the server has been scanned for 3m12s**

How to check if a file exists from a url

Do a request with curl and see if it returns a 404 status code. Do the request using the HEAD request method so it only returns the headers without a body.

How to check Spark Version

According to the Cloudera documentation - What's New in CDH 5.7.0 it includes Spark 1.6.0.

How can I dynamically switch web service addresses in .NET without a recompile?

If you are truly dynamically setting this, you should set the .Url field of instance of the proxy class you are calling.

Setting the value in the .config file from within your program:

  1. Is a mess;

  2. Might not be read until the next application start.

If it is only something that needs to be done once per installation, I'd agree with the other posters and use the .config file and the dynamic setting.

Python: how to print range a-z?

Try:

strng = ""
for i in range(97,123):
    strng = strng + chr(i)
print(strng)

How to enable ASP classic in IIS7.5

Add Authenticated Users

Make the file accessible to the Authenticated Users group. Right click your virtual directory and give the group read/write access to Authenticated Users.

I faced issue on windows 10 machine.

Insert line break in wrapped cell via code

Yes. The VBA equivalent of AltEnter is to use a linebreak character:

ActiveCell.Value = "I am a " & Chr(10) & "test"

Note that this automatically sets WrapText to True.

Proof:

Sub test()
Dim c As Range
Set c = ActiveCell
c.WrapText = False
MsgBox "Activcell WrapText is " & c.WrapText
c.Value = "I am a " & Chr(10) & "test"
MsgBox "Activcell WrapText is " & c.WrapText
End Sub

Java JTable getting the data of the selected row

using from ListSelectionModel:

ListSelectionModel cellSelectionModel = table.getSelectionModel();
cellSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

cellSelectionModel.addListSelectionListener(new ListSelectionListener() {
  public void valueChanged(ListSelectionEvent e) {
    String selectedData = null;

    int[] selectedRow = table.getSelectedRows();
    int[] selectedColumns = table.getSelectedColumns();

    for (int i = 0; i < selectedRow.length; i++) {
      for (int j = 0; j < selectedColumns.length; j++) {
        selectedData = (String) table.getValueAt(selectedRow[i], selectedColumns[j]);
      }
    }
    System.out.println("Selected: " + selectedData);
  }

});

see here.

Remove leading or trailing spaces in an entire column of data

I was able to use Find & Replace with the "Find what:" input field set to:

" * "

(space asterisk space with no double-quotes)

and "Replace with:" set to:

""

(nothing)

Overwriting txt file in java

Your code works fine for me. It replaced the text in the file as expected and didn't append.

If you wanted to append, you set the second parameter in

new FileWriter(fnew,false);

to true;

BACKUP LOG cannot be performed because there is no current database backup

In case the problem still exists go to Restoration Database page and Check "Restore all files to folder" in "Files" tab This might help

Get checkbox values using checkbox name using jquery

$('[name="CheckboxName"]:checked').each(function () {
    // do stuff
});

Remove all constraints affecting a UIView

The easier and efficient approach is to remove the view from superView and re add as subview again. this causes all the subview constraints get removed automagically.

Maximum execution time in phpMyadmin

Well for Wamp User,

Go to: wamp\apps\phpmyadmin3.3.9\libraries

Under line 536, locate $cfg['ExecTimeLimit'] = 0;

and change the value from 0 to 6000. e.g

$cfg['ExecTimeLimit'] = 0;

To

$cfg['ExecTimeLimit'] = 6000;

Restart wamp server and phew.

It works like magic !

Batch script: how to check for admin rights

Edit: copyitright has pointed out that this is unreliable. Approving read access with UAC will allow dir to succeed. I have a bit more script to offer another possibility, but it's not read-only.

reg query "HKLM\SOFTWARE\Foo" >NUL 2>NUL && goto :error_key_exists
reg add "HKLM\SOFTWARE\Foo" /f >NUL 2>NUL || goto :error_not_admin
reg delete "HKLM\SOFTWARE\Foo" /f >NUL 2>NUL || goto :error_failed_delete
goto :success

:error_failed_delete
  echo Error unable to delete test key
  exit /b 3
:error_key_exists
  echo Error test key exists
  exit /b 2
:error_not_admin
  echo Not admin
  exit /b 1
:success
  echo Am admin

Old answer below

Warning: unreliable


Based on a number of other good answers here and points brought up by and31415 I found that I am a fan of the following:

dir "%SystemRoot%\System32\config\DRIVERS" 2>nul >nul || echo Not Admin

Few dependencies and fast.

How to change the color of an image on hover

If the icon is from Font Awesome (https://fontawesome.com/icons/) then you could tap into the color css property to change it's background.

fb-icon{
color:none;
}

fb-icon:hover{
color:#0000ff;
}

This is irrespective of the color it had. So you could use an entirely different color in its usual state and define another in its active state.

How to replace (null) values with 0 output in PIVOT

You cannot place the IsNull() until after the data is selected so you will place the IsNull() around the final value in the SELECT:

SELECT CLASS,
  IsNull([AZ], 0) as [AZ],
  IsNull([CA], 0) as [CA],
  IsNull([TX], 0) as [TX]
FROM #TEMP
PIVOT 
(
  SUM(DATA)
  FOR STATE IN ([AZ], [CA], [TX])
) AS PVT
ORDER BY CLASS

How to use PDO to fetch results array in PHP?

Take a look at the PDOStatement.fetchAll method. You could also use fetch in an iterator pattern.

Code sample for fetchAll, from the PHP documentation:

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll(\PDO::FETCH_ASSOC);
print_r($result);

Results:

Array
(
    [0] => Array
        (
            [NAME] => pear
            [COLOUR] => green
        )

    [1] => Array
        (
            [NAME] => watermelon
            [COLOUR] => pink
        )
)

Create a .tar.bz2 file Linux

You are not indicating what to include in the archive.

Go one level outside your folder and try:

sudo tar -cvjSf folder.tar.bz2 folder

Or from the same folder try

sudo tar -cvjSf folder.tar.bz2 *

Cheers!

C# - Substring: index and length must refer to a location within the string

You need to check your statement like this :

string url = "www.example.com/aaa/bbb.jpg";
string lenght = url.Lenght-4;
if(url.Lenght > 15)//eg 15
{
 string newString = url.Substring(18, lenght);
}

How to create jar file with package structure?

You want

$ jar cvf asd.jar .

to specify the directory (e.g. .) to jar from. That will maintain your folder structure within the jar file.

Deep-Learning Nan loss reasons

Regularization can help. For a classifier, there is a good case for activity regularization, whether it is binary or a multi-class classifier. For a regressor, kernel regularization might be more appropriate.

Any easy way to use icons from resources?

in visual studio for vb.net, go to the project properties, click Add Resource > Existing File, select your Icon.

in your code: Me.Icon = My.Resources.IconResourceName

Android SDK location

If you have downloaded sdk manager zip (from https://developer.android.com/studio/#downloads), then you have Android SDK Location as root of the extracted folder.

So silly, But it took time for me as a beginner.

JS file gets a net::ERR_ABORTED 404 (Not Found)

As mentionned in comments: you need a way to send your static files to the client. This can be achieved with a reverse proxy like Nginx, or simply using express.static().

Put all your "static" (css, js, images) files in a folder dedicated to it, different from where you put your "views" (html files in your case). I'll call it static for the example. Once it's done, add this line in your server code:

app.use("/static", express.static('./static/'));

This will effectively serve every file in your "static" folder via the /static route.

Querying your index.js file in the client thus becomes:

<script src="static/index.js"></script>

UINavigationBar custom back button without title

It's actually pretty easy, here is what I do:

Objective C

// Set this in every view controller so that the back button displays back instead of the root view controller name
self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];

Swift 2

self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .Plain, target: nil, action: nil)

Swift 3

self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)

Put this line in the view controller that is pushing on to the stack (the previous view controller). The newly pushed view controller back button will now show whatever you put for initWithTitle, which in this case is an empty string.

How to add minutes to my Date

tl;dr

LocalDateTime.parse( 
    "2016-01-23 12:34".replace( " " , "T" )
)
.atZone( ZoneId.of( "Asia/Karachi" ) )
.plusMinutes( 10 )

java.time

Use the excellent java.time classes for date-time work. These classes supplant the troublesome old date-time classes such as java.util.Date and java.util.Calendar.

ISO 8601

The java.time classes use standard ISO 8601 formats by default for parsing/generating strings of date-time values. To make your input string comply, replace the SPACE in the middle with a T.

String input = "2016-01-23 12:34" ;
String inputModified = input.replace( " " , "T" );

LocalDateTime

Parse your input string as a LocalDateTime as it lacks any info about time zone or offset-from-UTC.

LocalDateTime ldt = LocalDateTime.parse( inputModified );

Add ten minutes.

LocalDateTime ldtLater = ldt.plusMinutes( 10 );

ldt.toString(): 2016-01-23T12:34

ldtLater.toString(): 2016-01-23T12:44

See live code in IdeOne.com.

That LocalDateTime has no time zone, so it does not represent a point on the timeline. Apply a time zone to translate to an actual moment. Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland, or Asia/Karachi. Never use the 3-4 letter abbreviation such as EST or IST or PKT as they are not true time zones, not standardized, and not even unique(!).

ZonedDateTime

If you know the intended time zone for this value, apply a ZoneId to get a ZonedDateTime.

ZoneId z = ZoneId.of( "Asia/Karachi" );
ZonedDateTime zdt = ldt.atZone( z );

zdt.toString(): 2016-01-23T12:44+05:00[Asia/Karachi]

Anomalies

Think about whether to add those ten minutes before or after adding a time zone. You may get a very different result because of anomalies such as Daylight Saving Time (DST) that shift the wall-clock time.

Whether you should add the 10 minutes before or after adding the zone depends on the meaning of your business scenario and rules.

Tip: When you intend a specific moment on the timeline, always keep the time zone information. Do not lose that info, as done with your input data. Is the value 12:34 meant to be noon in Pakistan or noon in France or noon in Québec? If you meant noon in Pakistan, say so by including at least the offset-from-UTC (+05:00), and better still, the name of the time zone (Asia/Karachi).

Instant

If you want the same moment as seen through the lens of UTC, extract an Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = zdt.toInstant();

Convert

Avoid the troublesome old date-time classes whenever possible. But if you must, you can convert. Call new methods added to the old classes.

java.util.Date utilDate = java.util.Date.from( instant );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to java.time.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

  • Java SE 8 and SE 9 and later
    • Built-in.
    • Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

char initial value in Java

As you will see in linked discussion there is no need for initializing char with special character as it's done for us and is represented by '\u0000' character code.

So if we want simply to check if specified char was initialized just write:

if(charVariable != '\u0000'){
 actionsOnInitializedCharacter();
}

Link to question: what's the default value of char?

Check if starting characters of a string are alphabetical in T-SQL

select * from my_table where my_field Like '[a-z][a-z]%'

Integer.toString(int i) vs String.valueOf(int i)

my openion is valueof() always called tostring() for representaion and so for rpresentaion of primtive type valueof is generalized.and java by default does not support Data type but it define its work with objaect and class its made all thing in cllas and made object .here Integer.toString(int i) create a limit that conversion for only integer.

How to find item with max value using linq?

With EF or LINQ to SQL:

var item = db.Items.OrderByDescending(i => i.Value).FirstOrDefault();

With LINQ to Objects I suggest to use morelinq extension MaxBy (get morelinq from nuget):

var item = items.MaxBy(i => i.Value);

Ruby: Calling class method from instance

Rather than referring to the literal name of the class, inside an instance method you can just call self.class.whatever.

class Foo
    def self.some_class_method
        puts self
    end

    def some_instance_method
        self.class.some_class_method
    end
end

print "Class method: "
Foo.some_class_method

print "Instance method: "
Foo.new.some_instance_method

Outputs:

Class method: Foo
Instance method: Foo

Android Material: Status bar color won't change

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
    getWindow().setStatusBarColor(getResources().getColor(R.color.actionbar));
}

Put this code in your Activity's onCreate method. This helped me.

What __init__ and self do in Python?

In this code:

class A(object):
    def __init__(self):
        self.x = 'Hello'

    def method_a(self, foo):
        print self.x + ' ' + foo

... the self variable represents the instance of the object itself. Most object-oriented languages pass this as a hidden parameter to the methods defined on an object; Python does not. You have to declare it explicitly. When you create an instance of the A class and call its methods, it will be passed automatically, as in ...

a = A()               # We do not pass any argument to the __init__ method
a.method_a('Sailor!') # We only pass a single argument

The __init__ method is roughly what represents a constructor in Python. When you call A() Python creates an object for you, and passes it as the first parameter to the __init__ method. Any additional parameters (e.g., A(24, 'Hello')) will also get passed as arguments--in this case causing an exception to be raised, since the constructor isn't expecting them.

How to get the process ID to kill a nohup process?

Suppose you are executing a java program with nohup you can get java process id by

`ps aux | grep java`

output

xxxxx     9643  0.0  0.0  14232   968 pts/2   

then you can kill the process by typing

sudo kill 9643

or lets say that you need to kill all the java processes then just use

sudo killall java

this command kills all the java processes. you can use this with process. just give the process name at the end of the command

sudo killall {processName}

How to detect a mobile device with JavaScript?

So I did this. Thank you all!

<head>
<script type="text/javascript">
    function DetectTheThing()
    {
       var uagent = navigator.userAgent.toLowerCase();
       if (uagent.search("iphone") > -1 || uagent.search("ipad") > -1 
       || uagent.search("android") > -1 || uagent.search("blackberry") > -1
       || uagent.search("webos") > -1)
          window.location.href ="otherindex.html";
    }
</script>

</head>

<body onload="DetectTheThing()">
VIEW NORMAL SITE
</body>

</html>

MySql: Tinyint (2) vs tinyint(1) - what is the difference?

mysql> CREATE TABLE tin3(id int PRIMARY KEY,val TINYINT(10) ZEROFILL);
Query OK, 0 rows affected (0.04 sec)

mysql> INSERT INTO tin3 VALUES(1,12),(2,7),(4,101);
Query OK, 3 rows affected (0.02 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> SELECT * FROM tin3;
+----+------------+
| id | val        |
+----+------------+
|  1 | 0000000012 |
|  2 | 0000000007 |
|  4 | 0000000101 |
+----+------------+
3 rows in set (0.00 sec)

mysql>

mysql> SELECT LENGTH(val) FROM tin3 WHERE id=2;
+-------------+
| LENGTH(val) |
+-------------+
|          10 |
+-------------+
1 row in set (0.01 sec)


mysql> SELECT val+1 FROM tin3 WHERE id=2;
+-------+
| val+1 |
+-------+
|     8 |
+-------+
1 row in set (0.00 sec)

remove double quotes from Json return data using Jquery

Someone here suggested using eval() to remove the quotes from a string. Don't do that, that's just begging for code injection.

Another way to do this that I don't see listed here is using:

let message = JSON.stringify(your_json_here); // "Hello World"
console.log(JSON.parse(message))              // Hello World

Check if event exists on element

I wrote a plugin called hasEventListener which exactly does that.

Hope this helps.

set the width of select2 input (through Angular-ui directive)

You need to specify the attribute width to resolve in order to preserve element width

$(document).ready(function() { 
    $("#myselect").select2({ width: 'resolve' });           
});

"Find next" in Vim

As discussed, there are several ways to search:

/pattern
?pattern
* (and g*, which I sometimes use in macros)
# (and g#)

plus, navigating prev/next with N and n.

You can also edit/recall your search history by pulling up the search prompt with / and then cycle with C-p/C-n. Even more useful is q/, which takes you to a window where you can navigate the search history.

Also for consideration is the all-important 'hlsearch' (type :hls to enable). This makes it much easier to find multiple instances of your pattern. You might even want make your matches extra bright with something like:

hi Search ctermfg=yellow ctermbg=red guifg=...

But then you might go crazy with constant yellow matches all over your screen. So you’ll often find yourself using :noh. This is so common that a mapping is in order:

nmap <leader>z :noh<CR>

I easily remember this one as z since I used to constantly type /zz<CR> (which is a fast-to-type uncommon occurrence) to clear my highlighting. But the :noh mapping is way better.

Limiting the number of characters in a string, and chopping off the rest

If you just want a maximum length, use StringUtils.left! No if or ternary ?: needed.

int maxLength = 5;
StringUtils.left(string, maxLength);

Output:

      null -> null
        "" -> ""
       "a" -> "a"
"abcd1234" -> "abcd1"

Left Documentation

Manifest Merger failed with multiple errors in Android Studio

Just add below code in your project Manifest application tag...

<application
        tools:node="replace">

How to make a char string from a C macro's value?

#define TEST_FUN_NAME #FUNC_NAME

see here

Open another page in php

<?php
    header("Location: index.html");
?>

Just make sure nothing is actually written to the page prior to this code, or it won't work.

ListView with Add and Delete Buttons in each Row in android

on delete button click event

public void delete(View v){                

    ListView listview1;
    ArrayList<E> datalist;

    final int position = listview1.getPositionForView((View) v.getParent());
    datalist.remove(position);
    myAdapter.notifyDataSetChanged();

}

How to make a class JSON serializable

First we need to make our object JSON-compliant, so we can dump it using the standard JSON module. I did it this way:

def serialize(o):
    if isinstance(o, dict):
        return {k:serialize(v) for k,v in o.items()}
    if isinstance(o, list):
        return [serialize(e) for e in o]
    if isinstance(o, bytes):
        return o.decode("utf-8")
    return o

Redirecting new tab on button click.(Response.Redirect) in asp.net C#

Wouldn't you be better off with

<asp:HyperLink ID="HyperLink1" runat="server" 
            NavigateUrl="CMS_1.aspx" 
            Target="_blank">
    Click here
</asp:HyperLink>

Because, to replicate your desired behavior on an asp:Button, you have to call window.open on the OnClientClick event of the button which looks a lot less cleaner than the above solution. Plus asp:HyperLink is there to handle scenarios like this.

If you want to replicate this using an asp:Button, do this.

<asp:Button ID="btn" runat="Server" 
        Text="SUBMIT"
        OnClientClick="javascript:return openRequestedPopup();"/>

JavaScript function.

var windowObjectReference;

function openRequestedPopup() {
    windowObjectReference = window.open("CMS_1.aspx",
              "DescriptiveWindowName",
              "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes");
}

C# guid and SQL uniqueidentifier

Here's a code snippet showing how to insert a GUID using a parameterised query:

    using(SqlConnection conn = new SqlConnection(connectionString))
    {
        conn.Open();
        using(SqlTransaction trans = conn.BeginTransaction())
        using (SqlCommand cmd = conn.CreateCommand())
        {
            cmd.Transaction = trans;
            cmd.CommandText = @"INSERT INTO [MYTABLE] ([GuidValue]) VALUE @guidValue;";
            cmd.Parameters.AddWithValue("@guidValue", Guid.NewGuid());
            cmd.ExecuteNonQuery();
            trans.Commit();
        }
    }

jQuery dialog popup

You can use the following script. It worked for me

The modal itself consists of a main modal container, a header, a body, and a footer. The footer contains the actions, which in this case is the OK button, the header holds the title and the close button, and the body contains the modal content.

 $(function () {
        modalPosition();
        $(window).resize(function () {
            modalPosition();
        });
        $('.openModal').click(function (e) {
            $('.modal, .modal-backdrop').fadeIn('fast');
            e.preventDefault();
        });
        $('.close-modal').click(function (e) {
            $('.modal, .modal-backdrop').fadeOut('fast');
        });
    });
    function modalPosition() {
        var width = $('.modal').width();
        var pageWidth = $(window).width();
        var x = (pageWidth / 2) - (width / 2);
        $('.modal').css({ left: x + "px" });
    }

Refer:- Modal popup using jquery in asp.net

if checkbox is checked, do this

It may happen that "this.checked" is always "on". Therefore, I recommend:

$('#checkbox').change(function() {
  if ($(this).is(':checked')) {
    console.log('Checked');
  } else {
    console.log('Unchecked');
  }
});

Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty

try import django then run django.setup() after the secret_key definition. like so:

SECRET_KEY = 'it5bs))q6toz-1gwf(+j+f9@rd8%_-0nx)p-2!egr*y1o51=45XXCV'
django.setup()

Markdown open a new window link

There is no such feature in markdown, however you can always use HTML inside markdown:

<a href="http://example.com/" target="_blank">example</a>

Enum "Inheritance"

Enums are not actual classes, even if they look like it. Internally, they are treated just like their underlying type (by default Int32). Therefore, you can only do this by "copying" single values from one enum to another and casting them to their integer number to compare them for equality.

How to find tags with only certain attributes - BeautifulSoup

You can use lambda functions in findAll as explained in documentation. So that in your case to search for td tag with only valign = "top" use following:

td_tag_list = soup.findAll(
                lambda tag:tag.name == "td" and
                len(tag.attrs) == 1 and
                tag["valign"] == "top")

Updating MySQL primary key

You can use the IGNORE keyword too, example:

 update IGNORE table set primary_field = 'value'...............

How to handle a single quote in Oracle SQL

Use two single-quotes

SQL> SELECT 'D''COSTA' name FROM DUAL;

NAME
-------
D'COSTA

Alternatively, use the new (10g+) quoting method:

SQL> SELECT q'$D'COSTA$' NAME FROM DUAL;

NAME
-------
D'COSTA

Display exact matches only with grep

Try the below command, because it works perfectly:

grep -ow "yourstring"

crosscheck:-

Remove the instance of word from file, then re-execute this command and it should display empty result.

How to solve a timeout error in Laravel 5

In Laravel:

Add set_time_limit(0) line on top of query.

set_time_limit(0);

$users = App\User::all();

It helps you in different large queries but you should need to improve query optimise.

Specifying ssh key in ansible playbook file

You can use the ansible.cfg file, it should look like this (There are other parameters which you might want to include):

[defaults]
inventory = <PATH TO INVENTORY FILE>
remote_user = <YOUR USER>
private_key_file =  <PATH TO KEY_FILE>

Hope this saves you some typing

How to change the height of a <br>?

Another way is to use an HR. But, and here's the cunning part, make it invisible.

Thus:

<hr style="height:30pt; visibility:hidden;" />

To make a cleaner BR break simulated using the HR: Btw works in all browsers!!

{ height:2px; visibility:hidden; margin-bottom:-1px; }

How do you transfer or export SQL Server 2005 data to Excel

Use "External data" from Excel. It can use ODBC connection to fetch data from external source: Data/Get External Data/New Database Query

That way, even if the data in the database changes, you can easily refresh.

Is it possible to save HTML page as PDF using JavaScript or jquery?

You can use Phantomjs. Download here and use the following example to test the html->pdf conversion feature https://github.com/ariya/phantomjs/blob/master/examples/rasterize.js

Example code:

phantomjs.exe examples/rasterize.js http://www.w3.org/Style/CSS/Test/CSS3/Selectors/current/xhtml/index.html sample.pdf