Programs & Examples On #Glossaries

Fastest way to get the first n elements of a List into an Array

It mostly depends on how big n is.

If n==0, nothing beats option#1 :)

If n is very large, toArray(new String[n]) is faster.

Is it possible to add an array or object to SharedPreferences on Android

This is the shared preferences code i use successfully, Refer this link:

  public class MainActivity extends Activity {

private static final int RESULT_SETTINGS = 1;
Button button;
public String a="dd";

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

 button = (Button) findViewById(R.id.btnoptions);


setContentView(R.layout.activity_main);

  // showUserSettings();
  }

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.settings, menu);
return true;
 }

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {

case R.id.menu_settings:
 Intent i = new Intent(this, UserSettingActivity.class);
 startActivityForResult(i, RESULT_SETTINGS);
 break;

 }

return true;
}

@Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data)     {
  super.onActivityResult(requestCode, resultCode, data);

 switch (requestCode) {
 case RESULT_SETTINGS:
 showUserSettings();
 break;

 } 

  }

  private void showUserSettings() {
 SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this);

 StringBuilder builder = new StringBuilder();

 builder.append("\n Pet: "
  + sharedPrefs.getString("prefpetname", "NULL"));

 builder.append("\n Address:"
 + sharedPrefs.getString("prefaddress","NULL" ));

 builder.append("\n Your name: "
 + sharedPrefs.getString("prefname", "NULL"));

 TextView settingsTextView = (TextView) findViewById(R.id.textUserSettings);


  settingsTextView.setText(builder.toString());


    }

   }

HAPPY CODING!

PHP Warning: PHP Startup: Unable to load dynamic library

If you just want to make the error disappear, and you don't need the extension, then by all means comment the line out in php.ini. But if you actually want to fix the problem here is some additional info.

There are various causes for this based on the exact module, but there are also some general guidelines.

  1. Open phpinfo() and look for extension_dir under the Core section. This is where your modules should be located.

For instance, /usr/lib/php/modules for Unix/Linux.

  1. If the file does in fact exist, make sure permissions are adequate.
  2. If the file does not exist, use the resources below to install it.

Installation on *nix (PEAR)
Installation of extensions on Windows

Validate a username and password against Active Directory?

Several solutions presented here lack the ability to differentiate between a wrong user / password, and a password that needs to be changed. That can be done in the following way:

using System;
using System.DirectoryServices.Protocols;
using System.Net;

namespace ProtocolTest
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                LdapConnection connection = new LdapConnection("ldap.fabrikam.com");
                NetworkCredential credential = new NetworkCredential("user", "password");
                connection.Credential = credential;
                connection.Bind();
                Console.WriteLine("logged in");
            }
            catch (LdapException lexc)
            {
                String error = lexc.ServerErrorMessage;
                Console.WriteLine(lexc);
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc);
            }
        }
    }
}

If the users password is wrong, or the user doesn't exists, error will contain

"8009030C: LdapErr: DSID-0C0904DC, comment: AcceptSecurityContext error, data 52e, v1db1",

if the users password needs to be changed, it will contain

"8009030C: LdapErr: DSID-0C0904DC, comment: AcceptSecurityContext error, data 773, v1db1"

The lexc.ServerErrorMessage data value is a hex representation of the Win32 Error Code. These are the same error codes which would be returned by otherwise invoking the Win32 LogonUser API call. The list below summarizes a range of common values with hex and decimal values:

525? user not found ?(1317)
52e? invalid credentials ?(1326)
530? not permitted to logon at this time? (1328)
531? not permitted to logon at this workstation? (1329)
532? password expired ?(1330)
533? account disabled ?(1331) 
701? account expired ?(1793)
773? user must reset password (1907)
775? user account locked (1909)

How to create a directory using Ansible

Directory can be created using file module only, as directory is nothing but a file.

# create a directory if it doesn't exist
- file:
    path: /etc/some_directory
    state: directory
    mode: 0755
    owner: foo
    group: foo

Python Serial: How to use the read or readline function to read more than 1 character at a time

Serial sends data 8 bits at a time, that translates to 1 byte and 1 byte means 1 character.

You need to implement your own method that can read characters into a buffer until some sentinel is reached. The convention is to send a message like 12431\n indicating one line.

So what you need to do is to implement a buffer that will store X number of characters and as soon as you reach that \n, perform your operation on the line and proceed to read the next line into the buffer.

Note you will have to take care of buffer overflow cases i.e. when a line is received that is longer than your buffer etc...

EDIT

import serial

ser = serial.Serial(
    port='COM5',\
    baudrate=9600,\
    parity=serial.PARITY_NONE,\
    stopbits=serial.STOPBITS_ONE,\
    bytesize=serial.EIGHTBITS,\
        timeout=0)

print("connected to: " + ser.portstr)

#this will store the line
line = []

while True:
    for c in ser.read():
        line.append(c)
        if c == '\n':
            print("Line: " + ''.join(line))
            line = []
            break

ser.close()

Select first 4 rows of a data.frame in R

If you have less than 4 rows, you can use the head function ( head(data, 4) or head(data, n=4)) and it works like a charm. But, assume we have the following dataset with 15 rows

>data <- data <- read.csv("./data.csv", sep = ";", header=TRUE)

>data
 LungCap Age Height Smoke Gender Caesarean
1    6.475   6   62.1    no   male        no
2   10.125  18   74.7   yes female        no
3    9.550  16   69.7    no female       yes
4   11.125  14   71.0    no   male        no
5    4.800   5   56.9    no   male        no
6    6.225  11   58.7    no female        no
7    4.950   8   63.3    no   male       yes
8    7.325  11   70.4    no  male         no
9    8.875  15   70.5    no   male        no
10   6.800  11   59.2    no   male        no
11   6.900  12   59.3    no   male        no
12   6.100  13   59.4    no   male        no
13   6.110  14   59.5    no   male        no
14   6.120  15   59.6    no   male        no
15   6.130  16   59.7    no   male        no

Let's say, you want to select the first 10 rows. The easiest way to do it would be data[1:10, ].

> data[1:10,]
   LungCap Age Height Smoke Gender Caesarean
1    6.475   6   62.1    no   male        no
2   10.125  18   74.7   yes female        no
3    9.550  16   69.7    no female       yes
4   11.125  14   71.0    no   male        no
5    4.800   5   56.9    no   male        no
6    6.225  11   58.7    no female        no
7    4.950   8   63.3    no   male       yes
8    7.325  11   70.4    no  male         no
9    8.875  15   70.5    no   male        no
10   6.800  11   59.2    no   male        no

However, let's say you try to retrieve the first 19 rows and see the what happens - you will have missing values

> data[1:19,]
     LungCap Age Height Smoke Gender Caesarean
1      6.475   6   62.1    no   male        no
2     10.125  18   74.7   yes female        no
3      9.550  16   69.7    no female       yes
4     11.125  14   71.0    no   male        no
5      4.800   5   56.9    no   male        no
6      6.225  11   58.7    no female        no
7      4.950   8   63.3    no   male       yes
8      7.325  11   70.4    no  male         no
9      8.875  15   70.5    no   male        no
10     6.800  11   59.2    no   male        no
11     6.900  12   59.3    no   male        no
12     6.100  13   59.4    no   male        no
13     6.110  14   59.5    no   male        no
14     6.120  15   59.6    no   male        no
15     6.130  16   59.7    no   male        no
NA        NA  NA     NA  <NA>   <NA>      <NA>
NA.1      NA  NA     NA  <NA>   <NA>      <NA>
NA.2      NA  NA     NA  <NA>   <NA>      <NA>
NA.3      NA  NA     NA  <NA>   <NA>      <NA>

and with the head() function,

> head(data, 19) # or head(data, n=19)
   LungCap Age Height Smoke Gender Caesarean
1    6.475   6   62.1    no   male        no
2   10.125  18   74.7   yes female        no
3    9.550  16   69.7    no female       yes
4   11.125  14   71.0    no   male        no
5    4.800   5   56.9    no   male        no
6    6.225  11   58.7    no female        no
7    4.950   8   63.3    no   male       yes
8    7.325  11   70.4    no  male         no
9    8.875  15   70.5    no   male        no
10   6.800  11   59.2    no   male        no
11   6.900  12   59.3    no   male        no
12   6.100  13   59.4    no   male        no
13   6.110  14   59.5    no   male        no
14   6.120  15   59.6    no   male        no
15   6.130  16   59.7    no   male        no

Hope this help!

How to check if number is divisible by a certain number?

n % x == 0

Means that n can be divided by x. So... for instance, in your case:

boolean isDivisibleBy20 = number % 20 == 0;

Also, if you want to check whether a number is even or odd (whether it is divisible by 2 or not), you can use a bitwise operator:

boolean even = (number & 1) == 0;
boolean odd  = (number & 1) != 0;

CSS3 Rotate Animation

Here is a demo. The correct animation CSS:

_x000D_
_x000D_
.image {_x000D_
    position: absolute;_x000D_
    top: 50%;_x000D_
    left: 50%;_x000D_
    width: 120px;_x000D_
    height: 120px;_x000D_
    margin:-60px 0 0 -60px;_x000D_
    -webkit-animation:spin 4s linear infinite;_x000D_
    -moz-animation:spin 4s linear infinite;_x000D_
    animation:spin 4s linear infinite;_x000D_
}_x000D_
@-moz-keyframes spin { 100% { -moz-transform: rotate(360deg); } }_x000D_
@-webkit-keyframes spin { 100% { -webkit-transform: rotate(360deg); } }_x000D_
@keyframes spin { 100% { -webkit-transform: rotate(360deg); transform:rotate(360deg); } }
_x000D_
<img class="image" src="http://i.stack.imgur.com/pC1Tv.jpg" alt="" width="120" height="120">
_x000D_
_x000D_
_x000D_


Some notes on your code:

  1. You've nested the keyframes inside the .image rule, and that's incorrect
  2. float:left won't work on absolutely positioned elements
  3. Have a look at caniuse: IE10 doesn't need the -ms- prefix

Do you recommend using semicolons after every statement in JavaScript?

JavaScript automatically inserts semicolons whilst interpreting your code, so if you put the value of the return statement below the line, it won't be returned:

Your Code:

return
5

JavaScript Interpretation:

return;
5;

Thus, nothing is returned, because of JavaScript's auto semicolon insertion

Cursor adapter and sqlite example

CursorAdapter Example with Sqlite

...
DatabaseHelper helper = new DatabaseHelper(this);
aListView = (ListView) findViewById(R.id.aListView);
Cursor c = helper.getAllContacts();
CustomAdapter adapter = new CustomAdapter(this, c);
aListView.setAdapter(adapter);
...

class CustomAdapter extends CursorAdapter {
    // CursorAdapter will handle all the moveToFirst(), getCount() logic for you :)

    public CustomAdapter(Context context, Cursor c) {
        super(context, c);
    }

    public void bindView(View view, Context context, Cursor cursor) {
        String id = cursor.getString(0);
        String name = cursor.getString(1);
        // Get all the values
        // Use it however you need to
        TextView textView = (TextView) view;
        textView.setText(name);
    }

    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        // Inflate your view here.
        TextView view = new TextView(context);
        return view;
    }
}

private final class DatabaseHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "db_name";
    private static final int DATABASE_VERSION = 1;
    private static final String CREATE_TABLE_TIMELINE = "CREATE TABLE IF NOT EXISTS table_name (_id INTEGER PRIMARY KEY AUTOINCREMENT, name varchar);";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_TIMELINE);
        db.execSQL("INSERT INTO ddd (name) VALUES ('One')");
        db.execSQL("INSERT INTO ddd (name) VALUES ('Two')");
        db.execSQL("INSERT INTO ddd (name) VALUES ('Three')");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    public Cursor getAllContacts() {
        String selectQuery = "SELECT  * FROM table_name;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        return cursor;
    }
}

How do I get the browser scroll position in jQuery?

Pure javascript can do!

var scrollTop = window.pageYOffset || document.documentElement.scrollTop;

Python Pandas: How to read only first n rows of CSV files in?

If you only want to read the first 999,999 (non-header) rows:

read_csv(..., nrows=999999)

If you only want to read rows 1,000,000 ... 1,999,999

read_csv(..., skiprows=1000000, nrows=999999)

nrows : int, default None Number of rows of file to read. Useful for reading pieces of large files*

skiprows : list-like or integer Row numbers to skip (0-indexed) or number of rows to skip (int) at the start of the file

and for large files, you'll probably also want to use chunksize:

chunksize : int, default None Return TextFileReader object for iteration

pandas.io.parsers.read_csv documentation

Angular + Material - How to refresh a data source (mat-table)

Trigger a change detection by using ChangeDetectorRef in the refresh() method just after receiving the new data, inject ChangeDetectorRef in the constructor and use detectChanges like this:

import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { LanguageModel, LANGUAGE_DATA } from '../../../../models/language.model';
import { LanguageAddComponent } from './language-add/language-add.component';
import { AuthService } from '../../../../services/auth.service';
import { LanguageDataSource } from './language-data-source';
import { LevelbarComponent } from '../../../../directives/levelbar/levelbar.component';
import { DataSource } from '@angular/cdk/collections';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import { MatSnackBar, MatDialog } from '@angular/material';

@Component({
  selector: 'app-language',
  templateUrl: './language.component.html',
  styleUrls: ['./language.component.scss']
})
export class LanguageComponent implements OnInit {
  displayedColumns = ['name', 'native', 'code', 'level'];
  teachDS: any;

  user: any;

  constructor(private authService: AuthService, private dialog: MatDialog,
              private changeDetectorRefs: ChangeDetectorRef) { }

  ngOnInit() {
    this.refresh();
  }

  add() {
    this.dialog.open(LanguageAddComponent, {
      data: { user: this.user },
    }).afterClosed().subscribe(result => {
      this.refresh();
    });
  }

  refresh() {
    this.authService.getAuthenticatedUser().subscribe((res) => {
      this.user = res;
      this.teachDS = new LanguageDataSource(this.user.profile.languages.teach);
      this.changeDetectorRefs.detectChanges();
    });
  }
}

Failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

Firstly, I would try a non-secure websocket connection. So remove one of the s's from the connection address:

conn = new WebSocket('ws://localhost:8080');

If that doesn't work, then the next thing I would check is your server's firewall settings. You need to open port 8080 both in TCP_IN and TCP_OUT.

Importing large sql file to MySql via command line

You can import .sql file using the standard input like this:

mysql -u <user> -p<password> <dbname> < file.sql

Note: There shouldn't space between <-p> and <password>

Reference: http://dev.mysql.com/doc/refman/5.0/en/mysql-batch-commands.html

Note for suggested edits: This answer was slightly changed by suggested edits to use inline password parameter. I can recommend it for scripts but you should be aware that when you write password directly in the parameter (-p<password>) it may be cached by a shell history revealing your password to anyone who can read the history file. Whereas -p asks you to input password by standard input.

Is System.nanoTime() completely useless?

This doesn't seem to be a problem on a Core 2 Duo running Windows XP and JRE 1.5.0_06.

In a test with three threads I don't see System.nanoTime() going backwards. The processors are both busy, and threads go to sleep occasionally to provoke moving threads around.

[EDIT] I would guess that it only happens on physically separate processors, i.e. that the counters are synchronized for multiple cores on the same die.

Get epoch for a specific date using Javascript

You can create a Date object, and call getTime on it:

new Date(2010, 6, 26).getTime() / 1000

Can I change the scroll speed using css or jQuery?

The scroll speed CAN be changed, adjusted, reversed, all of the above - via javascript (or a js library such as jQuery).

WHY would you want to do this? Parallax is just one of the reasons. I have no idea why anyone would argue against doing so -- the same negative arguments can be made against hiding DIVs, sliding elements up/down, etc. Websites are always a combination of technical functionality and UX design -- a good designer can use almost any technical capability to improve UX. That is what makes him/her good.

Toni Almeida of Portugal created a brilliant demo, reproduced below:

jsFiddle Demo

HTML:

<div id="myDiv">
    Use the mouse wheel (not the scroll bar) to scroll this DIV. You will see that the scroll eventually slows down, and then stops. <span class="boldit">Use the mouse wheel (not the scroll bar) to scroll this DIV. You will see that the scroll eventually slows down, and then stops. </span>
</div>

javascript/jQuery:

  function wheel(event) {
      var delta = 0;
      if (event.wheelDelta) {(delta = event.wheelDelta / 120);}
      else if (event.detail) {(delta = -event.detail / 3);}

      handle(delta);
      if (event.preventDefault) {(event.preventDefault());}
      event.returnValue = false;
  }

  function handle(delta) {
      var time = 1000;
      var distance = 300;

      $('html, body').stop().animate({
          scrollTop: $(window).scrollTop() - (distance * delta)
      }, time );
  }

  if (window.addEventListener) {window.addEventListener('DOMMouseScroll', wheel, false);}
    window.onmousewheel = document.onmousewheel = wheel;

Source:

How to change default scrollspeed,scrollamount,scrollinertia of a webpage

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

I wrote the Text-IO library, which can deal with the problem of System.console() being null when running an application from within an IDE.

It introduces an abstraction layer similar to the one proposed by McDowell. If System.console() returns null, the library switches to a Swing-based console.

In addition, Text-IO has a series of useful features:

  • supports reading values with various data types.
  • allows masking the input when reading sensitive data.
  • allows selecting a value from a list.
  • allows specifying constraints on the input values (format patterns, value ranges, length constraints etc.).

Usage example:

TextIO textIO = TextIoFactory.getTextIO();

String user = textIO.newStringInputReader()
        .withDefaultValue("admin")
        .read("Username");

String password = textIO.newStringInputReader()
        .withMinLength(6)
        .withInputMasking(true)
        .read("Password");

int age = textIO.newIntInputReader()
        .withMinVal(13)
        .read("Age");

Month month = textIO.newEnumInputReader(Month.class)
        .read("What month were you born in?");

textIO.getTextTerminal().println("User " + user + " is " + age + " years old, " +
        "was born in " + month + " and has the password " + password + ".");

In this image you can see the above code running in a Swing-based console.

Eclipse - Failed to create the java virtual machine

Recently i encounter this issue and try all of the above method but none of them works for me.

Here is another Trick for to solve this error is

i just delete the eclipse configuration file and eclipse start working.. i don't know why but it works.

Maybe this helps someone else.

How to remove focus from single editText

If I understand your question correctly, this should help you:

TextView tv1 = (TextView) findViewById(R.id.tv1);
tv1 .setFocusable(false);

Escape sequence \f - form feed - what exactly is it?

If you were programming for a 1980s-style printer, it would eject the paper and start a new page. You are virtually certain to never need it.

http://en.wikipedia.org/wiki/Form_feed

enumerate() for dictionary in python

Since you are using enumerate hence your i is actually the index of the key rather than the key itself.

So, you are getting 3 in the first column of the row 3 4even though there is no key 3.

enumerate iterates through a data structure(be it list or a dictionary) while also providing the current iteration number.

Hence, the columns here are the iteration number followed by the key in dictionary enum

Others Solutions have already shown how to iterate over key and value pair so I won't repeat the same in mine.

Vertically align text within a div

The accepted answer doesn't work for multi-line text.

I updated the JSfiddle to show CSS multiline text vertical align as explained here:

<div id="column-content">
    <div>yet another text content that should be centered vertically</div>
</div>

#column-content {
    border: 1px solid red;
    height: 200px;
    width: 100px;
}
div {
    display: table-cell;
    vertical-align:middle;
    text-align: center;
}

It also works with <br /> in "yet another..."

Select all where [first letter starts with B]

Following your comment posted to ceejayoz's answer, two things are messed up a litte:

  1. $first is not an array, it's a string. Replace $first = $first[0] . "%" by $first .= "%". Just for simplicity. (PHP string operators)

  2. The string being compared with LIKE operator should be quoted. Replace LIKE ".$first."") by LIKE '".$first."'"). (MySQL String Comparison Functions)

Check if a number has a decimal place/is a whole number

You can multiply it by 10 and then do a "modulo" operation/divison with 10, and check if result of that two operations is zero. Result of that two operations will give you first digit after the decimal point. If result is equal to zero then the number is a whole number.

if ( (int)(number * 10.0) % 10 == 0 ){
// your code
}

Jquery checking success of ajax post

I was wondering, why they didnt provide in jquery itself, so i made a few changes in jquery file ,,, here are the changed code block:

original Code block:

    post: function( url, data, callback, type ) {
    // shift arguments if data argument was omited
    if ( jQuery.isFunction( data ) ) {
        type = type || callback;
        callback = data;
        data = {};
    }

    return jQuery.ajax({
        type: "POST",
        url: url,
        data: data,
        success: callback,
        dataType: type
    });  

Changed Code block:

        post: function (url, data, callback, failcallback, type) {
        if (type === undefined || type === null) {
            if (!jQuery.isFunction(failcallback)) { 
            type=failcallback
        }
        else if (!jQuery.isFunction(callback)) {
            type = callback
        }
        }
        if (jQuery.isFunction(data) && jQuery.isFunction(callback)) {
            failcallback = callback;

        }
        // shift arguments if data argument was omited
        if (jQuery.isFunction(data)) {
            type = type || callback;
            callback = data;
            data = {};

        }


        return jQuery.ajax({
            type: "POST",
            url: url,
            data: data,
            success: callback,
            error:failcallback,
            dataType: type
        });
    },

This should help the one trying to catch error on $.Post in jquery.

Updated: Or there is another way to do this is :

   $.post(url,{},function(res){
        //To do write if call is successful
   }).error(function(p1,p2,p3){
             //To do Write if call is failed
          });

How to fetch all Git branches

To avoid the error message 'fatal: A branch named 'origin/master' already exists.', you may try my solution:

git branch -r | grep -v '\->'  | grep -v `git branch | awk '/\*/ { print $2; }'`| while read remote; do git branch --track "${remote#origin/}" "$remote"; done

What are the Ruby File.open modes and options?

In Ruby IO module documentation, I suppose.

Mode |  Meaning
-----+--------------------------------------------------------
"r"  |  Read-only, starts at beginning of file  (default mode).
-----+--------------------------------------------------------
"r+" |  Read-write, starts at beginning of file.
-----+--------------------------------------------------------
"w"  |  Write-only, truncates existing file
     |  to zero length or creates a new file for writing.
-----+--------------------------------------------------------
"w+" |  Read-write, truncates existing file to zero length
     |  or creates a new file for reading and writing.
-----+--------------------------------------------------------
"a"  |  Write-only, starts at end of file if file exists,
     |  otherwise creates a new file for writing.
-----+--------------------------------------------------------
"a+" |  Read-write, starts at end of file if file exists,
     |  otherwise creates a new file for reading and
     |  writing.
-----+--------------------------------------------------------
"b"  |  Binary file mode (may appear with
     |  any of the key letters listed above).
     |  Suppresses EOL <-> CRLF conversion on Windows. And
     |  sets external encoding to ASCII-8BIT unless explicitly
     |  specified.
-----+--------------------------------------------------------
"t"  |  Text file mode (may appear with
     |  any of the key letters listed above except "b").

ReactJs: What should the PropTypes be for this.props.children?

Try a custom propTypes :

 const  childrenPropTypeLogic = (props, propName, componentName) => {
          const prop = props[propName];
          return React.Children
                   .toArray(prop)
                   .find(child => child.type !== 'div') && new Error(`${componentName} only accepts "div" elements`);
 };


static propTypes = {

   children : childrenPropTypeLogic

}

Fiddle

_x000D_
_x000D_
const {Component, PropTypes} = React;_x000D_
_x000D_
 const  childrenPropTypeLogic = (props, propName, componentName) => {_x000D_
             var error;_x000D_
          var prop = props[propName];_x000D_
    _x000D_
          React.Children.forEach(prop, function (child) {_x000D_
            if (child.type !== 'div') {_x000D_
              error = new Error(_x000D_
                '`' + componentName + '` only accepts children of type `div`.'_x000D_
              );_x000D_
            }_x000D_
          });_x000D_
    _x000D_
          return error;_x000D_
    };_x000D_
    _x000D_
  _x000D_
_x000D_
class ContainerComponent extends Component {_x000D_
  static propTypes = {_x000D_
    children: childrenPropTypeLogic,_x000D_
  }_x000D_
_x000D_
  render() {_x000D_
    return (_x000D_
      <div>_x000D_
        {this.props.children}_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
class App extends Component {_x000D_
   render(){_x000D_
    return (_x000D_
    <ContainerComponent>_x000D_
        <div>1</div>_x000D_
        <div>2</div>_x000D_
      </ContainerComponent>_x000D_
    )_x000D_
   }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<App /> , document.querySelector('section'))
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
_x000D_
<section />
_x000D_
_x000D_
_x000D_

Reference requirements.txt for the install_requires kwarg in setuptools setup.py file

It can't take a file handle. The install_requires argument can only be a string or a list of strings.

You can, of course, read your file in the setup script and pass it as a list of strings to install_requires.

import os
from setuptools import setup

with open('requirements.txt') as f:
    required = f.read().splitlines()

setup(...
install_requires=required,
...)

Replacing &nbsp; from javascript dom text node

I think when you define a function with "var foo = function() {...};", the function is only defined after that line. In other words, try this:

var replaceHtmlEntites = (function() {
  var translate_re = /&(nbsp|amp|quot|lt|gt);/g;
  var translate = {
    "nbsp": " ",
    "amp" : "&",
    "quot": "\"",
    "lt"  : "<",
    "gt"  : ">"
  };
  return function(s) {
    return ( s.replace(translate_re, function(match, entity) {
      return translate[entity];
    }) );
  }
})();

var cleanText = text.replace(/^\xa0*([^\xa0]*)\xa0*$/g,"");
cleanText = replaceHtmlEntities(text);

Edit: Also, only use "var" the first time you declare a variable (you're using it twice on the cleanText variable).

Edit 2: The problem is the spelling of the function name. You have "var replaceHtmlEntites =". It should be "var replaceHtmlEntities ="

jQuery UI autocomplete with JSON

I use this script for autocomplete...

$('#custmoers_name').autocomplete({
    source: function (request, response) {

        // $.getJSON("<?php echo base_url('index.php/Json_cr_operation/autosearch_custmoers');?>", function (data) {
          $.getJSON("Json_cr_operation/autosearch_custmoers?term=" + request.term, function (data) {
          console.log(data);
            response($.map(data, function (value, key) {
                console.log(value);
                return {
                    label: value.label,
                    value: value.value
                };
            }));
        });
    },
    minLength: 1,
    delay: 100
});

My json return :- [{"label":"Mahesh Arun Wani","value":"1"}] after search m

but it display in dropdown [object object]...

SQL: Combine Select count(*) from multiple tables

SELECT 
(select count(*) from foo1 where ID = '00123244552000258')
+
(select count(*) from foo2 where ID = '00123244552000258')
+
(select count(*) from foo3 where ID = '00123244552000258')

This is an easy way.

How can I produce an effect similar to the iOS 7 blur view?

Actually I'd bet this would be rather simple to achieve. It probably wouldn't operate or look exactly like what Apple has going on but could be very close.

First of all, you'd need to determine the CGRect of the UIView that you will be presenting. Once you've determine that you would just need to grab an image of the part of the UI so that it can be blurred. Something like this...

- (UIImage*)getBlurredImage {
    // You will want to calculate this in code based on the view you will be presenting.
    CGSize size = CGSizeMake(200,200);

    UIGraphicsBeginImageContext(size);
    [view drawViewHierarchyInRect:(CGRect){CGPointZero, w, h} afterScreenUpdates:YES]; // view is the view you are grabbing the screen shot of. The view that is to be blurred.
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    // Gaussian Blur
    image = [image applyLightEffect];

    // Box Blur
    // image = [image boxblurImageWithBlur:0.2f];

    return image;
}

Gaussian Blur - Recommended

Using the UIImage+ImageEffects Category Apple's provided here, you'll get a gaussian blur that looks very much like the blur in iOS 7.

Box Blur

You could also use a box blur using the following boxBlurImageWithBlur: UIImage category. This is based on an algorythem that you can find here.

@implementation UIImage (Blur)

-(UIImage *)boxblurImageWithBlur:(CGFloat)blur {
    if (blur < 0.f || blur > 1.f) {
        blur = 0.5f;
    }
    int boxSize = (int)(blur * 50);
    boxSize = boxSize - (boxSize % 2) + 1;

    CGImageRef img = self.CGImage;

    vImage_Buffer inBuffer, outBuffer;

    vImage_Error error;

    void *pixelBuffer;

    CGDataProviderRef inProvider = CGImageGetDataProvider(img);
    CFDataRef inBitmapData = CGDataProviderCopyData(inProvider);

    inBuffer.width = CGImageGetWidth(img);
    inBuffer.height = CGImageGetHeight(img);
    inBuffer.rowBytes = CGImageGetBytesPerRow(img);

    inBuffer.data = (void*)CFDataGetBytePtr(inBitmapData);

    pixelBuffer = malloc(CGImageGetBytesPerRow(img) * CGImageGetHeight(img));

    if(pixelBuffer == NULL)
        NSLog(@"No pixelbuffer");

    outBuffer.data = pixelBuffer;
    outBuffer.width = CGImageGetWidth(img);
    outBuffer.height = CGImageGetHeight(img);
    outBuffer.rowBytes = CGImageGetBytesPerRow(img);

    error = vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, NULL, 0, 0, boxSize, boxSize, NULL, kvImageEdgeExtend);

    if (error) {
        NSLog(@"JFDepthView: error from convolution %ld", error);
    }

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef ctx = CGBitmapContextCreate(outBuffer.data,
                                         outBuffer.width,
                                         outBuffer.height,
                                         8,
                                         outBuffer.rowBytes,
                                         colorSpace,
                                         kCGImageAlphaNoneSkipLast);
    CGImageRef imageRef = CGBitmapContextCreateImage (ctx);
    UIImage *returnImage = [UIImage imageWithCGImage:imageRef];

    //clean up
    CGContextRelease(ctx);
    CGColorSpaceRelease(colorSpace);

    free(pixelBuffer);
    CFRelease(inBitmapData);

    CGImageRelease(imageRef);

    return returnImage;
}

@end

Now that you are calculating the screen area to blur, passing it into the blur category and receiving a UIImage back that has been blurred, now all that is left is to set that blurred image as the background of the view you will be presenting. Like I said, this will not be a perfect match for what Apple is doing, but it should still look pretty cool.

Hope it helps.

Should I use int or Int32

Use of Int or Int32 are the same Int is just sugar to simplify the code for the reader.

Use the Nullable variant Int? or Int32? when you work with databases on fields containing null. That will save you from a lot of runtime issues.

Eclipse : Maven search dependencies doesn't work

Eclipse artifact searching depends on repository's index file. It seems you did not download the index file.

Go to Window -> Prefrences -> Maven and check "Download repository index updates on start". Restart Eclipse and then look at the progress view. An index file should be downloading.

After downloading completely, artifact searching will be ready to use.

Maven Settings

UPDATE You also need to rebuild your Maven repository index in 'maven repository view'.

In this view , open 'Global Repositories', right-click 'central', check 'Full Index Enable', and then, click 'Rebuild Index' in the same menu.

A 66M index file will be downloaded.

Maven Repositories -> Rebuild Index

Sending email with gmail smtp with codeigniter email library

Perhaps your hosting server and email server are located at same place and you don't need to go for smtp authentication. Just keep every thing default like:

$config = array(        
    'protocol' => '',
    'smtp_host' => '',
    'smtp_port' => '',
    'smtp_user' => '[email protected]',
    'smtp_pass' => '**********'
    );

or

$config['protocol'] = '';
$config['smtp_host'] = '';
$config['smtp_port'] = ;
$config['smtp_user'] = '[email protected]';
$config['smtp_pass'] = 'password';

it works for me.

"RuntimeError: Make sure the Graphviz executables are on your system's path" after installing Graphviz 2.38

I had the same error message on Mac OS (El Capitan), using the PyCharm IDE. I had installed Graphviz using brew, as recommended in RZK's answer, and installed the graphviz python package using PyCharm (I could check Graphviz was installed correctly by trying dot -V in a terminal and getting: dot - graphviz version 2.40.1 (20161225.0304)). Yet I was still getting the error message when trying to call Graphviz from PyCharm.

I had to add the path /usr/local/bin in PyCharm options, as recommended in the answer to this question to resolve the problem.

What is the "hasClass" function with plain JavaScript?

hasClass function:

HTMLElement.prototype.hasClass = function(cls) {
    var i;
    var classes = this.className.split(" ");
    for(i = 0; i < classes.length; i++) {
        if(classes[i] == cls) {
            return true;
        }
    }
    return false;
};

addClass function:

HTMLElement.prototype.addClass = function(add) {
    if (!this.hasClass(add)){
        this.className = (this.className + " " + add).trim();
    }
};

removeClass function:

HTMLElement.prototype.removeClass = function(remove) {
    var newClassName = "";
    var i;
    var classes = this.className.replace(/\s{2,}/g, ' ').split(" ");
    for(i = 0; i < classes.length; i++) {
        if(classes[i] !== remove) {
            newClassName += classes[i] + " ";
        }
    }
    this.className = newClassName.trim();
};

What is an .axd file?

from Google

An .axd file is a HTTP Handler file. There are two types of .axd files.

  1. ScriptResource.axd
  2. WebResource.axd

These are files which are generated at runtime whenever you use ScriptManager in your Web app. This is being generated only once when you deploy it on the server.

Simply put the ScriptResource.AXD contains all of the clientside javascript routines for Ajax. Just because you include a scriptmanager that loads a script file it will never appear as a ScriptResource.AXD - instead it will be merely passed as the .js file you send if you reference a external script file. If you embed it in code then it may merely appear as part of the html as a tag and code but depending if you code according to how the ToolKit handles it - may or may not appear as as a ScriptResource.axd. ScriptResource.axd is only introduced with AJAX and you will never see it elsewhere

And ofcourse it is necessary

SHOW PROCESSLIST in MySQL command: sleep

Sleep meaning that thread is do nothing. Time is too large beacuse anthor thread query,but not disconnect server, default wait_timeout=28800;so you can set values smaller,eg 10. also you can kill the thread.

Using getline() in C++

i think you are not pausing the program before it ended so the output you are putting after getting the inpus is not seeing on the screen right?

do:

getchar();

before the end of the program

Eclipse error: indirectly referenced from required .class files?

This error occurs when the classes in the jar file does not follow the same structure as of the folder structure of the jar..

e.g. if you class file has package com.test.exam and the classes.jar created out of this class file has structure test.exam... error will be thrown. You need to correct the package structure of your classes.jar and then include it in ecplipse build path...

How to print / echo environment variables?

This works too, with the semi-colon.

NAME=sam; echo $NAME

Is there any way to have a fieldset width only be as wide as the controls in them?

            <table style="position: relative; top: -0px; left: 0px;">
                <tr>
                    <td>
                        <div>   
                            <fieldset style="width:0px">
                                <legend>A legend</legend>
                                <br/>
                                <table cellspacing="0" align="left">
                                    <tbody>
                                        <tr>
                                            <td align='left' style="white-space: nowrap;">
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </fieldset>
                        </div>
                    </td>
                </tr>
            </table>

Difference between Math.Floor() and Math.Truncate()

Math.Floor(): Returns the largest integer less than or equal to the specified double-precision floating-point number.

Math.Round(): Rounds a value to the nearest integer or to the specified number of fractional digits.

Create session factory in Hibernate 4

Yes, they have deprecated the previous buildSessionFactory API, and it's quite easy to do well.. you can do something like this..

EDIT : ServiceRegistryBuilder is deprecated. you must use StandardServiceRegistryBuilder

public void testConnection() throws Exception {

            logger.info("Trying to create a test connection with the database.");
            Configuration configuration = new Configuration();
            configuration.configure("hibernate_sp.cfg.xml");
            StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
            SessionFactory sessionFactory = configuration.buildSessionFactory(ssrb.build());
            Session session = sessionFactory.openSession();
            logger.info("Test connection with the database created successfuly.");
    }

For more reference and in depth detail, you can check the hibernate's official test case at https://github.com/hibernate/hibernate-orm/blob/master/hibernate-testing/src/main/java/org/hibernate/testing/junit4/BaseCoreFunctionalTestCase.java function (buildSessionFactory()).

libclntsh.so.11.1: cannot open shared object file.

If you have problem with libclntsh.so, need create symlink for libclntsh.so from /usr/lib/oracle/11.2/client64/lib to /usr/lib

How to update attributes without validation

USE update_attribute instead of update_attributes

Updates a single attribute and saves the record without going through the normal validation procedure.

if a.update_attribute('state', a.state)

Note:- 'update_attribute' update only one attribute at a time from the code given in question i think it will work for you.

Escaping backslash in string - javascript

I think this is closer to the answer you're looking for:

<input type="file">

$file = $(file);
var filename = fileElement[0].files[0].name;

Dynamically allocating an array of objects

For building containers you obviously want to use one of the standard containers (such as a std::vector). But this is a perfect example of the things you need to consider when your object contains RAW pointers.

If your object has a RAW pointer then you need to remember the rule of 3 (now the rule of 5 in C++11).

  • Constructor
  • Destructor
  • Copy Constructor
  • Assignment Operator
  • Move Constructor (C++11)
  • Move Assignment (C++11)

This is because if not defined the compiler will generate its own version of these methods (see below). The compiler generated versions are not always useful when dealing with RAW pointers.

The copy constructor is the hard one to get correct (it's non trivial if you want to provide the strong exception guarantee). The Assignment operator can be defined in terms of the Copy Constructor as you can use the copy and swap idiom internally.

See below for full details on the absolute minimum for a class containing a pointer to an array of integers.

Knowing that it is non trivial to get it correct you should consider using std::vector rather than a pointer to an array of integers. The vector is easy to use (and expand) and covers all the problems associated with exceptions. Compare the following class with the definition of A below.

class A
{ 
    std::vector<int>   mArray;
    public:
        A(){}
        A(size_t s) :mArray(s)  {}
};

Looking at your problem:

A* arrayOfAs = new A[5];
for (int i = 0; i < 5; ++i)
{
    // As you surmised the problem is on this line.
    arrayOfAs[i] = A(3);

    // What is happening:
    // 1) A(3) Build your A object (fine)
    // 2) A::operator=(A const&) is called to assign the value
    //    onto the result of the array access. Because you did
    //    not define this operator the compiler generated one is
    //    used.
}

The compiler generated assignment operator is fine for nearly all situations, but when RAW pointers are in play you need to pay attention. In your case it is causing a problem because of the shallow copy problem. You have ended up with two objects that contain pointers to the same piece of memory. When the A(3) goes out of scope at the end of the loop it calls delete [] on its pointer. Thus the other object (in the array) now contains a pointer to memory that has been returned to the system.

The compiler generated copy constructor; copies each member variable by using that members copy constructor. For pointers this just means the pointer value is copied from the source object to the destination object (hence shallow copy).

The compiler generated assignment operator; copies each member variable by using that members assignment operator. For pointers this just means the pointer value is copied from the source object to the destination object (hence shallow copy).

So the minimum for a class that contains a pointer:

class A
{
    size_t     mSize;
    int*       mArray;
    public:
         // Simple constructor/destructor are obvious.
         A(size_t s = 0) {mSize=s;mArray = new int[mSize];}
        ~A()             {delete [] mArray;}

         // Copy constructor needs more work
         A(A const& copy)
         {
             mSize  = copy.mSize;
             mArray = new int[copy.mSize];

             // Don't need to worry about copying integers.
             // But if the object has a copy constructor then
             // it would also need to worry about throws from the copy constructor.
             std::copy(&copy.mArray[0],&copy.mArray[c.mSize],mArray);

         }

         // Define assignment operator in terms of the copy constructor
         // Modified: There is a slight twist to the copy swap idiom, that you can
         //           Remove the manual copy made by passing the rhs by value thus
         //           providing an implicit copy generated by the compiler.
         A& operator=(A rhs) // Pass by value (thus generating a copy)
         {
             rhs.swap(*this); // Now swap data with the copy.
                              // The rhs parameter will delete the array when it
                              // goes out of scope at the end of the function
             return *this;
         }
         void swap(A& s) noexcept
         {
             using std::swap;
             swap(this.mArray,s.mArray);
             swap(this.mSize ,s.mSize);
         }

         // C++11
         A(A&& src) noexcept
             : mSize(0)
             , mArray(NULL)
         {
             src.swap(*this);
         }
         A& operator=(A&& src) noexcept
         {
             src.swap(*this);     // You are moving the state of the src object
                                  // into this one. The state of the src object
                                  // after the move must be valid but indeterminate.
                                  //
                                  // The easiest way to do this is to swap the states
                                  // of the two objects.
                                  //
                                  // Note: Doing any operation on src after a move 
                                  // is risky (apart from destroy) until you put it 
                                  // into a specific state. Your object should have
                                  // appropriate methods for this.
                                  // 
                                  // Example: Assignment (operator = should work).
                                  //          std::vector() has clear() which sets
                                  //          a specific state without needing to
                                  //          know the current state.
             return *this;
         }   
 }

PHP: Split string into array, like explode with no delimiter

What are you trying to accomplish? You can access characters in a string just like an array:

$s = 'abcd';
echo $s[0];

prints 'a'

Fatal error: Cannot use object of type stdClass as array in

Controller (Example: User.php)

<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Users extends CI_controller
{

    // Table
    protected  $table = 'users';

    function index()
    {
        $data['users'] = $this->model->ra_object($this->table);
        $this->load->view('users_list', $data);
    }
}

View (Example: users_list.php)

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Surname</th>
        </tr>
    </thead>

    <tbody>
        <?php foreach($users as $user) : ?>
            <tr>
            <td><?php echo $user->name; ?></td>
            <td><?php echo $user->surname; ?></th>
        </tr>
        <?php endforeach; ?>
    </tbody>
</table>
<!-- // User table -->

Restricting input to textbox: allowing only numbers and decimal point

If you want it for float values,

Here is the function I am using

_x000D_
_x000D_
<HTML>_x000D_
_x000D_
<HEAD>_x000D_
  <SCRIPT language=Javascript>_x000D_
    <!--_x000D_
    function check(e, value) {_x000D_
      //Check Charater_x000D_
      var unicode = e.charCode ? e.charCode : e.keyCode;_x000D_
      if (value.indexOf(".") != -1)_x000D_
        if (unicode == 46) return false;_x000D_
      if (unicode != 8)_x000D_
        if ((unicode < 48 || unicode > 57) && unicode != 46) return false;_x000D_
    }_x000D_
    //-->_x000D_
  </SCRIPT>_x000D_
</HEAD>_x000D_
_x000D_
<BODY>_x000D_
  <INPUT id="txtChar" onkeypress="return check(event,value)" type="text" name="txtChar">_x000D_
</BODY>_x000D_
_x000D_
</HTML>
_x000D_
_x000D_
_x000D_

Finding a branch point with Git?

I seem to be getting some joy with

git rev-list branch...master

The last line you get is the first commit on the branch, so then it's a matter of getting the parent of that. So

git rev-list -1 `git rev-list branch...master | tail -1`^

Seems to work for me and doesn't need diffs and so on (which is helpful as we don't have that version of diff)

Correction: This doesn't work if you are on the master branch, but I'm doing this in a script so that's less of an issue

cmd line rename file with date and time

Digging up the old thread because all solutions have missed the simplest fix...

It is failing because the substitution of the time variable results in a space in the filename, meaning it treats the last part of the filename as a parameter into the command.

The simplest solution is to just surround the desired filename in quotes "filename".

Then you can have any date pattern you want (with the exception of those illegal characters such as /,\,...)

I would suggest reverse date order YYYYMMDD-HHMM:

ren "somefile.txt" "somefile-%date:~10,4%%date:~7,2%%date:~4,2%-%time:~0,2%%time:~3,2%.txt"

How to check for empty array in vba macro

If you test on an array function it'll work for all bounds:

Function IsVarArrayEmpty(anArray As Variant)

Dim i As Integer

On Error Resume Next
    i = UBound(anArray,1)
If Err.number = 0 Then
    IsVarArrayEmpty = False
Else
    IsVarArrayEmpty = True
End If

End Function

How to efficiently use try...catch blocks in PHP

There is no any problem to write multiple lines of execution withing a single try catch block like below

try{
install_engine();
install_break();
}
catch(Exception $e){
show_exception($e->getMessage());
}

The moment any execption occure either in install_engine or install_break function the control will be passed to catch function. One more recommendation is to eat your exception properly. Which means instead of writing die('Message') it is always advisable to have exception process properly. You may think of using die() function in error handling but not in exception handling.

When you should use multiple try catch block You can think about multiple try catch block if you want the different code block exception to display different type of exception or you are trying to throw any exception from your catch block like below:

try{
    install_engine();
    install_break();
    }
    catch(Exception $e){
    show_exception($e->getMessage());
    }
try{
install_body();
paint_body();
install_interiour();
}
catch(Exception $e){
throw new exception('Body Makeover faield')
}

Lookup City and State by Zip Google Geocode Api

I found a couple of ways to do this with web based APIs. I think the US Postal Service would be the most accurate, since Zip codes are their thing, but Ziptastic looks much easier.

Using the US Postal Service HTTP/XML API

According to this page on the US Postal Service website which documents their XML based web API, specifically Section 4.0 (page 22) of this PDF document, they have a URL where you can send an XML request containing a 5 digit Zip Code and they will respond with an XML document containing the corresponding City and State.

According to their documentation, here's what you would send:

http://SERVERNAME/ShippingAPITest.dll?API=CityStateLookup&XML=<CityStateLookupRequest%20USERID="xxxxxxx"><ZipCode ID= "0"><Zip5>90210</Zip5></ZipCode></CityStateLookupRequest>

And here's what you would receive back:

<?xml version="1.0"?> 
<CityStateLookupResponse> 
    <ZipCode ID="0"> 
        <Zip5>90210</Zip5> 
        <City>BEVERLY HILLS</City> 
        <State>CA</State> 
    </ZipCode> 
</CityStateLookupResponse>

USPS does require that you register with them before you can use the API, but, as far as I could tell, there is no charge for access. By the way, their API has some other features: you can do Address Standardization and Zip Code Lookup, as well as the whole suite of tracking, shipping, labels, etc.

Using the Ziptastic HTTP/JSON API (no longer supported)

Update: As of August 13, 2017, Ziptastic is now a paid API and can be found here

This is a pretty new service, but according to their documentation, it looks like all you need to do is send a GET request to http://ziptasticapi.com, like so:

GET http://ziptasticapi.com/48867

And they will return a JSON object along the lines of:

{"country": "US", "state": "MI", "city": "OWOSSO"}

Indeed, it works. You can test this from a command line by doing something like:

curl http://ziptasticapi.com/48867 

Python Pandas iterate over rows and access column names

The item from iterrows() is not a Series, but a tuple of (index, Series), so you can unpack the tuple in the for loop like so:

for (idx, row) in df.iterrows():
    print(row.loc['A'])
    print(row.A)
    print(row.index)

#0.890618586836
#0.890618586836
#Index(['A', 'B', 'C', 'D'], dtype='object')

Linux command-line call not returning what it should from os.system?

Your code returns 0 if the execution of the commands passed is successful and non zero if it fails. The following program works on python2.7, haven checked 3 and versions above. Try this code.

>>> import commands
>>> ret = commands.getoutput("ps -p 2993 -o time --no-headers")
>>> print ret

jQuery changing css class to div

Yep, easily.

$("#mydiv").attr("class", "second");

Get list from pandas DataFrame column headers

Even though the solution that was provided above is nice. I would also expect something like frame.column_names() to be a function in pandas, but since it is not, maybe it would be nice to use the following syntax. It somehow preserves the feeling that you are using pandas in a proper way by calling the "tolist" function: frame.columns.tolist()

frame.columns.tolist() 

Using SHA1 and RSA with java.security.Signature vs. MessageDigest and Cipher

I have a similar problem, I tested adding code and found some interesting results. With this code I add, I can deduce that depending on the "provider" to use, the firm can be different? (because the data included in the encryption is not always equal in all providers).

Results of my test.

Conclusion.- Signature Decipher= ???(trash) + DigestInfo (if we know the value of "trash", the digital signatures will be equal)

IDE Eclipse OUTPUT...

Input data: This is the message being signed

Digest: 62b0a9ef15461c82766fb5bdaae9edbe4ac2e067

DigestInfo: 3021300906052b0e03021a0500041462b0a9ef15461c82766fb5bdaae9edbe4ac2e067

Signature Decipher: 1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff003021300906052b0e03021a0500041462b0a9ef15461c82766fb5bdaae9edbe4ac2e067

CODE

import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import org.bouncycastle.asn1.x509.DigestInfo;
import org.bouncycastle.asn1.DERObjectIdentifier;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
public class prueba {
/**
* @param args
* @throws NoSuchProviderException 
* @throws NoSuchAlgorithmException 
* @throws InvalidKeyException 
* @throws SignatureException 
* @throws NoSuchPaddingException 
* @throws BadPaddingException 
* @throws IllegalBlockSizeException 
*///
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
// TODO Auto-generated method stub
KeyPair keyPair = KeyPairGenerator.getInstance("RSA","BC").generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey puKey = keyPair.getPublic();
String plaintext = "This is the message being signed";
// Hacer la firma
Signature instance = Signature.getInstance("SHA1withRSA","BC");
instance.initSign(privateKey);
instance.update((plaintext).getBytes());
byte[] signature = instance.sign();
// En dos partes primero hago un Hash
MessageDigest digest = MessageDigest.getInstance("SHA1", "BC");
byte[] hash = digest.digest((plaintext).getBytes());
// El digest es identico a  openssl dgst -sha1 texto.txt
//MessageDigest sha1 = MessageDigest.getInstance("SHA1","BC");
//byte[] digest = sha1.digest((plaintext).getBytes());
AlgorithmIdentifier digestAlgorithm = new AlgorithmIdentifier(new
DERObjectIdentifier("1.3.14.3.2.26"), null);
// create the digest info
DigestInfo di = new DigestInfo(digestAlgorithm, hash);
byte[] digestInfo = di.getDEREncoded();
//Luego cifro el hash
Cipher cipher = Cipher.getInstance("RSA","BC");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] cipherText = cipher.doFinal(digestInfo);
//byte[] cipherText = cipher.doFinal(digest2);
Cipher cipher2 = Cipher.getInstance("RSA","BC");
cipher2.init(Cipher.DECRYPT_MODE, puKey);
byte[] cipherText2 = cipher2.doFinal(signature);
System.out.println("Input data: " + plaintext);
System.out.println("Digest: " + bytes2String(hash));
System.out.println("Signature: " + bytes2String(signature));
System.out.println("Signature2: " + bytes2String(cipherText));
System.out.println("DigestInfo: " + bytes2String(digestInfo));
System.out.println("Signature Decipher: " + bytes2String(cipherText2));
}

Is there a replacement for unistd.h for Windows (Visual C)?

Create your own unistd.h header and include the needed headers for function prototypes.

git: updates were rejected because the remote contains work that you do not have locally

You can override any checks that git does by using "force push". Use this command in terminal

git push -f origin master

However, you will potentially ignore the existing work that is in remote - you are effectively rewriting the remote's history to be exactly like your local copy.

I cannot start SQL Server browser

run > regedit > HKEY_LOCAL_MACHINE > SOFTWARE > WOW6432Node > Microsoft > Microsoft SQL Server > 90 > SQL Browser > SsrpListener=0

Find column whose name contains a specific string

# select columns containing 'spike'
df.filter(like='spike', axis=1)

You can also select by name, regular expression. Refer to: pandas.DataFrame.filter

ASP.NET Core 1.0 on IIS error 502.5

I have no idea why this worked for me, but I am using Windows Authentication and I had this bit of code on my BuildWebHost in Program.cs:

.UseStartup<Startup>()
.UseHttpSys(options =>
{
    options.Authentication.Schemes =
        AuthenticationSchemes.NTLM | AuthenticationSchemes.Negotiate;
    options.Authentication.AllowAnonymous = false;
})
.Build();

After removing the .UserHttpSys bit, it now works, and I can still authenticate as a domain user.

BuildWebHost now looks like

public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
    .UseStartup<Startup>()
    .Build();

Use jQuery to hide a DIV when the user clicks outside of it

$(document).ready(function() {

$('.headings').click(function () {$('#sub1').css("display",""); });
$('.headings').click(function () {return false;});
$('#sub1').click(function () {return false;});
$('body').click(function () {$('#sub1').css("display","none");

})});

org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 15

Update to Tomcat 7.0.58 (or newer).

See: https://bz.apache.org/bugzilla/show_bug.cgi?id=57173#c16

The performance improvement that triggered this regression has been reverted from from trunk, 8.0.x (for 8.0.16 onwards) and 7.0.x (for 7.0.58 onwards) and will not be reapplied.

DBNull if statement

The closest equivalent to your VB would be (see this):

Convert.IsDBNull()

But there are a number of ways to do this, and most are linked from here

How to combine class and ID in CSS selector?

.sectionA[id='content'] { color : red; }

Won't work when the doctype is html 4.01 though...

Can I apply a CSS style to an element name?

have you explored the possibility of using jQuery? It has a very reach selector model (similar in syntax to CSS) and even if your elements don't have IDs, you should be able to select them using parent --> child --> grandchild relationship. Once you have them selected, there's a very simple method call (I forget the exact name) that allows you to apply CSS style to the element(s).

It should be simple to use and as a bonus, you'll most likely be very cross-platform compatible.

How to use Google fonts in React.js?

If anyone looking for a solution with (.less) try below. Open your main or common less file and use like below.

@import (css) url('https://fonts.googleapis.com/css?family=Open+Sans:400,700');

body{
  font-family: "Open Sans", sans-serif;
}

How do I export an Android Studio project?

Windows:

First Open Command Window and set location of your android studio project folder like:

D:\MyApplication>

then type below command in it:

gradlew clean

then wait for complete clean process. after complete it now zip your project like below:

  • right click on your project folder
  • then select send to option now
  • select compressed via zip

Select multiple records based on list of Id's with linq

You can use Contains() for that. It will feel a little backwards when you're really trying to produce an IN clause, but this should do it:

var userProfiles = _dataContext.UserProfile
                               .Where(t => idList.Contains(t.Id));

I'm also assuming that each UserProfile record is going to have an int Id field. If that's not the case you'll have to adjust accordingly.

Host binding and Host listening

@HostListener is a decorator for the callback/event handler method, so remove the ; at the end of this line:

@HostListener('click', ['$event.target']);

Here's a working plunker that I generated by copying the code from the API docs, but I put the onClick() method on the same line for clarity:

import {Component, HostListener, Directive} from 'angular2/core';

@Directive({selector: 'button[counting]'})
class CountClicks {
  numberOfClicks = 0;
  @HostListener('click', ['$event.target']) onClick(btn) {
    console.log("button", btn, "number of clicks:", this.numberOfClicks++);
  }
}
@Component({
  selector: 'my-app',
  template: `<button counting>Increment</button>`,
  directives: [CountClicks]
})
export class AppComponent {
  constructor() { console.clear(); }
}

Host binding can also be used to listen to global events:

To listen to global events, a target must be added to the event name. The target can be window, document or body (reference)

@HostListener('document:keyup', ['$event'])
handleKeyboardEvent(kbdEvent: KeyboardEvent) { ... }

Location for session files in Apache/PHP

I believe its in /tmp/. Check your phpinfo function though, it should say session.save_path in there somewhere.

Android Fragment no view found for ID?

With Nested fragments

For me by using getChildFragmentManager() instead of getActivity().getSupportFragmentManager() resolved crash

java.lang.IllegalArgumentException: No view found for id

What is the best way to delete a component with CLI

destroy or something similar may come to the CLI, but it is not a primary focus at this time. So you will need to do this manually.

Delete the component directory (assuming you didn't use --flat) and then remove it from the NgModule in which it is declared.

If you are unsure of what to do, I suggest you have a "clean" app meaning no current git changes. Then generate a component and see what is changed in the repo so you can backtrack from there what you will need to do to delete a component.

Update

If you're just experimenting about what you want to generate, you can use the --dry-run flag to not produce any files on disk, just see the updated file list.

How to Load RSA Private Key From File

You need to convert your private key to PKCS8 format using following command:

openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key_file  -nocrypt > pkcs8_key

After this your java program can read it.

How can I tell if I'm running in 64-bit JVM or 32-bit JVM (from within a program)?

This is the way JNA solves this with Platform.is64Bit() (https://github.com/java-native-access/jna/blob/master/src/com/sun/jna/Platform.java)

 public static final boolean is64Bit() {
        String model = System.getProperty("sun.arch.data.model",
                                          System.getProperty("com.ibm.vm.bitmode"));
        if (model != null) {
            return "64".equals(model);
        }
        if ("x86-64".equals(ARCH)
            || "ia64".equals(ARCH)
            || "ppc64".equals(ARCH) || "ppc64le".equals(ARCH)
            || "sparcv9".equals(ARCH)
            || "mips64".equals(ARCH) || "mips64el".equals(ARCH)
            || "amd64".equals(ARCH)
            || "aarch64".equals(ARCH)) {
            return true;
        }
        return Native.POINTER_SIZE == 8;
}

ARCH = getCanonicalArchitecture(System.getProperty("os.arch"), osType);

static String getCanonicalArchitecture(String arch, int platform) {
        arch = arch.toLowerCase().trim();
        if ("powerpc".equals(arch)) {
            arch = "ppc";
        }
        else if ("powerpc64".equals(arch)) {
            arch = "ppc64";
        }
        else if ("i386".equals(arch) || "i686".equals(arch)) {
            arch = "x86";
        }
        else if ("x86_64".equals(arch) || "amd64".equals(arch)) {
            arch = "x86-64";
        }
        // Work around OpenJDK mis-reporting os.arch
        // https://bugs.openjdk.java.net/browse/JDK-8073139
        if ("ppc64".equals(arch) && "little".equals(System.getProperty("sun.cpu.endian"))) {
            arch = "ppc64le";
        }
        // Map arm to armel if the binary is running as softfloat build
        if("arm".equals(arch) && platform == Platform.LINUX && isSoftFloat()) {
            arch = "armel";
        }

        return arch;
    }

static {
        String osName = System.getProperty("os.name");
        if (osName.startsWith("Linux")) {
            if ("dalvik".equals(System.getProperty("java.vm.name").toLowerCase())) {
                osType = ANDROID;
                // Native libraries on android must be bundled with the APK
                System.setProperty("jna.nounpack", "true");
            }
            else {
                osType = LINUX;
            }
        }
        else if (osName.startsWith("AIX")) {
            osType = AIX;
        }
        else if (osName.startsWith("Mac") || osName.startsWith("Darwin")) {
            osType = MAC;
        }
        else if (osName.startsWith("Windows CE")) {
            osType = WINDOWSCE;
        }
        else if (osName.startsWith("Windows")) {
            osType = WINDOWS;
        }
        else if (osName.startsWith("Solaris") || osName.startsWith("SunOS")) {
            osType = SOLARIS;
        }
        else if (osName.startsWith("FreeBSD")) {
            osType = FREEBSD;
        }
        else if (osName.startsWith("OpenBSD")) {
            osType = OPENBSD;
        }
        else if (osName.equalsIgnoreCase("gnu")) {
            osType = GNU;
        }
        else if (osName.equalsIgnoreCase("gnu/kfreebsd")) {
            osType = KFREEBSD;
        }
        else if (osName.equalsIgnoreCase("netbsd")) {
            osType = NETBSD;
        }
        else {
            osType = UNSPECIFIED;
        }
}

Class file has wrong version 52.0, should be 50.0

It means your Java runtime version is 1.8, but your compiler version (javac) is 1.6. To simply solve it, just retreat the Java version from 1.8 to 1.6.

But if you don't want to change the Java runtime version, then do the following steps:

  1. JAVA_HOME= "your jdk v1.8 folder path", to make sure jdk is also v1.8 and use java -version and javac -version again to ensure it
  2. Make sure IntelliJ 's compiler mode is set to compliant with v1.6 But i have tried that. it didn't solve my problem.

Find duplicate records in MySQL

Powerlord answer is indeed the best and I would recommend one more change: use LIMIT to make sure db would not get overloaded:

SELECT firstname, lastname, list.address FROM list
INNER JOIN (SELECT address FROM list
GROUP BY address HAVING count(id) > 1) dup ON list.address = dup.address
LIMIT 10

It is a good habit to use LIMIT if there is no WHERE and when making joins. Start with small value, check how heavy the query is and then increase the limit.

Display List in a View MVC

You are passing wrong mode to you view. Your view is looking for @model IEnumerable<Standings.Models.Teams> and you are passing var model = tm.Name.ToList(); name list. You have to pass list of Teams.

You have to pass following model

var model = new List<Teams>();

model.Add(new Teams { Name =  new List<string>(){"Sky","ABC"}});
model.Add(new Teams { Name =  new List<string>(){"John","XYZ"} });
return View(model);

jQuery: Setting select list 'selected' based on text, failing strangely

In case someone google for this, the solutions above didn't work for me so i ended using "pure" javascript

document.getElementById("The id of the element").value = "The value"

And that would set the value and make the current value selected in the combo box. Tested in firefox.

it was easier than keep googling a solution for jQuery

How can I set the aspect ratio in matplotlib?

you should try with figaspect. It works for me. From the docs:

Create a figure with specified aspect ratio. If arg is a number, use that aspect ratio. > If arg is an array, figaspect will determine the width and height for a figure that would fit array preserving aspect ratio. The figure width, height in inches are returned. Be sure to create an axes with equal with and height, eg

Example usage:

  # make a figure twice as tall as it is wide
  w, h = figaspect(2.)
  fig = Figure(figsize=(w,h))
  ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
  ax.imshow(A, **kwargs)

  # make a figure with the proper aspect for an array
  A = rand(5,3)
  w, h = figaspect(A)
  fig = Figure(figsize=(w,h))
  ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
  ax.imshow(A, **kwargs)

Edit: I am not sure of what you are looking for. The above code changes the canvas (the plot size). If you want to change the size of the matplotlib window, of the figure, then use:

In [68]: f = figure(figsize=(5,1))

this does produce a window of 5x1 (wxh).

Detecting input change in jQuery?

If you've got HTML5:

  • oninput (fires only when a change actually happens, but does so immediately)

Otherwise you need to check for all these events which might indicate a change to the input element's value:

  • onchange
  • onkeyup (not keydown or keypress as the input's value won't have the new keystroke in it yet)
  • onpaste (when supported)

and maybe:

  • onmouseup (I'm not sure about this one)

Convert List to Pandas Dataframe Column

For Converting a List into Pandas Core Data Frame, we need to use DataFrame Method from pandas Package.

There are Different Ways to Perform the Above Operation.

import pandas as pd

  1. pd.DataFrame({'Column_Name':Column_Data})
  • Column_Name : String
  • Column_Data : List Form
  1. Data = pd.DataFrame(Column_Data)

    Data.columns = ['Column_Name']

So, for the above mentioned issue, the code snippet is

import pandas as pd

Content = ['Thanks You',
           'Its fine no problem',
           'Are you sure']

Data = pd.DataFrame({'Text': Content})

Passing a string array as a parameter to a function java

look at familiar main method which takes string array as param

Can't accept license agreement Android SDK Platform 24

This error can come if the system is not picking up the ANDROID_HOME environmental variable from the proper path. Make sure you have installed the Android SDK and have set the ANDROID_HOME variable properly to the appropriate path as in the below image:

ANDROID_HOME_PATH

If the ANDROID_HOME variable is not defined, the system tries to pick the path from a default path(this might not be the path where the Android SDK is defined, leading to this issue).

Why is "cursor:pointer" effect in CSS not working

I found a solution: use :hover with cursor: pointer if nothing else helps.

How to Use Content-disposition for force a file to download to the hard drive?

On the HTTP Response where you are returning the PDF file, ensure the content disposition header looks like:

Content-Disposition: attachment; filename=quot.pdf;

See content-disposition on the wikipedia MIME page.

How can I pause setInterval() functions?

You could use a flag to keep track of the status:

_x000D_
_x000D_
var output = $('h1');_x000D_
var isPaused = false;_x000D_
var time = 0;_x000D_
var t = window.setInterval(function() {_x000D_
  if(!isPaused) {_x000D_
    time++;_x000D_
    output.text("Seconds: " + time);_x000D_
  }_x000D_
}, 1000);_x000D_
_x000D_
//with jquery_x000D_
$('.pause').on('click', function(e) {_x000D_
  e.preventDefault();_x000D_
  isPaused = true;_x000D_
});_x000D_
_x000D_
$('.play').on('click', function(e) {_x000D_
  e.preventDefault();_x000D_
  isPaused = false;_x000D_
});
_x000D_
h1 {_x000D_
    font-family: Helvetica, Verdana, sans-serif;_x000D_
    font-size: 12px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<h1>Seconds: 0</h1>_x000D_
<button class="play">Play</button>_x000D_
<button class="pause">Pause</button>
_x000D_
_x000D_
_x000D_

This is just what I would do, I'm not sure if you can actually pause the setInterval.

Note: This system is easy and works pretty well for applications that don't require a high level of precision, but it won't consider the time elapsed in between ticks: if you click pause after half a second and later click play your time will be off by half a second.

How to remove all white spaces from a given text file

Try this:

tr -d " \t" <filename

See the manpage for tr(1) for more details.

Best way to make a shell script daemon?

Here is the minimal change to the original proposal to create a valid daemon in Bourne shell (or Bash):

#!/bin/sh
if [ "$1" != "__forked__" ]; then
    setsid "$0" __forked__ "$@" &
    exit
else
    shift
fi

trap 'siguser1=true' SIGUSR1
trap 'echo "Clean up and exit"; kill $sleep_pid; exit' SIGTERM
exec > outfile
exec 2> errfile
exec 0< /dev/null

while true; do
    (sleep 30000000 &>/dev/null) &
    sleep_pid=$!
    wait
    kill $sleep_pid &>/dev/null
    if [ -n "$siguser1" ]; then
        siguser1=''
        echo "Wait was interrupted by SIGUSR1, do things here."
    fi
done

Explanation:

  • Line 2-7: A daemon must be forked so it doesn't have a parent. Using an artificial argument to prevent endless forking. "setsid" detaches from starting process and terminal.
  • Line 9: Our desired signal needs to be differentiated from other signals.
  • Line 10: Cleanup is required to get rid of dangling "sleep" processes.
  • Line 11-13: Redirect stdout, stderr and stdin of the script.
  • Line 16: sleep in the background
  • Line 18: wait waits for end of sleep, but gets interrupted by (some) signals.
  • Line 19: Kill sleep process, because that is still running when signal is caught.
  • Line 22: Do the work if SIGUSR1 has been caught.

Guess it does not get any simpler than that.

What is Scala's yield?

Yes, as Earwicker said, it's pretty much the equivalent to LINQ's select and has very little to do with Ruby's and Python's yield. Basically, where in C# you would write

from ... select ??? 

in Scala you have instead

for ... yield ???

It's also important to understand that for-comprehensions don't just work with sequences, but with any type which defines certain methods, just like LINQ:

  • If your type defines just map, it allows for-expressions consisting of a single generator.
  • If it defines flatMap as well as map, it allows for-expressions consisting of several generators.
  • If it defines foreach, it allows for-loops without yield (both with single and multiple generators).
  • If it defines filter, it allows for-filter expressions starting with an if in the for expression.

How are echo and print different in PHP?

As the PHP.net manual suggests, take a read of this discussion.

One major difference is that echo can take multiple parameters to output. E.g.:

echo 'foo', 'bar';   // Concatenates the 2 strings
print('foo', 'bar'); // Fatal error

If you're looking to evaluate the outcome of an output statement (as below) use print. If not, use echo.

$res = print('test');
var_dump($res); //bool(true)

Removing "NUL" characters

I tried to use the \x00 and it didn't work for me when using C# and Regex. I had success with the following:

//The hexidecimal 0x0 is the null character  
mystring.Contains(Convert.ToChar(0x0).ToString() );  

// This will replace the character
mystring = mystring.Replace(Convert.ToChar(0x0).ToString(), "");  

How to start new activity on button click

Emmanuel,

I think the extra info should be put before starting the activity otherwise the data won't be available yet if you're accessing it in the onCreate method of NextActivity.

Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);

myIntent.putExtra("key", value);

CurrentActivity.this.startActivity(myIntent);

Correct way to push into state array

Using Functional Components and React Hooks

const [array,setArray] = useState([]);

Push value at the end:

setArray(oldArray => [...oldArray,newValue] );

Push value at the begging:

setArray(oldArray => [newValue,...oldArrays] );

PHP float with 2 decimal places: .00

As far as i know there is no solution for PHP to fix this. All other (above and below) answers given in this thread are nonsense.

The number_format function returns a string as result as written in PHP.net's own specification.

Functions like floatval/doubleval do return integers if you give as value 3.00 .

If you do typejuggling then you will get an integer as result.

If you use round() then you will get an integer as result.

The only possible solution that i can think of is using your database for type conversion to float. MySQL for example:

SELECT CAST('3.00' AS DECIMAL) AS realFloatValue;

Execute this using an abstraction layer which returns floats instead of strings and there you go.


JSON output modification

If you are looking for a solution to fix your JSON output to hold 2 decimals then you can probably use post-formatting like in the code below:

// PHP AJAX Controller

// some code here

// transform to json and then convert string to float with 2 decimals
$output = array('x' => 'y', 'price' => '0.00');
$json = json_encode($output);
$json = str_replace('"price":"'.$output['price'].'"', '"price":'.$output['price'].'', $json);

// output to browser / client
print $json;
exit();

Returns to client/browser:

{"x":"y","price":0.00}

Oracle Date TO_CHAR('Month DD, YYYY') has extra spaces in it

SQL> -- original . . .
SQL> select
  2  to_char( sysdate, 'Day "the" Ddth "of" Month, yyyy' ) dt
  3  from dual;

DT
----------------------------------------
Friday    the 13th of May      , 2016

SQL>
SQL> -- collapse repeated spaces . . .
SQL> select
  2  regexp_replace(
  3      to_char( sysdate, 'Day "the" Ddth "of" Month, yyyy' ),
  4      '  * *', ' ') datesp
  5  from dual;

DATESP
----------------------------------------
Friday the 13th of May , 2016

SQL>
SQL> -- and space before commma . . .
SQL> select
  2  regexp_replace(
  3      to_char( sysdate, 'Day "the" Ddth "of" Month, yyyy' ),
  4      '  *(,*) *', '\1 ') datesp
  5  from dual;

DATESP
----------------------------------------
Friday the 13th of May, 2016

SQL>
SQL> -- space before punctuation . . .
SQL> select
  2  regexp_replace(
  3      to_char( sysdate, 'Day "the" Ddth "of" Month, yyyy' ),
  4      '  *([.,/:;]*) *', '\1 ') datesp
  5  from dual;

DATESP
----------------------------------------
Friday the 13th of May, 2016

Case statement with multiple values in each 'when' block

In a case statement, a , is the equivalent of || in an if statement.

case car
   when 'toyota', 'lexus'
      # code
end

Some other things you can do with a Ruby case statement

Make child div stretch across width of page

I know this post is old, in case someone stumbles upon it in 2019, this would work try it.

//html
<div id="container">
<div id="help_panel">
<div class="help_panel_extra_if_you_want"> //then if you want to add some height and width if you want, do this.

</div>
</div>
</div>

//css
#container{
left: 0px;
top: 0px;
right: 0px;
z-index: 100;
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
-webkit-box-pack: start;
-webkit-justify-content: flex-start;
-ms-flex-pack: start;
justify-content: flex-start;    
position: relative;
height:650px;
margin-top:55px;
margin-bottom:-20px;
}

#help_panel {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
padding-right: 24px;
padding-left: 18px;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
-webkit-box-align: center;
-webkit-align-items: center;
-ms-flex-align: center;
align-items: center;

.help_panel_extra_if_you_want{
height:650px;
position: relative;
-webkit-box-orient: horizontal;
-webkit-box-direction: normal;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
-webkit-box-pack: justify;
-webkit-justify-content: space-between;
-ms-flex-pack: justify;
justify-content: space-between;
align-items: center;
display: flex;
width: 95%;
max-width: 1200px;
}

SHOULD GIVE YOU SOMETHING LIKE THIS This is how it would look, adjust the width and margin and padding to achieve what you want

How to enable remote access of mysql in centos?

In case of Allow IP to mysql server linux machine. you can do following command--

 nano /etc/httpd/conf.d/phpMyAdmin.conf  and add Desired IP.

<Directory /usr/share/phpMyAdmin/>
   AddDefaultCharset UTF-8
   Order allow,deny
   allow from all
   <IfModule mod_authz_core.c>
     # Apache 2.4
     <RequireAny>

    Require ip 192.168.9.1(Desired IP)

</RequireAny>
   </IfModule>
 <IfModule !mod_authz_core.c>
     # Apache 2.2
     Order Deny,Allow
     #Allow from All

     Allow from 192.168.9.1(Desired IP)

</IfModule>

And after Update, please restart using following command--

sudo systemctl restart httpd.service

RESTful Authentication via Spring

Regarding tokens carrying information, JSON Web Tokens (http://jwt.io) is a brilliant technology. The main concept is to embed information elements (claims) into the token, and then signing the whole token so that the validating end can verify that the claims are indeed trustworthy.

I use this Java implementation: https://bitbucket.org/b_c/jose4j/wiki/Home

There is also a Spring module (spring-security-jwt), but I haven't looked into what it supports.

MVC 4 - how do I pass model data to a partial view?

You're not actually passing the model to the Partial, you're passing a new ViewDataDictionary<LetLord.Models.Tenant>(). Try this:

@model LetLord.Models.Tenant
<div class="row-fluid">
    <div class="span4 well-border">
         @Html.Partial("~/Views/Tenants/_TenantDetailsPartial.cshtml", Model)
    </div>
</div>

How to create Python egg file

You are reading the wrong documentation. You want this: https://setuptools.readthedocs.io/en/latest/setuptools.html#develop-deploy-the-project-source-in-development-mode

  1. Creating setup.py is covered in the distutils documentation in Python's standard library documentation here. The main difference (for python eggs) is you import setup from setuptools, not distutils.

  2. Yep. That should be right.

  3. I don't think so. pyc files can be version and platform dependent. You might be able to open the egg (they should just be zip files) and delete .py files leaving .pyc files, but it wouldn't be recommended.

  4. I'm not sure. That might be “Development Mode”. Or are you looking for some “py2exe” or “py2app” mode?

Html: Difference between cell spacing and cell padding

This is the simple answer I can give.

enter image description here

How to generate .NET 4.0 classes from xsd?

Along with WSDL, I had xsd files. The above did not work in my case gave error. It worked as follows

wsdl /l:C# /out:D:\FileName.cs D:\NameApi\wsdl_1_1\RESAdapterService.wsdl 
D:\CXTypes.xsd D:\CTypes.xsd 
D:\Preferences.xsd 

Dealing with multiple Python versions and PIP?

/path/to/python2.{5,6} /path/to/pip install PackageName doesn't work?

For this to work on any python version that doesn't have pip already installed you need to download pip and do python*version* setup.py install. For example python3.3 setup.py install. This resolves the import error in the comments. (As suggested by @hbdgaf)

Performing Inserts and Updates with Dapper

Instead of using any 3rd party library for query operations, I would rather suggest writing queries on your own. Because using any other 3rd party packages would take away the main advantage of using dapper i.e. flexibility to write queries.

Now, there is a problem with writing Insert or Update query for the entire object. For this, one can simply create helpers like below:

InsertQueryBuilder:

 public static string InsertQueryBuilder(IEnumerable < string > fields) {


  StringBuilder columns = new StringBuilder();
  StringBuilder values = new StringBuilder();


  foreach(string columnName in fields) {
   columns.Append($ "{columnName}, ");
   values.Append($ "@{columnName}, ");

  }
  string insertQuery = $ "({ columns.ToString().TrimEnd(',', ' ')}) VALUES ({ values.ToString().TrimEnd(',', ' ')}) ";

  return insertQuery;
 }

Now, by simply passing the name of the columns to insert, the whole query will be created automatically, like below:

List < string > columns = new List < string > {
 "UserName",
 "City"
}
//QueryBuilder is the class having the InsertQueryBuilder()
string insertQueryValues = QueryBuilderUtil.InsertQueryBuilder(columns);

string insertQuery = $ "INSERT INTO UserDetails {insertQueryValues} RETURNING UserId";

Guid insertedId = await _connection.ExecuteScalarAsync < Guid > (insertQuery, userObj);

You can also modify the function to return the entire INSERT statement by passing the TableName parameter.

Make sure that the Class property names match with the field names in the database. Then only you can pass the entire obj (like userObj in our case) and values will be mapped automatically.

In the same way, you can have the helper function for UPDATE query as well:

  public static string UpdateQueryBuilder(List < string > fields) {
   StringBuilder updateQueryBuilder = new StringBuilder();

   foreach(string columnName in fields) {
    updateQueryBuilder.AppendFormat("{0}=@{0}, ", columnName);
   }
   return updateQueryBuilder.ToString().TrimEnd(',', ' ');
  }

And use it like:

List < string > columns = new List < string > {
 "UserName",
 "City"
}
//QueryBuilder is the class having the UpdateQueryBuilder()
string updateQueryValues = QueryBuilderUtil.UpdateQueryBuilder(columns);

string updateQuery =  $"UPDATE UserDetails SET {updateQueryValues} WHERE UserId=@UserId";

await _connection.ExecuteAsync(updateQuery, userObj);

Though in these helper functions also, you need to pass the name of the fields you want to insert or update but at least you have full control over the query and can also include different WHERE clauses as and when required.

Through this helper functions, you will save the following lines of code:

For Insert Query:

 $ "INSERT INTO UserDetails (UserName,City) VALUES (@UserName,@City) RETURNING UserId";

For Update Query:

$"UPDATE UserDetails SET UserName=@UserName, City=@City WHERE UserId=@UserId";

There seems to be a difference of few lines of code, but when it comes to performing insert or update operation with a table having more than 10 fields, one can feel the difference.

You can use the nameof operator to pass the field name in the function to avoid typos

Instead of:

List < string > columns = new List < string > {
 "UserName",
 "City"
}

You can write:

List < string > columns = new List < string > {
nameof(UserEntity.UserName),
nameof(UserEntity.City),
}

How to parse JSON in Java

There are many JSON libraries available in Java.

The most notorious ones are: Jackson, GSON, Genson, FastJson and org.json.

There are typically three things one should look at for choosing any library:

  1. Performance
  2. Ease of use (code is simple to write and legible) - that goes with features.
  3. For mobile apps: dependency/jar size

Specifically for JSON libraries (and any serialization/deserialization libs), databinding is also usually of interest as it removes the need of writing boiler-plate code to pack/unpack the data.

For 1, see this benchmark: https://github.com/fabienrenaud/java-json-benchmark I did using JMH which compares (jackson, gson, genson, fastjson, org.json, jsonp) performance of serializers and deserializers using stream and databind APIs. For 2, you can find numerous examples on the Internet. The benchmark above can also be used as a source of examples...

Quick takeaway of the benchmark: Jackson performs 5 to 6 times better than org.json and more than twice better than GSON.

For your particular example, the following code decodes your json with jackson:

public class MyObj {

    private PageInfo pageInfo;
    private List<Post> posts;

    static final class PageInfo {
        private String pageName;
        private String pagePic;
    }

    static final class Post {
        private String post_id;
        @JsonProperty("actor_id");
        private String actorId;
        @JsonProperty("picOfPersonWhoPosted")
        private String pictureOfPoster;
        @JsonProperty("nameOfPersonWhoPosted")
        private String nameOfPoster;
        private String likesCount;
        private List<String> comments;
        private String timeOfPost;
    }

    private static final ObjectMapper JACKSON = new ObjectMapper();
    public static void main(String[] args) throws IOException {
        MyObj o = JACKSON.readValue(args[0], MyObj.class); // assumes args[0] contains your json payload provided in your question.
    }
}

Let me know if you have any questions.

org.xml.sax.SAXParseException: Premature end of file for *VALID* XML

This is resolved. The problem was elsewhere. Another code in cron job was truncating XML to 0 length file. I have taken care of that.

What is default list styling (CSS)?

You cannot. Whenever there is any style sheet being applied that assigns a property to an element, there is no way to get to the browser defaults, for any instance of the element.

The (disputable) idea of reset.css is to get rid of browser defaults, so that you can start your own styling from a clean desk. No version of reset.css does that completely, but to the extent they do, the author using reset.css is supposed to completely define the rendering.

ldap_bind: Invalid Credentials (49)

I don't see an obvious problem with the above.

It's possible your ldap.conf is being overridden, but the command-line options will take precedence, ldapsearch will ignore BINDDN in the main ldap.conf, so the only parameter that could be wrong is the URI. (The order is ETCDIR/ldap.conf then ~/ldaprc or ~/.ldaprc and then ldaprc in the current directory, though there environment variables which can influence this too, see man ldapconf.)

Try an explicit URI:

ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base -H ldap://localhost

or prevent defaults with:

LDAPNOINIT=1 ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base

If that doesn't work, then some troubleshooting (you'll probably need the full path to the slapd binary for these):

  • make sure your slapd.conf is being used and is correct (as root)

    slapd -T test -f slapd.conf -d 65535

    You may have a left-over or default slapd.d configuration directory which takes preference over your slapd.conf (unless you specify your config explicitly with -f, slapd.conf is officially deprecated in OpenLDAP-2.4). If you don't get several pages of output then your binaries were built without debug support.

  • stop OpenLDAP, then manually start slapd in a separate terminal/console with debug enabled (as root, ^C to quit)

    slapd -h ldap://localhost -d 481

    then retry the search and see if you can spot the problem (there will be a lot of schema noise in the start of the output unfortunately). (Note: running slapd without the -u/-g options can change file ownerships which can cause problems, you should usually use those options, probably -u ldap -g ldap )

  • if debug is enabled, then try also

    ldapsearch -v -d 63 -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base

Will Google Android ever support .NET?

Miguel de Icaza's announced on his blog on the 17th of Feb 2010 that they are starting work on mono for android which will be called MonoDroid.

This will be similar to MonoTouch on the iphone but for android instead.

It will provide binding to the android UI, so apps will look and feel live native android apps. This will require you to write an android specific UI.

You will however be able to reuse you existing lower level libraries without the need to recompile.

Make xargs handle filenames that contain spaces

It depends on (a) how attached you are to the number 7 as opposed to, say, Lemons, and (b) whether any of your file names contain newlines (and whether you're willing to rename them if they do).

There are many ways to deal with it, but some of them are:

mplayer Lemon*.mp3

find . -name 'Lemon*.mp3' -exec mplayer {} ';'

i=0
for mp3 in *.mp3
do
    i=$((i+1))
    [ $i = 7 ] && mplayer "$mp3"
done

for mp3 in *.mp3
do
    case "$mp3" in
    (Lemon*) mplayer "$mp3";;
    esac
done

i=0
find . -name *.mp3 |
while read mp3
do
    i=$((i+1))
    [ $i = 7 ] && mplayer "$mp3"
done

The read loop doesn't work if file names contain newlines; the others work correctly even with newlines in the names (let alone spaces). For my money, if you have file names containing a newline, you should rename the file without the newline. Using the double quotes around the file name is key to the loops working correctly.

If you have GNU find and GNU xargs (or FreeBSD (*BSD?), or Mac OS X), you can also use the -print0 and -0 options, as in:

find . -name 'Lemon*.mp3' -print0 | xargs -0 mplayer

This works regardless of the contents of the name (the only two characters that cannot appear in a file name are slash and NUL, and the slash causes no problems in a file path, so using NUL as the name delimiter covers everything). However, if you need to filter out the first 6 entries, you need a program that handles 'lines' ended by NUL instead of newline...and I'm not sure there are any.

The first is by far the simplest for the specific case on hand; however, it may not generalize to cover your other scenarios that you've not yet listed.

master branch and 'origin/master' have diverged, how to 'undiverge' branches'?

I had this and am mystified as to what has caused it, even after reading the above responses. My solution was to do

git reset --hard origin/master

Then that just resets my (local) copy of master (which I assume is screwed up) to the correct point, as represented by (remote) origin/master.

WARNING: You will lose all changes not yet pushed to origin/master.

Maven compile: package does not exist

Not sure if there was file corruption or what, but after confirming proper pom configuration I was able to resolve this issue by deleting the jar from my local m2 repository, forcing Maven to download it again when I ran the tests.

How to create a numeric vector of zero length in R

If you read the help for vector (or numeric or logical or character or integer or double, 'raw' or complex etc ) then you will see that they all have a length (or length.out argument which defaults to 0

Therefore

numeric()
logical()
character()
integer()
double()
raw()
complex() 
vector('numeric')
vector('character')
vector('integer')
vector('double')
vector('raw')
vector('complex')

All return 0 length vectors of the appropriate atomic modes.

# the following will also return objects with length 0
list()
expression()
vector('list')
vector('expression')

Creating a chart in Excel that ignores #N/A or blank cells

I found a way to do it.

you can do an x,y scatterplot. it will ignore null records (i.e. rows)

Read/Write 'Extended' file properties (C#)

There's a CodeProject article for an ID3 reader. And a thread at kixtart.org that has more information for other properties. Basically, you need to call the GetDetailsOf() method on the folder shell object for shell32.dll.

Show default value in Spinner in android

Try below:

   <Spinner
    android:id="@+id/YourSpinnerId"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:prompt="Gender" />

How to specify HTTP error code?

I would recommend handling the sending of http error codes by using the Boom package.

Rename a file using Java

This is an easy way to rename a file:

        File oldfile =new File("test.txt");
        File newfile =new File("test1.txt");

        if(oldfile.renameTo(newfile)){
            System.out.println("File renamed");
        }else{
            System.out.println("Sorry! the file can't be renamed");
        }

A top-like utility for monitoring CUDA activity on a GPU

you can use nvidia-smi pmon -i 0 to monitor every process in GPU 0. including compute mode, sm usage, memory usage, encoder usage, decoder usage.

Uncaught ReferenceError: angular is not defined - AngularJS not working

Just to complement m59's correct answer, here is a working jsfiddle:

<body ng-app='myApp'>
    <div>
        <button my-directive>Click Me!</button>
    </div>
     <h1>{{2+3}}</h1>

</body>

Disable scrolling on `<input type=number>`

$(document).on("wheel", "input[type=number]", function (e) {
    $(this).blur();
});

JComboBox Selection Change Listener?

I would try the itemStateChanged() method of the ItemListener interface if jodonnell's solution fails.

Get multiple elements by Id

You can't have duplicate ids. Ids are supposed to be unique. You might want to use a specialized class instead.

MS Excel showing the formula in a cell instead of the resulting value

I tried everything I could find but nothing worked. Then I highlighted the formula column and right-clicked and selected 'clear contents'. That worked! Now I see the results, not the formula.

get string from right hand side

If you want to list last 3 chars, simplest way is

 select substr('123456',-3) from dual;

Find commit by hash SHA in Git

git log -1 --format="%an %ae%n%cn %ce" a2c25061

The Pretty Formats section of the git show documentation contains

  • format:<string>

The format:<string> format allows you to specify which information you want to show. It works a little bit like printf format, with the notable exception that you get a newline with %n instead of \n

The placeholders are:

  • %an: author name
  • %ae: author email
  • %cn: committer name
  • %ce: committer email

Required attribute HTML5

Note that

<input type="text" id="car" required="true" />

is wrong, it should be one of

<input type="text" id="car" required />
<input type="text" id="car" required="" />
<input type="text" id="car" required='' />
<input type="text" id="car" required=required />
<input type="text" id="car" required="required" />
<input type="text" id="car" required='required' />

This is because the true value suggests that the false value will make the form control optional, which is not the case.

Insert, on duplicate update in PostgreSQL?

PostgreSQL since version 9.5 has UPSERT syntax, with ON CONFLICT clause. with the following syntax (similar to MySQL)

INSERT INTO the_table (id, column_1, column_2) 
VALUES (1, 'A', 'X'), (2, 'B', 'Y'), (3, 'C', 'Z')
ON CONFLICT (id) DO UPDATE 
  SET column_1 = excluded.column_1, 
      column_2 = excluded.column_2;

Searching postgresql's email group archives for "upsert" leads to finding an example of doing what you possibly want to do, in the manual:

Example 38-2. Exceptions with UPDATE/INSERT

This example uses exception handling to perform either UPDATE or INSERT, as appropriate:

CREATE TABLE db (a INT PRIMARY KEY, b TEXT);

CREATE FUNCTION merge_db(key INT, data TEXT) RETURNS VOID AS
$$
BEGIN
    LOOP
        -- first try to update the key
        -- note that "a" must be unique
        UPDATE db SET b = data WHERE a = key;
        IF found THEN
            RETURN;
        END IF;
        -- not there, so try to insert the key
        -- if someone else inserts the same key concurrently,
        -- we could get a unique-key failure
        BEGIN
            INSERT INTO db(a,b) VALUES (key, data);
            RETURN;
        EXCEPTION WHEN unique_violation THEN
            -- do nothing, and loop to try the UPDATE again
        END;
    END LOOP;
END;
$$
LANGUAGE plpgsql;

SELECT merge_db(1, 'david');
SELECT merge_db(1, 'dennis');

There's possibly an example of how to do this in bulk, using CTEs in 9.1 and above, in the hackers mailing list:

WITH foos AS (SELECT (UNNEST(%foo[])).*)
updated as (UPDATE foo SET foo.a = foos.a ... RETURNING foo.id)
INSERT INTO foo SELECT foos.* FROM foos LEFT JOIN updated USING(id)
WHERE updated.id IS NULL;

See a_horse_with_no_name's answer for a clearer example.

sqldeveloper error message: Network adapter could not establish the connection error

Check the listener status to see if it is down:

ps -ef | grep tns

If you don't see output about the listener:

oracle 18244 /apps/oracle/product/11.2.0/db_1/bin/tnslsnr LISTENER -inherit

Then you will need to start it up. To do this, execute the lsnrctl command.

Type start in the LSNRCTL> prompt.

How to save select query results within temporary table?

In Sqlite:

CREATE TABLE T AS
SELECT * FROM ...;
-- Use temporary table `T`
DROP TABLE T;

C# Collection was modified; enumeration operation may not execute

I suspect the error is caused by this:

foreach (KeyValuePair<int, int> kvp in rankings)

rankings is a dictionary, which is IEnumerable. By using it in a foreach loop, you're specifying that you want each KeyValuePair from the dictionary in a deferred manner. That is, the next KeyValuePair is not returned until your loop iterates again.

But you're modifying the dictionary inside your loop:

rankings[kvp.Key] = rankings[kvp.Key] + 4;

which isn't allowed...so you get the exception.

You could simply do this

foreach (KeyValuePair<int, int> kvp in rankings.ToArray())

Count number of times value appears in particular column in MySQL

Take a look at the Group by function.

What the group by function does is pretuty much grouping the similar value for a given field. You can then show the number of number of time that this value was groupped using the COUNT function.

MySQL Documentation

You can also use the group by function with a good number of other function define by MySQL (see the above link).

mysql> SELECT student_name, AVG(test_score)
    ->        FROM student
    ->        GROUP BY student_name;

Saving binary data as file using JavaScript from a browser

To do this task download.js library can be used. Here is an example from library docs:

download("data:image/gif;base64,R0lGODlhRgAVAIcAAOfn5+/v7/f39////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////yH5BAAAAP8ALAAAAABGABUAAAj/AAEIHAgggMGDCAkSRMgwgEKBDRM+LBjRoEKDAjJq1GhxIMaNGzt6DAAypMORJTmeLKhxgMuXKiGSzPgSZsaVMwXUdBmTYsudKjHuBCoAIc2hMBnqRMqz6MGjTJ0KZcrz5EyqA276xJrVKlSkWqdGLQpxKVWyW8+iJcl1LVu1XttafTs2Lla3ZqNavAo37dm9X4eGFQtWKt+6T+8aDkxUqWKjeQUvfvw0MtHJcCtTJiwZsmLMiD9uplvY82jLNW9qzsy58WrWpDu/Lp0YNmPXrVMvRm3T6GneSX3bBt5VeOjDemfLFv1XOW7kncvKdZi7t/S7e2M3LkscLcvH3LF7HwSuVeZtjuPPe2d+GefPrD1RpnS6MGdJkebn4/+oMSAAOw==", "dlDataUrlBin.gif", "image/gif");

Android ListView with different layouts for each row

Take a look in the code below.

First, we create custom layouts. In this case, four types.

even.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:background="#ff500000"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/text"
        android:textColor="@android:color/white"
        android:layout_width="match_parent"
        android:layout_gravity="center"
        android:textSize="24sp"
        android:layout_height="wrap_content" />

 </LinearLayout>

odd.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:background="#ff001f50"
    android:gravity="right"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/text"
        android:textColor="@android:color/white"
        android:layout_width="wrap_content"
        android:layout_gravity="center"
        android:textSize="28sp"
        android:layout_height="wrap_content"  />

 </LinearLayout>

white.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:background="#ffffffff"
    android:gravity="right"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/text"
        android:textColor="@android:color/black"
        android:layout_width="wrap_content"
        android:layout_gravity="center"
        android:textSize="28sp"
        android:layout_height="wrap_content"   />

 </LinearLayout>

black.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:background="#ff000000"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/text"
        android:textColor="@android:color/white"
        android:layout_width="wrap_content"
        android:layout_gravity="center"
        android:textSize="33sp"
        android:layout_height="wrap_content"   />

 </LinearLayout>

Then, we create the listview item. In our case, with a string and a type.

public class ListViewItem {
        private String text;
        private int type;

        public ListViewItem(String text, int type) {
            this.text = text;
            this.type = type;
        }

        public String getText() {
            return text;
        }

        public void setText(String text) {
            this.text = text;
        }

        public int getType() {
            return type;
        }

        public void setType(int type) {
            this.type = type;
        }

    }

After that, we create a view holder. It's strongly recommended because Android OS keeps the layout reference to reuse your item when it disappears and appears back on the screen. If you don't use this approach, every single time that your item appears on the screen Android OS will create a new one and causing your app to leak memory.

public class ViewHolder {
        TextView text;

        public ViewHolder(TextView text) {
            this.text = text;
        }

        public TextView getText() {
            return text;
        }

        public void setText(TextView text) {
            this.text = text;
        }

    }

Finally, we create our custom adapter overriding getViewTypeCount() and getItemViewType(int position).

public class CustomAdapter extends ArrayAdapter {

        public static final int TYPE_ODD = 0;
        public static final int TYPE_EVEN = 1;
        public static final int TYPE_WHITE = 2;
        public static final int TYPE_BLACK = 3;

        private ListViewItem[] objects;

        @Override
        public int getViewTypeCount() {
            return 4;
        }

        @Override
        public int getItemViewType(int position) {
            return objects[position].getType();
        }

        public CustomAdapter(Context context, int resource, ListViewItem[] objects) {
            super(context, resource, objects);
            this.objects = objects;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder viewHolder = null;
            ListViewItem listViewItem = objects[position];
            int listViewItemType = getItemViewType(position);


            if (convertView == null) {

                if (listViewItemType == TYPE_EVEN) {
                    convertView = LayoutInflater.from(getContext()).inflate(R.layout.type_even, null);
                } else if (listViewItemType == TYPE_ODD) {
                    convertView = LayoutInflater.from(getContext()).inflate(R.layout.type_odd, null);
                } else if (listViewItemType == TYPE_WHITE) {
                    convertView = LayoutInflater.from(getContext()).inflate(R.layout.type_white, null);
                } else {
                    convertView = LayoutInflater.from(getContext()).inflate(R.layout.type_black, null);
                }

                TextView textView = (TextView) convertView.findViewById(R.id.text);
                viewHolder = new ViewHolder(textView);

                convertView.setTag(viewHolder);

            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            viewHolder.getText().setText(listViewItem.getText());

            return convertView;
        }

    }

And our activity is something like this:

private ListView listView;

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

        setContentView(R.layout.activity_main); // here, you can create a single layout with a listview

        listView = (ListView) findViewById(R.id.listview);

        final ListViewItem[] items = new ListViewItem[40];

        for (int i = 0; i < items.length; i++) {
            if (i == 4) {
                items[i] = new ListViewItem("White " + i, CustomAdapter.TYPE_WHITE);
            } else if (i == 9) {
                items[i] = new ListViewItem("Black " + i, CustomAdapter.TYPE_BLACK);
            } else if (i % 2 == 0) {
                items[i] = new ListViewItem("EVEN " + i, CustomAdapter.TYPE_EVEN);
            } else {
                items[i] = new ListViewItem("ODD " + i, CustomAdapter.TYPE_ODD);
            }
        }

        CustomAdapter customAdapter = new CustomAdapter(this, R.id.text, items);
        listView.setAdapter(customAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView adapterView, View view, int i, long l) {
                Toast.makeText(getBaseContext(), items[i].getText(), Toast.LENGTH_SHORT).show();
            }
        });

    }
}

now create a listview inside mainactivity.xml like this

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.example.shivnandan.gygy.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <ListView
        android:layout_width="match_parent"

        android:layout_height="match_parent"

        android:id="@+id/listView"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"


        android:layout_marginTop="100dp" />

</android.support.design.widget.CoordinatorLayout>

what is the size of an enum type data in C++?

An enum is nearly an integer. To simplify a lot

enum yourenum { a, b, c };

is almost like

#define a 0
#define b 1
#define c 2

Of course, it is not really true. I'm trying to explain that enum are some kind of coding...

Create table variable in MySQL

If you don't want to store table in database then @Evan Todd already has been provided temporary table solution.

But if you need that table for other users and want to store in db then you can use below procedure.

Create below ‘stored procedure’:

————————————

DELIMITER $$

USE `test`$$

DROP PROCEDURE IF EXISTS `sp_variable_table`$$

CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_variable_table`()
BEGIN

SELECT CONCAT(‘zafar_’,REPLACE(TIME(NOW()),’:',’_')) INTO @tbl;

SET @str=CONCAT(“create table “,@tbl,” (pbirfnum BIGINT(20) NOT NULL DEFAULT ’0', paymentModes TEXT ,paymentmodeDetails TEXT ,shippingCharges TEXT ,shippingDetails TEXT ,hypenedSkuCodes TEXT ,skuCodes TEXT ,itemDetails TEXT ,colorDesc TEXT ,size TEXT ,atmDesc TEXT ,promotional TEXT ,productSeqNumber VARCHAR(16) DEFAULT NULL,entity TEXT ,entityDetails TEXT ,kmtnmt TEXT ,rating BIGINT(1) DEFAULT NULL,discount DECIMAL(15,0) DEFAULT NULL,itemStockDetails VARCHAR(38) NOT NULL DEFAULT ”) ENGINE=INNODB DEFAULT CHARSET=utf8");
PREPARE stmt FROM @str;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SELECT ‘Table has been created’;
END$$

DELIMITER ;

———————————————–

Now you can execute this procedure to create a variable name table as per below-

call sp_variable_table();

You can check new table after executing below command-

use test;show tables like ‘%zafar%’; — test is here ‘database’ name.

You can also check more details at below path-

http://mydbsolutions.in/how-can-create-a-table-with-variable-name/

How do I rotate a picture in WinForms

You can easily do it by calling this method :

public static Bitmap RotateImage(Image image, float angle)
{
    if (image == null)
        throw new ArgumentNullException("image");

    PointF offset = new PointF((float)image.Width / 2, (float)image.Height / 2);

    //create a new empty bitmap to hold rotated image
    Bitmap rotatedBmp = new Bitmap(image.Width, image.Height);
    rotatedBmp.SetResolution(image.HorizontalResolution, image.VerticalResolution);

    //make a graphics object from the empty bitmap
    Graphics g = Graphics.FromImage(rotatedBmp);

    //Put the rotation point in the center of the image
    g.TranslateTransform(offset.X, offset.Y);

    //rotate the image
    g.RotateTransform(angle);

    //move the image back
    g.TranslateTransform(-offset.X, -offset.Y);

    //draw passed in image onto graphics object
    g.DrawImage(image, new PointF(0, 0));

    return rotatedBmp;
}

don't forget to add a reference to System.Drawing.dll on your project

Example of this method call :

Image image = new Bitmap("waves.png");
Image newImage = RotateImage(image, 360);
newImage.Save("newWaves.png");

What is considered a good response time for a dynamic, personalized web application?

Of course, it lays in the nature of your question, so answers are highly subjective.

The first response of a website is also only a small part of the time until a page is readable/usable.

I am annoyed by everything larger than 10 sec responses. I think a website should be rendered after 5-7 sec.

Btw: stackoverflow.com has an excellent response time!

Does WGET timeout?

The default timeout is 900 second. You can specify different timeout.

-T seconds
--timeout=seconds

The default is to retry 20 times. You can specify different tries.

-t number
--tries=number

link: wget man document

IE 8: background-size fix

Also i have found another useful link. It is a background hack used like this

.selector { background-size: cover; -ms-behavior: url(/backgroundsize.min.htc); }

https://github.com/louisremi/background-size-polyfill

SQL Column definition : default value and not null redundant?

Even with a default value, you can always override the column data with null.

The NOT NULL restriction won't let you update that row after it was created with null value

Chrome Extension - Get DOM content

For those who tried gkalpak answer and it did not work,

be aware that chrome will add the content script to a needed page only when your extension enabled during chrome launch and also a good idea restart browser after making these changes

How to find specific lines in a table using Selenium?

(.//*[table-locator])[n]

where n represents the specific line.

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

I like Dan Moulding's answer, I'll just add a bit of C++ style to it:

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

int to_int(const std::string &s, int base = 0)
{
    char *end;
    errno = 0;
    long result = std::strtol(s.c_str(), &end, base);
    if (errno == ERANGE || result > INT_MAX || result < INT_MIN)
        throw std::out_of_range("toint: string is out of range");
    if (s.length() == 0 || *end != '\0')
        throw std::invalid_argument("toint: invalid string");
    return result;
}

It works for both std::string and const char* through the implicit conversion. It's also useful for base conversion, e.g. all to_int("0x7b") and to_int("0173") and to_int("01111011", 2) and to_int("0000007B", 16) and to_int("11120", 3) and to_int("3L", 34); would return 123.

Unlike std::stoi it works in pre-C++11. Also unlike std::stoi, boost::lexical_cast and stringstream it throws exceptions for weird strings like "123hohoho".

NB: This function tolerates leading spaces but not trailing spaces, i.e. to_int(" 123") returns 123 while to_int("123 ") throws exception. Make sure this is acceptable for your use case or adjust the code.

Such function could be part of STL...

How do you monitor network traffic on the iPhone?

Com'on, no mention of Fiddler? Where's the love :)

Fiddler is a very popular HTTP debugger aimed at developers and not network admins (i.e. Wireshark).

Setting it up for iOS is fairly simple process. It can decrypt HTTPS traffic too!

Our mobile team is finally reliefed after QA department started using Fiddler to troubleshoot issues. Before fiddler, people fiddled around to know who to blame, mobile team or APIs team, but not anymore.

How to test if a double is zero?

Yes, it's a valid test although there's an implicit conversion from int to double. For clarity/simplicity you should use (foo.x == 0.0) to test. That will hinder NAN errors/division by zero, but the double value can in some cases be very very very close to 0, but not exactly zero, and then the test will fail (I'm talking about in general now, not your code). Division by that will give huge numbers.

If this has anything to do with money, do not use float or double, instead use BigDecimal.

ALTER DATABASE failed because a lock could not be placed on database

I managed to reproduce this error by doing the following.

Connection 1 (leave running for a couple of minutes)

CREATE DATABASE TESTING123
GO

USE TESTING123;

SELECT NEWID() AS X INTO FOO
FROM sys.objects s1,sys.objects s2,sys.objects s3,sys.objects s4 ,sys.objects s5 ,sys.objects s6

Connections 2 and 3

set lock_timeout 5;

ALTER DATABASE TESTING123 SET SINGLE_USER WITH ROLLBACK IMMEDIATE;

Allow docker container to connect to a local/host postgres database

Simple solution

Just add --network=host to docker run. That's all!

This way container will use the host's network, so localhost and 127.0.0.1 will point to the host (by default they point to a container). Example:

docker run -d --network=host \
  -e "DB_DBNAME=your_db" \
  -e "DB_PORT=5432" \
  -e "DB_USER=your_db_user" \
  -e "DB_PASS=your_db_password" \
  -e "DB_HOST=127.0.0.1" \
  --name foobar foo/bar

How do you find what version of libstdc++ library is installed on your linux machine?

The mechanism I tend to use is a combination of readelf -V to dump the .gnu.version information from libstdc++, and then a lookup table that matches the largest GLIBCXX_ value extracted.

readelf -sV /usr/lib/libstdc++.so.6 | sed -n 's/.*@@GLIBCXX_//p' | sort -u -V | tail -1

if your version of sort is too old to have the -V option (which sorts by version number) then you can use:

tr '.' ' ' | sort -nu -t ' ' -k 1 -k 2 -k 3 -k 4 | tr ' ' '.'

instead of the sort -u -V, to sort by up to 4 version digits.

In general, matching the ABI version should be good enough.

If you're trying to track down the libstdc++.so.<VERSION>, though, you can use a little bash like:

file=/usr/lib/libstdc++.so.6
while [ -h $file ]; do file=$(ls -l $file | sed -n 's/.*-> //p'); done
echo ${file#*.so.}

so for my system this yielded 6.0.10.

If, however, you're trying to get a binary that was compiled on systemX to work on systemY, then these sorts of things will only get you so far. In those cases, carrying along a copy of the libstdc++.so that was used for the application, and then having a run script that does an:

export LD_LIBRARY_PATH=<directory of stashed libstdc++.so>
exec application.bin "$@"

generally works around the issue of the .so that is on the box being incompatible with the version from the application. For more extreme differences in environment, I tend to just add all the dependent libraries until the application works properly. This is the linux equivalent of working around what, for windows, would be considered dll hell.

Difference between one-to-many and many-to-one relationship

From this page about Database Terminology

Most relations between tables are one-to-many.

Example:

  • One area can be the habitat of many readers.
  • One reader can have many subscriptions.
  • One newspaper can have many subscriptions.

A Many to One relation is the same as one-to-many, but from a different viewpoint.

  • Many readers live in one area.
  • Many subscriptions can be of one and the same reader.
  • Many subscriptions are for one and the same newspaper.

Android: how to parse URL String with spaces to URI object?

You should in fact URI-encode the "invalid" characters. Since the string actually contains the complete URL, it's hard to properly URI-encode it. You don't know which slashes / should be taken into account and which not. You cannot predict that on a raw String beforehand. The problem really needs to be solved at a higher level. Where does that String come from? Is it hardcoded? Then just change it yourself accordingly. Does it come in as user input? Validate it and show error, let the user solve itself.

At any way, if you can ensure that it are only the spaces in URLs which makes it invalid, then you can also just do a string-by-string replace with %20:

URI uri = new URI(string.replace(" ", "%20"));

Or if you can ensure that it's only the part after the last slash which needs to be URI-encoded, then you can also just do so with help of android.net.Uri utility class:

int pos = string.lastIndexOf('/') + 1;
URI uri = new URI(string.substring(0, pos) + Uri.encode(string.substring(pos)));

Do note that URLEncoder is insuitable for the task as it's designed to encode query string parameter names/values as per application/x-www-form-urlencoded rules (as used in HTML forms). See also Java URL encoding of query string parameters.

How do I use a delimiter with Scanner.useDelimiter in Java?

With Scanner the default delimiters are the whitespace characters.

But Scanner can define where a token starts and ends based on a set of delimiter, wich could be specified in two ways:

  1. Using the Scanner method: useDelimiter(String pattern)
  2. Using the Scanner method : useDelimiter(Pattern pattern) where Pattern is a regular expression that specifies the delimiter set.

So useDelimiter() methods are used to tokenize the Scanner input, and behave like StringTokenizer class, take a look at these tutorials for further information:

And here is an Example:

public static void main(String[] args) {

    // Initialize Scanner object
    Scanner scan = new Scanner("Anna Mills/Female/18");
    // initialize the string delimiter
    scan.useDelimiter("/");
    // Printing the tokenized Strings
    while(scan.hasNext()){
        System.out.println(scan.next());
    }
    // closing the scanner stream
    scan.close();
}

Prints this output:

Anna Mills
Female
18

Converting a float to a string without rounding it

len(repr(float(x)/3))

However I must say that this isn't as reliable as you think.

Floats are entered/displayed as decimal numbers, but your computer (in fact, your standard C library) stores them as binary. You get some side effects from this transition:

>>> print len(repr(0.1))
19
>>> print repr(0.1)
0.10000000000000001

The explanation on why this happens is in this chapter of the python tutorial.

A solution would be to use a type that specifically tracks decimal numbers, like python's decimal.Decimal:

>>> print len(str(decimal.Decimal('0.1')))
3

How to find the index of an element in an int array?

Binary search: Binary search can also be used to find the index of the array element in an array. But the binary search can only be used if the array is sorted. Java provides us with an inbuilt function which can be found in the Arrays library of Java which will rreturn the index if the element is present, else it returns -1. The complexity will be O(log n). Below is the implementation of Binary search.

public static int findIndex(int arr[], int t) { 
   int index = Arrays.binarySearch(arr, t); 
   return (index < 0) ? -1 : index; 
} 

Does Ruby have a string.startswith("abc") built in method?

Your question title and your question body are different. Ruby does not have a starts_with? method. Rails, which is a Ruby framework, however, does, as sepp2k states. See his comment on his answer for the link to the documentation for it.

You could always use a regular expression though:

if SomeString.match(/^abc/) 
   # SomeString starts with abc

^ means "start of string" in regular expressions

How to check if IEnumerable is null or empty?

I used simple if to check for it

check out my solution

foreach (Pet pet in v.Pets)
{
    if (pet == null)
    {
        Console.WriteLine(" No pet");// enumerator is empty
        break;
    }
    Console.WriteLine("  {0}", pet.Name);
}

PHP array value passes to next row

Change the checkboxes so that the name includes the index inside the brackets:

<input type="checkbox" class="checkbox_veh" id="checkbox_addveh<?php echo $i; ?>" <?php if ($vehicle_feature[$i]->check) echo "checked"; ?> name="feature[<?php echo $i; ?>]" value="<?php echo $vehicle_feature[$i]->id; ?>"> 

The checkboxes that aren't checked are never submitted. The boxes that are checked get submitted, but they get numbered consecutively from 0, and won't have the same indexes as the other corresponding input fields.

Please run `npm cache clean`

As of npm@5, the npm cache self-heals from corruption issues and data extracted from the cache is guaranteed to be valid. If you want to make sure everything is consistent, use npm cache verify instead. On the other hand, if you're debugging an issue with the installer, you can use npm install --cache /tmp/empty-cache to use a temporary cache instead of nuking the actual one.

If you're sure you want to delete the entire cache, rerun:

npm cache clean --force

A complete log of this run can be found in /Users/USERNAME/.npm/_logs/2019-01-08T21_29_30_811Z-debug.log.

C - freeing structs

You can't free types that aren't dynamically allocated. Although arrays are syntactically similar (int* x = malloc(sizeof(int) * 4) can be used in the same way that int x[4] is), calling free(firstName) would likely cause an error for the latter.

For example, take this code:

int x;
free(&x);

free() is a function which takes in a pointer. &x is a pointer. This code may compile, even though it simply won't work.

If we pretend that all memory is allocated in the same way, x is "allocated" at the definition, "freed" at the second line, and then "freed" again after the end of the scope. You can't free the same resource twice; it'll give you an error.

This isn't even mentioning the fact that for certain reasons, you may be unable to free the memory at x without closing the program.

tl;dr: Just free the struct and you'll be fine. Don't call free on arrays; only call it on dynamically allocated memory.

Why AVD Manager options are not showing in Android Studio

I found it from the icon. Please see the device icon.

enter image description here

Array from dictionary keys in swift

dict.allKeys is not a String. It is a [String], exactly as the error message tells you (assuming, of course, that the keys are all strings; this is exactly what you are asserting when you say that).

So, either start by typing componentArray as [AnyObject], because that is how it is typed in the Cocoa API, or else, if you cast dict.allKeys, cast it to [String], because that is how you have typed componentArray.

bootstrap responsive table content wrapping

_x000D_
_x000D_
.table td.abbreviation {_x000D_
  max-width: 30px;_x000D_
}_x000D_
.table td.abbreviation p {_x000D_
  white-space: nowrap;_x000D_
  overflow: hidden;_x000D_
  text-overflow: ellipsis;_x000D_
_x000D_
}
_x000D_
<table class="table">_x000D_
<tr>_x000D_
 <td class="abbreviation"><p>ABC DEF</p></td>_x000D_
</tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Can I set subject/content of email using mailto:?

If you want to add html content to your email, url encode your html code for the message body and include it in your mailto link code, but trouble is you can't set the type of the email from this link from plaintext to html, the client using the link needs their mail client to send html emails by default. In case you want to test here is the code for a simple mailto link, with an image wrapped in a link (angular style urls added for visibility):

<a href="mailto:?body=%3Ca%20href%3D%22{{ scope.url }}%22%3E%3Cimg%20src%3D%22{{ scope.url }}%22%20width%3D%22300%22%20%2F%3E%3C%2Fa%3E">

The html tags are url encoded.

Background images: how to fill whole div if image is small and vice versa

  1. I agree with yossi's example, stretch the image to fit the div but in a slightly different way (without background-image as this is a little inflexible in css 2.1). Show full image:

    <div id="yourdiv">
        <img id="theimage" src="image.jpg" alt="" />
    </div>
    
    #yourdiv img {
        width:100%;
      /*height will be automatic to remain aspect ratio*/
    }
    
  2. Show part of the image using background-position:

    #yourdiv 
    {
        background-image: url(image.jpg);
        background-repeat: no-repeat;
        background-position: 10px 25px;
    }
    
  3. Same as the first part of (1) the image will scale to the div so bigger or smaller will both work

  4. Same as yossi's.

How to declare 2D array in bash

2D array can be achieved in bash by declaring 1D array and then elements can be accessed using (r * col_size) + c). Below logic delcares 1D array (str_2d_arr) and prints as 2D array.

col_size=3
str_2d_arr=()
str_2d_arr+=('abc' '200' 'xyz')
str_2d_arr+=('def' '300' 'ccc')
str_2d_arr+=('aaa' '400' 'ddd')

echo "Print 2D array"
col_count=0
for elem in ${str_2d_arr[@]}; do
    if [ ${col_count} -eq ${col_size} ]; then
        echo ""
        col_count=0
    fi
    echo -e "$elem \c"
    ((col_count++))
done
echo ""

Output is

Print 2D array
abc 200 xyz 
def 300 ccc
aaa 400 ddd

Below logic is very useful to get each row from the above declared 1D array str_2d_arr.

# Get nth row and update to 2nd arg
get_row_n()
{
    row=$1
    local -n a=$2
    start_idx=$((row * col_size))
    for ((i = 0; i < ${col_size}; i++)); do
        idx=$((start_idx + i))
        a+=(${str_2d_arr[${idx}]})
    done
}

arr=()
get_row_n 0 arr
echo "Row 0"
for e in ${arr[@]}; do
    echo -e "$e \c"
done
echo ""

Output is

Row 0
abc 200 xyz

Why am I getting a " Traceback (most recent call last):" error?

At the beginning of your file you set raw_input to 0. Do not do this, at it modifies the built-in raw_input() function. Therefore, whenever you call raw_input(), it is essentially calling 0(), which raises the error. To remove the error, remove the first line of your code:

M = 1.6
# Miles to Kilometers 
# Celsius Celsius = (var1 - 32) * 5/9
# Gallons to liters Gallons = 3.6
# Pounds to kilograms Pounds = 0.45
# Inches to centimete Inches = 2.54


def intro():
    print("Welcome! This program will convert measures for you.")
    main()

def main():
    print("Select operation.")
    print("1.Miles to Kilometers")
    print("2.Fahrenheit to Celsius")
    print("3.Gallons to liters")
    print("4.Pounds to kilograms")
    print("5.Inches to centimeters")

    choice = input("Enter your choice by number: ")

    if choice == '1':
        convertMK()

    elif choice == '2':
        converCF()

    elif choice == '3':
        convertGL()

    elif choice == '4':
        convertPK()

    elif choice == '5':
        convertPK()

    else:
        print("Error")


def convertMK():
    input_M = float(raw_input(("Miles: ")))
    M_conv = (M) * input_M
    print("Kilometers: %f\n" % M_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print("I didn't quite understand that answer. Terminating.")
        main()

def converCF():
    input_F = float(raw_input(("Fahrenheit: ")))
    F_conv = (input_F - 32) * 5/9
    print("Celcius: %f\n") % F_conv
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print("I didn't quite understand that answer. Terminating.")
        main()

def convertGL():
    input_G = float(raw_input(("Gallons: ")))
    G_conv = input_G * 3.6
    print("Centimeters: %f\n" % G_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def convertPK():
    input_P = float(raw_input(("Pounds: ")))
    P_conv = input_P * 0.45
    print("Centimeters: %f\n" % P_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def convertIC():
    input_cm = float(raw_input(("Inches: ")))
    inches_conv = input_cm * 2.54
    print("Centimeters: %f\n" % inches_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def end():
    print("This program will close.")
    exit()

intro()

Responsive design with media query : screen size?

Responsive Web design (RWD) is a Web design approach aimed at crafting sites to provide an optimal viewing experience

When you design your responsive website you should consider the size of the screen and not the device type. The media queries helps you do that.

If you want to style your site per device, you can use the user agent value, but this is not recommended since you'll have to work hard to maintain your code for new devices, new browsers, browsers versions etc while when using the screen size, all of this does not matter.

You can see some standard resolutions in this link.

BUT, in my opinion, you should first design your website layout, and only then adjust it with media queries to fit possible screen sizes.

Why? As I said before, the screen resolutions variety is big and if you'll design a mobile version that is targeted to 320px your site won't be optimized to 350px screens or 400px screens.

TIPS

  1. When designing a responsive page, open it in your desktop browser and change the width of the browser to see how the width of the screen affects your layout and style.
  2. Use percentage instead of pixels, it will make your work easier.

Example

I have a table with 5 columns. The data looks good when the screen size is bigger than 600px so I add a breakpoint at 600px and hides 1 less important column when the screen size is smaller. Devices with big screens such as desktops and tablets will display all the data, while mobile phones with small screens will display part of the data.


State of mind

Not directly related to the question but important aspect in responsive design. Responsive design also relate to the fact that the user have a different state of mind when using a mobile phone or a desktop. For example, when you open your bank's site in the evening and check your stocks you want as much data on the screen. When you open the same page in the your lunch break your probably want to see few important details and not all the graphs of last year.

Read int values from a text file in C

How about this?

fscanf(file,"%d %d %d %d %d %d %d",&line1_1,&line1_2, &line1_3, &line2_1, &line2_2, &line3_1, &line3_2); 

In this case spaces in fscanf match multiple occurrences of any whitespace until the next token in found.

How to get current working directory using vba?

You have several options depending on what you're looking for. Workbook.Path returns the path of a saved workbook. Application.Path returns the path to the Excel executable. CurDir returns the current working path, this probably defaults to your My Documents folder or similar.

You can also use the windows scripting shell object's .CurrentDirectory property.

Set wshell = CreateObject("WScript.Shell")
Debug.Print wshell.CurrentDirectory

But that should get the same result as just

Debug.Print CurDir

Resize image with javascript canvas (smoothly)

I created a library that allows you to downstep any percentage while keeping all the color data.

https://github.com/danschumann/limby-resize/blob/master/lib/canvas_resize.js

That file you can include in the browser. The results will look like photoshop or image magick, preserving all the color data, averaging pixels, rather than taking nearby ones and dropping others. It doesn't use a formula to guess the averages, it takes the exact average.

Retrieving the first digit of a number

Almost certainly more efficient than using Strings:

int firstDigit(int x) {
    while (x > 9) {
        x /= 10;
    }
    return x;
}

(Works only for nonnegative integers.)

How to add native library to "java.library.path" with Eclipse launch (instead of overriding it)

Window->Preferences->Java->Installed JREs. Then choose your current JRE(JDK) and click Edit. Fill Default VM Arguments: -Djava.library.path=/usr/local/xuggler/lib. Done!

How generate unique Integers based on GUIDs

The GetHashCode function is specifically designed to create a well distributed range of integers with a low probability of collision, so for this use case is likely to be the best you can do.

But, as I'm sure you're aware, hashing 128 bits of information into 32 bits of information throws away a lot of data, so there will almost certainly be collisions if you have a sufficiently large number of GUIDs.

How to play .mp4 video in videoview in android?

Check the format of the video you are rendering. Rendering of mp4 format started from API level 11 and the format must be mp4(H.264)

I encountered the same problem, I had to convert my video to many formats before I hit the format: Use total video converter to convert the video to mp4. It works like a charm.

ReactJS: Maximum update depth exceeded error

onClick you should call function, thats called your function toggle.

onClick={() => this.toggle()}

Inline Form nested within Horizontal Form in Bootstrap 3

To make it work in Chrome (and bootply) i had to change code in this way:

<form class="form-horizontal">
  <div class="form-group">
    <label for="name" class="col-xs-2 control-label">Name</label>
    <div class="col-xs-10">
      <input type="text" class="form-control col-sm-10" name="name" placeholder="name" />
    </div>
  </div>

  <div class="form-group">
    <label for="birthday" class="col-xs-2 control-label">Birthday</label>
    <div class="col-xs-10">
      <div class="form-inline">
        <input type="text" class="form-control" placeholder="year" />
        <input type="text" class="form-control" placeholder="month" />
        <input type="text" class="form-control" placeholder="day" />
      </div>
    </div>
  </div>
</form>

Start an activity from a fragment

mFragmentFavorite in your code is a FragmentActivity which is not the same thing as a Fragment. That's why you're getting the type mismatch. Also, you should never call new on an Activity as that is not the proper way to start one.

If you want to start a new instance of mFragmentFavorite, you can do so via an Intent.

From a Fragment:

Intent intent = new Intent(getActivity(), mFragmentFavorite.class);
startActivity(intent);

From an Activity

Intent intent = new Intent(this, mFragmentFavorite.class);
startActivity(intent);

If you want to start aFavorite instead of mFragmentFavorite then you only need to change out their names in the created Intent.

Also, I recommend changing your class names to be more accurate. Calling something mFragmentFavorite is improper in that it's not a Fragment at all. Also, class declarations in Java typically start with a capital letter. You'd do well to name your class something like FavoriteActivity to be more accurate and conform to the language conventions. You will also need to rename the file to FavoriteActivity.java if you choose to do this since Java requires class names match the file name.

UPDATE

Also, it looks like you actually meant formFragmentFavorite to be a Fragment instead of a FragmentActivity based on your use of onCreateView. If you want mFragmentFavorite to be a Fragment then change the following line of code:

public class mFragmentFavorite extends FragmentActivity{

Make this instead read:

public class mFragmentFavorite extends Fragment {

error CS0103: The name ' ' does not exist in the current context

Simply move the declaration outside of the if block.

@{
string currentstore=HttpContext.Current.Request.ServerVariables["HTTP_HOST"];
string imgsrc="";
if (currentstore == "www.mydomain.com")
    {
    <link href="/path/to/my/stylesheets/styles1-print.css" rel="stylesheet" type="text/css" />
    imgsrc="/content/images/uploaded/store1_logo.jpg";
    }
else
    {
    <link href="/path/to/my/stylesheets/styles2-print.css" rel="stylesheet" type="text/css" />
    imgsrc="/content/images/uploaded/store2_logo.gif";
    }
}

<a href="@Url.RouteUrl("HomePage")" class="logo"><img  alt="" src="@imgsrc"></a>

You could make it a bit cleaner.

@{
string currentstore=HttpContext.Current.Request.ServerVariables["HTTP_HOST"];
string imgsrc="/content/images/uploaded/store2_logo.gif";
if (currentstore == "www.mydomain.com")
    {
    <link href="/path/to/my/stylesheets/styles1-print.css" rel="stylesheet" type="text/css" />
    imgsrc="/content/images/uploaded/store1_logo.jpg";
    }
else
    {
    <link href="/path/to/my/stylesheets/styles2-print.css" rel="stylesheet" type="text/css" />
    }
}

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 13: ordinal not in range(128)

python3x or higher

  1. load file in byte stream:
     body = ''
        for lines in open('website/index.html','rb'):
            decodedLine = lines.decode('utf-8')
            body = body+decodedLine.strip()
        return body
  1. use global setting:
    import io
    import sys
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')

Convert a string to int using sql query

You could use CAST or CONVERT:

SELECT CAST(MyVarcharCol AS INT) FROM Table

SELECT CONVERT(INT, MyVarcharCol) FROM Table

How to get the root dir of the Symfony2 application?

In Symfony 3.3 you can use

$projectRoot = $this->get('kernel')->getProjectDir();

to get the web/project root.

Unable to make the session state request to the session state server

One of my clients was facing the same issue. Following steps are taken to fix this.

 (1) Open Run. 

 (2) Type Services.msc

 (3) Select ASP.NET State Service

 (4) Right Click and Start it.

laravel foreach loop in controller

The view (blade template): Inside the loop you can retrieve whatever column you looking for

 @foreach ($products as $product)
   {{$product->sku}}
 @endforeach

CSS Cell Margin

Following Cian's solution of setting a border in place of a margin, I discovered you can set border color to transparent to avoid having to color match the background. Works in FF17, IE9, Chrome v23. Seems like a decent solution provided you don't also need an actual border.

VIM Disable Automatic Newline At End Of File

There is another way to approach this if you are using Git for source control. Inspired by an answer here, I wrote my own filter for use in a gitattributes file.

To install this filter, save it as noeol_filter somewhere in your $PATH, make it executable, and run the following commands:

git config --global filter.noeol.clean noeol_filter
git config --global filter.noeol.smudge cat

To start using the filter only for yourself, put the following line in your $GIT_DIR/info/attributes:

*.php filter=noeol

This will make sure you do not commit any newline at eof in a .php file, no matter what Vim does.

And now, the script itself:

#!/usr/bin/python

# a filter that strips newline from last line of its stdin
# if the last line is empty, leave it as-is, to make the operation idempotent
# inspired by: https://stackoverflow.com/questions/1654021/how-can-i-delete-a-newline-if-it-is-the-last-character-in-a-file/1663283#1663283

import sys

if __name__ == '__main__':
    try:
        pline = sys.stdin.next()
    except StopIteration:
        # no input, nothing to do
        sys.exit(0)

    # spit out all but the last line
    for line in sys.stdin:
        sys.stdout.write(pline)
        pline = line

    # strip newline from last line before spitting it out
    if len(pline) > 2 and pline.endswith("\r\n"):
        sys.stdout.write(pline[:-2])
    elif len(pline) > 1 and pline.endswith("\n"):
        sys.stdout.write(pline[:-1])
    else:
        sys.stdout.write(pline)

How do I make an HTML text box show a hint when empty?

For jQuery users: naspinski's jQuery link seems broken, but try this one: http://remysharp.com/2007/01/25/jquery-tutorial-text-box-hints/

You get a free jQuery plugin tutorial as a bonus. :)