Programs & Examples On #Remote access

Remote access is the connection to a data processing system from a remote location.

ERROR 2003 (HY000): Can't connect to MySQL server (111)

Not sure as cant see it in steps you mentioned.

Please try FLUSH PRIVILEGES [Reloads the privileges from the grant tables in the mysql database]:

flush privileges;

You need to execute it after GRANT

Hope this help!

Where can I get a virtual machine online?

You can get free Virtual Machine and many more things online for 3 months provided by Microsoft Azure. I guess you need VPN for learning purpose. For that it would suffice.

Refer http://www.windowsazure.com/en-us/pricing/free-trial/

Can't connect to Postgresql on port 5432

You probably need to either open up the port to access it in your LAN (or outside of it) or bind the network address to the port (make PostgreSQL listen on your LAN instead of just on localhost)

How to solve "sign_and_send_pubkey: signing failed: agent refused operation"?

As others have mentioned, there can be multiple reasons for this error.

If you are using SSH with Smart Card (PIV), and adding the card to ssh-agent with
ssh-add -s /usr/lib64/pkcs11/opensc-pkcs11.so
you may get the error
sign_and_send_pubkey: signing failed: agent refused operation
from ssh if the PIV authentication has expired, or if you have removed and reinserted the PIV card.

In that case, if you try to do another ssh-add -s you will still get an error:
Could not add card "/usr/lib64/opensc-pkcs11.so": agent refused operation

According to RedHat Bug 1609055 - pkcs11 support in agent is clunky, you instead need to do

ssh-add -e /usr/lib64/opensc-pkcs11.so
ssh-add -s /usr/lib64/opensc-pkcs11.so

Unable to connect to SQL Server instance remotely

Disable the firewall and try to connect.

If that works, then enable the firewall and

Windows Defender Firewall -> Advanced Settings -> Inbound Rules(Right Click) -> New Rules -> Port -> Allow Port 1433 (Public and Private) -> Add

Do the same for Outbound Rules.

Then Try again.

How can I run Tensorboard on a remote server?

  1. Find your local external IP by googling "whats my ip" or entering this command: wget http://ipinfo.io/ip -qO -
  2. Determine your remote external IP. This is probably what comes after your username when ssh-ing into the remote server. You can also wget http://ipinfo.io/ip -qO - again from there too.
  3. Secure your remote server traffic to just accept your local external IP address
  4. Run Tensorboard. Note the port it defaults to: 6006
  5. Enter your remote external IP address into your browser, followed by the port: 123.123.12.32:6006

If your remote server is open to traffic from your local IP address, you should be able to see your remote Tensorboard.

Warning: if all internet traffic can access your system (if you haven't specified a single IP address that can access it), anyone may be able to view your TensorBoard results and runaway with creating SkyNet themselves.

How can I flush GPU memory using CUDA (physical reset is unavailable)

check what is using your GPU memory with

sudo fuser -v /dev/nvidia*

Your output will look something like this:

                     USER        PID  ACCESS COMMAND
/dev/nvidia0:        root       1256  F...m  Xorg
                     username   2057  F...m  compiz
                     username   2759  F...m  chrome
                     username   2777  F...m  chrome
                     username   20450 F...m  python
                     username   20699 F...m  python

Then kill the PID that you no longer need on htop or with

sudo kill -9 PID.

In the example above, Pycharm was eating a lot of memory so I killed 20450 and 20699.

Use SQL Server Management Studio to connect remotely to an SQL Server Express instance hosted on an Azure Virtual Machine

The fact that you're getting an error from the Names Pipes Provider tells us that you're not using the TCP/IP protocol when you're trying to establish the connection. Try adding the "tcp" prefix and specifying the port number:

tcp:name.cloudapp.net,1433

Mysql adding user for remote access

Follow instructions (steps 1 to 3 don't needed in windows):

  1. Find mysql config to edit:

    /etc/mysql/my.cnf (Mysql 5.5)

    /etc/mysql/conf.d/mysql.cnf (Mysql 5.6+)

  2. Find bind-address=127.0.0.1 in config file change bind-address=0.0.0.0 (you can set bind address to one of your interface ips or like me use 0.0.0.0)

  3. Restart mysql service run on console: service restart mysql

  4. Create a user with a safe password for remote connection. To do this run following command in mysql (if you are linux user to reach mysql console run mysql and if you set password for root run mysql -p):

    GRANT ALL PRIVILEGES 
     ON *.* TO 'remote'@'%' 
     IDENTIFIED BY 'safe_password' 
     WITH GRANT OPTION;`
    

Now you should have a user with name of user and password of safe_password with capability of remote connect.

What is the most appropriate way to store user settings in Android application

you need to use the sqlite, security apit to store the passwords. here is best example, which stores passwords, -- passwordsafe. here is link for the source and explanation -- http://code.google.com/p/android-passwordsafe/

How do I debug error ECONNRESET in Node.js?

Had the same problem today. After some research i found a very useful --abort-on-uncaught-exception node.js option. Not only it provides much more verbose and useful error stack trace, but also saves core file on application crash allowing further debug.

Remove pattern from string with gsub

as.numeric(gsub(pattern=".*_", replacement = '', a)
[1] 5 7

Flexbox not giving equal width to elements

There is an important bit that is not mentioned in the article to which you linked and that is flex-basis. By default flex-basis is auto.

From the spec:

If the specified flex-basis is auto, the used flex basis is the value of the flex item’s main size property. (This can itself be the keyword auto, which sizes the flex item based on its contents.)

Each flex item has a flex-basis which is sort of like its initial size. Then from there, any remaining free space is distributed proportionally (based on flex-grow) among the items. With auto, that basis is the contents size (or defined size with width, etc.). As a result, items with bigger text within are being given more space overall in your example.

If you want your elements to be completely even, you can set flex-basis: 0. This will set the flex basis to 0 and then any remaining space (which will be all space since all basises are 0) will be proportionally distributed based on flex-grow.

li {
    flex-grow: 1;
    flex-basis: 0;
    /* ... */
}

This diagram from the spec does a pretty good job of illustrating the point.

And here is a working example with your fiddle.

Typescript input onchange event.target.value

lucky i find a solution. you can

import { ChangeEvent } from 'react';

and then write code like: e:ChangeEvent<HTMLInputElement>

How to set proxy for wget?

Type in command line :

$ export http_proxy=http://proxy_host:proxy_port

for authenticated proxy,

$ export http_proxy=http://username:password@proxy_host:proxy_port

and then run

$ wget fileurl

for https, just use https_proxy instead of http_proxy. You could also put these lines in your ~/.bashrc file so that you don't need to execute this everytime.

How to check a string for specific characters?

This will test if strings are made up of some combination or digits, the dollar sign, and a commas. Is that what you're looking for?

import re

s1 = 'Testing string'
s2 = '1234,12345$'

regex = re.compile('[0-9,$]+$')

if ( regex.match(s1) ):
   print "s1 matched"
else:
   print "s1 didn't match"

if ( regex.match(s2) ):
   print "s2 matched"
else:
   print "s2 didn't match"

How do I make a simple makefile for gcc on Linux?

Interesting, I didn't know make would default to using the C compiler given rules regarding source files.

Anyway, a simple solution that demonstrates simple Makefile concepts would be:

HEADERS = program.h headers.h

default: program

program.o: program.c $(HEADERS)
    gcc -c program.c -o program.o

program: program.o
    gcc program.o -o program

clean:
    -rm -f program.o
    -rm -f program

(bear in mind that make requires tab instead of space indentation, so be sure to fix that when copying)

However, to support more C files, you'd have to make new rules for each of them. Thus, to improve:

HEADERS = program.h headers.h
OBJECTS = program.o

default: program

%.o: %.c $(HEADERS)
    gcc -c $< -o $@

program: $(OBJECTS)
    gcc $(OBJECTS) -o $@

clean:
    -rm -f $(OBJECTS)
    -rm -f program

I tried to make this as simple as possible by omitting variables like $(CC) and $(CFLAGS) that are usually seen in makefiles. If you're interested in figuring that out, I hope I've given you a good start on that.

Here's the Makefile I like to use for C source. Feel free to use it:

TARGET = prog
LIBS = -lm
CC = gcc
CFLAGS = -g -Wall

.PHONY: default all clean

default: $(TARGET)
all: default

OBJECTS = $(patsubst %.c, %.o, $(wildcard *.c))
HEADERS = $(wildcard *.h)

%.o: %.c $(HEADERS)
    $(CC) $(CFLAGS) -c $< -o $@

.PRECIOUS: $(TARGET) $(OBJECTS)

$(TARGET): $(OBJECTS)
    $(CC) $(OBJECTS) -Wall $(LIBS) -o $@

clean:
    -rm -f *.o
    -rm -f $(TARGET)

It uses the wildcard and patsubst features of the make utility to automatically include .c and .h files in the current directory, meaning when you add new code files to your directory, you won't have to update the Makefile. However, if you want to change the name of the generated executable, libraries, or compiler flags, you can just modify the variables.

In either case, don't use autoconf, please. I'm begging you! :)

How to set bootstrap navbar active class with Angular JS?

You can also use this active-link directive https://stackoverflow.com/a/23138152/1387163

Parent li will get active class when location matches /url:

<li>
    <a href="#!/url" active-link active-link-parent>
</li>

How do I make jQuery wait for an Ajax call to finish before it returns?

I am not using $.ajax but the $.post and $.get functions, so if I need to wait for the response, I use this:

$.ajaxSetup({async: false});
$.get("...");

How do I get the selected element by name and then get the selected value from a dropdown using jQuery?

Remove the onchange event from the HTML Markup and bind it in your document ready event

<select  name="a[b]" >
     <option value='Choice 1'>Choice 1</option>
     <option value='Choice 2'>Choice 2</option>
</select>?

and Script

$(function(){    
    $("select[name='a[b]']").change(function(){
       alert($(this).val());        
    }); 
});

Working sample : http://jsfiddle.net/gLaR8/3/

Select a random sample of results from a query result

We were given and assignment to select only two records from the list of agents..i.e 2 random records for each agent over the span of a week etc.... and below is what we got and it works

with summary as (
Select Dbms_Random.Random As Ran_Number,
             colmn1,
             colm2,
             colm3
             Row_Number() Over(Partition By col2 Order By Dbms_Random.Random) As Rank
    From table1, table2
 Where Table1.Id = Table2.Id
 Order By Dbms_Random.Random Asc)
Select tab1.col2,
             tab1.col4,
             tab1.col5,
    From Summary s
 Where s.Rank <= 2;

How can I load storyboard programmatically from class?

The extension below will allow you to load a Storyboard and it's associated UIViewController. Example: If you have a UIViewController named ModalAlertViewController and a storyboard named "ModalAlert" e.g.

let vc: ModalAlertViewController = UIViewController.loadStoryboard("ModalAlert")

Will load both the Storyboard and UIViewController and vc will be of type ModalAlertViewController. Note Assumes that the storyboard's Storyboard ID has the same name as the storyboard and that the storyboard has been marked as Is Initial View Controller.

extension UIViewController {
    /// Loads a `UIViewController` of type `T` with storyboard. Assumes that the storyboards Storyboard ID has the same name as the storyboard and that the storyboard has been marked as Is Initial View Controller.
    /// - Parameter storyboardName: Name of the storyboard without .xib/nib suffix.
    static func loadStoryboard<T: UIViewController>(_ storyboardName: String) -> T? {
        let storyboard = UIStoryboard(name: storyboardName, bundle: nil)
        if let vc = storyboard.instantiateViewController(withIdentifier: storyboardName) as? T {
            vc.loadViewIfNeeded() // ensures vc.view is loaded before returning
            return vc
        }
        return nil
    }
}

Django - Reverse for '' not found. '' is not a valid view function or pattern name

Fix urlpatterns in urls.py file

For example, my app name is "simulator",

My URL pattern for login and logout looks like

urlpatterns = [
    ...
    ...
    url(r'^login/$', simulator.views.login_view, name="login"),
    url(r'^logout/$', simulator.views.logout_view, name="logout"),
    ...
    ...

]

How to get a jqGrid selected row cells value

You can use in this manner also

var rowId =$("#list").jqGrid('getGridParam','selrow');  
var rowData = jQuery("#list").getRowData(rowId);
var colData = rowData['UserId'];   // perticuler Column name of jqgrid that you want to access

increment date by one month

 <?php
              $selectdata ="select fromd,tod  from register where username='$username'";
            $q=mysqli_query($conm,$selectdata);
            $row=mysqli_fetch_array($q);

            $startdate=$row['fromd']; 
            $stdate=date('Y', strtotime($startdate));  

            $endate=$row['tod']; 
            $enddate=date('Y', strtotime($endate));  

            $years = range ($stdate,$enddate);
            echo '<select name="years" class="form-control">';
            echo '<option>SELECT</option>';
            foreach($years as $year)
              {   echo '<option value="'.$year.'"> '.$year.' </option>';  }
                echo '</select>'; ?>

Ansible: Store command's stdout in new variable?

A slight modification beyond @udondan's answer. I like to reuse the registered variable names with the set_fact to help keep the clutter to a minimum.

So if I were to register using the variable, psk, I'd use that same variable name with creating the set_fact.

Example

- name: generate PSK
  shell: openssl rand -base64 48
  register: psk
  delegate_to: 127.0.0.1
  run_once: true

- set_fact: 
    psk={{ psk.stdout }}

- debug: var=psk
  run_once: true

Then when I run it:

$ ansible-playbook -i inventory setup_ipsec.yml

 PLAY                                                                                                                                                                                [all] *************************************************************************************************************************************************************************

 TASK [Gathering                                                                                                                                                                     Facts] *************************************************************************************************************************************************************
 ok: [hostc.mydom.com]
 ok: [hostb.mydom.com]
 ok: [hosta.mydom.com]

 TASK [libreswan : generate                                                                                                                                                          PSK] ****************************************************************************************************************************************************
 changed: [hosta.mydom.com -> 127.0.0.1]

 TASK [libreswan :                                                                                                                                                                   set_fact] ********************************************************************************************************************************************************
 ok: [hosta.mydom.com]
 ok: [hostb.mydom.com]
 ok: [hostc.mydom.com]

 TASK [libreswan :                                                                                                                                                                   debug] ***********************************************************************************************************************************************************
 ok: [hosta.mydom.com] => {
     "psk": "6Tx/4CPBa1xmQ9A6yKi7ifONgoYAXfbo50WXPc1kGcird7u/pVso/vQtz+WdBIvo"
 }

 PLAY                                                                                                                                                                                RECAP *************************************************************************************************************************************************************************
 hosta.mydom.com    : ok=4    changed=1    unreachable=0    failed=0
 hostb.mydom.com    : ok=2    changed=0    unreachable=0    failed=0
 hostc.mydom.com    : ok=2    changed=0    unreachable=0    failed=0

How to implement class constants?

Angular 2 Provides a very nice feature called as Opaque Constants. Create a class & Define all the constants there using opaque constants.

import { OpaqueToken } from "@angular/core";

export let APP_CONFIG = new OpaqueToken("my.config");

export interface MyAppConfig {
    apiEndpoint: string;
}

export const AppConfig: MyAppConfig = {    
    apiEndpoint: "http://localhost:8080/api/"    
};

Inject it in providers in app.module.ts

You will be able to use it across every components.

EDIT for Angular 4 :

For Angular 4 the new concept is Injection Token & Opaque token is Deprecated in Angular 4.

Injection Token Adds functionalities on top of Opaque Tokens, it allows to attach type info on the token via TypeScript generics, plus Injection tokens, removes the need of adding @Inject

Example Code

Angular 2 Using Opaque Tokens

const API_URL = new OpaqueToken('apiUrl'); //no Type Check


providers: [
  {
    provide: DataService,
    useFactory: (http, apiUrl) => {
      // create data service
    },
    deps: [
      Http,
      new Inject(API_URL) //notice the new Inject
    ]
  }
]

Angular 4 Using Injection Tokens

const API_URL = new InjectionToken<string>('apiUrl'); // generic defines return value of injector


providers: [
  {
    provide: DataService,
    useFactory: (http, apiUrl) => {
      // create data service
    },
    deps: [
      Http,
      API_URL // no `new Inject()` needed!
    ]
  }
]

Injection tokens are designed logically on top of Opaque tokens & Opaque tokens are deprecated in Angular 4.

Delete worksheet in Excel using VBA

try this within your if statements:

Application.DisplayAlerts = False
Worksheets(“Sheetname”).Delete
Application.DisplayAlerts = True

Creating Roles in Asp.net Identity MVC 5

Here is the complete article describing how to create role, modify roles, delete roles and manage roles using ASP.NET Identity. This also contains User interface, controller methods etc.

http://www.dotnetfunda.com/articles/show/2898/working-with-roles-in-aspnet-identity-for-mvc

Hope this helpls

Thanks

warning about too many open figures

Use .clf or .cla on your figure object instead of creating a new figure. From @DavidZwicker

Assuming you have imported pyplot as

import matplotlib.pyplot as plt

plt.cla() clears an axis, i.e. the currently active axis in the current figure. It leaves the other axes untouched.

plt.clf() clears the entire current figure with all its axes, but leaves the window opened, such that it may be reused for other plots.

plt.close() closes a window, which will be the current window, if not specified otherwise. plt.close('all') will close all open figures.

The reason that del fig does not work is that the pyplot state-machine keeps a reference to the figure around (as it must if it is going to know what the 'current figure' is). This means that even if you delete your ref to the figure, there is at least one live ref, hence it will never be garbage collected.

Since I'm polling on the collective wisdom here for this answer, @JoeKington mentions in the comments that plt.close(fig) will remove a specific figure instance from the pylab state machine (plt._pylab_helpers.Gcf) and allow it to be garbage collected.

Gridview with two columns and auto resized images

Here's a relatively easy method to do this. Throw a GridView into your layout, setting the stretch mode to stretch the column widths, set the spacing to 0 (or whatever you want), and set the number of columns to 2:

res/layout/main.xml

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

    <GridView
        android:id="@+id/gridview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:verticalSpacing="0dp"
        android:horizontalSpacing="0dp"
        android:stretchMode="columnWidth"
        android:numColumns="2"/>

</FrameLayout>

Make a custom ImageView that maintains its aspect ratio:

src/com/example/graphicstest/SquareImageView.java

public class SquareImageView extends ImageView {
    public SquareImageView(Context context) {
        super(context);
    }

    public SquareImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SquareImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth()); //Snap to width
    }
}

Make a layout for a grid item using this SquareImageView and set the scaleType to centerCrop:

res/layout/grid_item.xml

<?xml version="1.0" encoding="utf-8"?>

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:layout_width="match_parent"
             android:layout_height="match_parent">

    <com.example.graphicstest.SquareImageView
        android:id="@+id/picture"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop"/>

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingTop="15dp"
        android:paddingBottom="15dp"
        android:layout_gravity="bottom"
        android:textColor="@android:color/white"
        android:background="#55000000"/>

</FrameLayout>

Now make some sort of adapter for your GridView:

src/com/example/graphicstest/MyAdapter.java

private final class MyAdapter extends BaseAdapter {
    private final List<Item> mItems = new ArrayList<Item>();
    private final LayoutInflater mInflater;

    public MyAdapter(Context context) {
        mInflater = LayoutInflater.from(context);

        mItems.add(new Item("Red",       R.drawable.red));
        mItems.add(new Item("Magenta",   R.drawable.magenta));
        mItems.add(new Item("Dark Gray", R.drawable.dark_gray));
        mItems.add(new Item("Gray",      R.drawable.gray));
        mItems.add(new Item("Green",     R.drawable.green));
        mItems.add(new Item("Cyan",      R.drawable.cyan));
    }

    @Override
    public int getCount() {
        return mItems.size();
    }

    @Override
    public Item getItem(int i) {
        return mItems.get(i);
    }

    @Override
    public long getItemId(int i) {
        return mItems.get(i).drawableId;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        View v = view;
        ImageView picture;
        TextView name;

        if (v == null) {
            v = mInflater.inflate(R.layout.grid_item, viewGroup, false);
            v.setTag(R.id.picture, v.findViewById(R.id.picture));
            v.setTag(R.id.text, v.findViewById(R.id.text));
        }

        picture = (ImageView) v.getTag(R.id.picture);
        name = (TextView) v.getTag(R.id.text);

        Item item = getItem(i);

        picture.setImageResource(item.drawableId);
        name.setText(item.name);

        return v;
    }

    private static class Item {
        public final String name;
        public final int drawableId;

        Item(String name, int drawableId) {
            this.name = name;
            this.drawableId = drawableId;
        }
    }
}

Set that adapter to your GridView:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    GridView gridView = (GridView)findViewById(R.id.gridview);
    gridView.setAdapter(new MyAdapter(this));
}

And enjoy the results:

Example GridView

Add table row in jQuery

If you are using Datatable JQuery plugin you can try.

oTable = $('#tblStateFeesSetup').dataTable({
            "bScrollCollapse": true,
            "bJQueryUI": true,
            ...
            ...
            //Custom Initializations.
            });

//Data Row Template of the table.
var dataRowTemplate = {};
dataRowTemplate.InvoiceID = '';
dataRowTemplate.InvoiceDate = '';
dataRowTemplate.IsOverRide = false;
dataRowTemplate.AmountOfInvoice = '';
dataRowTemplate.DateReceived = '';
dataRowTemplate.AmountReceived = '';
dataRowTemplate.CheckNumber = '';

//Add dataRow to the table.
oTable.fnAddData(dataRowTemplate);

Refer Datatables fnAddData Datatables API

How do I convert an integer to binary in JavaScript?

This is my code:

var x = prompt("enter number", "7");
var i = 0;
var binaryvar = " ";

function add(n) {
    if (n == 0) {
        binaryvar = "0" + binaryvar; 
    }
    else {
        binaryvar = "1" + binaryvar;
    }
}

function binary() {
    while (i < 1) {
        if (x == 1) {
            add(1);
            document.write(binaryvar);
            break;
        }
        else {
            if (x % 2 == 0) {
                x = x / 2;
                add(0);
            }
            else {
                x = (x - 1) / 2;
                add(1);
            }
        }
    }
}

binary();

Mongoose, update values in array of objects

In mongoose we can update, like simple array

user.updateInfoByIndex(0,"test")

User.methods.updateInfoByIndex = function(index, info) ={
    this.arrayField[index]=info
    this.save()
}

Difference between Destroy and Delete

Yes there is a major difference between the two methods Use delete_all if you want records to be deleted quickly without model callbacks being called

If you care about your models callbacks then use destroy_all

From the official docs

http://apidock.com/rails/ActiveRecord/Base/destroy_all/class

destroy_all(conditions = nil) public

Destroys the records matching conditions by instantiating each record and calling its destroy method. Each object’s callbacks are executed (including :dependent association options and before_destroy/after_destroy Observer methods). Returns the collection of objects that were destroyed; each will be frozen, to reflect that no changes should be made (since they can’t be persisted).

Note: Instantiation, callback execution, and deletion of each record can be time consuming when you’re removing many records at once. It generates at least one SQL DELETE query per record (or possibly more, to enforce your callbacks). If you want to delete many rows quickly, without concern for their associations or callbacks, use delete_all instead.

How to write to Console.Out during execution of an MSTest test

I had the same issue and I was "Running" the tests. If I instead "Debug" the tests the Debug output shows just fine like all others Trace and Console. I don't know though how to see the output if you "Run" the tests.

Javascript loop through object array?

You can use forEach method to iterate over array of objects.

data.messages.forEach(function(message){
    console.log(message)
});

Refer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

How do I validate a date string format in python?

The Python dateutil library is designed for this (and more). It will automatically convert this to a datetime object for you and raise a ValueError if it can't.

As an example:

>>> from dateutil.parser import parse
>>> parse("2003-09-25")
datetime.datetime(2003, 9, 25, 0, 0)

This raises a ValueError if the date is not formatted correctly:

>>> parse("2003-09-251")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/jacinda/envs/dod-backend-dev/lib/python2.7/site-packages/dateutil/parser.py", line 720, in parse
    return DEFAULTPARSER.parse(timestr, **kwargs)
  File "/Users/jacinda/envs/dod-backend-dev/lib/python2.7/site-packages/dateutil/parser.py", line 317, in parse
    ret = default.replace(**repl)
ValueError: day is out of range for month

dateutil is also extremely useful if you start needing to parse other formats in the future, as it can handle most known formats intelligently and allows you to modify your specification: dateutil parsing examples.

It also handles timezones if you need that.

Update based on comments: parse also accepts the keyword argument dayfirst which controls whether the day or month is expected to come first if a date is ambiguous. This defaults to False. E.g.

>>> parse('11/12/2001')
>>> datetime.datetime(2001, 11, 12, 0, 0) # Nov 12
>>> parse('11/12/2001', dayfirst=True)
>>> datetime.datetime(2001, 12, 11, 0, 0) # Dec 11

Is there a "not equal" operator in Python?

Use != or <>. Both stands for not equal.

The comparison operators <> and != are alternate spellings of the same operator. != is the preferred spelling; <> is obsolescent. [Reference: Python language reference]

JSONDecodeError: Expecting value: line 1 column 1

If you look at the output you receive from print() and also in your Traceback, you'll see the value you get back is not a string, it's a bytes object (prefixed by b):

b'{\n  "note":"This file    .....

If you fetch the URL using a tool such as curl -v, you will see that the content type is

Content-Type: application/json; charset=utf-8

So it's JSON, encoded as UTF-8, and Python is considering it a byte stream, not a simple string. In order to parse this, you need to convert it into a string first.

Change the last line of code to this:

info = json.loads(js.decode("utf-8"))

How to pass url arguments (query string) to a HTTP request on Angular?

Version 5+

With Angular 5 and up, you DON'T have to use HttpParams. You can directly send your json object as shown below.

let data = {limit: "2"};
this.httpClient.get<any>(apiUrl, {params: data});

Please note that data values should be string, ie; { params: {limit: "2"}}

Version 4.3.x+

Use HttpParams, HttpClient from @angular/common/http

import { HttpParams, HttpClient } from '@angular/common/http';
...
constructor(private httpClient: HttpClient) { ... }
...
let params = new HttpParams();
params = params.append("page", 1);
....
this.httpClient.get<any>(apiUrl, {params: params});

Also, try stringifying your nested object using JSON.stringify().

detect back button click in browser

Please try this (if the browser does not support "onbeforeunload"):

jQuery(document).ready(function($) {

  if (window.history && window.history.pushState) {

    $(window).on('popstate', function() {
      var hashLocation = location.hash;
      var hashSplit = hashLocation.split("#!/");
      var hashName = hashSplit[1];

      if (hashName !== '') {
        var hash = window.location.hash;
        if (hash === '') {
          alert('Back button was pressed.');
        }
      }
    });

    window.history.pushState('forward', null, './#forward');
  }

});

How to disable editing of elements in combobox for c#?

This is another method I use because changing DropDownSyle to DropDownList makes it look 3D and sometimes its just plain ugly.

You can prevent user input by handling the KeyPress event of the ComboBox like this.

private void ComboBox1_KeyPress(object sender, KeyPressEventArgs e)
{
      e.Handled = true;
}

How to build and run Maven projects after importing into Eclipse IDE

answer 1

  1. Right click on your project in eclipse
  2. go to maven -> Update Project

answer 2

simply press Alt+F5 after updating your pom.xml. This will build your project again and download all jar files

How can the Euclidean distance be calculated with NumPy?

import numpy as np
# any two python array as two points
a = [0, 0]
b = [3, 4]

You first change list to numpy array and do like this: print(np.linalg.norm(np.array(a) - np.array(b))). Second method directly from python list as: print(np.linalg.norm(np.subtract(a,b)))

How to Empty Caches and Clean All Targets Xcode 4 and later

You have to be careful about the xib file. I tried all the above and nothing worked for me. I was using custom UIButtons defined in the xib, and realized it might be related to the fact that I had assigned attributes there which were not changing programmatically. If you've defined images or text there, remove them. When I did, my programmatic changes began to take effect.

Change language for bootstrap DateTimePicker

Try this:

$( ".form_datetime" ).datepicker( $.datepicker.regional[ "zh-CN" ], { dateFormat: 'dd.mm.yyyy hh:ii' });

is it possible to add colors to python output?

IDLE's console does not support ANSI escape sequences, or any other form of escapes for coloring your output.

You can learn how to talk to IDLE's console directly instead of just treating it like normal stdout and printing to it (which is how it does things like color-coding your syntax), but that's pretty complicated. The idle documentation just tells you the basics of using IDLE itself, and its idlelib library has no documentation (well, there is a single line of documentation—"(New in 2.3) Support library for the IDLE development environment."—if you know where to find it, but that isn't very helpful). So, you need to either read the source, or do a whole lot of trial and error, to even get started.


Alternatively, you can run your script from the command line instead of from IDLE, in which case you can use whatever escape sequences your terminal handles. Most modern terminals will handle at least basic 16/8-color ANSI. Many will handle 16/16, or the expanded xterm-256 color sequences, or even full 24-bit colors. (I believe gnome-terminal is the default for Ubuntu, and in its default configuration it will handle xterm-256, but that's really a question for SuperUser or AskUbuntu.)

Learning to read the termcap entries to know which codes to enter is complicated… but if you only care about a single console—or are willing to just assume "almost everything handles basic 16/8-color ANSI, and anything that doesn't, I don't care about", you can ignore that part and just hardcode them based on, e.g., this page.

Once you know what you want to emit, it's just a matter of putting the codes in the strings before printing them.

But there are libraries that can make this all easier for you. One really nice library, which comes built in with Python, is curses. This lets you take over the terminal and do a full-screen GUI, with colors and spinning cursors and anything else you want. It is a little heavy-weight for simple uses, of course. Other libraries can be found by searching PyPI, as usual.

Laravel Mail::send() sending to multiple to or bcc addresses

With Laravel 5.6, if you want pass multiple emails with names, you need to pass array of associative arrays. Example pushing multiple recipients into the $to array:

$to[] = array('email' => $email, 'name' => $name);

Fixed two recipients:

$to = [['email' => '[email protected]', 'name' => 'User One'], 
       ['email' => '[email protected]', 'name' => 'User Two']];

The 'name' key is not mandatory. You can set it to 'name' => NULL or do not add to the associative array, then only 'email' will be used.

Eclipse Optimize Imports to Include Static Imports

Not exactly what I wanted, but I found a workaround. In Eclipse 3.4 (Ganymede), go to

Window->Preferences->Java->Editor->Content Assist

and check the checkbox for Use static imports (only 1.5 or higher).

This will not bring in the import on an Optimize Imports, but if you do a Quick Fix (CTRL + 1) on the line it will give you the option to add the static import which is good enough.

MySQL - length() vs char_length()

LENGTH() returns the length of the string measured in bytes.
CHAR_LENGTH() returns the length of the string measured in characters.

This is especially relevant for Unicode, in which most characters are encoded in two bytes. Or UTF-8, where the number of bytes varies. For example:

select length(_utf8 '€'), char_length(_utf8 '€')
--> 3, 1

As you can see the Euro sign occupies 3 bytes (it's encoded as 0xE282AC in UTF-8) even though it's only one character.

disable past dates on datepicker

Try this'
 <link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>

    <!-- table -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css">
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
    <!-- end table -->

    <script>
       $(function() {
        $('#example').DataTable();
        $("#from_date").datepicker({
            dateFormat: "mm/d/yy",
            maxDate: 0,

            onSelect: function () {



                var minDate = $(this).datepicker('getDate');

                $('#to_date').datepicker('setDate', minDate);
                $('#to_date').datepicker('option', 'maxDate', 0);
                $('#to_date').datepicker('option', 'minDate', minDate);
            }
        });
        $('#to_date').datepicker({
            dateFormat: "mm/d/yy"
        });

       });
       </script><link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>

    <!-- table -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css">
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
    <!-- end table -->

    <script>
       $(function() {
        $('#example').DataTable();
        $("#from_date").datepicker({
            dateFormat: "mm/d/yy",
            maxDate: 0,

            onSelect: function () {



                var minDate = $(this).datepicker('getDate');

                $('#to_date').datepicker('setDate', minDate);
                $('#to_date').datepicker('option', 'maxDate', 0);
                $('#to_date').datepicker('option', 'minDate', minDate);
            }
        });
        $('#to_date').datepicker({
            dateFormat: "mm/d/yy"
        });

       });
       </script><link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>

    <!-- table -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css">
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
    <!-- end table -->

    <script>
       $(function() {
        $('#example').DataTable();
        $("#from_date").datepicker({
            dateFormat: "mm/d/yy",
            maxDate: 0,

            onSelect: function () {



                var minDate = $(this).datepicker('getDate');

                $('#to_date').datepicker('setDate', minDate);
                $('#to_date').datepicker('option', 'maxDate', 0);
                $('#to_date').datepicker('option', 'minDate', minDate);
            }
        });
        $('#to_date').datepicker({
            dateFormat: "mm/d/yy"
        });

       });
       </script><link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>

    <!-- table -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css">
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
    <!-- end table -->

    <script>
       $(function() {
        $('#example').DataTable();
        $("#from_date").datepicker({
            dateFormat: "mm/d/yy",
            maxDate: 0,

            onSelect: function () {



                var minDate = $(this).datepicker('getDate');

                $('#to_date').datepicker('setDate', minDate);
                $('#to_date').datepicker('option', 'maxDate', 0);
                $('#to_date').datepicker('option', 'minDate', minDate);
            }
        });
        $('#to_date').datepicker({
            dateFormat: "mm/d/yy"
        });

       });
       </script><link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>

    <!-- table -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css">
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
    <!-- end table -->

    <script>
       $(function() {
        $('#example').DataTable();
        $("#from_date").datepicker({
            dateFormat: "mm/d/yy",
            maxDate: 0,

            onSelect: function () {



                var minDate = $(this).datepicker('getDate');

                $('#to_date').datepicker('setDate', minDate);
                $('#to_date').datepicker('option', 'maxDate', 0);
                $('#to_date').datepicker('option', 'minDate', minDate);
            }
        });
        $('#to_date').datepicker({
            dateFormat: "mm/d/yy"
        });

       });
       </script>

Throughput and bandwidth difference?

Here is another example to help you imagine what the difference could be depending on the situation.

Imagine

  • You have a 1 MB file (say a photo) that you would like to share with 3 friends.
  • Each of them, however, uses different cloud storage application - Google Drive, Microsoft OneDrive and Dropbox. Therefore they all create a folder and give you access so you can upload the file to their folder.
  • You open the URLs to these three folders in your browser (say in 3 different tabs) and drag-n-drop the file (more or less at the same time) to each tab so to upload it.
  • You are connected to the Internet via a fiber-optic cable which gives you the ability to transfer at speed of 1 Gb per second (i.e. this is your bandwidth - the max capacity that you can utilise your connection).

Knowing that, theoretically (assuming no data lost, no big protocol overhead, connection to the cloud storage services offers at least the same bandwidth, etc.) you can transfer one 1 MB file over the 1 Gbps connection for roughly: 1MB / 1 Gbps = 1 x 10^3 x 8 / 1x10^9 which gives about 8x10^-6 seconds or say roughly 10 ms. Now, you have 1 file that you want to upload to 3 destinations, your connection bandwidth is big enough so you can transfer the same file to 3 destinations at the same time (we can also assume you have a modern laptop equipped with multi-core CPU so data transfer over the 3 connections to Google Drive, MS OneDrive and Dropbox can be done in parallel). Therefore, instead of waiting for 30ms to transfer the same file to 3 different destinations you only have to wait for 10ms as you have a very good bandwidth.

Now let's consider what protocol is being used and what implications that brings. As you use your browser to upload the file, the protocol that is being used is HTTP/S which is running on top of the TCP protocol. An important property of the TCP protocol is that it makes sure that a batch of data has reached any destination successfully before sending the next batch of data. That is being done by the TCP sender waiting for acknowledgement (for short an ACK) that the first batch of data has been received before it starts sending the second batch of data. What this means is that if it takes 0.5s to transfer 1 batch of data one direction and then 0.5s to received an ACK then you need to wait for 1 second until 1 batch of data is transferred and successfully confirmed to have been received (again, let's assume no data lost, therefore no need to re-transfer the same batch). Because of this round trip needed by the TCP protocol there appears to be a blocker. The blocker is the delay you experience for one round trip which includes transferring 1 batch of data and its successful acknowledgement. With that in mind we need to see how big is one batch of data. This can vary but it's usually 64KB. So your actual traffic to 1 destination (i.e, the throughput) is bound by this delay (i.e., latency) and the batch size by the following equation:

throughput = batch size / latency

In our example the throughput is 64KB/s and as we can split 1 MB in roughly 15.6 batches of 64KB size, you will need about 15.6 seconds to transfer 1 MB of file. That is a major slowdown compared to the bandwidth-only based calculations we made early.

javascript push multidimensional array

Arrays must have zero based integer indexes in JavaScript. So:

var valueToPush = new Array();
valueToPush[0] = productID;
valueToPush[1] = itemColorTitle;
valueToPush[2] = itemColorPath;
cookie_value_add.push(valueToPush);

Or maybe you want to use objects (which are associative arrays):

var valueToPush = { }; // or "var valueToPush = new Object();" which is the same
valueToPush["productID"] = productID;
valueToPush["itemColorTitle"] = itemColorTitle;
valueToPush["itemColorPath"] = itemColorPath;
cookie_value_add.push(valueToPush);

which is equivalent to:

var valueToPush = { };
valueToPush.productID = productID;
valueToPush.itemColorTitle = itemColorTitle;
valueToPush.itemColorPath = itemColorPath;
cookie_value_add.push(valueToPush);

It's a really fundamental and crucial difference between JavaScript arrays and JavaScript objects (which are associative arrays) that every JavaScript developer must understand.

Assign an initial value to radio button as checked

Note that if you have two radio button with same "name" attribute and they have "required" attribute, then adding "checked" attribute to them won't make them checked.

Example: This makes both radio button remain unchecked.

<input type="radio" name="gender" value="male" required <?php echo "checked"; ?>/>
<input type="radio" name="gender" value="female" required />

This will makes the "male" radio button checked.

<input type="radio" name="gender" value="male" <?php echo "checked"; ?>/>
<input type="radio" name="gender" value="female" />

How to gzip all files in all sub-directories into one compressed file in bash

tar -zcvf compressFileName.tar.gz folderToCompress

everything in folderToCompress will go to compressFileName

Edit: After review and comments I realized that people may get confused with compressFileName without an extension. If you want you can use .tar.gz extension(as suggested) with the compressFileName

Regex Explanation ^.*$

"^.*$"

literally just means select everything

"^"  // anchors to the beginning of the line
".*" // zero or more of any character
"$"  // anchors to end of line

UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory'

Well, you're getting a java.lang.NoClassDefFoundError. In your pom.xml, hibernate-core version is 3.3.2.GA and declared after hibernate-entitymanager, so it prevails. You can remove that dependency, since will be inherited version 3.6.7.Final from hibernate-entitymanager.

You're using spring-boot as parent, so no need to declare version of some dependencies, since they are managed by spring-boot.

Also, hibernate-commons-annotations is inherited from hibernate-entitymanager and hibernate-annotations is an old version of hibernate-commons-annotations, you can remove both.

Finally, your pom.xml can look like this:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.elsys.internetprogramming.trafficspy.server</groupId>
    <artifactId>TrafficSpyService</artifactId>
    <version>0.1.0</version>

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

    <dependencies>
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cloud-connectors</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>javax.persistence</artifactId>
            <version>2.0.0</version>
        </dependency>

        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
        </dependency>

        <!-- MySQL -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>

    <properties>
        <java.version>1.7</java.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </repository>

        <repository>
            <id>codehaus</id>
            <url>http://repository.codehaus.org/org/codehaus</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </pluginRepository>
    </pluginRepositories>

</project>

Let me know if you have a problem.

Create autoincrement key in Java DB using NetBeans IDE

This may help you:

CREATE TABLE "custinf"

(    
   "CUST_ID" INT not null primary key
        GENERATED ALWAYS AS IDENTITY
        (START WITH 1, INCREMENT BY 1),   
   "FNAME" VARCHAR(50),     
   "LNAME" VARCHAR(50),
   "ADDR" VARCHAR(100),
   "SUBURB" VARCHAR(20),
   "PCODE" INTEGER,  
   "PHONE" INTEGER,
   "MOB" INTEGER,    
   "EMAIL" VARCHAR(100),
   "COMM" VARCHAR(450)    
);

That's how i got mine to work... to ages to get the frigging thing to actually understand me but that's the nature of code :D

BTW!- There is a way to do it in the ide interface goto the services window, expand your connection, expand your projects name, expand tables, right click indexes and select add index... the rest of the process speaks for itself really...

What is REST call and how to send a REST call?

REST is just a software architecture style for exposing resources.

  • Use HTTP methods explicitly.
  • Be stateless.
  • Expose directory structure-like URIs.
  • Transfer XML, JavaScript Object Notation (JSON), or both.

A typical REST call to return information about customer 34456 could look like:

http://example.com/customer/34456

Have a look at the IBM tutorial for REST web services

Using reflection in Java to create a new instance with the reference variable type set to the new instance class name?

If you knew the Class of ImplementationType you could create an instance of it. So what you are trying to do is not possible.

Subtract two variables in Bash

You can use:

((count = FIRSTV - SECONDV))

to avoid invoking a separate process, as per the following transcript:

pax:~$ FIRSTV=7
pax:~$ SECONDV=2
pax:~$ ((count = FIRSTV - SECONDV))
pax:~$ echo $count
5

Proper use of mutexes in Python

You have to unlock your Mutex at sometime...

Twitter Bootstrap 3, vertically center content

Option 1 is to use display:table-cell. You need to unfloat the Bootstrap col-* using float:none..

.center {
    display:table-cell;
    vertical-align:middle;
    float:none;
}

http://bootply.com/94394


Option 2 is display:flex to vertical align the row with flexbox:

.row.center {
   display: flex;
   align-items: center;
}

http://www.bootply.com/7rAuLpMCwr


Vertical centering is very different in Bootstrap 4. See this answer for Bootstrap 4 https://stackoverflow.com/a/41464397/171456

Warning: #1265 Data truncated for column 'pdd' at row 1

You are most likely pushing a string 'NULL' to the table, rather then an actual NULL, but other things may be going on as well, an illustration:

mysql> CREATE TABLE date_test (pdd DATE NOT NULL);
Query OK, 0 rows affected (0.11 sec)

mysql> INSERT INTO date_test VALUES (NULL);
ERROR 1048 (23000): Column 'pdd' cannot be null
mysql> INSERT INTO date_test VALUES ('NULL');
Query OK, 1 row affected, 1 warning (0.05 sec)

mysql> show warnings;
+---------+------+------------------------------------------+
| Level   | Code | Message                                  |
+---------+------+------------------------------------------+
| Warning | 1265 | Data truncated for column 'pdd' at row 1 |
+---------+------+------------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT * FROM date_test;
+------------+
| pdd        |
+------------+
| 0000-00-00 |
+------------+
1 row in set (0.00 sec)

mysql> ALTER TABLE date_test MODIFY COLUMN pdd DATE NULL;
Query OK, 1 row affected (0.15 sec)
Records: 1  Duplicates: 0  Warnings: 0

mysql> INSERT INTO date_test VALUES (NULL);
Query OK, 1 row affected (0.06 sec)

mysql> SELECT * FROM date_test;
+------------+
| pdd        |
+------------+
| 0000-00-00 |
| NULL       |
+------------+
2 rows in set (0.00 sec)

How to add a class to body tag?

You can extract that part of the URL using a simple regular expression:

var url = location.href;
var className = url.match(/\w+\/(\w+)_/)[1];
$('body').addClass(className);

How to establish ssh key pair when "Host key verification failed"

Task Passwordless authentication for suer.

Error : Host key verification failed.

Source :10.13.1.11 Target : 10.13.1.35

Temporary workaround :

[user@server~]$ ssh [email protected] The authenticity of host '10.13.1.35 (10.13.1.35)' can't be established. RSA key fingerprint is b8:ba:30:46:a9:ab:70:12:1a:f2:f1:61:69:73:0a:19. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added '10.13.1.35' (RSA) to the list of known hosts.

Try to authenticate user again...it will work.

What is the best practice for creating a favicon on a web site?

I used https://iconifier.net I uploaded my image, downloaded images zip file, added images to my server, followed the directions on the site including adding the links to my index.html and it worked. My favicon now shows on my iPhone in Safari when 'Add to home screen'

How do I make an Android EditView 'Done' button and hide the keyboard when clicked?

If the property does not change for the widget it may be better to use like android:imeOptions="actionDone" in the layout xml file.

Function of Project > Clean in Eclipse

I also faced the same issue with Eclipse when I ran the clean build with Maven, but there is a simple solution for this issue. We just need to run Maven update and then build or direct run the application. I hope it will solve the problem.

Use <Image> with a local file

We can do like below:

const item= {
    image: require("../../assets/dashboard/project1.jpeg"),
    location: "Chennai",
    status: 1,
    projectId: 1
}




<Image source={item.image} style={[{ width: 150, height: 150}]} />

Including non-Python files with setup.py

In setup.py under setup( :

setup(
   name = 'foo library'
   ...
  package_data={
   'foolibrary.folderA': ['*'],     # All files from folder A
   'foolibrary.folderB': ['*.txt']  #All text files from folder B
   },

Failed binder transaction when putting an bitmap dynamically in a widget

See my answer in this thread.

intent.putExtra("Some string",very_large_obj_for_binder_buffer);

You are exceeding the binder transaction buffer by transferring large element(s) from one activity to another activity.

Need to perform Wildcard (*,?, etc) search on a string using Regex

You may want to use WildcardPattern from System.Management.Automation assembly. See my answer here.

mat-form-field must contain a MatFormFieldControl

If all of the main code structure/configuration answers above don't solve your issue, here's one more thing to check: make sure that you haven't in some way invalidated your <input> tag.

For instance, I received the same mat-form-field must contain a MatFormFieldControl error message after accidentally putting a required attribute after a self-closing slash /, which effectively invalidated my <input/>. In other words, I did this (see the end of the input tag attributes):

wrong:

<input matInput type="text" name="linkUrl" [formControl]="listingForm.controls['linkUrl']" /required>

right:

<input matInput type="text" name="linkUrl" [formControl]="listingForm.controls['linkUrl']" required/>

If you make that mistake or something else to invalidate your <input>, then you could get the mat-form-field must contain a MatFormFieldControl error. Anyway, this is just one more thing to look for as you're debugging.

How do you run JavaScript script through the Terminal?

I tried researching that too but instead ended up using jsconsole.com by Remy Sharp (he also created jsbin.com). I'm running on Ubuntu 12.10 so I had to create a special icon but if you're on Windows and use Chrome simply go to Tools>Create Application Shortcuts (note this doesn't work very well, or at all in my case, on Ubuntu). This site works very like the Mac jsc console: actually it has some cool features too (like loading libraries/code from a URL) that I guess jsc does not.

Hope this helps.

vba listbox multicolumn add

Simplified example (with counter):

With Me.lstbox
    .ColumnCount = 2
    .ColumnWidths = "60;60"
    .AddItem
    .List(i, 0) = Company_ID
    .List(i, 1) = Company_name 
    i = i + 1

end with

Make sure to start the counter with 0, not 1 to fill up a listbox.

Running code in main thread from another thread

So most handy is to do sort of:

import android.os.AsyncTask
import android.os.Handler
import android.os.Looper

object Dispatch {
    fun asyncOnBackground(call: ()->Unit) {
        AsyncTask.execute {
            call()
        }
    }

    fun asyncOnMain(call: ()->Unit) {
        Handler(Looper.getMainLooper()).post {
            call()
        }
    }
}

And after:

Dispatch.asyncOnBackground {
    val value = ...// super processing
    Dispatch.asyncOnMain { completion(value)}
}

Is there an equivalent of lsusb for OS X

On Mac OS X, the Xcode developer suite includes the USB Proper.app application. This is found in /Developer/Applications/Utilities/. USB Prober will allow you to examine the device and interface descriptors.

Eclipse: How to install a plugin manually?

  1. Download your plugin
  2. Open Eclipse
  3. From the menu choose: Help / Install New Software...
  4. Click the Add button
  5. In the Add Repository dialog that appears, click the Archive button next to the Location field
  6. Select your plugin file, click OK

You could also just copy plugins to the eclipse/plugins directory, but it's not recommended.

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

simply write:

if(values > 0){
//positive
}
else{
//negative
}

open program minimized via command prompt

Try:

start  "" "C:\Program Files (x86)\Microsoft Office\Office12\WINWORD.EXE" --new-window/min

I had the same problem, but I was trying to open chrome.exe maximized. If I put the /min anywhere else in the command line, like before or after the empty title, it was ignored.

How to "select distinct" across multiple data frame columns in pandas?

There is no unique method for a df, if the number of unique values for each column were the same then the following would work: df.apply(pd.Series.unique) but if not then you will get an error. Another approach would be to store the values in a dict which is keyed on the column name:

In [111]:
df = pd.DataFrame({'a':[0,1,2,2,4], 'b':[1,1,1,2,2]})
d={}
for col in df:
    d[col] = df[col].unique()
d

Out[111]:
{'a': array([0, 1, 2, 4], dtype=int64), 'b': array([1, 2], dtype=int64)}

Compare every item to every other item in ArrayList

What's the problem with using for loop inside, just like outside?

for (int j = i + 1; j < list.size(); ++j) {
    ...
}

In general, since Java 5, I used iterators only once or twice.

Is there something like Codecademy for Java

Check out javapassion, they have a number of courses that encompass web programming, and were free (until circumstances conspired to make the website need to support itself).

Even with the nominal fee, you get a lot for an entire year. It's a bargain compared to the amount of time you'll be investing.

The other options are to look to Oracle's online tutorials, they lack the glitz of Codeacademy, but are surprisingly good. I haven't read the one on web programming, that might be embedded in the Java EE tutorial(s), which is not tuned for a new beginner to Java.

How to frame two for loops in list comprehension python

The appropriate LC would be

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

The order of the loops in the LC is similar to the ones in nested loops, the if statements go to the end and the conditional expressions go in the beginning, something like

[a if a else b for a in sequence]

See the Demo -

>>> tags = [u'man', u'you', u'are', u'awesome']
>>> entries = [[u'man', u'thats'],[ u'right',u'awesome']]
>>> [entry for tag in tags for entry in entries if tag in entry]
[[u'man', u'thats'], [u'right', u'awesome']]
>>> result = []
    for tag in tags:
        for entry in entries:
            if tag in entry:
                result.append(entry)


>>> result
[[u'man', u'thats'], [u'right', u'awesome']]

EDIT - Since, you need the result to be flattened, you could use a similar list comprehension and then flatten the results.

>>> result = [entry for tag in tags for entry in entries if tag in entry]
>>> from itertools import chain
>>> list(chain.from_iterable(result))
[u'man', u'thats', u'right', u'awesome']

Adding this together, you could just do

>>> list(chain.from_iterable(entry for tag in tags for entry in entries if tag in entry))
[u'man', u'thats', u'right', u'awesome']

You use a generator expression here instead of a list comprehension. (Perfectly matches the 79 character limit too (without the list call))

How can I open a URL in Android's web browser from my application?

So I've looked for this for a long time because all the other answers were opening default app for that link, but not default browser and that's what I wanted.

I finally managed to do so:

// gathering the default browser
final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://"));
final ResolveInfo resolveInfo = context.getPackageManager()
    .resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
String defaultBrowserPackageName = resolveInfo.activityInfo.packageName;


final Intent intent2 = new Intent(Intent.ACTION_VIEW);
intent2.setData(Uri.parse(url));

if (!defaultBrowserPackageName.equals("android") {
    // android = no default browser is set 
    // (android < 6 or fresh browser install or simply no default set)
    // if it's the case (not in this block), it will just use normal way.
    intent2.setPackage(defaultBrowserPackageName);
}

context.startActivity(intent2);

BTW, you can notice context.whatever, because I've used this for a static util method, if you are doing this in an activity, it's not needed.

Using Python, find anagrams for a list of words

here is the impressive solution.

funct alphabet_count_mapper:

for each word in the file/list

1.create a dictionary of alphabets/characters with initial count as 0.

2.keep count of all the alphabets in the word and increment the count in the above alphabet dict.

3.create alphabet count dict and return the tuple of the values of alphabet dict.

funct anagram_counter:

1.create a dictionary with alphabet count tuple as key and the count of the number of occurences against it.

2.iterate over the above dict and if the value > 1, add the value to the anagram count.

    import sys
    words_count_map_dict = {}
    fobj = open(sys.argv[1],"r")
    words = fobj.read().split('\n')[:-1]

    def alphabet_count_mapper(word):
        alpha_count_dict = dict(zip('abcdefghijklmnopqrstuvwxyz',[0]*26))
        for alpha in word:
            if alpha in alpha_count_dict.keys():
                alpha_count_dict[alpha] += 1
            else:
                alpha_count_dict.update(dict(alpha=0))
        return tuple(alpha_count_dict.values())

    def anagram_counter(words):
        anagram_count = 0
        for word in words:
            temp_mapper = alphabet_count_mapper(word)
            if temp_mapper in words_count_map_dict.keys():
                words_count_map_dict[temp_mapper] += 1
            else:
                words_count_map_dict.update({temp_mapper:1})
        for val in words_count_map_dict.values():
            if val > 1:
                anagram_count += val
        return anagram_count


    print anagram_counter(words)

run it with file path as command line argument

UPDATE multiple tables in MySQL using LEFT JOIN

UPDATE  t1
LEFT JOIN
        t2
ON      t2.id = t1.id
SET     t1.col1 = newvalue
WHERE   t2.id IS NULL

Note that for a SELECT it would be more efficient to use NOT IN / NOT EXISTS syntax:

SELECT  t1.*
FROM    t1
WHERE   t1.id NOT IN
        (
        SELECT  id
        FROM    t2
        )

See the article in my blog for performance details:

Unfortunately, MySQL does not allow using the target table in a subquery in an UPDATE statement, that's why you'll need to stick to less efficient LEFT JOIN syntax.

Newline in markdown table?

When you're exporting to HTML, using <br> works. However, if you're using pandoc to export to LaTeX/PDF as well, you should use grid tables:

+---------------+---------------+--------------------+
| Fruit         | Price         | Advantages         |
+===============+===============+====================+
| Bananas       | first line\   | first line\        |
|               | next line     | next line          |
+---------------+---------------+--------------------+
| Bananas       | first line\   | first line\        |
|               | next line     | next line          |
+---------------+---------------+--------------------+

How do I initialize a TypeScript Object with a JSON-Object?

you can do like below

export interface Instance {
  id?:string;
  name?:string;
  type:string;
}

and

var instance: Instance = <Instance>({
      id: null,
      name: '',
      type: ''
    });

Maven artifact and groupId naming

Consider following as for building basic first Maven application:

groupId

  • com.companyname.project

artifactId

  • project

version

  • 0.0.1

iPhone UILabel text soft shadow

In Swift 3, you can create an extension:

import UIKit

extension UILabel {
    func shadow() {
        self.layer.shadowColor = self.textColor.cgColor
        self.layer.shadowOffset = CGSize.zero
        self.layer.shadowRadius = 3.0
        self.layer.shadowOpacity = 0.5
        self.layer.masksToBounds = false
        self.layer.shouldRasterize = true
    }
}

and use it via:

label.shadow()

How to chain scope queries with OR instead of AND?

If you're looking to provide a scope (instead of explicitly working on the whole dataset) here's what you should do with Rails 5:

scope :john_or_smith, -> { where(name: "John").or(where(lastname: "Smith")) }

Or:

def self.john_or_smith
  where(name: "John").or(where(lastname: "Smith"))
end

'module' object is not callable - calling method in another file

The problem is in the import line. You are importing a module, not a class. Assuming your file is named other_file.py (unlike java, again, there is no such rule as "one class, one file"):

from other_file import findTheRange

if your file is named findTheRange too, following java's convenions, then you should write

from findTheRange import findTheRange

you can also import it just like you did with random:

import findTheRange
operator = findTheRange.findTheRange()

Some other comments:

a) @Daniel Roseman is right. You do not need classes here at all. Python encourages procedural programming (when it fits, of course)

b) You can build the list directly:

  randomList = [random.randint(0, 100) for i in range(5)]

c) You can call methods in the same way you do in java:

largestInList = operator.findLargest(randomList)
smallestInList = operator.findSmallest(randomList)

d) You can use built in function, and the huge python library:

largestInList = max(randomList)
smallestInList = min(randomList)

e) If you still want to use a class, and you don't need self, you can use @staticmethod:

class findTheRange():
    @staticmethod
    def findLargest(_list):
        #stuff...

Sourcetree - undo unpushed commits

  1. Right click on the commit you like to reset to (not the one you like to delete!)
  2. Select "Reset master to this commit"
  3. Select "Soft" reset.

A soft reset will keep your local changes.

Source: https://answers.atlassian.com/questions/153791/how-should-i-remove-push-commit-from-sourcetree

Edit

About git revert: This command creates a new commit which will undo other commits. E.g. if you have a commit which adds a new file, git revert could be used to make a commit which will delete the new file.

About applying a soft reset: Assume you have the commits A to E (A---B---C---D---E) and you like to delete the last commit (E). Then you can do a soft reset to commit D. With a soft reset commit E will be deleted from git but the local changes will be kept. There are more examples in the git reset documentation.

Java difference between FileWriter and BufferedWriter

BufferedWriter is more efficient if you

  • have multiple writes between flush/close
  • the writes are small compared with the buffer size.

In your example, you have only one write, so the BufferedWriter just add overhead you don't need.

so does that mean the first example writes the characters one by one and the second first buffers it to the memory and writes it once

In both cases, the string is written at once.

If you use just FileWriter your write(String) calls

 public void write(String str, int off, int len) 
        // some code
        str.getChars(off, (off + len), cbuf, 0);
        write(cbuf, 0, len);
 }

This makes one system call, per call to write(String).


Where BufferedWriter improves efficiency is in multiple small writes.

for(int i = 0; i < 100; i++) {
    writer.write("foorbar");
    writer.write(NEW_LINE);
}
writer.close();

Without a BufferedWriter this could make 200 (2 * 100) system calls and writes to disk which is inefficient. With a BufferedWriter, these can all be buffered together and as the default buffer size is 8192 characters this become just 1 system call to write.

AngularJS format JSON string output

Angular has a built-in filter for showing JSON

<pre>{{data | json}}</pre>

Note the use of the pre-tag to conserve whitespace and linebreaks

Demo:

_x000D_
_x000D_
angular.module('app', [])_x000D_
  .controller('Ctrl', ['$scope',_x000D_
    function($scope) {_x000D_
_x000D_
      $scope.data = {_x000D_
        a: 1,_x000D_
        b: 2,_x000D_
        c: {_x000D_
          d: "3"_x000D_
        },_x000D_
      };_x000D_
_x000D_
    }_x000D_
  ]);
_x000D_
<!DOCTYPE html>_x000D_
<html ng-app="app">_x000D_
_x000D_
  <head>_x000D_
    <script data-require="[email protected]" data-semver="1.2.15" src="//code.angularjs.org/1.2.15/angular.js"></script>_x000D_
  </head>_x000D_
_x000D_
  <body ng-controller="Ctrl">_x000D_
    <pre>{{data | json}}</pre>_x000D_
  </body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

There's also an angular.toJson method, but I haven't played around with that (Docs)

Selecting Values from Oracle Table Variable / Array?

The sql array type is not neccessary. Not if the element type is a primitive one. (Varchar, number, date,...)

Very basic sample:

declare
  type TPidmList is table of sgbstdn.sgbstdn_pidm%type;
  pidms TPidmList;
begin
  select distinct sgbstdn_pidm
  bulk collect into pidms
  from sgbstdn
  where sgbstdn_majr_code_1 = 'HS04'
  and sgbstdn_program_1 = 'HSCOMPH';

  -- do something with pidms

  open :someCursor for
    select value(t) pidm
    from table(pidms) t;
end;

When you want to reuse it, then it might be interesting to know how that would look like. If you issue several commands than those could be grouped in a package. The private package variable trick from above has its downsides. When you add variables to a package, you give it state and now it doesn't act as a stateless bunch of functions but as some weird sort of singleton object instance instead.

e.g. When you recompile the body, it will raise exceptions in sessions that already used it before. (because the variable values got invalided)

However, you could declare the type in a package (or globally in sql), and use it as a paramter in methods that should use it.

create package Abc as
  type TPidmList is table of sgbstdn.sgbstdn_pidm%type;

  function CreateList(majorCode in Varchar, 
                      program in Varchar) return TPidmList;

  function Test1(list in TPidmList) return PLS_Integer;
  -- "in" to make it immutable so that PL/SQL can pass a pointer instead of a copy
  procedure Test2(list in TPidmList);
end;

create package body Abc as

  function CreateList(majorCode in Varchar, 
                      program in Varchar) return TPidmList is
    result TPidmList;
  begin
    select distinct sgbstdn_pidm
    bulk collect into result
    from sgbstdn
    where sgbstdn_majr_code_1 = majorCode
    and sgbstdn_program_1 = program;

    return result;
  end;

  function Test1(list in TPidmList) return PLS_Integer is
    result PLS_Integer := 0;
  begin
    if list is null or list.Count = 0 then
      return result;
    end if;

    for i in list.First .. list.Last loop
      if ... then
        result := result + list(i);
      end if;
    end loop;
  end;

  procedure Test2(list in TPidmList) as
  begin
    ...
  end;

  return result;
end;

How to call it:

declare
  pidms constant Abc.TPidmList := Abc.CreateList('HS04', 'HSCOMPH');
  xyz PLS_Integer;
begin
  Abc.Test2(pidms);
  xyz := Abc.Test1(pidms);
  ...

  open :someCursor for
    select value(t) as Pidm,
           xyz as SomeValue
    from   table(pidms) t;
end;

How to increase image size of pandas.DataFrame.plot in jupyter notebook?

Try this:

import matplotlib as plt

after importing the file we can use matplotlib library but remember to use it as plt

df.plt(kind='line',figsize=(10,5))

after that the plot will be done and size increased. In figsize the 10 is for breadth and 5 is for height. Also other attributes can be added to the plot too.

Render partial from different folder (not shared)

I've created a workaround that seems to be working pretty well. I found the need to switch to the context of a different controller for action name lookup, view lookup, etc. To implement this, I created a new extension method for HtmlHelper:

public static IDisposable ControllerContextRegion(
    this HtmlHelper html, 
    string controllerName)
{
    return new ControllerContextRegion(html.ViewContext.RouteData, controllerName);
}

ControllerContextRegion is defined as:

internal class ControllerContextRegion : IDisposable
{
    private readonly RouteData routeData;
    private readonly string previousControllerName;

    public ControllerContextRegion(RouteData routeData, string controllerName)
    {
        this.routeData = routeData;
        this.previousControllerName = routeData.GetRequiredString("controller");
        this.SetControllerName(controllerName);
    }

    public void Dispose()
    {
        this.SetControllerName(this.previousControllerName);
    }

    private void SetControllerName(string controllerName)
    {
        this.routeData.Values["controller"] = controllerName;
    }
}

The way this is used within a view is as follows:

@using (Html.ControllerContextRegion("Foo")) {
    // Html.Action, Html.Partial, etc. now looks things up as though
    // FooController was our controller.
}

There may be unwanted side effects for this if your code requires the controller route component to not change, but in our code so far, there doesn't seem to be any negatives to this approach.

Why is there no Char.Empty like String.Empty?

The same reason there isn't an int.Empty. Containers can be empty, scalar values cannot. If you mean 0 (which is not empty), then use '\0'. If you mean null, then use null :)

Android - styling seek bar

Android seekbar custom material style, for other seekbar customizations http://www.zoftino.com/android-seekbar-and-custom-seekbar-examples

<style name="MySeekBar" parent="Widget.AppCompat.SeekBar">
    <item name="android:progressBackgroundTint">#f4511e</item>
    <item name="android:progressTint">#388e3c</item>
    <item name="android:colorControlActivated">#c51162</item>
</style>

seekbar custom material style

How do I count cells that are between two numbers in Excel?

If you have Excel 2007 or later use COUNTIFS with an "S" on the end, i.e.

=COUNTIFS(B2:B292,">10",B2:B292,"<10000")

You may need to change commas , to semi-colons ;

In earlier versions of excel use SUMPRODUCT like this

=SUMPRODUCT((B2:B292>10)*(B2:B292<10000))

Note: if you want to include exactly 10 change > to >= - similarly with 10000, change < to <=

How can I run Tensorboard on a remote server?

You don't need to do anything fancy. Just run:

tensorboard --host 0.0.0.0 <other args here>

and connect with your server url and port. The --host 0.0.0.0 tells tensorflow to listen from connections on all IPv4 addresses on the local machine.

What is recursion and when should I use it?

You want to use it anytime you have a tree structure. It is very useful in reading XML.

Defining a variable with or without export

As you might already know, UNIX allows processes to have a set of environment variables, which are key/value pairs, both key and value being strings. Operating system is responsible for keeping these pairs for each process separately.

Program can access its environment variables through this UNIX API:

  • char *getenv(const char *name);
  • int setenv(const char *name, const char *value, int override);
  • int unsetenv(const char *name);

Processes also inherit environment variables from parent processes. Operating system is responsible for creating a copy of all "envars" at the moment the child process is created.

Bash, among other shells, is capable of setting its environment variables on user request. This is what export exists for.

export is a Bash command to set environment variable for Bash. All variables set with this command would be inherited by all processes that this Bash would create.

More on Environment in Bash

Another kind of variable in Bash is internal variable. Since Bash is not just interactive shell, it is in fact a script interpreter, as any other interpreter (e.g. Python) it is capable of keeping its own set of variables. It should be mentioned that Bash (unlike Python) supports only string variables.

Notation for defining Bash variables is name=value. These variables stay inside Bash and have nothing to do with environment variables kept by operating system.

More on Shell Parameters (including variables)

Also worth noting that, according to Bash reference manual:

The environment for any simple command or function may be augmented temporarily by prefixing it with parameter assignments, as described in Shell Parameters. These assignment statements affect only the environment seen by that command.


To sum things up:

  • export is used to set environment variable in operating system. This variable will be available to all child processes created by current Bash process ever after.
  • Bash variable notation (name=value) is used to set local variables available only to current process of bash
  • Bash variable notation prefixing another command creates environment variable only for scope of that command.

alert a variable value

Note, while the above answers are correct, if you want, you can do something like:

alert("The variable named x1 has value:  " + x1);

"Untrusted App Developer" message when installing enterprise iOS Application

You cannot avoid this unless you distribute an application via the App Store.

You get this message because the application is signed via an enterprise certificate that has not yet been trusted by the user. Apple force this prompt to appear because the application that is being installed hasn't gone through the App Store review process so is technically untrusted.

Once the user has accepted the prompt, the certificate will be marked as trusted and the application can be installed (along with any other future applications that you wish to install that have been signed with the same certificate)

Note: As pointed out in the comments, as of iOS 8, uninstalling all applications from a specific certificate will cause the prompt to be shown again once an application from said certificate is re-installed.

Here is the link to Apple website that confirms this info: https://support.apple.com/en-us/HT204460

Returning JSON response from Servlet to Javascript/JSP page

I think that what you want to do is turn the JSON string back into an object when it arrives back in your XMLHttpRequest - correct?

If so, you need to eval the string to turn it into a JavaScript object - note that this can be unsafe as you're trusting that the JSON string isn't malicious and therefore executing it. Preferably you could use jQuery's parseJSON

How to insert selected columns from a CSV file to a MySQL database using LOAD DATA INFILE

Example:

contents of the ae.csv file:

"Date, xpto 14"
"code","number","year","C"
"blab","15885","2016","Y"
"aeea","15883","1982","E"
"xpto","15884","1986","B"
"jrgg","15885","1400","A"

CREATE TABLE Tabletmp (  
    rec VARCHAR(9) 
);

For put only column 3:

LOAD DATA INFILE '/local/ae.csv' 
INTO TABLE Tabletmp
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 2 LINES
(@col1, @col2, @col3, @col4, @col5)
set rec = @col3;


select * from Tabletmp;
    2016
    1982
    1986
    1400

Can I get the name of the current controller in the view?

controller_path holds the path of the controller used to serve the current view. (ie: admin/settings).

and

controller_name holds the name of the controller used to serve the current view. (ie: settings).

Angular 2: 404 error occur when I refresh through the browser

Perhaps you can do it while registering your root with RouterModule. You can pass a second object with property useHash:true like the below:

import { NgModule }       from '@angular/core';
import { BrowserModule  } from '@angular/platform-browser';
import { AppComponent }   from './app.component';
import { ROUTES }   from './app.routes';

@NgModule({
    declarations: [AppComponent],
    imports: [BrowserModule],
    RouterModule.forRoot(ROUTES ,{ useHash: true }),],
    providers: [],
    bootstrap: [AppComponent],
})
export class AppModule {}

C/C++ include header file order

To add my own brick to the wall.

  1. Each header needs to be self-sufficient, which can only be tested if it's included first at least once
  2. One should not mistakenly modify the meaning of a third-party header by introducing symbols (macro, types, etc.)

So I usually go like this:

// myproject/src/example.cpp
#include "myproject/example.h"

#include <algorithm>
#include <set>
#include <vector>

#include <3rdparty/foo.h>
#include <3rdparty/bar.h>

#include "myproject/another.h"
#include "myproject/specific/bla.h"

#include "detail/impl.h"

Each group separated by a blank line from the next one:

  • Header corresponding to this cpp file first (sanity check)
  • System headers
  • Third-party headers, organized by dependency order
  • Project headers
  • Project private headers

Also note that, apart from system headers, each file is in a folder with the name of its namespace, just because it's easier to track them down this way.

SQL Query NOT Between Two Dates

If the 'NOT' is put before the start_date it should work. For some reason (I don't know why) when 'NOT' is put before 'BETWEEN' it seems to return everything.

NOT (start_date BETWEEN CAST('2009-12-15' AS DATE) AND CAST('2010-01-02' AS DATE))

Android M - check runtime permission - how to determine if the user checked "Never ask again"?

I had the same problem and I figured it out. To make life much simpler, I wrote an util class to handle runtime permissions.

public class PermissionUtil {
    /*
    * Check if version is marshmallow and above.
    * Used in deciding to ask runtime permission
    * */
    public static boolean shouldAskPermission() {
        return (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M);
    }
private static boolean shouldAskPermission(Context context, String permission){
        if (shouldAskPermission()) {
            int permissionResult = ActivityCompat.checkSelfPermission(context, permission);
            if (permissionResult != PackageManager.PERMISSION_GRANTED) {
                return true;
            }
        }
        return false;
    }
public static void checkPermission(Context context, String permission, PermissionAskListener listener){
/*
        * If permission is not granted
        * */
        if (shouldAskPermission(context, permission)){
/*
            * If permission denied previously
            * */
            if (((Activity)context).shouldShowRequestPermissionRationale(permission)) {
                listener.onPermissionPreviouslyDenied();
            } else {
                /*
                * Permission denied or first time requested
                * */
if (PreferencesUtil.isFirstTimeAskingPermission(context, permission)) {
                    PreferencesUtil.firstTimeAskingPermission(context, permission, false);
                    listener.onPermissionAsk();
                } else {
                    /*
                    * Handle the feature without permission or ask user to manually allow permission
                    * */
                    listener.onPermissionDisabled();
                }
            }
        } else {
            listener.onPermissionGranted();
        }
    }
/*
    * Callback on various cases on checking permission
    *
    * 1.  Below M, runtime permission not needed. In that case onPermissionGranted() would be called.
    *     If permission is already granted, onPermissionGranted() would be called.
    *
    * 2.  Above M, if the permission is being asked first time onPermissionAsk() would be called.
    *
    * 3.  Above M, if the permission is previously asked but not granted, onPermissionPreviouslyDenied()
    *     would be called.
    *
    * 4.  Above M, if the permission is disabled by device policy or the user checked "Never ask again"
    *     check box on previous request permission, onPermissionDisabled() would be called.
    * */
    public interface PermissionAskListener {
/*
        * Callback to ask permission
        * */
        void onPermissionAsk();
/*
        * Callback on permission denied
        * */
        void onPermissionPreviouslyDenied();
/*
        * Callback on permission "Never show again" checked and denied
        * */
        void onPermissionDisabled();
/*
        * Callback on permission granted
        * */
        void onPermissionGranted();
    }
}

And the PreferenceUtil methods are as follows.

public static void firstTimeAskingPermission(Context context, String permission, boolean isFirstTime){
SharedPreferences sharedPreference = context.getSharedPreferences(PREFS_FILE_NAME, MODE_PRIVATE;
 sharedPreference.edit().putBoolean(permission, isFirstTime).apply();
 }
public static boolean isFirstTimeAskingPermission(Context context, String permission){
return context.getSharedPreferences(PREFS_FILE_NAME, MODE_PRIVATE).getBoolean(permission, true);
}

Now, all you need is to use the method * checkPermission* with proper arguments.

Here is an example,

PermissionUtil.checkPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    new PermissionUtil.PermissionAskListener() {
                        @Override
                        public void onPermissionAsk() {
                            ActivityCompat.requestPermissions(
                                    thisActivity,
              new String[]{Manifest.permission.READ_CONTACTS},
                            REQUEST_EXTERNAL_STORAGE
                            );
                        }
@Override
                        public void onPermissionPreviouslyDenied() {
                       //show a dialog explaining permission and then request permission
                        }
@Override
                        public void onPermissionDisabled() {
Toast.makeText(context, "Permission Disabled.", Toast.LENGTH_SHORT).show();
                        }
@Override
                        public void onPermissionGranted() {
                            readContacts();
                        }
                    });

how does my app know whether the user has checked the "Never ask again"?

If user checked Never ask again, you'll get callback on onPermissionDisabled.

Happy coding :)

mysqldump & gzip commands to properly create a compressed file of a MySQL database using crontab

First the mysqldump command is executed and the output generated is redirected using the pipe. The pipe is sending the standard output into the gzip command as standard input. Following the filename.gz, is the output redirection operator (>) which is going to continue redirecting the data until the last filename, which is where the data will be saved.

For example, this command will dump the database and run it through gzip and the data will finally land in three.gz

mysqldump -u user -pupasswd my-database | gzip > one.gz > two.gz > three.gz

$> ls -l
-rw-r--r--  1 uname  grp     0 Mar  9 00:37 one.gz
-rw-r--r--  1 uname  grp  1246 Mar  9 00:37 three.gz
-rw-r--r--  1 uname  grp     0 Mar  9 00:37 two.gz

My original answer is an example of redirecting the database dump to many compressed files (without double compressing). (Since I scanned the question and seriously missed - sorry about that)

This is an example of recompressing files:

mysqldump -u user -pupasswd my-database | gzip -c > one.gz; gzip -c one.gz > two.gz; gzip -c two.gz > three.gz

$> ls -l
-rw-r--r--  1 uname  grp  1246 Mar  9 00:44 one.gz
-rw-r--r--  1 uname  grp  1306 Mar  9 00:44 three.gz
-rw-r--r--  1 uname  grp  1276 Mar  9 00:44 two.gz

This is a good resource explaining I/O redirection: http://www.codecoffee.com/tipsforlinux/articles2/042.html

If Cell Starts with Text String... Formula

As of Excel 2019 you could do this. The "Error" at the end is the default.

SWITCH(LEFT(A1,1), "A", "Pick Up", "B", "Collect", "C", "Prepaid", "Error")

Microsoft Excel Switch Documentation

Can I loop through a table variable in T-SQL?

You can loop through the table variable or you can cursor through it. This is what we usually call a RBAR - pronounced Reebar and means Row-By-Agonizing-Row.

I would suggest finding a SET-BASED answer to your question (we can help with that) and move away from rbars as much as possible.

\r\n, \r and \n what is the difference between them?

A carriage return (\r) makes the cursor jump to the first column (begin of the line) while the newline (\n) jumps to the next line and eventually to the beginning of that line. So to be sure to be at the first position within the next line one uses both.

Inserting an image with PHP and FPDF

You can use $pdf->GetX() and $pdf->GetY() to get current cooridnates and use them to insert image.

$pdf->Image($image1, 5, $pdf->GetY(), 33.78);

or even

$pdf->Image($image1, 5, null, 33.78);

(ALthough in first case you can add a number to create a bit of a space)

$pdf->Image($image1, 5, $pdf->GetY() + 5, 33.78);

Getting URL hash location, and using it in jQuery

location.hash is not safe for IE , in case of IE ( including IE9 ) , if your page contains iframe , then after manual refresh inside iframe content get location.hash value is old( value for first page load ). while manual retrieved value is different than location.hash so always retrieve it through document.URL

var hash = document.URL.substr(document.URL.indexOf('#')+1) 

How do I copy items from list to list without foreach?

Easy to map different set of list by linq without for loop

var List1= new List<Entities1>();

var List2= new List<Entities2>();

var List2 = List1.Select(p => new Entities2
        {
            EntityCode = p.EntityCode,
            EntityId = p.EntityId,
            EntityName = p.EntityName
        }).ToList();

Convert text into number in MySQL query

To get number try with SUBSTRING_INDEX(field, '-', 1) then convert.

C++ float array initialization

You only initialize the first N positions to the values in braces and all others are initialized to 0. In this case, N is the number of arguments you passed to the initialization list, i.e.,

float arr1[10] = { };       // all elements are 0
float arr2[10] = { 0 };     // all elements are 0
float arr3[10] = { 1 };     // first element is 1, all others are 0
float arr4[10] = { 1, 2 };  // first element is 1, second is 2, all others are 0

Identifying and removing null characters in UNIX

I’d use tr:

tr < file-with-nulls -d '\000' > file-without-nulls

If you are wondering if input redirection in the middle of the command arguments works, it does. Most shells will recognize and deal with I/O redirection (<, >, …) anywhere in the command line, actually.

ValueError: math domain error

You may also use math.log1p.

According to the official documentation :

math.log1p(x)

Return the natural logarithm of 1+x (base e). The result is calculated in a way which is accurate for x near zero.

You may convert back to the original value using math.expm1 which returns e raised to the power x, minus 1.

Random shuffling of an array

Here is a solution using Apache Commons Math 3.x (for int[] arrays only):

MathArrays.shuffle(array);

http://commons.apache.org/proper/commons-math/javadocs/api-3.6.1/org/apache/commons/math3/util/MathArrays.html#shuffle(int[])

Alternatively, Apache Commons Lang 3.6 introduced new shuffle methods to the ArrayUtils class (for objects and any primitive type).

ArrayUtils.shuffle(array);

http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/ArrayUtils.html#shuffle-int:A-

Watching variables contents in Eclipse IDE

You can add a watchpoint for each variable you're interested in.

A watchpoint is a special breakpoint that stops the execution of an application whenever the value of a given expression changes, without specifying where it might occur. Unlike breakpoints (which are line-specific), watchpoints are associated with files. They take effect whenever a specified condition is true, regardless of when or where it occurred. You can set a watchpoint on a global variable by highlighting the variable in the editor, or by selecting it in the Outline view.

How do I mock an autowired @Value field in Spring with Mockito?

You can use the magic of Spring's ReflectionTestUtils.setField in order to avoid making any modifications whatsoever to your code.

The comment from Michal Stochmal provides an example:

use ReflectionTestUtils.setField(bean, "fieldName", "value"); before invoking your bean method during test.

Check out this tutorial for even more information, although you probably won't need it since the method is very easy to use

UPDATE

Since the introduction of Spring 4.2.RC1 it is now possible to set a static field without having to supply an instance of the class. See this part of the documentation and this commit.

Oracle copy data to another table

Creating a table and copying the data in a single command:

create table T_NEW as
  select * from T;

* This will not copy PKs, FKs, Triggers, etc.

Create web service proxy in Visual Studio from a WSDL file

On the side note: if you have all of the files locally (not only wsdl file but also xsd files) you can invoke wsdl.exe in that manner:

wsdl.exe [path to your wsdl file] [paths to xsd files imported by wsdl]

That way wsdl.exe can resolve all dependecies locally and correctly generates proxy class.

Maybe it will save somebody some time - it solves "missing type" error when service is not avaliable online.

final keyword in method parameters

Java always makes a copy of parameters before sending them to methods. This means the final doesn't mean any difference for the calling code. This only means that inside the method the variables can not be reassigned.

Note that if you have a final object, you can still change the attributes of the object. This is because objects in Java really are pointers to objects. And only the pointer is copied (and will be final in your method), not the actual object.

Windows service with timer

You need to put your main code on the OnStart method.

This other SO answer of mine might help.

You will need to put some code to enable debugging within visual-studio while maintaining your application valid as a windows-service. This other SO thread cover the issue of debugging a windows-service.

EDIT:

Please see also the documentation available here for the OnStart method at the MSDN where one can read this:

Do not use the constructor to perform processing that should be in OnStart. Use OnStart to handle all initialization of your service. The constructor is called when the application's executable runs, not when the service runs. The executable runs before OnStart. When you continue, for example, the constructor is not called again because the SCM already holds the object in memory. If OnStop releases resources allocated in the constructor rather than in OnStart, the needed resources would not be created again the second time the service is called.

Is there a way to make npm install (the command) to work behind proxy?

On Windows system

Try removing the proxy and registry settings (if already set) and set environment variables on command line via

SET HTTP_PROXY=http://username:password@domain:port
SET HTTPS_PROXY=http://username:password@domain:port

then try to run npm install. By this, you'll not set the proxy in .npmrc but for that session it will work.

Android: how to draw a border to a LinearLayout

Extend LinearLayout/RelativeLayout and use it straight on the XML

package com.pkg_name ;
...imports...
public class LinearLayoutOutlined extends LinearLayout {
    Paint paint;    

    public LinearLayoutOutlined(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
        setWillNotDraw(false) ;
        paint = new Paint();
    }
    public LinearLayoutOutlined(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
        setWillNotDraw(false) ;
        paint = new Paint();
    }
    @Override
    protected void onDraw(Canvas canvas) {
        /*
        Paint fillPaint = paint;
        fillPaint.setARGB(255, 0, 255, 0);
        fillPaint.setStyle(Paint.Style.FILL);
        canvas.drawPaint(fillPaint) ;
        */

        Paint strokePaint = paint;
        strokePaint.setARGB(255, 255, 0, 0);
        strokePaint.setStyle(Paint.Style.STROKE);
        strokePaint.setStrokeWidth(2);  
        Rect r = canvas.getClipBounds() ;
        Rect outline = new Rect( 1,1,r.right-1, r.bottom-1) ;
        canvas.drawRect(outline, strokePaint) ;
    }

}

<?xml version="1.0" encoding="utf-8"?>

<com.pkg_name.LinearLayoutOutlined
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
    android:layout_width=...
    android:layout_height=...
   >
   ... your widgets here ...

</com.pkg_name.LinearLayoutOutlined>

how to check confirm password field in form without reloading page

Using Native setCustomValidity

Compare the password/confirm-password input values on their change event and setCustomValidity accordingly:

_x000D_
_x000D_
function onChange() {_x000D_
  const password = document.querySelector('input[name=password]');_x000D_
  const confirm = document.querySelector('input[name=confirm]');_x000D_
  if (confirm.value === password.value) {_x000D_
    confirm.setCustomValidity('');_x000D_
  } else {_x000D_
    confirm.setCustomValidity('Passwords do not match');_x000D_
  }_x000D_
}
_x000D_
<form>_x000D_
  <label>Password: <input name="password" type="password" onChange="onChange()" /> </label><br />_x000D_
  <label>Confirm : <input name="confirm"  type="password" onChange="onChange()" /> </label><br />_x000D_
  <input type="submit" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

CSS to keep element at "fixed" position on screen

You may be looking for position: fixed.

Works everywhere except IE6 and many mobile devices.

How to move a marker in Google Maps API

You are using the correct API, but is the "marker" variable visible to the entire script. I don't see this marker variable declared globally.

What is the equivalent of 'describe table' in SQL Server?

I wrote an sql*plus DESC(RIBE) like select (displays the column comments, too) in t-sql:

USE YourDB
GO

DECLARE @objectName NVARCHAR(128) = 'YourTable';

SELECT
  a.[NAME]
 ,a.[TYPE]
 ,a.[CHARSET]
 ,a.[COLLATION]
 ,a.[NULLABLE]
 ,a.[DEFAULT]
 ,b.[COMMENTS]
-- ,a.[ORDINAL_POSITION]
FROM
  (
    SELECT
      COLUMN_NAME                                     AS [NAME]
     ,CASE DATA_TYPE
        WHEN 'char'       THEN DATA_TYPE  + '(' + CAST(CHARACTER_MAXIMUM_LENGTH AS VARCHAR) + ')'
        WHEN 'numeric'    THEN DATA_TYPE  + '(' + CAST(NUMERIC_PRECISION AS VARCHAR) + ', ' + CAST(NUMERIC_SCALE AS VARCHAR) + ')'
        WHEN 'nvarchar'   THEN DATA_TYPE  + '(' + CAST(CHARACTER_MAXIMUM_LENGTH AS VARCHAR) + ')'
        WHEN 'varbinary'  THEN DATA_TYPE + '(' + CAST(CHARACTER_MAXIMUM_LENGTH AS VARCHAR) + ')'
        WHEN 'varchar'    THEN DATA_TYPE   + '(' + CAST(CHARACTER_MAXIMUM_LENGTH AS VARCHAR) + ')'
        ELSE DATA_TYPE
      END                                             AS [TYPE]
     ,CHARACTER_SET_NAME                              AS [CHARSET]
     ,COLLATION_NAME                                  AS [COLLATION]
     ,IS_NULLABLE                                     AS [NULLABLE]
     ,COLUMN_DEFAULT                                  AS [DEFAULT]
     ,ORDINAL_POSITION
    FROM   
      INFORMATION_SCHEMA.COLUMNS
    WHERE
      TABLE_NAME = @objectName
  ) a
  FULL JOIN
  (
   SELECT
     CAST(value AS NVARCHAR)                        AS [COMMENTS]
    ,CAST(objname AS NVARCHAR)                      AS [NAME]
   FROM
     ::fn_listextendedproperty ('MS_Description', 'user', 'dbo', 'table', @objectName, 'column', default)
  ) b
  ON a.NAME COLLATE YourCollation = b.NAME COLLATE YourCollation
ORDER BY
  a.[ORDINAL_POSITION];

The above mentioned select can be used in a system marked stored procedure and it can be called from any database of your instance on a simple way:

USE master;
GO

IF OBJECT_ID('sp_desc', 'P') IS NOT NULL
  DROP PROCEDURE sp_desc
GO

CREATE PROCEDURE sp_desc (
  @tableName  nvarchar(128)
) AS
BEGIN
  DECLARE @dbName       sysname;
  DECLARE @schemaName   sysname;
  DECLARE @objectName   sysname;
  DECLARE @objectID     int;
  DECLARE @tmpTableName varchar(100);
  DECLARE @sqlCmd       nvarchar(4000);

  SELECT @dbName = PARSENAME(@tableName, 3);
  IF @dbName IS NULL SELECT @dbName = DB_NAME();

  SELECT @schemaName = PARSENAME(@tableName, 2);
  IF @schemaName IS NULL SELECT @schemaName = SCHEMA_NAME();

  SELECT @objectName = PARSENAME(@tableName, 1);
  IF @objectName IS NULL
    BEGIN
      PRINT 'Object is missing from your function call!';
      RETURN;
    END;

  SELECT @objectID = OBJECT_ID(@dbName + '.' + @schemaName + '.' + @objectName);
  IF @objectID IS NULL
    BEGIN
      PRINT 'Object [' + @dbName + '].[' + @schemaName + '].[' + @objectName + '] does not exist!';
      RETURN;
    END;

  SELECT @tmpTableName = '#tmp_DESC_' + CAST(@@SPID AS VARCHAR) + REPLACE(REPLACE(REPLACE(REPLACE(CAST(CONVERT(CHAR, GETDATE(), 121) AS VARCHAR), '-', ''), ' ', ''), ':', ''), '.', '');
  --PRINT @tmpTableName;
  SET @sqlCmd = '
    USE ' + @dbName + '
    CREATE TABLE ' + @tmpTableName + ' (
      [NAME]              nvarchar(128) NOT NULL
     ,[TYPE]              varchar(50)
     ,[CHARSET]           varchar(50)
     ,[COLLATION]         varchar(50)
     ,[NULLABLE]          varchar(3)
     ,[DEFAULT]           nvarchar(4000)
     ,[COMMENTS]          nvarchar(3750));

    INSERT INTO ' + @tmpTableName + '
    SELECT
      a.[NAME]
     ,a.[TYPE]
     ,a.[CHARSET]
     ,a.[COLLATION]
     ,a.[NULLABLE]
     ,a.[DEFAULT]
     ,b.[COMMENTS]
    FROM
      (
        SELECT
          COLUMN_NAME                                     AS [NAME]
         ,CASE DATA_TYPE
            WHEN ''char''      THEN DATA_TYPE + ''('' + CAST(CHARACTER_MAXIMUM_LENGTH AS VARCHAR) + '')''
            WHEN ''numeric''   THEN DATA_TYPE + ''('' + CAST(NUMERIC_PRECISION AS VARCHAR) + '', '' + CAST(NUMERIC_SCALE AS VARCHAR) + '')''
            WHEN ''nvarchar''  THEN DATA_TYPE + ''('' + CAST(CHARACTER_MAXIMUM_LENGTH AS VARCHAR) + '')''
            WHEN ''varbinary'' THEN DATA_TYPE + ''('' + CAST(CHARACTER_MAXIMUM_LENGTH AS VARCHAR) + '')''
            WHEN ''varchar''   THEN DATA_TYPE + ''('' + CAST(CHARACTER_MAXIMUM_LENGTH AS VARCHAR) + '')''
            ELSE DATA_TYPE
          END                                             AS [TYPE]
         ,CHARACTER_SET_NAME                              AS [CHARSET]
         ,COLLATION_NAME                                  AS [COLLATION]
         ,IS_NULLABLE                                     AS [NULLABLE]
         ,COLUMN_DEFAULT                                  AS [DEFAULT]
         ,ORDINAL_POSITION
        FROM   
          INFORMATION_SCHEMA.COLUMNS
        WHERE   
          TABLE_NAME = ''' + @objectName + '''
      ) a
      FULL JOIN
      (
         SELECT
           CAST(value AS NVARCHAR)                        AS [COMMENTS]
          ,CAST(objname AS NVARCHAR)                      AS [NAME]
         FROM
           ::fn_listextendedproperty (''MS_Description'', ''user'', ''' + @schemaName + ''', ''table'', ''' + @objectName + ''', ''column'', default)
      ) b
      ON a.NAME COLLATE Hungarian_CI_AS = b.NAME COLLATE Hungarian_CI_AS
    ORDER BY
      a.[ORDINAL_POSITION];

    SELECT * FROM ' + @tmpTableName + ';'

    --PRINT @sqlCmd;

    EXEC sp_executesql @sqlCmd;
    RETURN;
END;
GO

EXEC sys.sp_MS_marksystemobject sp_desc
GO

To execute the procedure type:

EXEC sp_desc 'YourDB.YourSchema.YourTable';

If you want to get a description an object of the current database (and schema) simple type:

EXEC sp_desc 'YourTable';

As sp_desc is a system marked procedure, you can even leave the exec command, too (not recommended anyway):

sp_desc 'YourTable';

Creating a dictionary from a CSV file

If you are OK with using the numpy package, then you can do something like the following:

import numpy as np

lines = np.genfromtxt("coors.csv", delimiter=",", dtype=None)
my_dict = dict()
for i in range(len(lines)):
   my_dict[lines[i][0]] = lines[i][1]

XPath query to get nth instance of an element

This seems to work:

/descendant::input[@id="search_query"][2]

I go this from "XSLT 2.0 and XPath 2.0 Programmer's Reference, 4th Edition" by Michael Kay.

There is also a note in the "Abbreviated Syntax" section of the XML Path Language specification http://www.w3.org/TR/xpath/#path-abbrev that provided a clue.

How to check if bootstrap modal is open, so I can use jquery validate?

Bootstrap 2 , 3 Check is any modal open in page :

if($('.modal.in').length)

compatible version Bootstrap 2 , 3 , 4+

if($('.modal.in, .modal.show').length)

Only Bootstrap 4+

if($('.modal.show').length)

How to use UIScrollView in Storyboard

Here are the steps that worked for me on iOS 7 and XCode 5.

  1. Drag a ViewController (it comes with UIView "View").

    1.1 Select "View Controller" and select "File Inspector" and uncheck "Auto layout".

  2. Drag a ScrollView (as child of ViewController's UIView "View")
  3. Select ScrollView and open "Identity Inspector".
  4. Enter "contentSize" for keyPath. Select "Size" for Type. And Enter {320, 1000} for value.

    Note: Step 4 is simply saying that the scroller contains some content whose size is 320x1000 units. So setting contentSize will make scroller work.

  5. Select View Controller, Select "Attributes Inspector" then select Freeform from Size.

    Note: step 5 will allow us to change the size of "View" that the view controller comes with.

  6. Select "View" and then select "Size Inspector".

  7. Set Width to 320 and height to 1000.

Note: 5, 6 & 7 is purely for us to see stretched or entire expanded view inside StoryBoard. Note: Make sure to unselect "Auto Layout" on View Controller.

Your View hierarchy should look like: hierarchy

Correct MySQL configuration for Ruby on Rails Database.yml file

If you have multiple databases for testing and development this might help

development:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: DBNAME
  pool: 5
  username: usr
  password: paswd
  shost: localhost
test:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: DBNAME
  pool: 5
  username: usr
  password: paswd
  shost: localhost
production:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: DBNAME
  pool: 5
  username: usr
  password: paswd
  shost: localhost

Reading a json file in Android

Put that file in assets.

For project created in Android Studio project you need to create assets folder under the main folder.

Read that file as:

public String loadJSONFromAsset(Context context) {
        String json = null;
        try {
            InputStream is = context.getAssets().open("file_name.json");

            int size = is.available();

            byte[] buffer = new byte[size];

            is.read(buffer);

            is.close();

            json = new String(buffer, "UTF-8");


        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;

    }

and then you can simply read this string return by this function as

JSONObject obj = new JSONObject(json_return_by_the_function);

For further details regarding JSON see http://www.vogella.com/articles/AndroidJSON/article.html

Hope you will get what you want.

AutoComplete TextBox in WPF

Nimgoble's is the version I used in 2015. Thought I'd put it here as this question was top of the list in google for "wpf autocomplete textbox"

  1. Install nuget package for project in Visual Studio

  2. Add a reference to the library in the xaml:
    xmlns:behaviors="clr-namespace:WPFTextBoxAutoComplete;assembly=WPFTextBoxAutoComplete"

  3. Create a textbox and bind the AutoCompleteBehaviour to List<String> (TestItems):
    <TextBox Text="{Binding TestText, UpdateSourceTrigger=PropertyChanged}" behaviors:AutoCompleteBehavior.AutoCompleteItemsSource="{Binding TestItems}" />

IMHO this is much easier to get started and manage than the other options listed above.

Using await outside of an async function

Top level await is not supported. There are a few discussions by the standards committee on why this is, such as this Github issue.

There's also a thinkpiece on Github about why top level await is a bad idea. Specifically he suggests that if you have code like this:

// data.js
const data = await fetch( '/data.json' );
export default data;

Now any file that imports data.js won't execute until the fetch completes, so all of your module loading is now blocked. This makes it very difficult to reason about app module order, since we're used to top level Javascript executing synchronously and predictably. If this were allowed, knowing when a function gets defined becomes tricky.

My perspective is that it's bad practice for your module to have side effects simply by loading it. That means any consumer of your module will get side effects simply by requiring your module. This badly limits where your module can be used. A top level await probably means you're reading from some API or calling to some service at load time. Instead you should just export async functions that consumers can use at their own pace.

Pods stuck in Terminating status

Delete the finalizers block from resource (pod,deployment,ds etc...) yaml:

"finalizers": [
  "foregroundDeletion"
]

How to generate a QR Code for an Android application?

Here is my simple and working function to generate a Bitmap! I Use ZXing1.3.jar only! I've also set Correction Level to High!

PS: x and y are reversed, it's normal, because bitMatrix reverse x and y. This code works perfectly with a square image.

public static Bitmap generateQrCode(String myCodeText) throws WriterException {
    Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
    hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // H = 30% damage

    QRCodeWriter qrCodeWriter = new QRCodeWriter();

    int size = 256;

    ByteMatrix bitMatrix = qrCodeWriter.encode(myCodeText,BarcodeFormat.QR_CODE, size, size, hintMap);
    int width = bitMatrix.width();
    Bitmap bmp = Bitmap.createBitmap(width, width, Bitmap.Config.RGB_565);
    for (int x = 0; x < width; x++) {
        for (int y = 0; y < width; y++) {
            bmp.setPixel(y, x, bitMatrix.get(x, y)==0 ? Color.BLACK : Color.WHITE);
        }
    }
    return bmp;
}

EDIT

It's faster to use bitmap.setPixels(...) with a pixel int array instead of bitmap.setPixel one by one:

        BitMatrix bitMatrix = writer.encode(inputValue, BarcodeFormat.QR_CODE, size, size);
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        int[] pixels = new int[width * height];
        for (int y = 0; y < height; y++) {
            int offset = y * width;
            for (int x = 0; x < width; x++) {
                pixels[offset + x] = bitMatrix.get(x, y) ? BLACK : WHITE;
            }
        }

        bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);

How to access full source of old commit in BitBucket?

Search it for a long time, and finally, I found how to do it:)

Please check this image which illustrates steps. enter image description here

IntelliJ show JavaDocs tooltip on mouse over

For Intellij 15, use the checkbox in File > Settings > Editor > General option Show quick documentation on mouse move.

enter image description here

You can also get there by typing "quick" or something similar in the search box:

enter image description here

Websocket connections with Postman

You can use the tool APIC available here https://chrome.google.com/webstore/detail/apic-complete-api-solutio/ggnhohnkfcpcanfekomdkjffnfcjnjam. This tool allows you to test websocket which use either StompJS or native Websocket. More info here at www.apic.app

How to import .py file from another directory?

You can add to the system-path at runtime:

import sys
sys.path.insert(0, 'path/to/your/py_file')

import py_file

This is by far the easiest way to do it.

How can I resize an image using Java?

Thumbnailator is an open-source image resizing library for Java with a fluent interface, distributed under the MIT license.

I wrote this library because making high-quality thumbnails in Java can be surprisingly difficult, and the resulting code could be pretty messy. With Thumbnailator, it's possible to express fairly complicated tasks using a simple fluent API.

A simple example

For a simple example, taking a image and resizing it to 100 x 100 (preserving the aspect ratio of the original image), and saving it to an file can achieved in a single statement:

Thumbnails.of("path/to/image")
    .size(100, 100)
    .toFile("path/to/thumbnail");

An advanced example

Performing complex resizing tasks is simplified with Thumbnailator's fluent interface.

Let's suppose we want to do the following:

  1. take the images in a directory and,
  2. resize them to 100 x 100, with the aspect ratio of the original image,
  3. save them all to JPEGs with quality settings of 0.85,
  4. where the file names are taken from the original with thumbnail. appended to the beginning

Translated to Thumbnailator, we'd be able to perform the above with the following:

Thumbnails.of(new File("path/to/directory").listFiles())
    .size(100, 100)
    .outputFormat("JPEG")
    .outputQuality(0.85)
    .toFiles(Rename.PREFIX_DOT_THUMBNAIL);

A note about image quality and speed

This library also uses the progressive bilinear scaling method highlighted in Filthy Rich Clients by Chet Haase and Romain Guy in order to generate high-quality thumbnails while ensuring acceptable runtime performance.

Java: how to convert HashMap<String, Object> to array

HashMap<String, String> hashMap = new HashMap<>();
String[] stringValues= new String[hashMap.values().size()];
hashMap.values().toArray(stringValues);

How to get file name when user select a file via <input type="file" />?

You can get the file name, but you cannot get the full client file-system path.

Try to access to the value attribute of your file input on the change event.

Most browsers will give you only the file name, but there are exceptions like IE8 which will give you a fake path like: "C:\fakepath\myfile.ext" and older versions (IE <= 6) which actually will give you the full client file-system path (due its lack of security).

document.getElementById('fileInput').onchange = function () {
  alert('Selected file: ' + this.value);
};

How to run Maven from another directory (without cd to project dir)?

I don't think maven supports this. If you're on Unix, and don't want to leave your current directory, you could use a small shell script, a shell function, or just a sub-shell:

user@host ~/project$ (cd ~/some/location; mvn install)
[ ... mvn build ... ]
user@host ~/project$

As a bash function (which you could add to your ~/.bashrc):

function mvn-there() {
  DIR="$1"
  shift
  (cd $DIR; mvn "$@")     
} 

user@host ~/project$ mvn-there ~/some/location install)
[ ... mvn build ... ]
user@host ~/project$

I realize this doesn't answer the specific question, but may provide you with what you're after. I'm not familiar with the Windows shell, though you should be able to reach a similar solution there as well.

Regards

get current date from [NSDate date] but set the time to 10:00 am

You can use this method for any minute / hour / period (aka am/pm) combination:

- (NSDate *)todayModifiedWithHours:(NSString *)hours
                           minutes:(NSString *)minutes
                         andPeriod:(NSString *)period
{
    NSDate *todayModified = NSDate.date;

    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

    NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSMinuteCalendarUnit fromDate:todayModified];

    [components setMinute:minutes.intValue];

    int hour = 0;

    if ([period.uppercaseString isEqualToString:@"AM"]) {

        if (hours.intValue == 12) {
            hour = 0;
        }
        else {
            hour = hours.intValue;
        }
    }
    else if ([period.uppercaseString isEqualToString:@"PM"]) {

        if (hours.intValue != 12) {
            hour = hours.intValue + 12;
        }
        else {
            hour = 12;
        }
    }
    [components setHour:hour];

    todayModified = [calendar dateFromComponents:components];

    return todayModified;
}

Requested Example:

NSDate *todayAt10AM = [self todayModifiedWithHours:@"10"
                                           minutes:@"00"
                                         andPeriod:@"am"];

How do relative file paths work in Eclipse?

Paraphrasing from http://java.sun.com/javase/6/docs/api/java/io/File.html:

The classes under java.io resolve relative pathnames against the current user directory, which is typically the directory in which the virtual machine was started.

Eclipse sets the working directory to the top-level project folder.

MySQL "NOT IN" query

Be carefull NOT IN is not an alias for <> ANY, but for <> ALL!

http://dev.mysql.com/doc/refman/5.0/en/any-in-some-subqueries.html

SELECT c FROM t1 LEFT JOIN t2 USING (c) WHERE t2.c IS NULL

cant' be replaced by

SELECT c FROM t1 WHERE c NOT IN (SELECT c FROM t2)

You must use

SELECT c FROM t1 WHERE c <> ANY (SELECT c FROM t2)

How to read a list of files from a folder using PHP?

There is also a really simple way to do this with the help of the RecursiveTreeIterator class, answered here: https://stackoverflow.com/a/37548504/2032235

Http Get using Android HttpURLConnection

I have created with callBack(delegate) response to Activity class.

public class WebService extends AsyncTask<String, Void, String> {

    private Context mContext;
    private OnTaskDoneListener onTaskDoneListener;
    private String urlStr = "";

    public WebService(Context context, String url, OnTaskDoneListener onTaskDoneListener) {
        this.mContext = context;
        this.urlStr = url;
        this.onTaskDoneListener = onTaskDoneListener;
    }

    @Override
    protected String doInBackground(String... params) {
        try {

            URL mUrl = new URL(urlStr);
            HttpURLConnection httpConnection = (HttpURLConnection) mUrl.openConnection();
            httpConnection.setRequestMethod("GET");
            httpConnection.setRequestProperty("Content-length", "0");
            httpConnection.setUseCaches(false);
            httpConnection.setAllowUserInteraction(false);
            httpConnection.setConnectTimeout(100000);
            httpConnection.setReadTimeout(100000);

            httpConnection.connect();

            int responseCode = httpConnection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader br = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line + "\n");
                }
                br.close();
                return sb.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

        if (onTaskDoneListener != null && s != null) {
            onTaskDoneListener.onTaskDone(s);
        } else
            onTaskDoneListener.onError();
    }
}

where

public interface OnTaskDoneListener {
    void onTaskDone(String responseData);

    void onError();
}

You can modify according to your needs. It's for get

Loop X number of times

Use:

1..10 | % { write "loop $_" }

Output:

PS D:\temp> 1..10 | % { write "loop $_" }
loop 1
loop 2
loop 3
loop 4
loop 5
loop 6
loop 7
loop 8
loop 9
loop 10

Remove table row after clicking table row delete button

You can use jQuery click instead of using onclick attribute, Try the following:

$('table').on('click', 'input[type="button"]', function(e){
   $(this).closest('tr').remove()
})

Demo

How do you set your pythonpath in an already-created virtualenv?

I modified my activate script to source the file .virtualenvrc, if it exists in the current directory, and to save/restore PYTHONPATH on activate/deactivate.

You can find the patched activate script here.. It's a drop-in replacement for the activate script created by virtualenv 1.11.6.

Then I added something like this to my .virtualenvrc:

export PYTHONPATH="${PYTHONPATH:+$PYTHONPATH:}/some/library/path"

How to Lazy Load div background images

It's been a moment that this question is asked, but this doesn't mean that we can't share other answers in 2020. Here is an awesome plugin with jquery:jQuery Lazy

The basic usage of Lazy:

HTML

<!-- load background images of other element types -->
<div class="lazy" data-src="path/to/image.jpg"></div>
enter code here

JS

 $('.lazy').Lazy({
    // your configuration goes here
    scrollDirection: 'vertical',
    effect: 'fadeIn',
    visibleOnly: true,
    onError: function(element) {
        console.log('error loading ' + element.data('src'));
    }
});

and your background images are lazy loading. That's all!

To see real examples and more details check this link lazy-doc.

Error: Cannot find module 'ejs'

Add dependency in package.json and then run npm install

    {
  ...
  ... 
  "dependencies": {
    "express": "*",
    "ejs": "*",
  }
}

How to create a new object instance from a Type

Wouldn't the generic T t = new T(); work?

Map with Key as String and Value as List in Groovy

you don't need to declare Map groovy internally recognizes it

def personDetails = [firstName:'John', lastName:'Doe', fullName:'John Doe']

// print the values..
    println "First Name: ${personDetails.firstName}"
    println "Last Name: ${personDetails.lastName}"

http://grails.asia/groovy-map-tutorial

How to duplicate a git repository? (without forking)

I have noticed some of the other answers here use a bare clone and then mirror push to the new repository, however this does not work for me and when I open the new repository after that, the files look mixed up and not as I expect.

Here is a solution that definitely works for copying the files, although it does not preserve the original repository's revision history.

  1. git clone the repository onto your local machine.
  2. cd into the project directory and then run rm -rf .git to remove all the old git metadata including commit history, etc.
  3. Initialize a fresh git repository by running git init.
  4. Run git add . ; git commit -am "Initial commit" - Of course you can call this commit what you want.
  5. Set the origin to your new repository git remote add origin https://github.com/user/repo-name (replace the url with the url to your new repository)
  6. Push it to your new repository with git push origin master.

Print string and variable contents on the same line in R

A trick would be to include your piece of code into () like this:

(wd <- getwd())

which means that the current working directory is assigned to wd and then printed.

What does the percentage sign mean in Python

What does the percentage sign mean?

It's an operator in Python that can mean several things depending on the context. A lot of what follows was already mentioned (or hinted at) in the other answers but I thought it could be helpful to provide a more extensive summary.

% for Numbers: Modulo operation / Remainder / Rest

The percentage sign is an operator in Python. It's described as:

x % y       remainder of x / y

So it gives you the remainder/rest that remains if you "floor divide" x by y. Generally (at least in Python) given a number x and a divisor y:

x == y * (x // y) + (x % y)

For example if you divide 5 by 2:

>>> 5 // 2
2
>>> 5 % 2
1

>>> 2 * (5 // 2) + (5 % 2)
5

In general you use the modulo operation to test if a number divides evenly by another number, that's because multiples of a number modulo that number returns 0:

>>> 15 % 5  # 15 is 3 * 5
0

>>> 81 % 9  # 81 is 9 * 9
0

That's how it's used in your example, it cannot be a prime if it's a multiple of another number (except for itself and one), that's what this does:

if n % x == 0:
    break

If you feel that n % x == 0 isn't very descriptive you could put it in another function with a more descriptive name:

def is_multiple(number, divisor):
    return number % divisor == 0

...

if is_multiple(n, x):
    break

Instead of is_multiple it could also be named evenly_divides or something similar. That's what is tested here.

Similar to that it's often used to determine if a number is "odd" or "even":

def is_odd(number):
    return number % 2 == 1

def is_even(number):
    return number % 2 == 0

And in some cases it's also used for array/list indexing when wrap-around (cycling) behavior is wanted, then you just modulo the "index" by the "length of the array" to achieve that:

>>> l = [0, 1, 2]
>>> length = len(l)
>>> for index in range(10):
...     print(l[index % length])
0
1
2
0
1
2
0
1
2
0

Note that there is also a function for this operator in the standard library operator.mod (and the alias operator.__mod__):

>>> import operator
>>> operator.mod(5, 2)  # equivalent to 5 % 2
1

But there is also the augmented assignment %= which assigns the result back to the variable:

>>> a = 5
>>> a %= 2  # identical to: a = a % 2
>>> a
1

% for strings: printf-style String Formatting

For strings the meaning is completely different, there it's one way (in my opinion the most limited and ugly) for doing string formatting:

>>> "%s is %s." % ("this", "good") 
'this is good'

Here the % in the string represents a placeholder followed by a formatting specification. In this case I used %s which means that it expects a string. Then the string is followed by a % which indicates that the string on the left hand side will be formatted by the right hand side. In this case the first %s is replaced by the first argument this and the second %s is replaced by the second argument (good).

Note that there are much better (probably opinion-based) ways to format strings:

>>> "{} is {}.".format("this", "good")
'this is good.'

% in Jupyter/IPython: magic commands

To quote the docs:

To Jupyter users: Magics are specific to and provided by the IPython kernel. Whether magics are available on a kernel is a decision that is made by the kernel developer on a per-kernel basis. To work properly, Magics must use a syntax element which is not valid in the underlying language. For example, the IPython kernel uses the % syntax element for magics as % is not a valid unary operator in Python. While, the syntax element has meaning in other languages.

This is regularly used in Jupyter notebooks and similar:

In [1]:  a = 10
         b = 20
         %timeit a + b   # one % -> line-magic

54.6 ns ± 2.7 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

In [2]:  %%timeit  # two %% -> cell magic 
         a ** b

362 ns ± 8.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

The % operator on arrays (in the NumPy / Pandas ecosystem)

The % operator is still the modulo operator when applied to these arrays, but it returns an array containing the remainder of each element in the array:

>>> import numpy as np
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

>>> a % 2
array([0, 1, 0, 1, 0, 1, 0, 1, 0, 1])

Customizing the % operator for your own classes

Of course you can customize how your own classes work when the % operator is applied to them. Generally you should only use it to implement modulo operations! But that's a guideline, not a hard rule.

Just to provide a simple example that shows how it works:

class MyNumber(object):
    def __init__(self, value):
        self.value = value

    def __mod__(self, other):
        print("__mod__ called on '{!r}'".format(self))
        return self.value % other

    def __repr__(self):
        return "{self.__class__.__name__}({self.value!r})".format(self=self)

This example isn't really useful, it just prints and then delegates the operator to the stored value, but it shows that __mod__ is called when % is applied to an instance:

>>> a = MyNumber(10)
>>> a % 2
__mod__ called on 'MyNumber(10)'
0

Note that it also works for %= without explicitly needing to implement __imod__:

>>> a = MyNumber(10)
>>> a %= 2
__mod__ called on 'MyNumber(10)'

>>> a
0

However you could also implement __imod__ explicitly to overwrite the augmented assignment:

class MyNumber(object):
    def __init__(self, value):
        self.value = value

    def __mod__(self, other):
        print("__mod__ called on '{!r}'".format(self))
        return self.value % other

    def __imod__(self, other):
        print("__imod__ called on '{!r}'".format(self))
        self.value %= other
        return self

    def __repr__(self):
        return "{self.__class__.__name__}({self.value!r})".format(self=self)

Now %= is explicitly overwritten to work in-place:

>>> a = MyNumber(10)
>>> a %= 2
__imod__ called on 'MyNumber(10)'

>>> a
MyNumber(0)

More elegant "ps aux | grep -v grep"

You could use preg_split instead of explode and split on [ ]+ (one or more spaces). But I think in this case you could go with preg_match_all and capturing:

preg_match_all('/[ ]php[ ]+\S+[ ]+(\S+)/', $input, $matches);
$result = $matches[1];

The pattern matches a space, php, more spaces, a string of non-spaces (the path), more spaces, and then captures the next string of non-spaces. The first space is mostly to ensure that you don't match php as part of a user name but really only as a command.

An alternative to capturing is the "keep" feature of PCRE. If you use \K in the pattern, everything before it is discarded in the match:

preg_match_all('/[ ]php[ ]+\S+[ ]+\K\S+/', $input, $matches);
$result = $matches[0];

I would use preg_match(). I do something similar for many of my system management scripts. Here is an example:

$test = "user     12052  0.2  0.1 137184 13056 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust1 cron
user     12054  0.2  0.1 137184 13064 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust3 cron
user     12055  0.6  0.1 137844 14220 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust4 cron
user     12057  0.2  0.1 137184 13052 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust89 cron
user     12058  0.2  0.1 137184 13052 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust435 cron
user     12059  0.3  0.1 135112 13000 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust16 cron
root     12068  0.0  0.0 106088  1164 pts/1    S+   10:00   0:00 sh -c ps aux | grep utilities > /home/user/public_html/logs/dashboard/currentlyPosting.txt
root     12070  0.0  0.0 103240   828 pts/1    R+   10:00   0:00 grep utilities";

$lines = explode("\n", $test);

foreach($lines as $line){
        if(preg_match("/.php[\s+](cust[\d]+)[\s+]cron/i", $line, $matches)){
                print_r($matches);
        }

}

The above prints:

Array
(
    [0] => .php cust1 cron
    [1] => cust1
)
Array
(
    [0] => .php cust3 cron
    [1] => cust3
)
Array
(
    [0] => .php cust4 cron
    [1] => cust4
)
Array
(
    [0] => .php cust89 cron
    [1] => cust89
)
Array
(
    [0] => .php cust435 cron
    [1] => cust435
)
Array
(
    [0] => .php cust16 cron
    [1] => cust16
)

You can set $test to equal the output from exec. the values you are looking for would be in the if statement under the foreach. $matches[1] will have the custx value.

How do I push a local Git branch to master branch in the remote?

You can also do it this way to reference the previous branch implicitly:

git checkout mainline
git pull
git merge -
git push

How to get the current time as datetime

One line Swift 5.2

let date = String(DateFormatter.localizedString(from: NSDate() as Date, dateStyle: .medium, timeStyle: .short))

How to create a responsive image that also scales up in Bootstrap 3

Try the following in your CSS stylesheet:

.img-responsive{
  max-width: 100%;
  height: auto;
}

Command to close an application of console?

So you didn't say you wanted the application to quit or exit abruptly, so as another option, perhaps just have the response loop end out elegantly. (I am assuming you have a while loop waiting for user instructions. This is some code from a project I just wrote today.

        Console.WriteLine("College File Processor");
        Console.WriteLine("*************************************");
        Console.WriteLine("(H)elp");
        Console.WriteLine("Process (W)orkouts");
        Console.WriteLine("Process (I)nterviews");
        Console.WriteLine("Process (P)ro Days");
        Console.WriteLine("(S)tart Processing");
        Console.WriteLine("E(x)it");
        Console.WriteLine("*************************************");

        string response = "";
        string videotype = "";
        bool starting = false;
        bool exiting = false;

        response = Console.ReadLine();

        while ( response != "" )
        {
            switch ( response  )
            {
                case "H":
                case "h":
                    DisplayHelp();
                    break;

                case "W":
                case "w":
                    Console.WriteLine("Video Type set to Workout");
                    videotype = "W";
                    break;

                case "I":
                case "i":
                    Console.WriteLine("Video Type set to Interview");
                    videotype = "I";
                    break;

                case "P":
                case "p":
                    Console.WriteLine("Video Type set to Pro Day");
                    videotype = "P";
                    break;

                case "S":
                case "s":
                    if ( videotype == "" )
                    {
                        Console.WriteLine("Please Select Video Type Before Starting");
                    }
                    else
                    {
                        Console.WriteLine("Starting...");
                        starting = true;
                    }
                    break;

                case "E":
                case "e":
                    Console.WriteLine("Good Bye!");
                    System.Threading.Thread.Sleep(100);
                    exiting = true;
                    break;
            }

            if ( starting || exiting)
            {
                break;
            }
            else
            {
                response = Console.ReadLine();
            }
        }

        if ( starting )
        {
            ProcessFiles();
        }

How do I programmatically set device orientation in iOS 7?

If you want only portrait mode, in iOS 9 (Xcode 7) you can:

  • Going to Info.plist
  • Select "Supported interface orientations" item
  • Delete "Landscape(left home button)" and "Landscape(right home button)"

enter image description here

How to make an image center (vertically & horizontally) inside a bigger div

I love jumping on old bandwagons!

Here's a 2015 update to this answer. I started using CSS3 transform to do my dirty work for positioning. This allows you to not have to make any extra HTML, you don't have to do math (finding half-widths of things) you can use it on any element!

Here's an example (with fiddle at the end). Your HTML:

<div class="bigDiv">
    <div class="smallDiv">
    </div>
</div>

With accompanying CSS:

.bigDiv {
    width:200px;
    height:200px;
    background-color:#efefef;
    position:relative;
}
.smallDiv {
    width:50px;
    height:50px;
    background-color:#cc0000;
    position:absolute;
    top:50%;
    left:50%;
    transform:translate(-50%, -50%);
}

What I do a lot these days is I will give a class to things I want centered and just re-use that class every time. For example:

<div class="bigDiv">
    <div class="smallDiv centerThis">
    </div>
</div>

css

.bigDiv {
    width:200px;
    height:200px;
    background-color:#efefef;
    position:relative;
}
.smallDiv {
    width:50px;
    height:50px;
    background-color:#cc0000;
}
.centerThis {
    position:absolute;
    top:50%;
    left:50%;
    transform:translate(-50%, -50%);
}

This way, I will always be able to center something in it's container. You just have to make sure that the thing you want centered is in a container that has a position defined.

Here's a fiddle

BTW: This works for centering BIGGER divs inside SMALLER divs as well.

What is the difference between HTTP 1.1 and HTTP 2.0?

HTTP/2 supports queries multiplexing, headers compression, priority and more intelligent packet streaming management. This results in reduced latency and accelerates content download on modern web pages.

More details here.

How to keep an iPhone app running on background fully operational

You can perform tasks for a limited time after your application is directed to go to the background, but only for the duration provided. Running for longer than this will cause your application to be terminated. See the "Completing a Long-Running Task in the Background" section of the iOS Application Programming Guide for how to go about this.

Others have piggybacked on playing audio in the background as a means of staying alive as a background process, but Apple will only accept such an application if the audio playback is a legitimate function. Item 2.16 on Apple's published review guidelines states:

Multitasking apps may only use background services for their intended purposes: VoIP, audio playback, location, task completion, local notifications, etc

Check if checkbox is checked with jQuery

As per the jQuery documentation there are following ways to check if a checkbox is checked or not. Lets consider a checkbox for example (Check Working jsfiddle with all examples)

<input type="checkbox" name="mycheckbox" id="mycheckbox" />
<br><br>
<input type="button" id="test-with-checked" value="Test with checked" />
<input type="button" id="test-with-is" value="Test with is" />
<input type="button" id="test-with-prop" value="Test with prop" />

Example 1 - With checked

$("#test-with-checked").on("click", function(){
    if(mycheckbox.checked) {
        alert("Checkbox is checked.");
    } else {
        alert("Checkbox is unchecked.");
    }
}); 

Example 2 - With jQuery is, NOTE - :checked

var check;
$("#test-with-is").on("click", function(){
    check = $("#mycheckbox").is(":checked");
    if(check) {
        alert("Checkbox is checked.");
    } else {
        alert("Checkbox is unchecked.");
    }
}); 

Example 3 - With jQuery prop

var check;
$("#test-with-prop").on("click", function(){
    check = $("#mycheckbox").prop("checked");
    if(check) {
         alert("Checkbox is checked.");
    } else {
        alert("Checkbox is unchecked.");
    }
}); 

Check Working jsfiddle

No server in windows>preferences

Follow the below steps:

1.Goto Help -> Install new Software
2.Give address http://download.eclipse.org/releases/oxygen and name as your choice.
3.Search for Java EE and choose 1.Eclipse Java EE Developer Tools 
4.Search for JST and choose 2.JST Server Adapters 3.JST Server Adapters 
5.Click next and accept the license agreement.

Find the server option in the window-->preferences and add server as you need

What is the difference between require and require-dev sections in composer.json?

General rule is that you want packages from require-dev section only in development (dev) environments, for example local environment.

Packages in require-dev section are packages which help you debug app, run tests etc.

At staging and production environment you probably want only packages from require section.

But anyway you can run composer install --no-dev and composer update --no-dev on any environment, command will install only packages from required section not from require-dev, but probably you want to run this only at staging and production environments not on local.

Theoretically you can put all packages in require section and nothing will happened, but you don't want developing packages at production environment because of the following reasons :

  1. speed
  2. potential of expose some debuging info
  3. etc

Some good candidates for require-dev are :

"filp/whoops": "^2.0",
"fzaninotto/faker": "^1.4",
"mockery/mockery": "^1.0",
"nunomaduro/collision": "^2.0",
"phpunit/phpunit": "^7.0"

you can see what above packages are doing and you will see why you don't need them on production.

See more here : https://getcomposer.org/doc/04-schema.md

How to make child process die after parent exits?

I found 2 solutions, both not perfect.

1.Kill all children by kill(-pid) when received SIGTERM signal.
Obviously, this solution can not handle "kill -9", but it do work for most case and very simple because it need not to remember all child processes.


    var childProc = require('child_process').spawn('tail', ['-f', '/dev/null'], {stdio:'ignore'});

    var counter=0;
    setInterval(function(){
      console.log('c  '+(++counter));
    },1000);

    if (process.platform.slice(0,3) != 'win') {
      function killMeAndChildren() {
        /*
        * On Linux/Unix(Include Mac OS X), kill (-pid) will kill process group, usually
        * the process itself and children.
        * On Windows, an JOB object has been applied to current process and children,
        * so all children will be terminated if current process dies by anyway.
        */
        console.log('kill process group');
        process.kill(-process.pid, 'SIGKILL');
      }

      /*
      * When you use "kill pid_of_this_process", this callback will be called
      */
      process.on('SIGTERM', function(err){
        console.log('SIGTERM');
        killMeAndChildren();
      });
    }

By same way, you can install 'exit' handler like above way if you call process.exit somewhere. Note: Ctrl+C and sudden crash have automatically been processed by OS to kill process group, so no more here.

2.Use chjj/pty.js to spawn your process with controlling terminal attached.
When you kill current process by anyway even kill -9, all child processes will be automatically killed too (by OS?). I guess that because current process hold another side of the terminal, so if current process dies, the child process will get SIGPIPE so dies.


    var pty = require('pty.js');

    //var term =
    pty.spawn('any_child_process', [/*any arguments*/], {
      name: 'xterm-color',
      cols: 80,
      rows: 30,
      cwd: process.cwd(),
      env: process.env
    });
    /*optionally you can install data handler
    term.on('data', function(data) {
      process.stdout.write(data);
    });
    term.write(.....);
    */

How do I update a GitHub forked repository?

There are two main things on keeping a forked repository always update for good.

1. Create the branches from the fork master and do changes there.

So when your Pull Request is accepted then you can safely delete the branch as your contributed code will be then live in your master of your forked repository when you update it with the upstream. By this your master will always be in clean condition to create a new branch to do another change.

2. Create a scheduled job for the fork master to do update automatically.

This can be done with cron. Here is for an example code if you do it in linux.

$ crontab -e

put this code on the crontab file to execute the job in hourly basis.

0 * * * * sh ~/cron.sh

then create the cron.sh script file and a git interaction with ssh-agent and/or expect as below

#!/bin/sh
WORKDIR=/path/to/your/dir   
REPOSITORY=<name of your repo>
MASTER="[email protected]:<username>/$REPOSITORY.git"   
[email protected]:<upstream>/<name of the repo>.git  

cd $WORKDIR && rm -rf $REPOSITORY
eval `ssh-agent` && expect ~/.ssh/agent && ssh-add -l
git clone $MASTER && cd $REPOSITORY && git checkout master
git remote add upstream $UPSTREAM && git fetch --prune upstream
if [ `git rev-list HEAD...upstream/master --count` -eq 0 ]
then
    echo "all the same, do nothing"
else
    echo "update exist, do rebase!"
    git reset --hard upstream/master
    git push origin master --force
fi
cd $WORKDIR && rm -rf $REPOSITORY
eval `ssh-agent -k`

Check your forked repository. From time to time it will always show this notification:

This branch is even with <upstream>:master.

enter image description here

How do I apply the for-each loop to every character in a String?

For Travers an String you can also use charAt() with the string.

like :

String str = "xyz"; // given String
char st = str.charAt(0); // for example we take 0 index element 
System.out.println(st); // print the char at 0 index 

charAt() is method of string handling in java which help to Travers the string for specific character.

Persistent invalid graphics state error when using ggplot2

I ran into this same error and solved it by running:

dev.off()

and then running the plot again. I think the graphics device was messed up earlier somehow by exporting some graphics and it didn't get reset. This worked for me and it's simpler than reinstalling ggplot2.

How do you list all triggers in a MySQL database?

For showing a particular trigger in a particular schema you can try the following:

select * from information_schema.triggers where 
information_schema.triggers.trigger_name like '%trigger_name%' and 
information_schema.triggers.trigger_schema like '%data_base_name%'

What is difference between sjlj vs dwarf vs seh?

SJLJ (setjmp/longjmp): – available for 32 bit and 64 bit – not “zero-cost”: even if an exception isn’t thrown, it incurs a minor performance penalty (~15% in exception heavy code) – allows exceptions to traverse through e.g. windows callbacks

DWARF (DW2, dwarf-2) – available for 32 bit only – no permanent runtime overhead – needs whole call stack to be dwarf-enabled, which means exceptions cannot be thrown over e.g. Windows system DLLs.

SEH (zero overhead exception) – will be available for 64-bit GCC 4.8.

source: https://wiki.qt.io/MinGW-64-bit

Fastest way to list all primes below N

For the fastest code, the numpy solution is the best. For purely academic reasons, though, I'm posting my pure python version, which is a bit less than 50% faster than the cookbook version posted above. Since I make the entire list in memory, you need enough space to hold everything, but it seems to scale fairly well.

def daniel_sieve_2(maxNumber):
    """
    Given a number, returns all numbers less than or equal to
    that number which are prime.
    """
    allNumbers = range(3, maxNumber+1, 2)
    for mIndex, number in enumerate(xrange(3, maxNumber+1, 2)):
        if allNumbers[mIndex] == 0:
            continue
        # now set all multiples to 0
        for index in xrange(mIndex+number, (maxNumber-3)/2+1, number):
            allNumbers[index] = 0
    return [2] + filter(lambda n: n!=0, allNumbers)

And the results:

>>>mine = timeit.Timer("daniel_sieve_2(1000000)",
...                    "from sieves import daniel_sieve_2")
>>>prev = timeit.Timer("get_primes_erat(1000000)",
...                    "from sieves import get_primes_erat")
>>>print "Mine: {0:0.4f} ms".format(min(mine.repeat(3, 1))*1000)
Mine: 428.9446 ms
>>>print "Previous Best {0:0.4f} ms".format(min(prev.repeat(3, 1))*1000)
Previous Best 621.3581 ms

How can I parse a time string containing milliseconds in it with python?

I know this is an older question but I'm still using Python 2.4.3 and I needed to find a better way of converting the string of data to a datetime.

The solution if datetime doesn't support %f and without needing a try/except is:

    (dt, mSecs) = row[5].strip().split(".") 
    dt = datetime.datetime(*time.strptime(dt, "%Y-%m-%d %H:%M:%S")[0:6])
    mSeconds = datetime.timedelta(microseconds = int(mSecs))
    fullDateTime = dt + mSeconds 

This works for the input string "2010-10-06 09:42:52.266000"

How to add an UIViewController's view as subview

Use:

[self.view addSubview:obj.view];

How to transition to a new view controller with code only using Swift

SWIFT

Usually for normal transition we use,

let next:SecondViewController = SecondViewController()
self.presentViewController(next, animated: true, completion: nil)

But sometimes when using navigation controller, you might face a black screen. In that case, you need to use like,

let next:ThirdViewController = storyboard?.instantiateViewControllerWithIdentifier("ThirdViewController") as! ThirdViewController
self.navigationController?.pushViewController(next, animated: true)

Moreover none of the above solution preserves navigationbar when you call from storyboard or single xib to another xib. If you use nav bar and want to preserve it just like normal push, you have to use,

Let's say, "MyViewController" is identifier for MyViewController

let viewController = MyViewController(nibName: "MyViewController", bundle: nil)
self.navigationController?.pushViewController(viewController, animated: true)

How to set .net Framework 4.5 version in IIS 7 application pool

There is no 4.5 application pool. You can use any 4.5 application in 4.0 app pool. The .NET 4.5 is "just" an in-place-update not a major new version.

How to check Spark Version

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

What Are The Best Width Ranges for Media Queries

best bet is targeting features not devices unless you have to, bootstrap do well and you can extend on their breakpoints, for instance targeting pixel density and larger screens above 1920

How do I get the find command to print out the file size with the file name?

If you need to get total size, here is a script proposal

#!/bin/bash
totalSize=0

allSizes=`find . -type f -name *.ear -exec stat -c "%s" {} \;`

for fileSize in $allSizes; do
    totalSize=`echo "$(($totalSize+$fileSize))"`
done
echo "Total size is $totalSize bytes"

How to increment a JavaScript variable using a button press event

The purist way to do this would be to add event handlers to the button, instead of mixing behavior with the content (LSM, Layered Semantic Markup)

<input type="button" value="Increment" id="increment"/>

<script type="text/javascript">
    var count = 0;
    // JQuery way
    $('#increment').click(function (e) {
        e.preventDefault();
        count++;
    });
    // YUI way
    YAHOO.util.Event.on('increment', 'click', function (e) {
        YAHOO.util.Event.preventDefault(e);
        count++;
    });
    // Simple way
    document.getElementById('increment').onclick = function (e) {
        count++;
        if (e.preventDefault) {
            e.preventDefault();
        }
        e.returnValue = false;
    };
</script>

select records from postgres where timestamp is in certain range

SELECT * 
FROM reservations 
WHERE arrival >= '2012-01-01'
AND arrival < '2013-01-01'
   ;

BTW if the distribution of values indicates that an index scan will not be the worth (for example if all the values are in 2012), the optimiser could still choose a full table scan. YMMV. Explain is your friend.

How to save username and password in Git?

From the comment by rifrol, on Linux Ubuntu, from this answer, here's how in Ubuntu:

sudo apt-get install libsecret-1-0 libsecret-1-dev
cd /usr/share/doc/git/contrib/credential/libsecret
sudo make
git config --global credential.helper /usr/share/doc/git/contrib/credential/libsecret/git-credential-libsecret

Some other distro's provide the binary so you don't have to build it.

In OS X it typically comes "built" with a default module of "osxkeychain" so you get it for free.

print spaces with String.format()

You need to specify the minimum width of the field.

String.format("%" + numberOfSpaces + "s", ""); 

Why do you want to generate a String of spaces of a certain length.

If you want a column of this length with values then you can do:

String.format("%" + numberOfSpaces + "s", "Hello"); 

which gives you numberOfSpaces-5 spaces followed by Hello. If you want Hello to appear on the left then add a minus sign in before numberOfSpaces.

Save bitmap to file function

  1. You need an appropriate permission in manifest.xml:

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    
  2. out.flush() check the out is not null..

  3. String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() + 
                                "/PhysicsSketchpad";
    File dir = new File(file_path);
    if(!dir.exists())
        dir.mkdirs();
    File file = new File(dir, "sketchpad" + pad.t_id + ".png");
    FileOutputStream fOut = new FileOutputStream(file);
    
    bmp.compress(Bitmap.CompressFormat.PNG, 85, fOut);
    fOut.flush();
    fOut.close();
    

Manifest Merger failed with multiple errors in Android Studio

this is very simple error only occur when you define any activity call two time in mainifest.xml file Example like

<activity android:name="com.futuretech.mpboardexam.Game" ></activity>

//and launcher also------like that



//solution:use only one 

In vb.net, how to get the column names from a datatable

Look at

For Each c as DataColumn in dt.Columns
  '... = c.ColumnName
Next

or:

dt.GetDataTableSchema(...)